Search in sources :

Example 1 with DOMErrorHandlerImpl

use of org.eclipse.titan.designer.properties.data.DOMErrorHandlerImpl in project titan.EclipsePlug-ins by eclipse.

the class TITANProjectExporter method saveAll.

/**
 * Saves all project information of "project" into the tpd file given output
 * file "projectFile" Prerequisites: project and projectFile are set properly
 *
 * @return true if the save was successful
 */
public boolean saveAll() {
    if (project == null) {
        ErrorReporter.logError("Invalid project");
        return false;
    }
    if (projectFile == null || projectFile.trim().length() == 0) {
        return false;
    }
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder;
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        ErrorReporter.logExceptionStackTrace(e);
        return false;
    }
    DOMImplementation impl = builder.getDOMImplementation();
    final Document document = impl.createDocument(null, "TITAN_Project_File_Information", null);
    Element root = document.getDocumentElement();
    root.setAttribute("version", "1.0");
    boolean result = saveProjectInformation(root, project, packAllProjectsIntoOne, !packAllProjectsIntoOne);
    if (!result) {
        return false;
    }
    ProjectFileHandler.indentNode(document, document.getDocumentElement(), 1);
    System.setProperty(DOMImplementationRegistry.PROPERTY, ProjectFormatConstants.DOM_IMPLEMENTATION_SOURCE);
    DOMImplementationRegistry registry = null;
    try {
        registry = DOMImplementationRegistry.newInstance();
    } catch (ClassNotFoundException ce) {
        ErrorReporter.logExceptionStackTrace(ce);
        return false;
    } catch (InstantiationException ie) {
        ErrorReporter.logExceptionStackTrace(ie);
        return false;
    } catch (IllegalAccessException iae) {
        ErrorReporter.logExceptionStackTrace(iae);
        return false;
    }
    // Specifying "LS 3.0" in the features list ensures that the
    // DOMImplementation
    // object implements the load and save features of the DOM 3.0
    // specification.
    DOMImplementation domImpl = registry.getDOMImplementation(ProjectFormatConstants.LOAD_SAVE_VERSION);
    DOMImplementationLS domImplLS = (DOMImplementationLS) domImpl;
    // If the mode is MODE_SYNCHRONOUS, the parse and parseURI
    // methods of the LSParser
    // object return the org.w3c.dom.Document object. If the mode is
    // MODE_ASYNCHRONOUS,
    // the parse and parseURI methods return null.
    LSParser parser = domImplLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, ProjectFormatConstants.XML_SCHEMA);
    DOMConfiguration config = parser.getDomConfig();
    DOMErrorHandlerImpl errorHandler = new DOMErrorHandlerImpl();
    config.setParameter("error-handler", errorHandler);
    config.setParameter("validate", Boolean.TRUE);
    config.setParameter("schema-type", ProjectFormatConstants.XML_SCHEMA);
    config.setParameter("validate-if-schema", Boolean.TRUE);
    LSSerializer dom3Writer = domImplLS.createLSSerializer();
    LSOutput output = domImplLS.createLSOutput();
    IPath projectFilePath = Path.fromOSString(projectFile);
    URI projectFileURI = URIUtil.toURI(projectFilePath);
    try {
        StringWriter sw = new StringWriter();
        output.setCharacterStream(sw);
        output.setEncoding("UTF-8");
        dom3Writer.write(document, output);
        String temporaloutput = sw.getBuffer().toString();
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(projectFile));
        bufferedWriter.write(temporaloutput);
        bufferedWriter.flush();
        bufferedWriter.close();
        IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(projectFileURI);
        for (final IFile file : files) {
            file.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
        }
    } catch (IOException e) {
        ErrorReporter.logExceptionStackTrace(e);
    } catch (final CoreException e) {
        ErrorReporter.logExceptionStackTrace(e);
    }
    ProjectBuildPropertyData.setLoadLocation(project, projectFileURI.getPath().toString());
    ProjectBuildPropertyData.setProjectAlreadyExported(project, true);
    return true;
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) IFile(org.eclipse.core.resources.IFile) Element(org.w3c.dom.Element) DOMImplementationLS(org.w3c.dom.ls.DOMImplementationLS) FileWriter(java.io.FileWriter) LSParser(org.w3c.dom.ls.LSParser) DOMImplementation(org.w3c.dom.DOMImplementation) DOMConfiguration(org.w3c.dom.DOMConfiguration) Document(org.w3c.dom.Document) URI(java.net.URI) BufferedWriter(java.io.BufferedWriter) StringWriter(java.io.StringWriter) DOMImplementationRegistry(org.w3c.dom.bootstrap.DOMImplementationRegistry) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) LSOutput(org.w3c.dom.ls.LSOutput) DOMErrorHandlerImpl(org.eclipse.titan.designer.properties.data.DOMErrorHandlerImpl) IPath(org.eclipse.core.runtime.IPath) LSSerializer(org.w3c.dom.ls.LSSerializer) IOException(java.io.IOException) CoreException(org.eclipse.core.runtime.CoreException) DocumentBuilder(javax.xml.parsers.DocumentBuilder)

Example 2 with DOMErrorHandlerImpl

use of org.eclipse.titan.designer.properties.data.DOMErrorHandlerImpl in project titan.EclipsePlug-ins by eclipse.

the class TpdImporter method internalFinish.

/**
 * Internal function used to do the import job. It is needed to extract this
 * functionality in order to be able to handle erroneous situations.
 *
 * @param projectFile
 *            the file path string of the project descriptor file (tpd)
 * @param projectsCreated
 *            the list of projects created so far. In case of problems we
 *            will try to delete them.
 * @param monitor
 *            the monitor used to report progress.
 *
 * @return true if the import was successful, false otherwise.
 */
public boolean internalFinish(final String projectFile, final boolean isSkipExistingProjects, final boolean isOpenPropertiesForAllImports, final List<IProject> projectsCreated, final IProgressMonitor monitor, final List<String> searchPaths) {
    if (projectFile == null || "".equals(projectFile.trim())) {
        return false;
    }
    if (searchPaths != null) {
        this.searchPaths = new ArrayList<String>(searchPaths);
    }
    System.setProperty(DOMImplementationRegistry.PROPERTY, ProjectFormatConstants.DOM_IMPLEMENTATION_SOURCE);
    DOMImplementationRegistry registry = null;
    try {
        registry = DOMImplementationRegistry.newInstance();
    } catch (Exception e) {
        ErrorReporter.logExceptionStackTrace("While importing from `" + projectFile + "'", e);
        activatePreviousSettings();
        return false;
    }
    // Specifying "LS 3.0" in the features list ensures that the
    // DOMImplementation
    // object implements the load and save features of the DOM 3.0
    // specification.
    final DOMImplementation domImpl = registry.getDOMImplementation(ProjectFormatConstants.LOAD_SAVE_VERSION);
    domImplLS = (DOMImplementationLS) domImpl;
    // If the mode is MODE_SYNCHRONOUS, the parse and parseURI
    // methods of the LSParser
    // object return the org.w3c.dom.Document object. If the mode is
    // MODE_ASYNCHRONOUS, the parse and parseURI methods return null.
    parser = domImplLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, ProjectFormatConstants.XML_SCHEMA);
    config = parser.getDomConfig();
    DOMErrorHandlerImpl errorHandler = new DOMErrorHandlerImpl();
    config.setParameter("error-handler", errorHandler);
    config.setParameter("validate", Boolean.TRUE);
    config.setParameter("schema-type", ProjectFormatConstants.XML_SCHEMA);
    config.setParameter("well-formed", Boolean.TRUE);
    config.setParameter("validate-if-schema", Boolean.TRUE);
    Validator tpdValidator = null;
    try {
        final Schema tpdXsd = getTPDSchema();
        tpdValidator = tpdXsd.newValidator();
    } catch (Exception e) {
        ErrorReporter.INTERNAL_ERROR(e.getMessage());
    // Hint: cp $TTCN3_DIR/etc/xsd/TPD.xsd designer/schema/
    }
    URI resolvedProjectFileURI = TITANPathUtilities.resolvePath(projectFile, (URI) null);
    // ====================================
    if (!loadURIDocuments(resolvedProjectFileURI, tpdValidator)) {
        return false;
    }
    final SubMonitor progress = SubMonitor.convert(monitor, 3);
    progress.setTaskName("Loading data");
    IProgressMonitor projectCreationMonitor = progress.newChild(1);
    projectCreationMonitor.beginTask("Creating required projects", projectsToImport.size());
    // ========================
    // Create projects and
    // store load location
    // (where they are loaded from)
    // ========================
    Map<URI, IProject> projectMap = new HashMap<URI, IProject>();
    for (URI file : projectsToImport.keySet()) {
        Document actualDocument = projectsToImport.get(file);
        IProject project = createProject(actualDocument.getDocumentElement(), file.equals(resolvedProjectFileURI) || !isSkipExistingProjects);
        if (project == null) {
            projectCreationMonitor.worked(1);
            if (file.equals(resolvedProjectFileURI)) {
                projectCreationMonitor.done();
                progress.done();
                return false;
            } else {
                continue;
            }
        }
        projectsCreated.add(project);
        projectMap.put(file, project);
        try {
            project.setPersistentProperty(new QualifiedName(ProjectBuildPropertyData.QUALIFIER, ProjectBuildPropertyData.LOAD_LOCATION), file.getPath().toString());
        } catch (CoreException e) {
            ErrorReporter.logExceptionStackTrace("While loading referenced project from `" + file.getPath() + "'", e);
        }
        projectCreationMonitor.worked(1);
    }
    projectCreationMonitor.done();
    IProgressMonitor normalInformationLoadingMonitor = progress.newChild(1);
    normalInformationLoadingMonitor.beginTask("Loading directly stored project information", projectsToImport.size());
    // ====================================
    for (URI file : projectsToImport.keySet()) {
        if (!projectMap.containsKey(file)) {
            normalInformationLoadingMonitor.worked(1);
            continue;
        }
        IProject project = projectMap.get(file);
        IPath projectFileFolderPath = new Path(file.getPath()).removeLastSegments(1);
        URI projectFileFolderURI = URIUtil.toURI(projectFileFolderPath);
        Document actualDocument = projectsToImport.get(file);
        if (this.searchPaths != null && !this.searchPaths.isEmpty()) {
            String tpdNameAttrVal = tpdNameAttrMap.get(project.getName());
            String tpdURIVal = tpdURIMap.get(project.getName());
            if (tpdNameAttrVal != null) {
                try {
                    project.setPersistentProperty(new QualifiedName(ProjectBuildPropertyData.QUALIFIER, ProjectBuildPropertyData.USE_TPD_NAME), tpdNameAttrVal);
                } catch (CoreException e) {
                    ErrorReporter.logExceptionStackTrace("While setting `useTpdName' for project `" + project.getName() + "'", e);
                }
            }
            if (tpdURIVal != null) {
                try {
                    project.setPersistentProperty(new QualifiedName(ProjectBuildPropertyData.QUALIFIER, ProjectBuildPropertyData.ORIG_TPD_URI), tpdURIVal);
                } catch (CoreException e) {
                    ErrorReporter.logExceptionStackTrace("While setting `origTpdURI' for project `" + project.getName() + "'", e);
                }
            }
        }
        Element mainElement = actualDocument.getDocumentElement();
        // === Get the copyright text ===
        Node node = mainElement.getFirstChild();
        // default value. This will be changed for PreferenceConstants.COPYRIGHT_DEFAULT_STRING at export
        String commentStr = "";
        if (node != null && node.getNodeType() == Element.COMMENT_NODE) {
            // process comment node
            Comment comment = (Comment) node;
            commentStr = comment.getData();
        }
        try {
            project.setPersistentProperty(new QualifiedName(ProjectBuildPropertyData.QUALIFIER, ProjectBuildPropertyData.PROJECT_COPYRIGHT_STRING_ID), commentStr);
        } catch (CoreException e) {
            ErrorReporter.logExceptionStackTrace("While setting `copyright string' for project `" + project.getName() + "'", e);
        }
        if (!loadProjectDataFromNode(mainElement, project, projectFileFolderURI)) {
            return false;
        }
        normalInformationLoadingMonitor.worked(1);
    }
    normalInformationLoadingMonitor.done();
    // =====================================
    // Load information from packed projects
    // =====================================
    IPath mainProjectFileFolderPath = new Path(resolvedProjectFileURI.getPath()).removeLastSegments(1);
    URI mainProjectFileFolderURI = URIUtil.toURI(mainProjectFileFolderPath);
    List<Node> packedProjects = loadPackedProjects(projectsToImport.get(resolvedProjectFileURI));
    IProgressMonitor packedInformationLoadingMonitor = progress.newChild(1);
    packedInformationLoadingMonitor.beginTask("Loading packed project information", packedProjects.size());
    for (Node node : packedProjects) {
        IProject project = createProject(node, false);
        if (project == null) {
            packedInformationLoadingMonitor.worked(1);
            continue;
        }
        projectsCreated.add(project);
        try {
            project.setPersistentProperty(new QualifiedName(ProjectBuildPropertyData.QUALIFIER, ProjectBuildPropertyData.LOAD_LOCATION), resolvedProjectFileURI.toString());
        } catch (CoreException e) {
            ErrorReporter.logExceptionStackTrace("While loading packed project `" + project.getName() + "'", e);
        }
        if (!loadProjectDataFromNode(node, project, mainProjectFileFolderURI)) {
            return false;
        }
        packedInformationLoadingMonitor.worked(1);
    }
    packedInformationLoadingMonitor.done();
    IProject mainProject = projectMap.get(resolvedProjectFileURI);
    if (mainProject == null) {
        progress.done();
        return false;
    }
    try {
        mainProject.setPersistentProperty(new QualifiedName(ProjectBuildPropertyData.QUALIFIER, ProjectBuildPropertyData.USE_TPD_NAME), mainProject.getName() + ".tpd");
    } catch (CoreException e) {
        ErrorReporter.logExceptionStackTrace("While setting `useTpdName' for project `" + mainProject.getName() + "'", e);
    }
    List<WorkspaceJob> jobs = new ArrayList<WorkspaceJob>();
    List<IProject> projectsToBeConfigured;
    if (isOpenPropertiesForAllImports) {
        projectsToBeConfigured = projectsCreated;
    } else {
        projectsToBeConfigured = new ArrayList<IProject>();
        projectsToBeConfigured.add(mainProject);
    }
    if (!headless) {
        for (final IProject project : projectsToBeConfigured) {
            WorkspaceJob loadJob = new WorkspaceJob("Property initilizer for " + project.getName()) {

                @Override
                public IStatus runInWorkspace(final IProgressMonitor monitor) {
                    Display.getDefault().asyncExec(new Runnable() {

                        @Override
                        public void run() {
                            PreferenceDialog dialog = PreferencesUtil.createPropertyDialogOn(null, project, GeneralConstants.PROJECT_PROPERTY_PAGE, null, null);
                            if (dialog != null) {
                                dialog.open();
                            }
                        }
                    });
                    return Status.OK_STATUS;
                }
            };
            loadJob.setUser(false);
            loadJob.setSystem(true);
            loadJob.setRule(project.getWorkspace().getRuleFactory().refreshRule(project));
            loadJob.setProperty(IProgressConstants.ICON_PROPERTY, ImageCache.getImageDescriptor("titan.gif"));
            loadJob.schedule();
            jobs.add(loadJob);
        }
        for (WorkspaceJob job : jobs) {
            try {
                job.join();
            } catch (InterruptedException e) {
                ErrorReporter.logExceptionStackTrace("Interrupted while performing: " + job.getName(), e);
            }
        }
    }
    activatePreviousSettings();
    progress.done();
    return true;
}
Also used : HashMap(java.util.HashMap) Schema(javax.xml.validation.Schema) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) DOMImplementation(org.w3c.dom.DOMImplementation) Document(org.w3c.dom.Document) URI(java.net.URI) PreferenceDialog(org.eclipse.jface.preference.PreferenceDialog) DOMImplementationRegistry(org.w3c.dom.bootstrap.DOMImplementationRegistry) DOMErrorHandlerImpl(org.eclipse.titan.designer.properties.data.DOMErrorHandlerImpl) IPath(org.eclipse.core.runtime.IPath) Path(org.eclipse.core.runtime.Path) Comment(org.w3c.dom.Comment) IPath(org.eclipse.core.runtime.IPath) QualifiedName(org.eclipse.core.runtime.QualifiedName) SubMonitor(org.eclipse.core.runtime.SubMonitor) WorkspaceJob(org.eclipse.core.resources.WorkspaceJob) URISyntaxException(java.net.URISyntaxException) CoreException(org.eclipse.core.runtime.CoreException) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SAXException(org.xml.sax.SAXException) IOException(java.io.IOException) IProject(org.eclipse.core.resources.IProject) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) CoreException(org.eclipse.core.runtime.CoreException) Validator(javax.xml.validation.Validator)

Example 3 with DOMErrorHandlerImpl

use of org.eclipse.titan.designer.properties.data.DOMErrorHandlerImpl in project titan.EclipsePlug-ins by eclipse.

the class GenerateBuilderInformation method generateInfoForProject.

private void generateInfoForProject(final IProject project) throws CoreException {
    final boolean win32 = Platform.OS_WIN32.equals(Platform.getOS());
    final boolean reportDebugInformation = Platform.getPreferencesService().getBoolean(ProductConstants.PRODUCT_ID_DESIGNER, PreferenceConstants.DISPLAYDEBUGINFORMATION, false, null);
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder;
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        ErrorReporter.logExceptionStackTrace(e);
        return;
    }
    final DOMImplementation impl = builder.getDOMImplementation();
    final Document document = impl.createDocument(null, "TITAN_External_Builder_Information", null);
    final Element root = document.getDocumentElement();
    root.setAttribute("version", "1.0");
    String temp;
    Node node;
    final Element makefileSettings = document.createElement("Makefile_settings");
    root.appendChild(makefileSettings);
    for (int i = 0; i < MakefileCreationData.MAKEFILE_PROPERTIES.length; i++) {
        try {
            temp = project.getPersistentProperty(new QualifiedName(ProjectBuildPropertyData.QUALIFIER, MakefileCreationData.MAKEFILE_PROPERTIES[i]));
            node = document.createElement(MakefileCreationData.MAKEFILE_TAGS[i]);
            node.appendChild(document.createTextNode(temp));
            makefileSettings.appendChild(node);
        } catch (CoreException ce) {
            ErrorReporter.logExceptionStackTrace(ce);
        }
    }
    final String projectLocationStr = project.getLocation().toOSString();
    node = document.createElement("projectName");
    node.appendChild(document.createTextNode(project.getName()));
    makefileSettings.appendChild(node);
    node = document.createElement("projectRoot");
    node.appendChild(document.createTextNode(project.getLocationURI().toString()));
    makefileSettings.appendChild(node);
    temp = project.getPersistentProperty(new QualifiedName(ProjectBuildPropertyData.QUALIFIER, "workingDir"));
    node = document.createElement("workingDirectory");
    node.appendChild(document.createTextNode(TITANPathUtilities.resolvePathURI(temp, projectLocationStr).toString()));
    makefileSettings.appendChild(node);
    temp = project.getPersistentProperty(new QualifiedName(ProjectBuildPropertyData.QUALIFIER, "targetExecutable"));
    node = document.createElement("targetExecutable");
    node.appendChild(document.createTextNode(TITANPathUtilities.resolvePathURI(temp, projectLocationStr).toString()));
    makefileSettings.appendChild(node);
    temp = project.getPersistentProperty(new QualifiedName(ProjectBuildPropertyData.QUALIFIER, "makefileUpdateScript"));
    node = document.createElement("MakefileScript");
    node.appendChild(document.createTextNode(TITANPathUtilities.resolvePathURI(temp, projectLocationStr).toString()));
    makefileSettings.appendChild(node);
    temp = project.getPersistentProperty(new QualifiedName(ProjectBuildPropertyData.QUALIFIER, "makefileFlags"));
    node = document.createElement("MakefileFlags");
    node.appendChild(document.createTextNode(temp));
    makefileSettings.appendChild(node);
    final Element projectsElement = document.createElement("ReferencedProjects");
    root.appendChild(projectsElement);
    final IProject[] referencedProjects = ProjectBasedBuilder.getProjectBasedBuilder(project).getReferencedProjects();
    for (IProject tempProject : referencedProjects) {
        final Element element = document.createElement("ReferencedProject");
        element.setAttribute("name", tempProject.getName());
        element.setAttribute("location", tempProject.getLocationURI().toString());
        if (win32 && tempProject.getLocation() != null) {
            final String converted = PathConverter.convert(tempProject.getLocation().toOSString(), reportDebugInformation, TITANDebugConsole.getConsole());
            final Path path = new Path(converted);
            element.setAttribute("cygwinPath", URIUtil.toURI(path).toString());
        }
        projectsElement.appendChild(element);
    }
    final Element filesElement = document.createElement("Files");
    root.appendChild(filesElement);
    final TITANBuilderResourceVisitor visitor = ProjectBasedBuilder.getProjectBasedBuilder(project).getResourceVisitor();
    final Map<String, IFile> files = visitor.getFiles();
    for (IFile file : files.values()) {
        final Element element = document.createElement("File");
        element.setAttribute("path", file.getLocationURI().toString());
        if (win32 && file.getLocation() != null) {
            final String fileLocation = file.getLocation().toOSString();
            final String converted = PathConverter.convert(fileLocation, reportDebugInformation, TITANDebugConsole.getConsole());
            if (!converted.equals(fileLocation)) {
                final Path path = new Path(converted);
                element.setAttribute("cygwinPath", URIUtil.toURI(path).toString());
            }
        }
        element.setAttribute("relativePath", org.eclipse.core.runtime.URIUtil.makeRelative(file.getLocationURI(), project.getLocationURI()).toString());
        filesElement.appendChild(element);
    }
    final Map<String, IFile> contralStorageFiles = visitor.getCentralStorageFiles();
    for (IFile file : contralStorageFiles.values()) {
        final Element element = document.createElement("File");
        final String fileLocation = file.getLocation().toString();
        element.setAttribute("path", fileLocation);
        if (win32 && file.getLocation() != null) {
            final String converted = PathConverter.convert(fileLocation, reportDebugInformation, TITANDebugConsole.getConsole());
            if (!converted.equals(fileLocation)) {
                final Path path = new Path(converted);
                element.setAttribute("cygwinPath", URIUtil.toURI(path).toString());
            }
        }
        element.setAttribute("relativePath", org.eclipse.core.runtime.URIUtil.makeRelative(file.getLocationURI(), project.getLocationURI()).toString());
        element.setAttribute("centralStorage", "true");
        filesElement.appendChild(element);
    }
    final Map<String, IFile> filesOfReferencedProjects = ProjectBasedBuilder.getProjectBasedBuilder(project).getFilesofReferencedProjects();
    for (IFile file : filesOfReferencedProjects.values()) {
        final Element element = document.createElement("File");
        element.setAttribute("path", file.getLocationURI().toString());
        if (win32 && file.getLocation() != null) {
            final String fileLocation = file.getLocation().toOSString();
            final String converted = PathConverter.convert(fileLocation, reportDebugInformation, TITANDebugConsole.getConsole());
            if (!converted.equals(fileLocation)) {
                final Path path = new Path(converted);
                element.setAttribute("cygwinPath", URIUtil.toURI(path).toString());
            }
        }
        element.setAttribute("relativePath", org.eclipse.core.runtime.URIUtil.makeRelative(file.getLocationURI(), project.getLocationURI()).toString());
        element.setAttribute("fromProject", file.getProject().getName());
        filesElement.appendChild(element);
    }
    ProjectFileHandler.indentNode(document, document.getDocumentElement(), 1);
    System.setProperty(DOMImplementationRegistry.PROPERTY, DOM_IMPLEMENTATION_SOURCE);
    DOMImplementationRegistry registry = null;
    try {
        registry = DOMImplementationRegistry.newInstance();
    } catch (ClassNotFoundException ce) {
        ErrorReporter.logExceptionStackTrace(ce);
        return;
    } catch (InstantiationException ie) {
        ErrorReporter.logExceptionStackTrace(ie);
        return;
    } catch (IllegalAccessException iae) {
        ErrorReporter.logExceptionStackTrace(iae);
        return;
    }
    // Specifying "LS 3.0" in the features list ensures that the
    // DOMImplementation
    // object implements the load and save features of the DOM 3.0
    // specification.
    final DOMImplementation domImpl = registry.getDOMImplementation(LOAD_SAVE_VERSION);
    final DOMImplementationLS domImplLS = (DOMImplementationLS) domImpl;
    // If the mode is MODE_SYNCHRONOUS, the parse and parseURI
    // methods of
    // the LSParser
    // object return the org.w3c.dom.Document object. If the mode is
    // MODE_ASYNCHRONOUS,
    // the parse and parseURI methods return null.
    final LSParser parser = domImplLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, XML_SCHEMA);
    final DOMConfiguration config = parser.getDomConfig();
    final DOMErrorHandlerImpl errorHandler = new DOMErrorHandlerImpl();
    config.setParameter("error-handler", errorHandler);
    config.setParameter("validate", Boolean.TRUE);
    config.setParameter("schema-type", XML_SCHEMA);
    config.setParameter("validate-if-schema", Boolean.TRUE);
    final LSSerializer dom3Writer = domImplLS.createLSSerializer();
    final LSOutput output = domImplLS.createLSOutput();
    final IFile propertiesFile = project.getFile('/' + "external_build_information.xml");
    final File file = propertiesFile.getLocation().toFile();
    StringWriter sw = null;
    try {
        propertiesFile.refreshLocal(IResource.DEPTH_ZERO, null);
        sw = new StringWriter();
        output.setCharacterStream(sw);
        output.setEncoding("UTF-8");
        dom3Writer.write(document, output);
        final String temporaloutput = sw.getBuffer().toString();
        // temporalStorage will hold the contents of the
        // existing .TITAN_properties file
        String temporalStorage = null;
        if (propertiesFile.isAccessible() && file.exists() && file.canRead()) {
            final InputStream is = propertiesFile.getContents(true);
            final BufferedReader br = new BufferedReader(new InputStreamReader(is));
            final StringBuilder sb = new StringBuilder();
            boolean firstLine = true;
            String line = br.readLine();
            while (line != null) {
                if (firstLine) {
                    firstLine = false;
                } else {
                    sb.append('\n');
                }
                sb.append(line);
                line = br.readLine();
            }
            temporalStorage = sb.toString();
            br.close();
        }
        // one will be overwritten by the new one.
        if (temporalStorage == null || !temporalStorage.equals(temporaloutput)) {
            if (file.exists()) {
                propertiesFile.setContents(new ByteArrayInputStream(temporaloutput.getBytes()), IResource.FORCE | IResource.KEEP_HISTORY, null);
            } else {
                propertiesFile.create(new ByteArrayInputStream(temporaloutput.getBytes()), IResource.FORCE, null);
            }
            try {
                propertiesFile.refreshLocal(IResource.DEPTH_ZERO, null);
            } catch (CoreException e) {
                ErrorReporter.logExceptionStackTrace(e);
            }
        }
    } catch (IOException e) {
        ErrorReporter.logExceptionStackTrace(e);
    } catch (CoreException e) {
        ErrorReporter.logExceptionStackTrace(e);
    } finally {
        if (sw != null) {
            try {
                sw.close();
            } catch (IOException e) {
                ErrorReporter.logExceptionStackTrace(e);
            }
        }
    }
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) IFile(org.eclipse.core.resources.IFile) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) DOMImplementationLS(org.w3c.dom.ls.DOMImplementationLS) LSParser(org.w3c.dom.ls.LSParser) DOMImplementation(org.w3c.dom.DOMImplementation) DOMConfiguration(org.w3c.dom.DOMConfiguration) Document(org.w3c.dom.Document) StringWriter(java.io.StringWriter) DOMImplementationRegistry(org.w3c.dom.bootstrap.DOMImplementationRegistry) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) LSOutput(org.w3c.dom.ls.LSOutput) DOMErrorHandlerImpl(org.eclipse.titan.designer.properties.data.DOMErrorHandlerImpl) Path(org.eclipse.core.runtime.Path) InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) QualifiedName(org.eclipse.core.runtime.QualifiedName) LSSerializer(org.w3c.dom.ls.LSSerializer) IOException(java.io.IOException) IProject(org.eclipse.core.resources.IProject) CoreException(org.eclipse.core.runtime.CoreException) TITANBuilderResourceVisitor(org.eclipse.titan.designer.core.TITANBuilderResourceVisitor) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedReader(java.io.BufferedReader) IFile(org.eclipse.core.resources.IFile) File(java.io.File)

Example 4 with DOMErrorHandlerImpl

use of org.eclipse.titan.designer.properties.data.DOMErrorHandlerImpl in project titan.EclipsePlug-ins by eclipse.

the class GUIProjectImporter method getDocumentFromFile.

/**
 * Helper function to convert the file provided into an XML document.
 *
 * @param file
 *                the project file to be read.
 *
 * @return the XML document read from the file or null if there was an
 *         error.
 */
private Document getDocumentFromFile(final String file) {
    // DOMImplementationRegistry is a factory that enables
    // applications to obtain instances of a DOMImplementation.
    System.setProperty(DOMImplementationRegistry.PROPERTY, DOM_IMPLEMENTATION_SOURCE);
    DOMImplementationRegistry registry = null;
    try {
        registry = DOMImplementationRegistry.newInstance();
    } catch (ClassNotFoundException ce) {
        ErrorReporter.logExceptionStackTrace(ce);
        return null;
    } catch (InstantiationException ie) {
        ErrorReporter.logExceptionStackTrace(ie);
        return null;
    } catch (IllegalAccessException iae) {
        ErrorReporter.logExceptionStackTrace(iae);
        return null;
    }
    // Specifying "LS 3.0" in the features list ensures that the
    // DOMImplementation
    // object implements the load and save features of the DOM 3.0
    // specification.
    DOMImplementation domImpl = registry.getDOMImplementation(LOAD_SAVE_VERSION);
    DOMImplementationLS domImplLS = (DOMImplementationLS) domImpl;
    // If the mode is MODE_SYNCHRONOUS, the parse and parseURI
    // methods of the LSParser
    // object return the org.w3c.dom.Document object. If the mode is
    // MODE_ASYNCHRONOUS, the parse and parseURI methods return null.
    LSParser parser = domImplLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, XML_SCHEMA);
    DOMConfiguration config = parser.getDomConfig();
    DOMErrorHandlerImpl errorHandler = new DOMErrorHandlerImpl();
    config.setParameter("error-handler", errorHandler);
    config.setParameter("validate", Boolean.TRUE);
    config.setParameter("schema-type", XML_SCHEMA);
    config.setParameter("validate-if-schema", Boolean.TRUE);
    final LSInput lsInput = domImplLS.createLSInput();
    try {
        InputStream istream = new FileInputStream(file);
        lsInput.setByteStream(istream);
        Document document = parser.parse(lsInput);
        istream.close();
        return document;
    } catch (IOException e) {
        ErrorReporter.logExceptionStackTrace(e);
        return null;
    } catch (DOMException e) {
        ErrorReporter.logExceptionStackTrace(e);
        return null;
    } catch (LSException e) {
        ErrorReporter.logExceptionStackTrace(e);
        return null;
    }
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) DOMImplementationLS(org.w3c.dom.ls.DOMImplementationLS) LSParser(org.w3c.dom.ls.LSParser) DOMImplementation(org.w3c.dom.DOMImplementation) DOMConfiguration(org.w3c.dom.DOMConfiguration) IOException(java.io.IOException) Document(org.w3c.dom.Document) FileInputStream(java.io.FileInputStream) DOMException(org.w3c.dom.DOMException) LSInput(org.w3c.dom.ls.LSInput) DOMImplementationRegistry(org.w3c.dom.bootstrap.DOMImplementationRegistry) LSException(org.w3c.dom.ls.LSException) DOMErrorHandlerImpl(org.eclipse.titan.designer.properties.data.DOMErrorHandlerImpl)

Aggregations

IOException (java.io.IOException)4 DOMErrorHandlerImpl (org.eclipse.titan.designer.properties.data.DOMErrorHandlerImpl)4 DOMImplementation (org.w3c.dom.DOMImplementation)4 Document (org.w3c.dom.Document)4 DOMImplementationRegistry (org.w3c.dom.bootstrap.DOMImplementationRegistry)4 CoreException (org.eclipse.core.runtime.CoreException)3 DOMConfiguration (org.w3c.dom.DOMConfiguration)3 Element (org.w3c.dom.Element)3 DOMImplementationLS (org.w3c.dom.ls.DOMImplementationLS)3 LSParser (org.w3c.dom.ls.LSParser)3 InputStream (java.io.InputStream)2 StringWriter (java.io.StringWriter)2 URI (java.net.URI)2 DocumentBuilder (javax.xml.parsers.DocumentBuilder)2 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)2 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)2 IFile (org.eclipse.core.resources.IFile)2 IProject (org.eclipse.core.resources.IProject)2 IPath (org.eclipse.core.runtime.IPath)2 Path (org.eclipse.core.runtime.Path)2