Skip to content

Commit

Permalink
format
Browse files Browse the repository at this point in the history
  • Loading branch information
tisoft committed Sep 25, 2021
1 parent b22690a commit 14ee011
Show file tree
Hide file tree
Showing 5 changed files with 130 additions and 86 deletions.
145 changes: 88 additions & 57 deletions lib/src/sortPom/java/com/diffplug/spotless/pom/JoinClassLoader.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,25 @@
/*
* Copyright 2021 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.diffplug.spotless.pom;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.security.SecureClassLoader;
import java.util.Enumeration;
import java.util.Vector;

Expand All @@ -16,66 +30,83 @@
*/
public class JoinClassLoader extends ClassLoader {

private ClassLoader[] delegateClassLoaders;
private ClassLoader[] delegateClassLoaders;

public JoinClassLoader (ClassLoader parent, ClassLoader... delegateClassLoaders) {
super(parent);
this.delegateClassLoaders = delegateClassLoaders; }
public JoinClassLoader(ClassLoader parent, ClassLoader... delegateClassLoaders) {
super(parent);
this.delegateClassLoaders = delegateClassLoaders;
}

protected Class<?> findClass (String name) throws ClassNotFoundException {
// It would be easier to call the loadClass() methods of the delegateClassLoaders
// here, but we have to load the class from the byte code ourselves, because we
// need it to be associated with our class loader.
String path = name.replace('.', '/') + ".class";
URL url = findResource(path);
if (url == null) {
throw new ClassNotFoundException(name); }
ByteBuffer byteCode;
try {
byteCode = loadResource(url); }
catch (IOException e) {
throw new ClassNotFoundException(name, e); }
return defineClass(name, byteCode, null); }
protected Class<?> findClass(String name) throws ClassNotFoundException {
// It would be easier to call the loadClass() methods of the delegateClassLoaders
// here, but we have to load the class from the byte code ourselves, because we
// need it to be associated with our class loader.
String path = name.replace('.', '/') + ".class";
URL url = findResource(path);
if (url == null) {
throw new ClassNotFoundException(name);
}
ByteBuffer byteCode;
try {
byteCode = loadResource(url);
} catch (IOException e) {
throw new ClassNotFoundException(name, e);
}
return defineClass(name, byteCode, null);
}

private ByteBuffer loadResource (URL url) throws IOException {
InputStream stream = null;
try {
stream = url.openStream();
int initialBufferCapacity = Math.min(0x40000, stream.available() + 1);
if (initialBufferCapacity <= 2) {
initialBufferCapacity = 0x10000; }
else {
initialBufferCapacity = Math.max(initialBufferCapacity, 0x200); }
ByteBuffer buf = ByteBuffer.allocate(initialBufferCapacity);
while (true) {
if (!buf.hasRemaining()) {
ByteBuffer newBuf = ByteBuffer.allocate(2*buf.capacity());
buf.flip();
newBuf.put(buf);
buf = newBuf; }
int len = stream.read(buf.array(), buf.position(), buf.remaining());
if (len <= 0) {
break; }
((Buffer)buf).position(buf.position()+len); }
((Buffer)buf).flip();
return buf; }
finally {
if (stream != null) {
stream.close(); }}}
private ByteBuffer loadResource(URL url) throws IOException {
InputStream stream = null;
try {
stream = url.openStream();
int initialBufferCapacity = Math.min(0x40000, stream.available() + 1);
if (initialBufferCapacity <= 2) {
initialBufferCapacity = 0x10000;
} else {
initialBufferCapacity = Math.max(initialBufferCapacity, 0x200);
}
ByteBuffer buf = ByteBuffer.allocate(initialBufferCapacity);
while (true) {
if (!buf.hasRemaining()) {
ByteBuffer newBuf = ByteBuffer.allocate(2 * buf.capacity());
buf.flip();
newBuf.put(buf);
buf = newBuf;
}
int len = stream.read(buf.array(), buf.position(), buf.remaining());
if (len <= 0) {
break;
}
((Buffer) buf).position(buf.position() + len);
}
((Buffer) buf).flip();
return buf;
} finally {
if (stream != null) {
stream.close();
}
}
}

protected URL findResource (String name) {
for (ClassLoader delegate : delegateClassLoaders) {
URL resource = delegate.getResource(name);
if (resource != null) {
return resource; }}
return null; }
protected URL findResource(String name) {
for (ClassLoader delegate : delegateClassLoaders) {
URL resource = delegate.getResource(name);
if (resource != null) {
return resource;
}
}
return null;
}

protected Enumeration<URL> findResources (String name) throws IOException {
Vector<URL> vector = new Vector<URL>();
for (ClassLoader delegate : delegateClassLoaders) {
Enumeration<URL> enumeration = delegate.getResources(name);
while (enumeration.hasMoreElements()) {
vector.add(enumeration.nextElement()); }}
return vector.elements(); }
protected Enumeration<URL> findResources(String name) throws IOException {
Vector<URL> vector = new Vector<URL>();
for (ClassLoader delegate : delegateClassLoaders) {
Enumeration<URL> enumeration = delegate.getResources(name);
while (enumeration.hasMoreElements()) {
vector.add(enumeration.nextElement());
}
}
return vector.elements();
}

}
Original file line number Diff line number Diff line change
@@ -1,18 +1,33 @@
/*
* Copyright 2021 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.diffplug.spotless.pom;

import com.diffplug.spotless.FormatterFunc;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.logging.Logger;

import org.apache.commons.io.IOUtils;

import com.diffplug.spotless.FormatterFunc;

import sortpom.SortPomImpl;
import sortpom.logger.SortPomLogger;
import sortpom.parameter.PluginParameters;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.logging.Logger;

class SortPomFormatterFunc implements FormatterFunc {
private static final Logger logger = Logger.getLogger(SortPomStep.class.getName());
private final SortPomStep.InternalState state;
Expand Down Expand Up @@ -46,15 +61,15 @@ public void error(String content) {
logger.severe(content);
}
}, PluginParameters.builder()
.setPomFile(pom)
.setFileOutput(false, null, null, false)
.setEncoding(state.encoding)
.setFormatting(state.lineSeparator, state.expandEmptyElements, state.spaceBeforeCloseEmptyElement, state.keepBlankLines)
.setIndent(state.nrOfIndentSpace, state.indentBlankLines, state.indentSchemaLocation)
.setSortOrder(state.sortOrderFile, state.predefinedSortOrder)
.setSortEntities(state.sortDependencies, state.sortDependencyExclusions, state.sortPlugins, state.sortProperties, state.sortModules, state.sortExecutions)
.setTriggers(false)
.build());
.setPomFile(pom)
.setFileOutput(false, null, null, false)
.setEncoding(state.encoding)
.setFormatting(state.lineSeparator, state.expandEmptyElements, state.spaceBeforeCloseEmptyElement, state.keepBlankLines)
.setIndent(state.nrOfIndentSpace, state.indentBlankLines, state.indentSchemaLocation)
.setSortOrder(state.sortOrderFile, state.predefinedSortOrder)
.setSortEntities(state.sortDependencies, state.sortDependencyExclusions, state.sortPlugins, state.sortProperties, state.sortModules, state.sortExecutions)
.setTriggers(false)
.build());
sortPom.sortPom();
return IOUtils.toString(new FileReader(pom));
}
Expand Down
20 changes: 9 additions & 11 deletions lib/src/sortPom/java/com/diffplug/spotless/pom/SortPomStep.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,11 @@
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.function.Function;
import java.util.logging.Logger;

import com.diffplug.spotless.JarState;

import com.diffplug.spotless.Provisioner;

import com.diffplug.spotless.FormatterFunc;
import com.diffplug.spotless.FormatterStep;
import com.diffplug.spotless.JarState;
import com.diffplug.spotless.Provisioner;

public class SortPomStep {

Expand All @@ -44,6 +40,7 @@ private SortPomStep() {}
public static FormatterStep create(String encoding, String lineSeparator, boolean expandEmptyElements, boolean spaceBeforeCloseEmptyElement, boolean keepBlankLines, int nrOfIndentSpace, boolean indentBlankLines, boolean indentSchemaLocation, String predefinedSortOrder, String sortOrderFile, String sortDependencies, String sortDependencyExclusions, String sortPlugins, boolean sortProperties, boolean sortModules, boolean sortExecutions, Provisioner provisioner) {
return FormatterStep.createLazy(NAME, () -> new State(encoding, lineSeparator, expandEmptyElements, spaceBeforeCloseEmptyElement, keepBlankLines, nrOfIndentSpace, indentBlankLines, indentSchemaLocation, predefinedSortOrder, sortOrderFile, sortDependencies, sortDependencyExclusions, sortPlugins, sortProperties, sortModules, sortExecutions, provisioner), State::createFormat);
}

static final class InternalState implements Serializable {
private static final long serialVersionUID = 1L;

Expand Down Expand Up @@ -98,6 +95,7 @@ static final class InternalState implements Serializable {
this.sortExecutions = sortExecutions;
}
}

static final class State implements Serializable {
private static final long serialVersionUID = 1L;
final JarState jarState;
Expand All @@ -106,24 +104,24 @@ static final class State implements Serializable {

State(String encoding, String lineSeparator, boolean expandEmptyElements, boolean spaceBeforeCloseEmptyElement, boolean keepBlankLines, int nrOfIndentSpace, boolean indentBlankLines, boolean indentSchemaLocation, String predefinedSortOrder, String sortOrderFile, String sortDependencies, String sortDependencyExclusions, String sortPlugins, boolean sortProperties, boolean sortModules, boolean sortExecutions, Provisioner provisioner) throws IOException {
this.jarState = JarState.from("com.github.ekryd.sortpom:sortpom-sorter:3.0.0", provisioner);
this.internalState=new InternalState(encoding, lineSeparator, expandEmptyElements, spaceBeforeCloseEmptyElement, keepBlankLines, nrOfIndentSpace, indentBlankLines, indentSchemaLocation, predefinedSortOrder, sortOrderFile, sortDependencies, sortDependencyExclusions, sortPlugins, sortProperties, sortModules, sortExecutions);
this.internalState = new InternalState(encoding, lineSeparator, expandEmptyElements, spaceBeforeCloseEmptyElement, keepBlankLines, nrOfIndentSpace, indentBlankLines, indentSchemaLocation, predefinedSortOrder, sortOrderFile, sortDependencies, sortDependencyExclusions, sortPlugins, sortProperties, sortModules, sortExecutions);
}

FormatterFunc createFormat() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, IOException {
ClassLoader classLoader = new JoinClassLoader(null, this.getClass().getClassLoader(), jarState.getClassLoader());
Constructor<?> constructor = classLoader.loadClass(SortPomFormatterFunc.class.getName()).getConstructor(classLoader.loadClass(InternalState.class.getName()));
constructor.setAccessible(true);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(out);
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(internalState);
ObjectInputStream ois=new ObjectInputStream(new ByteArrayInputStream(out.toByteArray())){
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray())) {
@Override
protected Class<?> resolveClass(ObjectStreamClass desc) throws ClassNotFoundException {
return classLoader.loadClass(desc.getName());
}
};
Object state=ois.readObject();
Object formatterFunc=constructor.newInstance(state);
Object state = ois.readObject();
Object formatterFunc = constructor.newInstance(state);
Method apply = formatterFunc.getClass().getMethod("apply", String.class);
apply.setAccessible(true);
return input -> (String) apply.invoke(formatterFunc, input);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
import org.apache.maven.plugins.annotations.Parameter;

import com.diffplug.spotless.FormatterStep;
import com.diffplug.spotless.pom.SortPomStep;
import com.diffplug.spotless.maven.FormatterStepConfig;
import com.diffplug.spotless.maven.FormatterStepFactory;
import com.diffplug.spotless.pom.SortPomStep;

public class SortPom implements FormatterStepFactory {
@Parameter
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@
*/
package com.diffplug.spotless.maven.pom;

import com.diffplug.spotless.maven.MavenIntegrationHarness;

import org.junit.jupiter.api.Test;

import com.diffplug.spotless.maven.MavenIntegrationHarness;

public class SortPomTest extends MavenIntegrationHarness {
@Test
public void testSortPomWithDefaultConfig() throws Exception {
Expand Down

0 comments on commit 14ee011

Please sign in to comment.