diff --git a/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/builder/tests/ApiBuilderTest.java b/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/builder/tests/ApiBuilderTest.java index 9a83d0f1eb..5e21b1b5e9 100644 --- a/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/builder/tests/ApiBuilderTest.java +++ b/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/builder/tests/ApiBuilderTest.java @@ -16,11 +16,9 @@ import java.io.File; import java.io.FileInputStream; -import java.io.FileOutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URI; -import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; @@ -65,6 +63,7 @@ import org.eclipse.pde.api.tools.internal.provisional.IApiMarkerConstants; import org.eclipse.pde.api.tools.internal.provisional.model.IApiComponent; import org.eclipse.pde.api.tools.internal.provisional.problems.IApiProblemTypes; +import org.eclipse.pde.api.tools.internal.util.Util; import org.eclipse.pde.api.tools.model.tests.TestSuiteHelper; import org.eclipse.pde.api.tools.tests.util.FileUtils; import org.eclipse.pde.api.tools.tests.util.ProjectUtils; @@ -75,6 +74,7 @@ import org.eclipse.ui.wizards.datatransfer.FileSystemStructureProvider; import org.eclipse.ui.wizards.datatransfer.ImportOperation; import org.osgi.service.prefs.BackingStoreException; +import org.w3c.dom.Document; import junit.framework.Test; import junit.framework.TestSuite; @@ -335,7 +335,7 @@ protected static void exportApiComponent(IProject project, IApiComponent apiComp // create API Description, this should be the first step because // otherwise we might trigger a resource change that maybe invalidates // our component before we can process it! - String xml = componentToXml(apiComponent); + Document xml = componentToXml(apiComponent); // now we have the xml and can go on... File root = baselineLocation.toFile(); File componentDir = new File(root, project.getName()); @@ -357,14 +357,10 @@ protected static void exportApiComponent(IProject project, IApiComponent apiComp IFolder output = project.getFolder("bin"); //$NON-NLS-1$ FileUtils.copyFolder(output, componentDir); // copy description - File desc = new File(componentDir, ".api_description"); //$NON-NLS-1$ - desc.createNewFile(); - try (FileOutputStream stream = new FileOutputStream(desc)) { - stream.write(xml.getBytes(StandardCharsets.UTF_8)); - } + Util.writeDocumentToFile(xml, componentDir.toPath().resolve(".api_description")); //$NON-NLS-1$ } - private static String componentToXml(IApiComponent apiComponent) throws CoreException { + private static Document componentToXml(IApiComponent apiComponent) throws CoreException { ApiDescriptionXmlCreator visitor = new ApiDescriptionXmlCreator(apiComponent); apiComponent.getApiDescription().accept(visitor, null); return visitor.getXML(); diff --git a/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/comparator/tests/ClassDeltaTests.java b/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/comparator/tests/ClassDeltaTests.java index 9ac23d6d78..7b34c6b941 100644 --- a/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/comparator/tests/ClassDeltaTests.java +++ b/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/comparator/tests/ClassDeltaTests.java @@ -157,7 +157,7 @@ public void test5() { try { DeltaXmlVisitor xmlVisitor = new DeltaXmlVisitor(); delta.accept(xmlVisitor); - assertNotNull("No XML", xmlVisitor.getXML()); //$NON-NLS-1$ + assertNotNull("No XML", xmlVisitor.getDocument()); //$NON-NLS-1$ } catch (CoreException e) { ApiPlugin.log(e); } @@ -2469,7 +2469,7 @@ public void test99() { try { DeltaXmlVisitor xmlVisitor = new DeltaXmlVisitor(); delta.accept(xmlVisitor); - assertNotNull("No XML", xmlVisitor.getXML()); //$NON-NLS-1$ + assertNotNull("No XML", xmlVisitor.getDocument()); //$NON-NLS-1$ } catch (CoreException e) { ApiPlugin.log(e); } diff --git a/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/model/tests/ApiDescriptionTests.java b/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/model/tests/ApiDescriptionTests.java index 3e6eb95f0d..a521ed251e 100644 --- a/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/model/tests/ApiDescriptionTests.java +++ b/apitools/org.eclipse.pde.api.tools.tests/src/org/eclipse/pde/api/tools/model/tests/ApiDescriptionTests.java @@ -48,6 +48,7 @@ import org.eclipse.pde.api.tools.internal.util.Signatures; import org.eclipse.pde.api.tools.internal.util.Util; import org.junit.Test; +import org.w3c.dom.Document; /** * Tests API manifest implementation. @@ -347,7 +348,7 @@ public void endVisitElement(IElementDescriptor element, IApiAnnotations descript * @return XML for the API description * @throws CoreException if something goes terribly wrong */ - private String getApiDescriptionXML(IApiComponent apiComponent) throws CoreException { + private Document getApiDescriptionXML(IApiComponent apiComponent) throws CoreException { ApiDescriptionXmlCreator xmlVisitor = new ApiDescriptionXmlCreator(apiComponent); apiComponent.getApiDescription().accept(xmlVisitor, null); return xmlVisitor.getXML(); @@ -377,7 +378,7 @@ public void testPersistRestoreXML() throws CoreException, IOException { // write back to XML and then re-create IApiComponent component = TestSuiteHelper.createTestingApiComponent("test", "test", settings); //$NON-NLS-1$ //$NON-NLS-2$ - String writeXML = getApiDescriptionXML(component); + String writeXML = Util.serializeDocument(getApiDescriptionXML(component)); IApiDescription restored = new ApiDescription(null); ApiDescriptionProcessor.annotateApiSettings(null, restored, writeXML); diff --git a/apitools/org.eclipse.pde.api.tools.ui/src/org/eclipse/pde/api/tools/ui/internal/actions/ExportSessionAction.java b/apitools/org.eclipse.pde.api.tools.ui/src/org/eclipse/pde/api/tools/ui/internal/actions/ExportSessionAction.java index 350f31fb6d..68e2c34795 100644 --- a/apitools/org.eclipse.pde.api.tools.ui/src/org/eclipse/pde/api/tools/ui/internal/actions/ExportSessionAction.java +++ b/apitools/org.eclipse.pde.api.tools.ui/src/org/eclipse/pde/api/tools/ui/internal/actions/ExportSessionAction.java @@ -114,17 +114,13 @@ protected IStatus run(IProgressMonitor monitor) { return Status.error(ActionMessages.ExportSessionAction_failed_to_create_parent_folders); } } - try (BufferedWriter writer = new BufferedWriter(new FileWriter(xmlOutputFile))) { - DeltaXmlVisitor visitor = new DeltaXmlVisitor(); - Object data = activeSession.getModel().getRoot().getData(); - if (data instanceof IDelta) { - IDelta delta = (IDelta) data; - progress.split(25); - delta.accept(visitor); - writer.write(visitor.getXML()); - writer.flush(); - progress.worked(25); - } + DeltaXmlVisitor visitor = new DeltaXmlVisitor(); + Object data = activeSession.getModel().getRoot().getData(); + if (data instanceof IDelta delta) { + progress.split(25); + delta.accept(visitor); + Util.writeDocumentToFile(visitor.getDocument(), xmlOutputFile.toPath()); + progress.worked(25); } } catch (IOException | CoreException e) { ApiPlugin.log(e); diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/APIFileGenerator.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/APIFileGenerator.java index 7ebdcda0cd..628504cf47 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/APIFileGenerator.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/APIFileGenerator.java @@ -23,6 +23,7 @@ import java.io.StringReader; import java.io.StringWriter; import java.nio.file.Files; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; @@ -48,6 +49,7 @@ import org.eclipse.pde.api.tools.internal.util.Util; import org.osgi.framework.BundleException; import org.osgi.framework.Constants; +import org.w3c.dom.Document; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; @@ -151,25 +153,15 @@ public void generateAPIFile() { return; } // check if the .api_description file exists - File targetProjectFolder = new File(this.targetFolder); - if (!targetProjectFolder.exists()) { - targetProjectFolder.mkdirs(); - } else if (!targetProjectFolder.isDirectory()) { + Path apiDescriptionFile = Path.of(this.targetFolder,IApiCoreConstants.API_DESCRIPTION_XML_NAME); + Path projectFolder = apiDescriptionFile.getParent(); + if (Files.exists(projectFolder) && !Files.isDirectory(projectFolder)) { if (this.debug) { System.err.println("Must be a directory : " + this.targetFolder); //$NON-NLS-1$ } throw new IllegalArgumentException( NLS.bind(CoreMessages.api_generation_targetFolderNotADirectory, this.targetFolder)); } - File apiDescriptionFile = new File(targetProjectFolder, IApiCoreConstants.API_DESCRIPTION_XML_NAME); - if (apiDescriptionFile.exists()) { - // get rid of the existing one - // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=414053 - if (this.debug) { - System.out.println("Existing api description file deleted"); //$NON-NLS-1$ - } - apiDescriptionFile.delete(); - } // create the directory class file container used to resolve // signatures during tag scanning String[] allBinaryLocations = this.binaryLocations.split(File.pathSeparator); @@ -282,8 +274,8 @@ public void generateAPIFile() { try { ApiDescriptionXmlCreator xmlVisitor = new ApiDescriptionXmlCreator(this.projectName, this.projectName); apiDescription.accept(xmlVisitor, null); - String xml = xmlVisitor.getXML(); - Util.saveFile(apiDescriptionFile, xml); + Document xml = xmlVisitor.getXML(); + Util.writeDocumentToFile(xml, apiDescriptionFile); } catch (CoreException | IOException e) { ApiPlugin.log(e); } diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiBaselineManager.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiBaselineManager.java index d48bf30468..190bed2f4d 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiBaselineManager.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiBaselineManager.java @@ -16,12 +16,10 @@ import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; -import java.io.OutputStream; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -322,7 +320,7 @@ private String getDefaultProfilePref() { * Persists all of the cached elements to individual xml files named with * the id of the API baseline */ - private void persistStateCache() throws CoreException, IOException { + private void persistStateCache() throws CoreException { if (savelocation == null) { return; } @@ -333,45 +331,31 @@ private void persistStateCache() throws CoreException, IOException { node.remove(DEFAULT_BASELINE); } if (baselinecache != null && !hasinfos.isEmpty()) { - File dir = new File(savelocation.toOSString()); - Files.createDirectories(dir.toPath()); - IApiBaseline baseline = null; + Path dir = savelocation.toPath(); for (Entry entry : baselinecache.entrySet()) { String id = entry.getKey(); - baseline = entry.getValue(); + IApiBaseline baseline = entry.getValue(); if (!isBaselineLoaded(baseline)) { continue; } - File file = savelocation.append(id + BASELINE_FILE_EXTENSION).toFile(); - if (!file.exists()) { - try { - Files.createFile(file.toPath()); - } catch (IOException ioe) { - ApiPlugin.log(new IOException("Unable to save API baseline with id: '" + id + "'", ioe)); //$NON-NLS-1$ //$NON-NLS-2$ - continue; - } - } - try (FileOutputStream fout = new FileOutputStream(file)) { - writeBaselineDescription(baseline, fout); - // need to save the api baseline state in order to be able - // to reload it later - handlecache.put(baseline.getName(), file.getAbsolutePath()); - fout.flush(); - } + Path file = dir.resolve(id + BASELINE_FILE_EXTENSION); + writeBaselineDescription(baseline, file); + // need to save the api baseline state in order to be able + // to reload it later + handlecache.put(baseline.getName(), file.toAbsolutePath().toString()); } } } /** - * Writes out the current state of the {@link IApiBaseline} as XML to the - * given output stream + * Writes the current state of the {@link IApiBaseline} as XML to the given file */ - private void writeBaselineDescription(IApiBaseline baseline, OutputStream stream) throws CoreException { - String xml = getProfileXML(baseline); + private void writeBaselineDescription(IApiBaseline baseline, Path file) throws CoreException { + Document xml = getProfileXML(baseline); try { - stream.write(xml.getBytes(StandardCharsets.UTF_8)); + Util.writeDocumentToFile(xml, file); } catch (IOException e) { - throw new CoreException(Status.error("Error writing pofile descrition", e)); //$NON-NLS-1$ + throw new CoreException(Status.error("Error writing profile descrition", e)); //$NON-NLS-1$ } } @@ -383,7 +367,7 @@ private void writeBaselineDescription(IApiBaseline baseline, OutputStream stream * @throws CoreException if an exception occurs while retrieving the xml * string representation */ - private String getProfileXML(IApiBaseline baseline) throws CoreException { + private Document getProfileXML(IApiBaseline baseline) throws CoreException { Document document = Util.newDocument(); Element root = document.createElement(IApiXmlConstants.ELEMENT_APIPROFILE); document.appendChild(root); @@ -417,7 +401,7 @@ private String getProfileXML(IApiBaseline baseline) throws CoreException { // clear the temporary hashset allComponentSet.clear(); } - return Util.serializeDocument(document); + return document; } /** @@ -483,7 +467,7 @@ public IApiComponent[] readBaselineComponents(ApiBaseline baseline, InputStream } } restored = components.toArray(new IApiComponent[components.size()]); - // Avoid unstable bundle traversal order to simplify our life + // Avoid unstable bundle traversal order to simplify our life Arrays.sort(restored, (o1, o2) -> o1.getName().compareTo(o2.getName())); } } catch (IOException | SAXException e) { @@ -512,13 +496,9 @@ public void saving(ISaveContext context) throws CoreException { if (!fNeedsSaving) { return; } - try { - persistStateCache(); - cleanStateCache(); - fNeedsSaving = false; - } catch (IOException e) { - ApiPlugin.log(e); - } + persistStateCache(); + cleanStateCache(); + fNeedsSaving = false; } /** diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiDescriptionManager.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiDescriptionManager.java index ca63467199..4323edb634 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiDescriptionManager.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiDescriptionManager.java @@ -16,6 +16,7 @@ import java.io.File; import java.io.IOException; import java.nio.file.Files; +import java.nio.file.Path; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; @@ -49,6 +50,7 @@ import org.eclipse.pde.api.tools.internal.provisional.model.IApiElement; import org.eclipse.pde.api.tools.internal.provisional.scanner.ScannerMessages; import org.eclipse.pde.api.tools.internal.util.Util; +import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; @@ -227,11 +229,10 @@ public synchronized void saving(ISaveContext context) throws CoreException { IJavaProject project = entry.getKey(); ProjectApiDescription desc = (ProjectApiDescription) entry.getValue(); if (desc.isModified()) { - File dir = API_DESCRIPTIONS_CONTAINER_PATH.append(project.getElementName()).toFile(); - dir.mkdirs(); - String xml = desc.getXML(); + Path dir = API_DESCRIPTIONS_CONTAINER_PATH.append(project.getElementName()).toPath(); + Document xml = desc.getXML(); try { - Util.saveFile(new File(dir, IApiCoreConstants.API_DESCRIPTION_XML_NAME), xml); + Util.writeDocumentToFile(xml, dir.resolve(IApiCoreConstants.API_DESCRIPTION_XML_NAME)); desc.setModified(false); } catch (IOException e) { abort(MessageFormat.format(ScannerMessages.ApiDescriptionManager_0, project.getElementName()), e); diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiDescriptionXmlCreator.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiDescriptionXmlCreator.java index 9b66805843..20197e191b 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiDescriptionXmlCreator.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiDescriptionXmlCreator.java @@ -136,13 +136,12 @@ public void endVisitElement(IElementDescriptor element, IApiAnnotations descript } /** - * Returns the settings as a UTF-8 string containing XML. + * Returns the settings as a XML {@link Document}. * - * @return XML * @throws CoreException if something goes wrong */ - public String getXML() throws CoreException { - return Util.serializeDocument(fDoc); + public Document getXML() { + return fDoc; } @Override diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiFilterStore.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiFilterStore.java index 99516faee2..5fc9306050 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiFilterStore.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/ApiFilterStore.java @@ -15,6 +15,7 @@ import java.io.IOException; import java.io.InputStream; +import java.nio.file.Files; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -122,7 +123,7 @@ public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { } return Status.CANCEL_STATUS; } - String xml = getStoreAsXml(filters); + Document xml = getXmlDocument(filters); IFile file = project.getFile(API_FILTERS_XML_PATH); if (xml == null) { if (ApiPlugin.DEBUG_FILTER_STORE) { @@ -149,25 +150,15 @@ public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { lineDelimiter = TextUtilities.getDefaultLineDelimiter(document); } - String lineSeparator = System.lineSeparator(); - if (lineDelimiter != null && !lineDelimiter.equals(lineSeparator)) { - xml = xml.replaceAll(lineSeparator, lineDelimiter); - } - try (InputStream xstream = Util.getInputStreamFromString(xml)) { - if (xstream == null) { - return Status.CANCEL_STATUS; - } - if (file.getProject().isAccessible()) { - if (!file.exists()) { - IFolder folder = (IFolder) file.getParent(); - if (!folder.exists()) { - folder.create(true, true, localmonitor); - } - file.create(xstream, true, localmonitor); - } else { - file.setContents(xstream, true, false, localmonitor); - } + if (file.getProject().isAccessible()) { + String lineSeparator = System.lineSeparator(); + if (lineDelimiter != null && !lineDelimiter.equals(lineSeparator)) { + String content = Util.serializeDocument(xml).replaceAll(lineSeparator, lineDelimiter); + Files.writeString(file.getLocation().toPath(), content); + } else { + Util.writeDocumentToFile(xml, file.getLocation().toPath()); } + file.refreshLocal(IResource.DEPTH_ZERO, localmonitor); } fTriggeredChange = true; fNeedsSaving = false; @@ -365,7 +356,8 @@ public synchronized boolean removeFilters(IApiProblemFilter[] filters) { * @param filtermap the mapping of filters to convert to XML * @return an XML string representation of the given mapping of filters */ - synchronized String getStoreAsXml(Map>> filtermap) throws CoreException { + synchronized Document getXmlDocument(Map>> filtermap) + throws CoreException { if (filtermap == null) { if (ApiPlugin.DEBUG_FILTER_STORE) { System.out.println("no filter map returning null XML for project [" + fProject.getElementName() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ @@ -467,7 +459,7 @@ synchronized String getStoreAsXml(Map scanResult) throws Exception { Collections.sort(scanResult, (o1, o2) -> ((Consumer) o1).name.compareTo(((Consumer) o2).name)); - + Path reportIndex = Path.of(getHtmlLocation(), "index.html"); //$NON-NLS-1$ try { - File reportIndex = new File(getHtmlLocation(), "index.html"); //$NON-NLS-1$ - if (!reportIndex.exists()) { - reportIndex.createNewFile(); - } setReportIndex(reportIndex); StringBuilder buffer = new StringBuilder(); @@ -515,13 +508,9 @@ protected void writeIndexPage(List scanResult) throws Exception { buffer.append(W3C_FOOTER); buffer.append(CLOSE_BODY).append(CLOSE_HTML); - // write the file - try (PrintWriter writer = new PrintWriter( - new OutputStreamWriter(new FileOutputStream(reportIndex), StandardCharsets.UTF_8))) { - writer.print(buffer.toString()); - } + Files.writeString(reportIndex, buffer); } catch (IOException e) { - throw new Exception(NLS.bind(SearchMessages.ioexception_writing_html_file, getReportIndex().getAbsolutePath())); + throw new Exception(NLS.bind(SearchMessages.ioexception_writing_html_file, reportIndex.toAbsolutePath())); } } @@ -534,16 +523,8 @@ protected void writeIndexPage(List scanResult) throws Exception { * @param producers a map of producer name to a {@link Producer} object */ protected void writeConsumerReport(Consumer consumer, Map producers) throws Exception { - File originhtml = null; + Path originhtml = Path.of(getHtmlLocation(), consumer.name, "index.html"); //$NON-NLS-1$ try { - File htmlroot = new File(getHtmlLocation(), consumer.name); - if (!htmlroot.exists()) { - htmlroot.mkdirs(); - } - originhtml = new File(htmlroot, "index.html"); //$NON-NLS-1$ - if (!originhtml.exists()) { - originhtml.createNewFile(); - } StringBuilder buffer = new StringBuilder(); buffer.append(HTML_HEADER); buffer.append(OPEN_HTML).append(OPEN_HEAD).append(CONTENT_TYPE_META); @@ -576,13 +557,10 @@ protected void writeConsumerReport(Consumer consumer, Map prod buffer.append(OPEN_P).append("").append(SearchMessages.UseReportConverter_back_to_bundle_index).append(CLOSE_A).append(CLOSE_P); //$NON-NLS-1$ buffer.append(W3C_FOOTER); - try (PrintWriter writer = new PrintWriter( - new OutputStreamWriter(new FileOutputStream(originhtml), StandardCharsets.UTF_8))) { - writer.println(buffer.toString()); - writer.flush(); - } + writeString(originhtml, buffer); } catch (IOException ioe) { - throw new Exception(NLS.bind(SearchMessages.ioexception_writing_html_file, originhtml.getAbsolutePath()), ioe); + throw new Exception(NLS.bind(SearchMessages.ioexception_writing_html_file, originhtml.toAbsolutePath()), + ioe); } } @@ -596,16 +574,9 @@ protected void writeConsumerReport(Consumer consumer, Map prod * @param producer producer to write the report for */ protected void writeProducerReport(Consumer parentConsumer, Producer producer) throws Exception { - File originhtml = null; + Path htmlroot = Path.of(getHtmlLocation(), parentConsumer.name, producer.name); + Path originhtml = htmlroot.resolve("index.html"); //$NON-NLS-1$ try { - File htmlroot = IPath.fromOSString(getHtmlLocation()).append(parentConsumer.name).append(producer.name).toFile(); - if (!htmlroot.exists()) { - htmlroot.mkdirs(); - } - originhtml = new File(htmlroot, "index.html"); //$NON-NLS-1$ - if (!originhtml.exists()) { - originhtml.createNewFile(); - } StringBuilder buffer = new StringBuilder(); buffer.append(HTML_HEADER); buffer.append(OPEN_HTML).append(OPEN_HEAD).append(CONTENT_TYPE_META); @@ -630,11 +601,8 @@ protected void writeProducerReport(Consumer parentConsumer, Producer producer) t CountGroup counts = type.counts; String fqname = Signatures.getQualifiedTypeSignature((IReferenceTypeDescriptor) type.desc); - File typefile = new File(htmlroot, fqname + HTML_EXTENSION); - if (!typefile.exists()) { - typefile.createNewFile(); - } - String link = extractLinkFrom(htmlroot, typefile.getAbsolutePath()); + Path typefile = htmlroot.resolve(fqname + HTML_EXTENSION); + String link = extractLinkFrom(htmlroot.toFile(), typefile.toAbsolutePath().toString()); buffer.append(getReferenceTableEntry(counts, link, fqname, false)); writeTypePage(type.referencingMembers, type, typefile, fqname); } @@ -644,13 +612,9 @@ protected void writeProducerReport(Consumer parentConsumer, Producer producer) t buffer.append(OPEN_P).append("").append(NLS.bind(SearchMessages.ConsumerReportConvertor_BackLinkToConsumer, parentConsumer.name)).append(CLOSE_A).append(CLOSE_P); //$NON-NLS-1$ buffer.append(W3C_FOOTER); - try (PrintWriter writer = new PrintWriter( - new OutputStreamWriter(new FileOutputStream(originhtml), StandardCharsets.UTF_8))) { - writer.println(buffer.toString()); - writer.flush(); - } + writeString(originhtml, buffer); } catch (IOException ioe) { - throw new Exception(NLS.bind(SearchMessages.ioexception_writing_html_file, originhtml.getAbsolutePath())); + throw new Exception(NLS.bind(SearchMessages.ioexception_writing_html_file, originhtml.toAbsolutePath())); } } diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/MissingRefMetadata.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/MissingRefMetadata.java index 6bb36e8783..61ba7e9e5e 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/MissingRefMetadata.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/MissingRefMetadata.java @@ -13,12 +13,9 @@ *******************************************************************************/ package org.eclipse.pde.api.tools.internal.search; -import java.io.BufferedWriter; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.OutputStreamWriter; -import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.text.DateFormat; import java.util.Calendar; @@ -124,7 +121,7 @@ public static MissingRefMetadata getMetadata(File xmlFile) throws Exception { } @Override - public void serializeToFile(File file) throws IOException, CoreException { + public void serializeToFile(Path file) throws IOException, CoreException { Document doc = Util.newDocument(); Element root = doc.createElement(MissingRefMetadata.METADATA); doc.appendChild(root); @@ -145,11 +142,7 @@ public void serializeToFile(File file) throws IOException, CoreException { root.appendChild(child); child.setAttribute(MissingRefMetadata.VALUE, apiusescans); - try (BufferedWriter writer = new BufferedWriter( - new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))) { - writer.write(Util.serializeDocument(doc)); - writer.flush(); - } + Util.writeDocumentToFile(doc, file); } /** diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/MissingRefReportConverter.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/MissingRefReportConverter.java index ee3f5bed8d..313a2678fe 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/MissingRefReportConverter.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/MissingRefReportConverter.java @@ -14,11 +14,9 @@ package org.eclipse.pde.api.tools.internal.search; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -77,16 +75,8 @@ public void endVisitComponent() { } private void writeIndexFileForComponent(Report report) throws Exception { - File originhtml = null; + Path originhtml = Path.of(getHtmlLocation(), report.name, "index.html"); //$NON-NLS-1$ try { - File htmlroot = new File(getHtmlLocation(), report.name); - if (!htmlroot.exists()) { - htmlroot.mkdirs(); - } - originhtml = new File(htmlroot, "index.html"); //$NON-NLS-1$ - if (!originhtml.exists()) { - originhtml.createNewFile(); - } StringBuilder buffer = new StringBuilder(); buffer.append(HTML_HEADER); buffer.append(OPEN_HTML).append(OPEN_HEAD).append(CONTENT_TYPE_META); @@ -126,13 +116,10 @@ private void writeIndexFileForComponent(Report report) throws Exception { buffer.append(W3C_FOOTER); buffer.append(CLOSE_BODY); - try (PrintWriter writer = new PrintWriter( - new OutputStreamWriter(new FileOutputStream(originhtml), StandardCharsets.UTF_8))) { - writer.println(buffer.toString()); - writer.flush(); - } + writeString(originhtml, buffer); } catch (IOException ioe) { - throw new Exception(NLS.bind(SearchMessages.ioexception_writing_html_file, originhtml.getAbsolutePath())); + throw new Exception( + NLS.bind(SearchMessages.ioexception_writing_html_file, originhtml.toAbsolutePath())); } } @@ -327,10 +314,7 @@ protected void writeIndexPage(List result) throws Exception { Collections.sort(result, (o1, o2) -> ((Report) o1).name.compareTo(((Report) o2).name)); try { - File reportIndex = new File(getHtmlLocation(), "index.html"); //$NON-NLS-1$ - if (!reportIndex.exists()) { - reportIndex.createNewFile(); - } + Path reportIndex = Path.of(getHtmlLocation(), "index.html"); //$NON-NLS-1$ // setReportIndex(reportIndex); StringBuilder buffer = new StringBuilder(); @@ -375,12 +359,7 @@ protected void writeIndexPage(List result) throws Exception { buffer.append(W3C_FOOTER); buffer.append(CLOSE_BODY).append(CLOSE_HTML); - // write the file - try (PrintWriter writer = new PrintWriter( - new OutputStreamWriter(new FileOutputStream(reportIndex), StandardCharsets.UTF_8))) { - writer.print(buffer.toString()); - writer.flush(); - } + Files.writeString(reportIndex, buffer); } catch (IOException e) { throw new Exception(NLS.bind(SearchMessages.ioexception_writing_html_file, getReportIndex().getAbsolutePath())); } diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/ReferenceLookupVisitor.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/ReferenceLookupVisitor.java index 77508ef723..f7b559327a 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/ReferenceLookupVisitor.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/ReferenceLookupVisitor.java @@ -13,12 +13,8 @@ *******************************************************************************/ package org.eclipse.pde.api.tools.internal.search; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.OutputStreamWriter; -import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.ArrayList; import java.util.List; @@ -198,25 +194,15 @@ public void endVisitComponent(IComponentDescriptor target) { @Override public void endVisitScan() { - File rootfile = new File(location); - File file = new File(rootfile, "not_searched.xml"); //$NON-NLS-1$ + Path file = Path.of(location, "not_searched.xml"); //$NON-NLS-1$ try { // generate missing bundles information - if (!rootfile.exists()) { - rootfile.mkdirs(); - } - if (!file.exists()) { - file.createNewFile(); - } Document doc = Util.newDocument(); Element root = doc.createElement(IApiXmlConstants.ELEMENT_COMPONENTS); doc.appendChild(root); addMissingComponents(missingComponents, SearchMessages.ReferenceLookupVisitor_0, doc, root); addMissingComponents(skippedComponents, SearchMessages.SkippedComponent_component_was_excluded, doc, root); - try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));) { - writer.write(Util.serializeDocument(doc)); - writer.flush(); - } + Util.writeDocumentToFile(doc, file); } catch (IOException | CoreException e) { ApiPlugin.log("Failed to report missing bundles into " + file, e); //$NON-NLS-1$ } diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/UseMetadata.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/UseMetadata.java index 6b36b5f266..854889deb9 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/UseMetadata.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/UseMetadata.java @@ -13,12 +13,8 @@ *******************************************************************************/ package org.eclipse.pde.api.tools.internal.search; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.OutputStreamWriter; -import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import org.eclipse.core.runtime.CoreException; import org.eclipse.pde.api.tools.internal.provisional.search.IApiSearchRequestor; @@ -138,7 +134,7 @@ public UseMetadata(int searchflags, String scopepattern, String refpattern, Stri this.description = description; } @Override - public void serializeToFile(File file) throws IOException, CoreException { + public void serializeToFile(Path file) throws IOException, CoreException { Document doc = Util.newDocument(); Element root = doc.createElement(METADATA); doc.appendChild(root); @@ -196,11 +192,7 @@ public void serializeToFile(File file) throws IOException, CoreException { root.appendChild(child); child.setAttribute(VALUE, this.additionalfilters); - try (BufferedWriter writer = new BufferedWriter( - new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))) { - writer.write(Util.serializeDocument(doc)); - writer.flush(); - } + Util.writeDocumentToFile(doc, file); } /** diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/UseReportConverter.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/UseReportConverter.java index fbe143c573..16b49b8b86 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/UseReportConverter.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/UseReportConverter.java @@ -16,12 +16,10 @@ import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -756,8 +754,8 @@ public File getReportIndex() { return htmlIndex; } - protected void setReportIndex(File index) { - htmlIndex = index; + protected void setReportIndex(Path index) { + htmlIndex = index.toFile(); } /** @@ -880,11 +878,7 @@ void writeMetaPage(File htmlroot) throws Exception { // do nothing if no meta.xml file return; } - String filename = "meta"; //$NON-NLS-1$ - File meta = new File(htmlroot, filename + HTML_EXTENSION); - if (!meta.exists()) { - meta.createNewFile(); - } + Path meta = htmlroot.toPath().resolve("meta" + HTML_EXTENSION); //$NON-NLS-1$ StringBuilder buffer = new StringBuilder(); buffer.append(HTML_HEADER); buffer.append(OPEN_HTML).append(OPEN_HEAD).append(CONTENT_TYPE_META); @@ -896,12 +890,10 @@ void writeMetaPage(File htmlroot) throws Exception { buffer.append(W3C_FOOTER); // write file - try (PrintWriter writer = new PrintWriter( - new OutputStreamWriter(new FileOutputStream(meta), StandardCharsets.UTF_8))) { - writer.println(buffer.toString()); - writer.flush(); + try { + Files.writeString(meta, buffer); } catch (IOException ioe) { - throw new Exception(NLS.bind(SearchMessages.ioexception_writing_html_file, meta.getAbsolutePath())); + throw new Exception(NLS.bind(SearchMessages.ioexception_writing_html_file, meta.toAbsolutePath())); } } @@ -912,14 +904,8 @@ void writeMetaPage(File htmlroot) throws Exception { */ protected boolean writeMissingBundlesPage(final File htmlroot) throws Exception { boolean hasMissing = false; - File missing = null; + Path missing = htmlroot.toPath().resolve("missing" + HTML_EXTENSION); //$NON-NLS-1$ try { - String filename = "missing"; //$NON-NLS-1$ - missing = new File(htmlroot, filename + HTML_EXTENSION); - if (!missing.exists()) { - missing.createNewFile(); - } - File file = new File(getReportsRoot(), "not_searched.xml"); //$NON-NLS-1$ if (!file.exists()) { // try /xml in case a raw reports root was specified @@ -953,14 +939,9 @@ protected boolean writeMissingBundlesPage(final File htmlroot) throws Exception buffer.append(BR).append("").append(SearchMessages.UseReportConverter_back_to_not_searched).append(CLOSE_A); //$NON-NLS-1$ buffer.append(W3C_FOOTER); - // write file - try (PrintWriter writer = new PrintWriter( - new OutputStreamWriter(new FileOutputStream(missing), StandardCharsets.UTF_8))) { - writer.println(buffer.toString()); - writer.flush(); - } + Files.writeString(missing, buffer); } catch (IOException ioe) { - throw new Exception(NLS.bind(SearchMessages.ioexception_writing_html_file, missing.getAbsolutePath())); + throw new Exception(NLS.bind(SearchMessages.ioexception_writing_html_file, missing.toAbsolutePath())); } return hasMissing; } @@ -1023,16 +1004,9 @@ String getNotSearchedXSLPath() { * @param referees the listing of referencing bundles */ protected void writeReferencedMemberPage(final Report report, final List referees) throws Exception { - File originhtml = null; + Path htmlroot = Path.of(getHtmlLocation(), report.name); + Path originhtml = htmlroot.resolve("index.html"); //$NON-NLS-1$ try { - File htmlroot = new File(getHtmlLocation(), report.name); - if (!htmlroot.exists()) { - htmlroot.mkdirs(); - } - originhtml = new File(htmlroot, "index.html"); //$NON-NLS-1$ - if (!originhtml.exists()) { - originhtml.createNewFile(); - } StringBuilder buffer = new StringBuilder(); buffer.append(HTML_HEADER); buffer.append(OPEN_HTML).append(OPEN_HEAD).append(CONTENT_TYPE_META); @@ -1055,11 +1029,8 @@ protected void writeReferencedMemberPage(final Report report, final List r CountGroup counts = type.counts; String fqname = Signatures.getQualifiedTypeSignature((IReferenceTypeDescriptor) type.desc); - File typefile = new File(htmlroot, fqname + HTML_EXTENSION); - if (!typefile.exists()) { - typefile.createNewFile(); - } - String link = extractLinkFrom(htmlroot, typefile.getAbsolutePath()); + Path typefile = htmlroot.resolve(fqname + HTML_EXTENSION); + String link = extractLinkFrom(htmlroot.toFile(), typefile.toAbsolutePath().toString()); buffer.append(getReferenceTableEntry(counts, link, fqname, false)); writeTypePage(map, type, typefile, fqname); } @@ -1087,13 +1058,9 @@ protected void writeReferencedMemberPage(final Report report, final List r buffer.append(OPEN_P).append("").append(SearchMessages.UseReportConverter_back_to_bundle_index).append(CLOSE_A).append(CLOSE_P); //$NON-NLS-1$ buffer.append(W3C_FOOTER); - try (PrintWriter writer = new PrintWriter( - new OutputStreamWriter(new FileOutputStream(originhtml), StandardCharsets.UTF_8))) { - writer.println(buffer.toString()); - writer.flush(); - } + writeString(originhtml, buffer); } catch (IOException ioe) { - throw new Exception(NLS.bind(SearchMessages.ioexception_writing_html_file, originhtml.getAbsolutePath())); + throw new Exception(NLS.bind(SearchMessages.ioexception_writing_html_file, originhtml.toAbsolutePath())); } } @@ -1135,7 +1102,7 @@ protected String getReferencedTypeTitle(String bundle) { /** * Writes the page that displays all of the members used in a type */ - void writeTypePage(Map map, Type type, File typefile, String typename) throws Exception { + void writeTypePage(Map map, Type type, Path typefile, String typename) throws Exception { StringBuilder buffer = new StringBuilder(); buffer.append(HTML_HEADER); buffer.append(OPEN_HTML).append(OPEN_HEAD).append(CONTENT_TYPE_META); @@ -1174,13 +1141,10 @@ void writeTypePage(Map map, Type type, File typefile, .append(SearchMessages.UseReportConverter_back_to_bundle_index).append(CLOSE_A).append(CLOSE_P); buffer.append(W3C_FOOTER); - // write the file - try (PrintWriter writer = new PrintWriter( - new OutputStreamWriter(new FileOutputStream(typefile), StandardCharsets.UTF_8))) { - writer.print(buffer.toString()); - writer.flush(); + try { + Files.writeString(typefile, buffer); } catch (IOException ioe) { - throw new Exception(NLS.bind(SearchMessages.ioexception_writing_html_file, typefile.getAbsolutePath())); + throw new Exception(NLS.bind(SearchMessages.ioexception_writing_html_file, typefile.toAbsolutePath())); } } @@ -1316,12 +1280,8 @@ protected String getIndexTitle() { */ protected void writeIndexPage(List scanResult) throws Exception { Collections.sort(scanResult, (o1, o2) -> ((Report) o1).name.compareTo(((Report) o2).name)); - + Path reportIndex = Path.of(getHtmlLocation(), "index.html"); //$NON-NLS-1$ try { - File reportIndex = new File(getHtmlLocation(), "index.html"); //$NON-NLS-1$ - if (!reportIndex.exists()) { - reportIndex.createNewFile(); - } setReportIndex(reportIndex); StringBuilder buffer = new StringBuilder(); @@ -1376,14 +1336,9 @@ protected void writeIndexPage(List scanResult) throws Exception { buffer.append(W3C_FOOTER); buffer.append(CLOSE_BODY).append(CLOSE_HTML); - // write the file - try (PrintWriter writer = new PrintWriter( - new OutputStreamWriter(new FileOutputStream(reportIndex), StandardCharsets.UTF_8))) { - writer.print(buffer.toString()); - writer.flush(); - } + Files.writeString(reportIndex, buffer); } catch (IOException e) { - throw new Exception(NLS.bind(SearchMessages.ioexception_writing_html_file, getReportIndex().getAbsolutePath())); + throw new Exception(NLS.bind(SearchMessages.ioexception_writing_html_file, reportIndex.toAbsolutePath())); } } @@ -1570,6 +1525,11 @@ void writeFilterCount(StringBuilder buffer) throws Exception { } + void writeString(Path file, CharSequence string) throws IOException { + Files.createDirectories(file.getParent()); + Files.writeString(file, string); + } + /** * Returns the use metadata from this scan */ diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/XmlReferenceDescriptorWriter.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/XmlReferenceDescriptorWriter.java index 6817aee3cb..90cee6ef32 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/XmlReferenceDescriptorWriter.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/XmlReferenceDescriptorWriter.java @@ -13,13 +13,9 @@ *******************************************************************************/ package org.eclipse.pde.api.tools.internal.search; -import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.OutputStreamWriter; -import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -299,11 +295,7 @@ private void writeGroup(String origin, String referee, File parent, String name, } } root.setAttribute(IApiXmlConstants.ATTR_REFERENCE_COUNT, Integer.toString(count)); - try (BufferedWriter writer = new BufferedWriter( - new OutputStreamWriter(new FileOutputStream(out), StandardCharsets.UTF_8))) { - writer.write(Util.serializeDocument(doc)); - writer.flush(); - } + Util.writeDocumentToFile(doc, out.toPath()); } } diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/XmlSearchReporter.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/XmlSearchReporter.java index f4712304c6..481754b1f1 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/XmlSearchReporter.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/search/XmlSearchReporter.java @@ -13,12 +13,8 @@ *******************************************************************************/ package org.eclipse.pde.api.tools.internal.search; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.OutputStreamWriter; -import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -140,15 +136,8 @@ public void reportNotSearched(IApiElement[] elements) { if (this.debug) { System.out.println("Writing file for projects that were not searched..."); //$NON-NLS-1$ } - File rootfile = new File(fLocation); - File file = new File(rootfile, "not_searched.xml"); //$NON-NLS-1$ + Path file = Path.of(fLocation, "not_searched.xml"); //$NON-NLS-1$ try { - if (!rootfile.exists()) { - rootfile.mkdirs(); - } - if (!file.exists()) { - file.createNewFile(); - } Document doc = Util.newDocument(); Element root = doc.createElement(IApiXmlConstants.ELEMENT_COMPONENTS); doc.appendChild(root); @@ -162,10 +151,7 @@ public void reportNotSearched(IApiElement[] elements) { comp.setAttribute(IApiXmlConstants.SKIPPED_DETAILS, component.getErrorDetails()); root.appendChild(comp); } - try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));) { - writer.write(Util.serializeDocument(doc)); - writer.flush(); - } + Util.writeDocumentToFile(doc, file); } catch (IOException | CoreException e) { ApiPlugin.log("Failed to report missing projects into " + file, e); //$NON-NLS-1$ } @@ -180,14 +166,7 @@ public void reportMetadata(IMetadata data) { if (this.debug) { System.out.println("Writing file for projects that were not searched..."); //$NON-NLS-1$ } - File rootfile = new File(fLocation); - if (!rootfile.exists()) { - rootfile.mkdirs(); - } - File file = new File(rootfile, "meta.xml"); //$NON-NLS-1$ - if (!file.exists()) { - file.createNewFile(); - } + Path file = Path.of(fLocation, "meta.xml"); //$NON-NLS-1$ data.serializeToFile(file); } catch (IOException | CoreException ce) { ApiPlugin.log(ce); @@ -199,16 +178,8 @@ public void reportCounts() { if (this.debug) { System.out.println("Writing file for counting total references..."); //$NON-NLS-1$ } - File rootfile = new File(fLocation); - File file = new File(rootfile, "counts.xml"); //$NON-NLS-1$ + Path file = Path.of(fLocation, "counts.xml"); //$NON-NLS-1$ try { - if (!rootfile.exists()) { - rootfile.mkdirs(); - } - if (!file.exists()) { - file.createNewFile(); - } - Document doc = Util.newDocument(); Element root = doc.createElement(IApiXmlConstants.ELEMENT_REPORTED_COUNT); doc.appendChild(root); @@ -217,10 +188,7 @@ public void reportCounts() { root.setAttribute(IApiXmlConstants.ATTR_COUNT_INTERNAL, Integer.toString(internalCount)); root.setAttribute(IApiXmlConstants.ATTR_COUNT_FILTERED, Integer.toString(AntFilterStore.filteredAPIProblems.size())); - try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));) { - writer.write(Util.serializeDocument(doc)); - writer.flush(); - } + Util.writeDocumentToFile(doc, file); } catch (IOException | CoreException e) { ApiPlugin.log("Failed to report tota counts into " + file, e); //$NON-NLS-1$ } diff --git a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/util/Util.java b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/util/Util.java index 2378cf0f85..14944ef99d 100644 --- a/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/util/Util.java +++ b/apitools/org.eclipse.pde.api.tools/src/org/eclipse/pde/api/tools/internal/util/Util.java @@ -14,21 +14,17 @@ package org.eclipse.pde.api.tools.internal.util; import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.LineNumberReader; -import java.io.PrintWriter; +import java.io.OutputStream; import java.io.StringReader; import java.lang.reflect.Field; import java.nio.ByteBuffer; @@ -448,9 +444,7 @@ public static File createEEFile(IVMInstall jre) throws IOException { String eeid = getStrictCompatibleEE(jre); String string = Util.generateEEContents(jre, eeid); File eeFile = createTempFile("eed", ".ee"); //$NON-NLS-1$ //$NON-NLS-2$ - try (FileOutputStream outputStream = new FileOutputStream(eeFile)) { - outputStream.write(string.getBytes(StandardCharsets.UTF_8)); - } + Files.writeString(eeFile.toPath(), string); return eeFile; } @@ -1757,21 +1751,6 @@ public static Element parseDocument(String document) throws CoreException { } } - /** - * Save the given contents into the given file. The file parent folder must - * exist. - * - * @param file the given file target - * @param contents the given contents - * @throws IOException if an IOException occurs while saving the file - */ - public static void saveFile(File file, String contents) throws IOException { - try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) { - writer.write(contents); - writer.flush(); - } - } - /** * Returns the contents of the given file as a string, or null * @@ -1798,6 +1777,21 @@ public static InputStream getInputStreamFromString(String string) { return new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8)); } + /** + * Serializes the given XML document into the given file. + * + * @param document XML document to serialize + * @param file the file to which the document is written + * @return a string representing the given document + * @throws CoreException if unable to serialize the document + */ + public static void writeDocumentToFile(Document document, Path file) throws CoreException, IOException { + Files.createDirectories(file.getParent()); + try (OutputStream stream = Files.newOutputStream(file)) { + serializeDocument(document, stream); + } + } + /** * Serializes the given XML document into a UTF-8 string. * @@ -1806,7 +1800,13 @@ public static InputStream getInputStreamFromString(String string) { * @throws CoreException if unable to serialize the document */ public static String serializeDocument(Document document) throws CoreException { - try (ByteArrayOutputStream s = new ByteArrayOutputStream()) { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + serializeDocument(document, stream); + return stream.toString(StandardCharsets.UTF_8); + } + + private static void serializeDocument(Document document, OutputStream s) throws CoreException { + try (s) { @SuppressWarnings("restriction") TransformerFactory factory = org.eclipse.core.internal.runtime.XmlProcessorFactory .createTransformerFactoryWithErrorOnDOCTYPE(); @@ -1817,7 +1817,6 @@ public static String serializeDocument(Document document) throws CoreException { DOMSource source = new DOMSource(document); StreamResult outputTarget = new StreamResult(s); transformer.transform(source, outputTarget); - return s.toString(StandardCharsets.UTF_8); } catch (TransformerException | IOException e) { throw new CoreException(Status.error("Unable to serialize XML document.", e)); //$NON-NLS-1$ } @@ -1828,7 +1827,6 @@ public static String serializeDocument(Document document) throws CoreException { * it doesn't exist) */ public static void unzip(String zipPath, String destDirPath) throws IOException, CoreException { - byte[] buf = new byte[8192]; File destDir = new File(destDirPath); try (InputStream zipIn = new FileInputStream(zipPath); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(zipIn));) { ZipEntry zEntry; @@ -1854,12 +1852,7 @@ public static void unzip(String zipPath, String destDirPath) throws IOException, if (!outFileCanonicalPath.startsWith(destDirCanonicalPath + File.separator)) { throw new CoreException(Status.error(MessageFormat.format("Entry is outside of the target dir: : {0}", filePath), null)); //$NON-NLS-1$ } - try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outFile))) { - int n = 0; - while ((n = zis.read(buf)) >= 0) { - outputStream.write(buf, 0, n); - } - } + Files.copy(zis, outFile.toPath()); } } } @@ -1870,32 +1863,17 @@ public static void unzip(String zipPath, String destDirPath) throws IOException, */ public static void guntar(String zipPath, String destDirPath) throws TarException, IOException { try (TarFile tarFile = new TarFile(new File(zipPath))) { - byte[] buf = new byte[8192]; + Path destDir = Path.of(destDirPath); for (TarEntry zEntry : tarFile.entries()) { // if it is empty directory, create it if (zEntry.getFileType() == TarEntry.DIRECTORY) { - new File(destDirPath, zEntry.getName()).mkdirs(); + Files.createDirectories(destDir.resolve(zEntry.getName())); continue; } // if it is a file, extract it - String filePath = zEntry.getName(); - int lastSeparator = filePath.lastIndexOf("/"); //$NON-NLS-1$ - String fileDir = ""; //$NON-NLS-1$ - if (lastSeparator >= 0) { - fileDir = filePath.substring(0, lastSeparator); - } - // create directory for a file - new File(destDirPath, fileDir).mkdirs(); - // write file - File outFile = new File(destDirPath, filePath); - try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outFile))) { - int n = 0; - try (BufferedInputStream stream = new BufferedInputStream(tarFile.getInputStream(zEntry))) { - while ((n = stream.read(buf)) >= 0) { - outputStream.write(buf, 0, n); - } - } - } + Path outFile = destDir.resolve(zEntry.getName()); + Files.createDirectories(outFile.getParent()); + Files.copy(tarFile.getInputStream(zEntry), outFile); } } } @@ -1907,16 +1885,13 @@ public static File getEEDescriptionFile() { // generate a fake 1.6 ee file try { File fakeEEFile = createTempFile("eefile", ".ee"); //$NON-NLS-1$ //$NON-NLS-2$ - try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(fakeEEFile)))) { - writer.print("-Djava.home="); //$NON-NLS-1$ - writer.println(System.getProperty("java.home")); //$NON-NLS-1$ - writer.print("-Dee.bootclasspath="); //$NON-NLS-1$ - writer.println(getJavaClassLibsAsString()); - writer.println("-Dee.language.level=1.6"); //$NON-NLS-1$ - writer.println("-Dee.class.library.level=JavaSE-1.6"); //$NON-NLS-1$ - writer.flush(); - return fakeEEFile; - } + Files.writeString(fakeEEFile.toPath(), String.format(""" + -Djava.home=%s + -Dee.bootclasspath=%s + -Dee.language.level=1.6 + -Dee.class.library.level=JavaSE-1.6 + """, System.getProperty("java.home"), getJavaClassLibsAsString())); //$NON-NLS-1$//$NON-NLS-2$ + return fakeEEFile; } catch (IOException e) { return null; } diff --git a/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/APIDeprecationTask.java b/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/APIDeprecationTask.java index 8d9709cb3e..b8d9529caf 100644 --- a/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/APIDeprecationTask.java +++ b/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/APIDeprecationTask.java @@ -13,9 +13,7 @@ *******************************************************************************/ package org.eclipse.pde.api.tools.internal.tasks; -import java.io.BufferedWriter; import java.io.File; -import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; @@ -30,6 +28,7 @@ import org.eclipse.pde.api.tools.internal.provisional.comparator.IDelta; import org.eclipse.pde.api.tools.internal.provisional.model.IApiBaseline; import org.eclipse.pde.api.tools.internal.util.FilteredElements; +import org.eclipse.pde.api.tools.internal.util.Util; /** * Ant task to retrieve all deprecation changes (addition or removal) between @@ -138,19 +137,11 @@ public void execute() throws BuildException { // delete the file // TODO we might want to customize it outputFile.delete(); - } else { - File outputDir = outputFile.getParentFile(); - if (!outputDir.exists()) { - if (!outputDir.mkdirs()) { - throw new BuildException(NLS.bind(Messages.errorCreatingParentReportFile, outputDir.getAbsolutePath())); - } - } } - try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) { + try { FilterListDeltaVisitor visitor = new FilterListDeltaVisitor(excludedElements, includedElements, FilterListDeltaVisitor.CHECK_DEPRECATION); delta.accept(visitor); - writer.write(visitor.getXML()); - writer.flush(); + Util.writeDocumentToFile(visitor.getDocument(), outputFile.toPath()); if (this.debug) { String potentialExcludeList = visitor.getPotentialExcludeList(); if (potentialExcludeList.length() != 0) { diff --git a/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/APIFreezeTask.java b/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/APIFreezeTask.java index 37d32318b1..795541178f 100644 --- a/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/APIFreezeTask.java +++ b/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/APIFreezeTask.java @@ -13,12 +13,12 @@ *******************************************************************************/ package org.eclipse.pde.api.tools.internal.tasks; -import java.io.BufferedWriter; import java.io.File; -import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.HashMap; import java.util.Map; @@ -37,6 +37,7 @@ import org.eclipse.pde.api.tools.internal.provisional.model.IApiComponent; import org.eclipse.pde.api.tools.internal.provisional.model.IApiScope; import org.eclipse.pde.api.tools.internal.util.FilteredElements; +import org.eclipse.pde.api.tools.internal.util.Util; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -91,19 +92,11 @@ public void execute() throws BuildException { System.out.println("No include list location"); //$NON-NLS-1$ } } - File outputFile = new File(this.reportLocation); - if (outputFile.exists()) { - if (outputFile.isDirectory()) { - // the output file cannot be a directory - throw new BuildException(NLS.bind(Messages.reportLocationHasToBeAFile, outputFile.getAbsolutePath())); - } - } else { - File outputDir = outputFile.getParentFile(); - if (!outputDir.exists()) { - if (!outputDir.mkdirs()) { - throw new BuildException(NLS.bind(Messages.errorCreatingParentReportFile, outputDir.getAbsolutePath())); - } - } + Path outputFile = Path.of(this.reportLocation); + + if (Files.isDirectory(outputFile)) { + // the output file cannot be a directory + throw new BuildException(NLS.bind(Messages.reportLocationHasToBeAFile, outputFile.toAbsolutePath())); } int index = this.reportLocation.lastIndexOf('.'); if (index == -1 || !this.reportLocation.substring(index).equalsIgnoreCase(".xml")) { //$NON-NLS-1$ @@ -172,7 +165,7 @@ public void execute() throws BuildException { } if (delta != ApiComparator.NO_DELTA) { // dump the report in the appropriate folder - try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) { + try { FilterListDeltaVisitor visitor = new FilterListDeltaVisitor(excludedElements, includedElements, FilterListDeltaVisitor.CHECK_OTHER); delta.accept(visitor); @@ -182,10 +175,7 @@ public void execute() throws BuildException { // to add warnings in the html addResolverErrors(doc); } - - String serializedXml = org.eclipse.pde.api.tools.internal.util.Util.serializeDocument(doc); - writer.write(serializedXml); - writer.flush(); + Util.writeDocumentToFile(doc, outputFile); if (this.debug) { String potentialExcludeList = visitor.getPotentialExcludeList(); if (potentialExcludeList.length() != 0) { @@ -201,13 +191,12 @@ public void execute() throws BuildException { } } else { // create a xml file with 0 delta and a comment - try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) { - writer.write(""); //$NON-NLS-1$ - writer.newLine(); - writer.write(""); //$NON-NLS-1$ - writer.newLine(); - writer.write(""); //$NON-NLS-1$ - writer.flush(); + try { + Files.writeString(outputFile, """ + + + + """); //$NON-NLS-1$ } catch (IOException e) { ApiPlugin.log(e); } diff --git a/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/APIToolsAnalysisTask.java b/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/APIToolsAnalysisTask.java index e14243d3a1..e8d744244a 100644 --- a/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/APIToolsAnalysisTask.java +++ b/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/APIToolsAnalysisTask.java @@ -191,7 +191,6 @@ private Summary createProblemSummary(String componentID, IApiProblem[] apiProble private void dumpReport(Summary[] summaries, List nonAPIBundleNames, Map bundlesWithErrors) { ProblemCounter counter = new ProblemCounter(); for (Summary summary : summaries) { - String contents = null; String componentID = summary.componentID; // Filtering should be done during analysis to save time, but filter @@ -241,20 +240,15 @@ private void dumpReport(Summary[] summaries, List nonAPIBundleNames, Map } report.appendChild(category); } - - contents = Util.serializeDocument(document); + saveReport(componentID, document, "report.xml"); //$NON-NLS-1$ } catch (DOMException | CoreException e) { throw new BuildException(e); } - if (contents != null) { - saveReport(componentID, contents, "report.xml"); //$NON-NLS-1$ - } } // Write out a list of components skipped because they aren't API Tools // enabled if (nonAPIBundleNames != null && !nonAPIBundleNames.isEmpty()) { - String contents = null; try { Document document = Util.newDocument(); Element report = document.createElement(IApiXmlConstants.ELEMENT_API_TOOL_REPORT); @@ -267,17 +261,13 @@ private void dumpReport(Summary[] summaries, List nonAPIBundleNames, Map report.appendChild(bundle); } } - contents = Util.serializeDocument(document); + saveReport("Skipped Bundles", document, "report.xml"); //$NON-NLS-1$ //$NON-NLS-2$ } catch (DOMException | CoreException e) { throw new BuildException(e); } - if (contents != null) { - saveReport("Skipped Bundles", contents, "report.xml"); //$NON-NLS-1$ //$NON-NLS-2$ - } } // Write out problem count file - String contents = null; try { Document document = Util.newDocument(); Element root = document.createElement(IApiXmlConstants.ELEMENT_REPORTED_COUNT); @@ -285,13 +275,10 @@ private void dumpReport(Summary[] summaries, List nonAPIBundleNames, Map root.setAttribute(IApiXmlConstants.ATTR_TOTAL, Integer.toString(counter.total)); root.setAttribute(IApiXmlConstants.ATTR_COUNT_WARNINGS, Integer.toString(counter.warnings)); root.setAttribute(IApiXmlConstants.ATTR_COUNT_ERRORS, Integer.toString(counter.errors)); - contents = Util.serializeDocument(document); + saveReport(null, document, "counts.xml"); //$NON-NLS-1$ } catch (DOMException | CoreException e) { throw new BuildException(e); } - if (contents != null) { - saveReport(null, contents, "counts.xml"); //$NON-NLS-1$ - } } /** diff --git a/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/CommonUtilsTask.java b/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/CommonUtilsTask.java index aeb161b610..09327f8144 100644 --- a/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/CommonUtilsTask.java +++ b/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/CommonUtilsTask.java @@ -13,10 +13,9 @@ *******************************************************************************/ package org.eclipse.pde.api.tools.internal.tasks; -import java.io.BufferedWriter; import java.io.File; -import java.io.FileWriter; import java.io.IOException; +import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Set; @@ -32,6 +31,7 @@ import org.eclipse.pde.api.tools.internal.util.FilteredElements; import org.eclipse.pde.api.tools.internal.util.TarException; import org.eclipse.pde.api.tools.internal.util.Util; +import org.w3c.dom.Document; /** * Common code for API Tools Ant tasks. @@ -167,31 +167,20 @@ protected static FilteredElements initializeFilteredElements(String filterListLo * * @param componentID Name of the component to create a child directory for * or null to put the report in the XML root - * @param contents contents to output to the report + * @param document the document to output to the report * @param reportname name of the file to output to */ - protected void saveReport(String componentID, String contents, String reportname) { - File dir = new File(this.reportLocation); - if (!dir.exists()) { - if (!dir.mkdirs()) { - throw new BuildException(NLS.bind(Messages.errorCreatingReportDirectory, this.reportLocation)); - } - } + protected void saveReport(String componentID, Document document, String reportname) { + Path dir = Path.of(this.reportLocation); // If the caller has provided a component id, create a child directory if (componentID != null) { - dir = new File(dir, componentID); - if (!dir.exists()) { - if (!dir.mkdirs()) { - throw new BuildException(NLS.bind(Messages.errorCreatingReportDirectory, dir)); - } - } + dir = dir.resolve(componentID); } - File reportFile = new File(dir, reportname); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(reportFile))) { - writer.write(contents); - writer.flush(); - } catch (IOException e) { - ApiPlugin.log(e); + Path reportFile = dir.resolve(reportname); + try { + Util.writeDocumentToFile(document, reportFile); + } catch (IOException | CoreException e) { + throw new BuildException(NLS.bind(Messages.errorCreatingReportDirectory, dir), e); } } diff --git a/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/CompareTask.java b/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/CompareTask.java index db5854905c..5aa97929cd 100644 --- a/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/CompareTask.java +++ b/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/CompareTask.java @@ -13,9 +13,7 @@ *******************************************************************************/ package org.eclipse.pde.api.tools.internal.tasks; -import java.io.BufferedWriter; import java.io.File; -import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; @@ -160,23 +158,16 @@ public void execute() throws BuildException { throw new BuildException(Messages.errorInComparison); } // dump the report in the appropriate folder - File outputDir = new File(this.reportLocation); - if (!outputDir.exists()) { - if (!outputDir.mkdirs()) { - throw new BuildException(NLS.bind(Messages.errorCreatingParentReportFile, outputDir.getAbsolutePath())); - } - } File outputFile = new File(this.reportLocation, REPORT_XML_FILE_NAME); if (outputFile.exists()) { // delete the file // TODO we might want to customize it outputFile.delete(); } - try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) { + try { FilterListDeltaVisitor visitor = new FilterListDeltaVisitor(excludedElements, includedElements, FilterListDeltaVisitor.CHECK_ALL); delta.accept(visitor); - writer.write(visitor.getXML()); - writer.flush(); + Util.writeDocumentToFile(visitor.getDocument(), outputFile.toPath()); if (this.debug) { String potentialExcludeList = visitor.getPotentialExcludeList(); if (potentialExcludeList.length() != 0) { diff --git a/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/MissingRefProblemsTask.java b/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/MissingRefProblemsTask.java index 344888576f..6c922fbf14 100644 --- a/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/MissingRefProblemsTask.java +++ b/apitools/org.eclipse.pde.api.tools/src_ant/org/eclipse/pde/api/tools/internal/tasks/MissingRefProblemsTask.java @@ -14,13 +14,10 @@ package org.eclipse.pde.api.tools.internal.tasks; import java.io.BufferedInputStream; -import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.OutputStreamWriter; -import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -201,7 +198,7 @@ public void execute() throws BuildException { profile.dispose(); StubApiComponent.disposeAllCaches(); deleteBaseline(super.currentBaselineLocation, baselineInstallDir); - writeMetaData(new File(this.reportLocation, "meta.xml")); //$NON-NLS-1$ + writeMetaData(Path.of(this.reportLocation, "meta.xml")); //$NON-NLS-1$ } Summary[] summaries = createAllSummaries(allProblems); @@ -253,18 +250,11 @@ private void addDefaultProperties() { this.properties.put(IApiProblemTypes.API_USE_SCAN_FIELD_SEVERITY, ApiPlugin.VALUE_ERROR); } - private void writeMetaData(File file) { + private void writeMetaData(Path file) { try { - if (!file.exists()) { - file.getParentFile().mkdirs(); - if (!file.createNewFile()) { - return; // could not create meta.xml - } - } if (super.debug) { - System.out.println("Writing metadata to " + file.getAbsolutePath()); //$NON-NLS-1$ + System.out.println("Writing metadata to " + file.toAbsolutePath()); //$NON-NLS-1$ } - MissingRefMetadata metadata = new MissingRefMetadata(super.currentBaselineLocation, super.reportLocation, this.apiUseScans); metadata.serializeToFile(file); } catch (IOException | CoreException e) { @@ -291,9 +281,7 @@ private Summary[] createAllSummaries(Map allProblems) { private void dumpReport(Summary[] summaries) { for (Summary summary : summaries) { - String contents = null; String componentID = summary.fComponentID; - try { Document document = Util.newDocument(); Element report = document.createElement(IApiXmlConstants.ELEMENT_API_TOOL_REPORT); @@ -307,13 +295,10 @@ private void dumpReport(Summary[] summaries) { insertAPIProblems(category, document, summary.fApiProblems); report.appendChild(category); - contents = Util.serializeDocument(document); + saveReport(componentID, document, "report.xml"); //$NON-NLS-1$ } catch (DOMException | CoreException e) { throw new BuildException(e); } - if (contents != null) { - saveReport(componentID, contents, "report.xml"); //$NON-NLS-1$ - } } } @@ -326,14 +311,7 @@ public void reportNotSearched(Set notSearchedList) { if (this.debug) { System.out.println("Writing file for projects that were not searched..."); //$NON-NLS-1$ } - File rootfile = new File(reportLocation); - if (!rootfile.exists()) { - rootfile.mkdirs(); - } - File file = new File(rootfile, "not_searched.xml"); //$NON-NLS-1$ - if (!file.exists()) { - file.createNewFile(); - } + Path file = Path.of(reportLocation, "not_searched.xml"); //$NON-NLS-1$ Document doc = Util.newDocument(); Element root = doc.createElement(IApiXmlConstants.ELEMENT_COMPONENTS); root.setAttribute("ShowMissing", "false"); //$NON-NLS-1$ //$NON-NLS-2$ @@ -346,10 +324,7 @@ public void reportNotSearched(Set notSearchedList) { comp.setAttribute(IApiXmlConstants.SKIPPED_DETAILS, component.getErrorDetails()); root.appendChild(comp); } - try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));) { - writer.write(Util.serializeDocument(doc)); - writer.flush(); - } + Util.writeDocumentToFile(doc, file); } catch (IOException | CoreException e) { ApiPlugin.log(e); }