Jandex based Java Knowledge integration

This commit is contained in:
BoykoAlex
2016-11-08 10:19:58 -05:00
parent 6df038a93a
commit 010104ec8b
83 changed files with 3782 additions and 576 deletions

View File

@@ -12,14 +12,17 @@ package org.springframework.ide.vscode.application.properties.metadata.types;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.ide.vscode.commons.java.IType;
import org.springframework.ide.vscode.commons.java.Signature;
import org.springframework.ide.vscode.commons.util.ArrayUtils;
import org.springframework.ide.vscode.commons.java.IArrayType;
import org.springframework.ide.vscode.commons.java.IClassType;
import org.springframework.ide.vscode.commons.java.IJavaType;
import org.springframework.ide.vscode.commons.java.IParameterizedType;
import org.springframework.ide.vscode.commons.java.IPrimitiveType;
import org.springframework.ide.vscode.commons.java.IVoidType;
import org.springframework.ide.vscode.commons.util.Assert;
import org.springframework.ide.vscode.commons.util.Log;
import org.springframework.ide.vscode.commons.util.StringUtil;
import org.springframework.ide.vscode.commons.yaml.schema.YType;
/**
@@ -76,51 +79,74 @@ public class Type implements YType {
* Not all valid typeSig have a representation as a Type object. This may
* return null if no corresponding representation can be constructed.
*/
public static Type fromSignature(String typeSig, IType context) {
//TODO: does this work correctly with nested types (i.e like Map$Entry)
Type type = TYPE_FROM_SIG.get(typeSig);
if (type!=null) {
return type;
}
int kind = Signature.getTypeSignatureKind(typeSig);
//Essentially, Type object only able to represent class types with with generic parameters
// as long as these generic parameters are fully concrete (i.e. do not contain unbound type
// variables. For now only support the simplest case (no generics) and bail out returning null if we
// see something we don't understand.
if (kind==Signature.CLASS_TYPE_SIGNATURE) {
boolean shouldResolve = typeSig.charAt(0)==Signature.C_UNRESOLVED;
String erasure = Signature.getTypeErasure(typeSig);
String pkg = Signature.getSignatureQualifier(erasure);
String nam = Signature.getSignatureSimpleName(erasure);
String[] params = Signature.getTypeParameters(typeSig);
String[] args = Signature.getTypeArguments(typeSig);
if (shouldResolve) {
erasure = tryToResolve(qualifiedName(pkg, nam), context);
} else {
erasure = qualifiedName(pkg, nam);
// public static Type fromSignature(String typeSig, IType context) {
// //TODO: does this work correctly with nested types (i.e like Map$Entry)
// Type type = TYPE_FROM_SIG.get(typeSig);
// if (type!=null) {
// return type;
// }
// int kind = Signature.getTypeSignatureKind(typeSig);
// //Essentially, Type object only able to represent class types with with generic parameters
// // as long as these generic parameters are fully concrete (i.e. do not contain unbound type
// // variables. For now only support the simplest case (no generics) and bail out returning null if we
// // see something we don't understand.
// if (kind==Signature.CLASS_TYPE_SIGNATURE) {
// boolean shouldResolve = typeSig.charAt(0)==Signature.C_UNRESOLVED;
// String erasure = Signature.getTypeErasure(typeSig);
// String pkg = Signature.getSignatureQualifier(erasure);
// String nam = Signature.getSignatureSimpleName(erasure);
// String[] params = Signature.getTypeParameters(typeSig);
// String[] args = Signature.getTypeArguments(typeSig);
// if (shouldResolve) {
// erasure = tryToResolve(qualifiedName(pkg, nam), context);
// } else {
// erasure = qualifiedName(pkg, nam);
// }
// if (ArrayUtils.hasElements(params)) {
// //TODO: handle this case
// return null;
// } else if (ArrayUtils.hasElements(args)) {
// Type[] argTypes = new Type[args.length];
// for (int i = 0; i < argTypes.length; i++) {
// argTypes[i] = fromSignature(args[i], context);
// }
// return new Type(erasure, argTypes);
// } else {
// return new Type(erasure, null);
// }
// } else if (kind==Signature.ARRAY_TYPE_SIGNATURE) {
// Type elementType = fromSignature(Signature.getElementType(typeSig), context);
// if (elementType!=null) {
// int arrayCount = Signature.getArrayCount(typeSig);
// return elementType.asArray(arrayCount);
// }
// }
// return null;
// }
public static Type fromJavaType(IJavaType javaType) {
if (javaType instanceof IPrimitiveType || javaType instanceof IVoidType) {
Type type = TYPE_FROM_SIG.get(javaType.name());
if (type != null) {
return type;
}
if (ArrayUtils.hasElements(params)) {
//TODO: handle this case
return null;
} else if (ArrayUtils.hasElements(args)) {
Type[] argTypes = new Type[args.length];
for (int i = 0; i < argTypes.length; i++) {
argTypes[i] = fromSignature(args[i], context);
}
return new Type(erasure, argTypes);
} else {
return new Type(erasure, null);
}
} else if (kind==Signature.ARRAY_TYPE_SIGNATURE) {
Type elementType = fromSignature(Signature.getElementType(typeSig), context);
} else if (javaType instanceof IClassType) {
return new Type(javaType.name(), null);
} else if (javaType instanceof IParameterizedType) {
IParameterizedType parameterizedType = (IParameterizedType) javaType;
List<Type> arguments = parameterizedType.arguments().map(Type::fromJavaType).collect(Collectors.toList());
return new Type(parameterizedType.name(), arguments.toArray(new Type[arguments.size()]));
} else if (javaType instanceof IArrayType) {
IArrayType arrayType = (IArrayType) javaType;
Type elementType = fromJavaType(arrayType.component());
if (elementType!=null) {
int arrayCount = Signature.getArrayCount(typeSig);
return elementType.asArray(arrayCount);
return elementType.asArray(arrayType.dimensions());
}
}
return null;
}
public Type asArray(int arrayCount) {
Assert.isLegal(arrayCount>0);
StringBuilder arrayErasure = new StringBuilder(erasure);
@@ -130,32 +156,32 @@ public class Type implements YType {
return new Type(arrayErasure.toString(), params);
}
private static String qualifiedName(String pkg, String nam) {
if (StringUtil.hasText(pkg)) {
return pkg + "." + nam;
} else {
return nam;
}
}
private static String tryToResolve(String typeName, IType context) {
try {
String[][] resolved = context.resolveType(typeName);
if (ArrayUtils.hasElements(resolved)) {
String pkg = resolved[0][0];
String nam = resolved[0][1];
if (StringUtil.hasText(pkg)) {
return pkg+"."+nam;
} else {
//No . in front of default package
return nam;
}
}
} catch (Exception e) {
Log.log(e);
}
return typeName;
}
// private static String qualifiedName(String pkg, String nam) {
// if (StringUtil.hasText(pkg)) {
// return pkg + "." + nam;
// } else {
// return nam;
// }
// }
//
// private static String tryToResolve(String typeName, IType context) {
// try {
// String[][] resolved = context.resolveType(typeName);
// if (ArrayUtils.hasElements(resolved)) {
// String pkg = resolved[0][0];
// String nam = resolved[0][1];
// if (StringUtil.hasText(pkg)) {
// return pkg+"."+nam;
// } else {
// //No . in front of default package
// return nam;
// }
// }
// } catch (Exception e) {
// Log.log(e);
// }
// return typeName;
// }
//////////////////////////////////////////////////
@@ -179,7 +205,7 @@ public class Type implements YType {
private static void sig2type(String sig, Class<?> cls) {
TYPE_FROM_SIG.put(sig, TypeParser.parse(cls.getName()));
}
@Override
public int hashCode() {
final int prime = 31;

View File

@@ -17,9 +17,11 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.inject.Provider;
@@ -32,7 +34,6 @@ import org.springframework.ide.vscode.commons.java.IJavaElement;
import org.springframework.ide.vscode.commons.java.IJavaProject;
import org.springframework.ide.vscode.commons.java.IMethod;
import org.springframework.ide.vscode.commons.java.IType;
import org.springframework.ide.vscode.commons.java.Signature;
import org.springframework.ide.vscode.commons.util.AlwaysFailingParser;
import org.springframework.ide.vscode.commons.util.ArrayUtils;
import org.springframework.ide.vscode.commons.util.Assert;
@@ -273,27 +274,20 @@ public class TypeUtil {
}
IType type = findType(enumType.getErasure());
if (type!=null && type.isEnum()) {
IField[] fields = type.getFields();
ImmutableList.Builder<StsValueHint> enums = ImmutableList.builder();
boolean addOriginal = caseMode == EnumCaseMode.ORIGNAL || caseMode == EnumCaseMode.ALIASED;
boolean addLowerCased = caseMode == EnumCaseMode.LOWER_CASE || caseMode == EnumCaseMode.ALIASED;
if (fields!=null) {
ImmutableList.Builder<StsValueHint> enums = ImmutableList.builder();
boolean addOriginal = caseMode==EnumCaseMode.ORIGNAL||caseMode==EnumCaseMode.ALIASED;
boolean addLowerCased = caseMode==EnumCaseMode.LOWER_CASE||caseMode==EnumCaseMode.ALIASED;
for (int i = 0; i < fields.length; i++) {
IField f = fields[i];
Provider<HtmlSnippet> jdoc = StsValueHint.javaDocSnippet(f);
if (f.isEnumConstant()) {
String rawName = f.getElementName();
if (addOriginal) {
enums.add(StsValueHint.create(rawName, f));
}
if (addLowerCased) {
enums.add(StsValueHint.create(StringUtil.upperCaseToHyphens(rawName), f));
}
}
type.getFields().filter(f -> f.isEnumConstant()).forEach(f -> {
String rawName = f.getElementName();
if (addOriginal) {
enums.add(StsValueHint.create(rawName, f));
}
return enums.build();
}
if (addLowerCased) {
enums.add(StsValueHint.create(StringUtil.upperCaseToHyphens(rawName), f));
}
});
return enums.build();
}
} catch (Exception e) {
Log.log(e);
@@ -543,7 +537,6 @@ public class TypeUtil {
return findType(beanType.getErasure());
}
private static final String[] NO_PARAMS = new String[0];
private static final Map<String, ValueProviderStrategy> VALUE_HINTERS = new HashMap<>();
static {
valueHints("java.nio.charset.Charset", new LazyProvider<String[]>() {
@@ -622,31 +615,29 @@ public class TypeUtil {
}
} else {
String typename = type.getErasure();
IType eclipseType = findType(typename);
IType typeFromIndex = findType(typename);
//TODO: handle type parameters.
if (eclipseType!=null) {
List<IMethod> getters = getGetterMethods(eclipseType);
//TODO: getters inherited from super classes?
if (getters!=null && !getters.isEmpty()) {
ArrayList<TypedProperty> properties = new ArrayList<>(getters.size());
for (IMethod m : getters) {
Deprecation deprecation = DeprecationUtil.extract(m);
Type propType = null;
try {
propType = Type.fromSignature(m.getReturnType(), eclipseType);
} catch (Exception e) {
Log.log(e);
}
if (beanMode.includesHyphenated()) {
properties.add(new TypedProperty(getterOrSetterNameToProperty(m.getElementName()), propType, deprecation));
}
if (beanMode.includesCamelCase()) {
properties.add(new TypedProperty(getterOrSetterNameToCamelName(m.getElementName()), propType, deprecation));
}
if (typeFromIndex != null) {
ArrayList<TypedProperty> properties = new ArrayList<>();
getGetterMethods(typeFromIndex).forEach(m -> {
Deprecation deprecation = DeprecationUtil.extract(m);
Type propType = null;
try {
propType = Type.fromJavaType(m.getReturnType());
} catch (Exception e) {
Log.log(e);
}
return properties;
}
if (beanMode.includesHyphenated()) {
properties.add(new TypedProperty(getterOrSetterNameToProperty(m.getElementName()), propType,
deprecation));
}
if (beanMode.includesCamelCase()) {
properties.add(new TypedProperty(getterOrSetterNameToCamelName(m.getElementName()), propType,
deprecation));
}
});
return properties;
}
}
return null;
@@ -691,35 +682,24 @@ public class TypeUtil {
return camelName;
}
private List<IMethod> getGetterMethods(IType eclipseType) {
try {
if (eclipseType!=null && eclipseType.isClass()) {
IMethod[] allMethods = eclipseType.getMethods();
if (ArrayUtils.hasElements(allMethods)) {
ArrayList<IMethod> getters = new ArrayList<>();
for (IMethod m : allMethods) {
if (!isStatic(m) && isPublic(m)) {
String mname = m.getElementName();
if (
(mname.startsWith("get") && mname.length()>=4) ||
(mname.startsWith("is") && mname.length()>=3)
) {
//Need at least x chars or the property name will be empty.
String sig = m.getSignature();
int numParams = Signature.getParameterCount(sig);
if (numParams==0) {
getters.add(m);
}
}
private Stream<IMethod> getGetterMethods(IType eclipseType) {
if (eclipseType != null && eclipseType.isClass()) {
return eclipseType.getMethods().filter(m -> {
if (!isStatic(m) && isPublic(m)) {
String mname = m.getElementName();
if ((mname.startsWith("get") && mname.length() >= 4)
|| (mname.startsWith("is") && mname.length() >= 3)) {
// Need at least x chars or the property name will be
// empty.
if (m.parameters().count() == 0) {
return true;
}
}
return getters;
}
}
} catch (Exception e) {
Log.log(e);
return false;
});
}
return null;
return Stream.empty();
}
// private List<IMethod> getSetterMethods(IType eclipseType) {
@@ -818,26 +798,22 @@ public class TypeUtil {
}
public IMethod getSetter(Type beanType, String propName) {
public Optional<IMethod> getSetter(Type beanType, String propName) {
try {
String setterName = "set" + StringUtil.hyphensToCamelCase(propName, true);
IType type = findType(beanType);
for (IMethod m : type.getMethods()) {
if (setterName.equals(m.getElementName())) {
return m;
}
}
return type.getMethods().filter(m -> setterName.equals(m.getElementName())).findFirst();
} catch (Exception e) {
Log.log(e);
}
return null;
return Optional.empty();
}
public IJavaElement getGetter(Type beanType, String propName) {
String getterName = "get" + StringUtil.hyphensToCamelCase(propName, true);
IType type = findType(beanType);
IMethod m = type.getMethod(getterName, NO_PARAMS);
IMethod m = type.getMethod(getterName, Stream.empty());
if (m.exists()) {
return m;
}

View File

@@ -10,12 +10,11 @@
*******************************************************************************/
package org.springframework.ide.vscode.application.properties.metadata.util;
import java.util.Optional;
import org.springframework.boot.configurationmetadata.Deprecation;
import org.springframework.ide.vscode.commons.java.IAnnotatable;
import org.springframework.ide.vscode.commons.java.IAnnotation;
import org.springframework.ide.vscode.commons.java.IJavaElement;
import org.springframework.ide.vscode.commons.java.IMemberValuePair;
import org.springframework.ide.vscode.commons.util.Log;
import com.google.common.collect.ImmutableSet;
@@ -32,36 +31,29 @@ public class DeprecationUtil {
* Extract {@link Deprecation} info from annotations on a {@link IJavaElement}
*/
public static Deprecation extract(IJavaElement je) {
Optional<Deprecation> deprecation = Optional.empty();
if (je instanceof IAnnotatable) {
return extract((IAnnotatable)je);
deprecation = extract((IAnnotatable)je);
}
return null;
return deprecation.isPresent() ? deprecation.get() : null;
}
/**
* Extract {@link Deprecation} info from annotations on a {@link IJavaElement}
*/
private static Deprecation extract(IAnnotatable m) {
try {
for (IAnnotation a : m.getAnnotations()) {
if (DEPRECATED_ANOT_NAMES.contains(a.getElementName())) {
Deprecation d = new Deprecation();
for (IMemberValuePair pair : a.getMemberValuePairs()) {
String name = pair.getMemberName();
if (name.equals("reason")) {
d.setReason((String) pair.getValue());
} else if (name.equals("replacement")) {
d.setReplacement((String) pair.getValue());
}
}
return d;
private static Optional<Deprecation> extract(IAnnotatable m) {
return m.getAnnotations().filter(a -> DEPRECATED_ANOT_NAMES.contains(a.getElementName())).map(a -> {
Deprecation d = new Deprecation();
a.getMemberValuePairs().forEach(pair -> {
String name = pair.getMemberName();
if (name.equals("reason")) {
d.setReason((String) pair.getValue());
} else if (name.equals("replacement")) {
d.setReplacement((String) pair.getValue());
}
}
} catch (Exception e) {
Log.log(e);
}
return null;
});
return d;
}).findFirst();
}
}

View File

@@ -11,10 +11,9 @@
package org.springframework.ide.vscode.boot.properties.metadata;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Stream;
import org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty;
import org.springframework.boot.configurationmetadata.ValueHint;
@@ -88,8 +87,8 @@ public class PropertiesMetadataTestData {
public SpringPropertyIndex createIndex() {
SpringPropertyIndex index = new SpringPropertyIndex(ValueProviderRegistry.getDefault(), new IClasspath() {
@Override
public Collection<Path> getClasspathEntries() throws Exception {
return Collections.emptyList();
public Stream<Path> getClasspathEntries() throws Exception {
return Stream.empty();
}
});
for (ConfigurationMetadataProperty propertyInfo : datas.values()) {

View File

@@ -17,7 +17,6 @@ import static org.junit.Assert.assertNull;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.ide.vscode.application.properties.metadata.types.Type;
import org.springframework.ide.vscode.application.properties.metadata.types.TypeParser;
@@ -31,13 +30,10 @@ import org.springframework.ide.vscode.project.harness.ProjectsHarness;
/**
* Tests for TypeUtil
*
* TODO: {@link IJavaProject#findType(String)} (or IClasspath#findType(String)) needs to be implemented then uncomment the tests!
*
* @author Kris De Volder
* @author Alex Boyko
*
*/
@Ignore
public class TypeUtilTest {
private ProjectsHarness projects = ProjectsHarness.INSTANCE;
@@ -132,14 +128,14 @@ public class TypeUtilTest {
assertEquals(TypeParser.parse(expectedType), actualType);
}
@Test
public void testTypeFromSignature() throws Exception {
useProject("enums-boot-1.3.2-app");
assertType("java.lang.String", Type.fromSignature("QString;", project.findType("demo.ColorData")));
assertType("java.lang.String", Type.fromSignature("Ljava.lang.String;", project.findType("demo.ColorData")));
assertType("java.lang.String[]", Type.fromSignature("[Ljava.lang.String;", project.findType("demo.ColorData")));
assertType("java.lang.String[]", Type.fromSignature("[QString;", project.findType("demo.ColorData")));
}
// @Test
// public void testTypeFromSignature() throws Exception {
// useProject("enums-boot-1.3.2-app");
// assertType("java.lang.String", Type.fromSignature("QString;", project.findType("demo.ColorData")));
// assertType("java.lang.String", Type.fromSignature("Ljava.lang.String;", project.findType("demo.ColorData")));
// assertType("java.lang.String[]", Type.fromSignature("[Ljava.lang.String;", project.findType("demo.ColorData")));
// assertType("java.lang.String[]", Type.fromSignature("[QString;", project.findType("demo.ColorData")));
// }
private void useProject(String name) throws Exception {
project = projects.mavenProject(name);;

View File

@@ -18,5 +18,10 @@
<artifactId>commons-util</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.jboss</groupId>
<artifactId>jandex</artifactId>
<version>2.0.3.Final</version>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,30 @@
package org.springframework.ide.vscode.commons.jandex;
import static org.springframework.ide.vscode.commons.jandex.Wrappers.wrap;
import org.jboss.jandex.ArrayType;
import org.springframework.ide.vscode.commons.java.IArrayType;
import org.springframework.ide.vscode.commons.java.IJavaType;
final class ArrayTypeWrapper extends TypeWrapper<ArrayType> implements IArrayType {
ArrayTypeWrapper(ArrayType type) {
super(type);
}
@Override
public String name() {
return getType().name().toString();
}
@Override
public int dimensions() {
return getType().dimensions();
}
@Override
public IJavaType component() {
return wrap(getType().component());
}
}

View File

@@ -0,0 +1,17 @@
package org.springframework.ide.vscode.commons.jandex;
import org.jboss.jandex.ClassType;
import org.springframework.ide.vscode.commons.java.IClassType;
final class ClassTypeWrapper extends TypeWrapper<ClassType> implements IClassType {
ClassTypeWrapper(ClassType type) {
super(type);
}
@Override
public String name() {
return getType().name().toString();
}
}

View File

@@ -0,0 +1,124 @@
package org.springframework.ide.vscode.commons.jandex;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.jboss.jandex.CompositeIndex;
import org.jboss.jandex.DotName;
import org.jboss.jandex.IndexReader;
import org.jboss.jandex.IndexView;
import org.jboss.jandex.Indexer;
import org.jboss.jandex.JarIndexer;
import org.springframework.ide.vscode.commons.java.IType;
import org.springframework.ide.vscode.commons.util.Log;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
public class JandexIndex {
@FunctionalInterface
public static interface IndexFileFinder {
File findIndexFile(File jarFile);
}
private Supplier<IndexView> index;
public JandexIndex(Stream<Path> classpathEntries) {
this(classpathEntries, jarFile -> null, Optional.empty());
}
public JandexIndex(Stream<Path> classpathEntries, IndexFileFinder indexFileFinder) {
this(classpathEntries, indexFileFinder, Optional.empty());
}
public JandexIndex(Stream<Path> classpathEntries, Optional<JandexIndex> baseIndex) {
this(classpathEntries, jarFile -> null, baseIndex);
}
public JandexIndex(Stream<Path> classpathEntries, IndexFileFinder indexFileFinder, Optional<JandexIndex> baseIndex) {
index = Suppliers.memoize(() -> {
if (baseIndex.isPresent()) {
return CompositeIndex.create(baseIndex.get().index.get(), buildIndex(classpathEntries, indexFileFinder));
} else {
return buildIndex(classpathEntries, indexFileFinder);
}
});
}
private static CompositeIndex buildIndex(Stream<Path> classpathEntries, IndexFileFinder indexFileFinder) {
return CompositeIndex.create(classpathEntries
.map(entry -> entry.toFile())
.map(file -> {
if (file.isFile() && file.getName().endsWith(".jar")) {
return indexJar(file, indexFileFinder);
} else if (file.isDirectory()) {
return indexFolder(file);
} else {
return Optional.<IndexView>empty();
}
})
.filter(o -> o.isPresent())
.map(o -> o.get())
.collect(Collectors.toList()));
}
private static Optional<IndexView> indexFolder(File folder) {
Indexer indexer = new Indexer();
for (Iterator<File> itr = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder).iterator(); itr.hasNext();) {
File file = itr.next();
if (file.isFile() && file.getName().endsWith(".class")) {
try {
final InputStream stream = new FileInputStream(file);
try {
indexer.index(stream);
} finally {
try {
stream.close();
} catch (Exception ignore) {
}
}
} catch (Exception e) {
Log.log(e);
}
}
}
return Optional.of(indexer.complete());
}
private static Optional<IndexView> indexJar(File file, IndexFileFinder indexFileFinder) {
try {
File indexFile = indexFileFinder.findIndexFile(file);
if (indexFile != null) {
if (indexFile.createNewFile()) {
return Optional.of(JarIndexer
.createJarIndex(file, new Indexer(), indexFile,
false, false, true, System.out, System.err)
.getIndex());
} else {
return Optional.of(new IndexReader(new FileInputStream(indexFile)).read());
}
} else {
return Optional.of(JarIndexer
.createJarIndex(file, new Indexer(), file.canWrite(), file.getParentFile().canWrite(), true)
.getIndex());
}
} catch (IOException e) {
Log.log(e);
}
return Optional.empty();
}
public IType findType(String fqName) {
IndexView compositeIndex = index.get();
return Wrappers.wrap(compositeIndex, compositeIndex.getClassByName(DotName.createSimple(fqName)));
}
}

View File

@@ -0,0 +1,31 @@
package org.springframework.ide.vscode.commons.jandex;
import static org.springframework.ide.vscode.commons.jandex.Wrappers.wrap;
import java.util.stream.Stream;
import org.jboss.jandex.ParameterizedType;
import org.springframework.ide.vscode.commons.java.IJavaType;
import org.springframework.ide.vscode.commons.java.IParameterizedType;
final class ParameterizedTypeWrapper extends TypeWrapper<ParameterizedType> implements IParameterizedType {
ParameterizedTypeWrapper(ParameterizedType type) {
super(type);
}
@Override
public String name() {
return getType().name().toString();
}
@Override
public IJavaType owner() {
return wrap(getType().owner());
}
@Override
public Stream<IJavaType> arguments() {
return getType().arguments().stream().map(Wrappers::wrap);
}
}

View File

@@ -0,0 +1,17 @@
package org.springframework.ide.vscode.commons.jandex;
import org.jboss.jandex.TypeVariable;
import org.springframework.ide.vscode.commons.java.ITypeVariable;
final class TypeVariableWrapper extends TypeWrapper<TypeVariable> implements ITypeVariable {
TypeVariableWrapper(TypeVariable type) {
super(type);
}
@Override
public String name() {
return getType().name().toString();
}
}

View File

@@ -0,0 +1,34 @@
package org.springframework.ide.vscode.commons.jandex;
class TypeWrapper<T> {
private T type;
TypeWrapper(T type) {
this.type = type;
}
T getType() {
return type;
}
@Override
public int hashCode() {
return type.hashCode();
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object obj) {
if (obj instanceof TypeWrapper) {
return type.equals(((TypeWrapper<T>)obj).type);
}
return super.equals(obj);
}
@Override
public String toString() {
return type.toString();
}
}

View File

@@ -0,0 +1,17 @@
package org.springframework.ide.vscode.commons.jandex;
import org.jboss.jandex.UnresolvedTypeVariable;
import org.springframework.ide.vscode.commons.java.IUnresolvedTypeVariable;
final class UnresolvedTypeVariableWrapper extends TypeWrapper<UnresolvedTypeVariable> implements IUnresolvedTypeVariable {
UnresolvedTypeVariableWrapper(UnresolvedTypeVariable type) {
super(type);
}
@Override
public String name() {
return getType().name().toString();
}
}

View File

@@ -0,0 +1,17 @@
package org.springframework.ide.vscode.commons.jandex;
import org.jboss.jandex.WildcardType;
import org.springframework.ide.vscode.commons.java.IWildcardType;
final class WildcardTypeWrapper extends TypeWrapper<WildcardType> implements IWildcardType {
WildcardTypeWrapper(WildcardType type) {
super(type);
}
@Override
public String name() {
throw new UnsupportedOperationException("Not yet implemented");
}
}

View File

@@ -0,0 +1,350 @@
package org.springframework.ide.vscode.commons.jandex;
import static org.springframework.ide.vscode.commons.util.Assert.isNotNull;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationValue;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.FieldInfo;
import org.jboss.jandex.IndexView;
import org.jboss.jandex.MethodInfo;
import org.jboss.jandex.PrimitiveType;
import org.jboss.jandex.Type;
import org.springframework.ide.vscode.commons.java.IAnnotation;
import org.springframework.ide.vscode.commons.java.IField;
import org.springframework.ide.vscode.commons.java.IJavaType;
import org.springframework.ide.vscode.commons.java.IMemberValuePair;
import org.springframework.ide.vscode.commons.java.IMethod;
import org.springframework.ide.vscode.commons.java.IPrimitiveType;
import org.springframework.ide.vscode.commons.java.IType;
import org.springframework.ide.vscode.commons.java.IVoidType;
import org.springframework.ide.vscode.commons.util.HtmlSnippet;
public class Wrappers {
private static final int AccEnum = 0x4000;
public static IType wrap(IndexView index, ClassInfo info) {
if (info == null) {
return null;
}
return new IType() {
@Override
public int getFlags() {
return info.flags();
}
@Override
public IType getDeclaringType() {
DotName enclosingClass = info.enclosingClass();
return enclosingClass == null ? null : wrap(index, index.getClassByName(enclosingClass));
}
@Override
public String getElementName() {
return info.simpleName();
}
@Override
public HtmlSnippet getJavaDoc() {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public boolean exists() {
return true;
}
@Override
public Stream<IAnnotation> getAnnotations() {
// TODO: check correctness!
return info.annotations().get(info.name()).stream().map(Wrappers::wrap);
}
@Override
public boolean isClass() {
return true;
}
@Override
public boolean isEnum() {
return (info.flags() & AccEnum) != 0;
}
@Override
public boolean isInterface() {
return false;
}
@Override
public String getFullyQualifiedName() {
return info.name().toString();
}
@Override
public IField getField(String name) {
return wrap(index, info.field(name));
}
@Override
public Stream<IField> getFields() {
return info.fields().stream().map(f -> {
return wrap(index, f);
});
}
@Override
public IMethod getMethod(String name, Stream<IJavaType> parameters) {
List<Type> typeParameters = parameters.map(Wrappers::from).collect(Collectors.toList());
return wrap(index, info.method(name, typeParameters.toArray(new Type[typeParameters.size()])));
}
@Override
public Stream<IMethod> getMethods() {
return info.methods().stream().map(m -> {
return wrap(index, m);
});
}
@Override
public String toString() {
return info.toString();
}
};
}
public static IField wrap(IndexView index, FieldInfo field) {
if (field == null) {
return null;
}
return new IField() {
@Override
public int getFlags() {
return field.flags();
}
@Override
public IType getDeclaringType() {
return wrap(index, field.declaringClass());
}
@Override
public String getElementName() {
return field.name();
}
@Override
public HtmlSnippet getJavaDoc() {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public boolean exists() {
return true;
}
@Override
public Stream<IAnnotation> getAnnotations() {
return field.annotations().stream().map(a -> {
return wrap(a);
});
}
@Override
public boolean isEnumConstant() {
return (field.flags() & AccEnum) != 0;
}
@Override
public String toString() {
return field.toString();
}
};
}
public static IMethod wrap(IndexView index, MethodInfo method) {
isNotNull(index);
isNotNull(method);
return new IMethod() {
@Override
public int getFlags() {
return method.flags();
}
@Override
public IType getDeclaringType() {
return wrap(index, method.declaringClass());
}
@Override
public String getElementName() {
return method.name();
}
@Override
public HtmlSnippet getJavaDoc() {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public boolean exists() {
return true;
}
@Override
public Stream<IAnnotation> getAnnotations() {
return method.annotations().stream().map(Wrappers::wrap);
}
@Override
public IJavaType getReturnType() {
return wrap(method.returnType());
}
// @Override
// public String getSignature() {
// StringBuilder sb = new StringBuilder();
// sb.append('(');
// method.parameters().forEach(p -> sb.append(signature(p)));
// sb.append(')');
// sb.append(getReturnType());
// return sb.toString();
// }
@Override
public String toString() {
return method.toString();
}
@Override
public Stream<IJavaType> parameters() {
return method.parameters().stream().map(Wrappers::wrap);
}
};
}
public static IAnnotation wrap(AnnotationInstance annotation) {
isNotNull(annotation);
return new IAnnotation() {
@Override
public String getElementName() {
return annotation.name().toString();
}
@Override
public HtmlSnippet getJavaDoc() {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public boolean exists() {
return true;
}
@Override
public Stream<IMemberValuePair> getMemberValuePairs() {
return annotation.values().stream().map(av -> {
return wrap(av);
});
}
@Override
public String toString() {
return annotation.toString();
}
};
}
public static IMemberValuePair wrap(AnnotationValue annotationValue) {
if (annotationValue == null) {
return null;
}
return new IMemberValuePair() {
@Override
public String getMemberName() {
return annotationValue.name();
}
@Override
public Object getValue() {
return annotationValue.value();
}
@Override
public String toString() {
return annotationValue.toString();
}
};
}
public static Type createParameterTypeFromSignature(IndexView index, String signature) {
if (signature == null) {
return null;
}
throw new UnsupportedOperationException("Not yet implemented");
}
public static IPrimitiveType wrap(PrimitiveType type) {
switch (type.primitive()) {
case SHORT:
return IPrimitiveType.SHORT;
case LONG:
return IPrimitiveType.LONG;
case BYTE:
return IPrimitiveType.BYTE;
case DOUBLE:
return IPrimitiveType.DOUBLE;
case BOOLEAN:
return IPrimitiveType.BOOLEAN;
case CHAR:
return IPrimitiveType.CHAR;
case FLOAT:
return IPrimitiveType.FLOAT;
case INT:
return IPrimitiveType.INT;
}
throw new IllegalArgumentException("Invalid Java primitive type! " + type.toString());
}
@SuppressWarnings("unchecked")
private static Type from(IJavaType type) {
if (type instanceof TypeWrapper) {
return ((TypeWrapper<Type>)type).getType();
}
throw new IllegalArgumentException("Not a Jandex wrapped typed!");
}
public static IJavaType wrap(Type type) {
switch (type.kind()) {
case ARRAY:
return new ArrayTypeWrapper(type.asArrayType());
case CLASS:
return new ClassTypeWrapper(type.asClassType());
case PARAMETERIZED_TYPE:
return new ParameterizedTypeWrapper(type.asParameterizedType());
case PRIMITIVE:
return wrap(type.asPrimitiveType());
case TYPE_VARIABLE:
return new TypeVariableWrapper(type.asTypeVariable());
case UNRESOLVED_TYPE_VARIABLE:
return new UnresolvedTypeVariableWrapper(type.asUnresolvedTypeVariable());
case VOID:
return IVoidType.DEFAULT;
case WILDCARD_TYPE:
return new WildcardTypeWrapper(type.asWildcardType());
}
throw new IllegalArgumentException("Invalid Java Type " + type.toString());
}
}

View File

@@ -1,7 +1,9 @@
package org.springframework.ide.vscode.commons.java;
import java.util.stream.Stream;
public interface IAnnotatable extends IJavaElement {
IAnnotation[] getAnnotations();
Stream<IAnnotation> getAnnotations();
}

View File

@@ -1,5 +1,7 @@
package org.springframework.ide.vscode.commons.java;
import java.util.stream.Stream;
public interface IAnnotation extends IJavaElement {
/**
@@ -10,6 +12,6 @@ public interface IAnnotation extends IJavaElement {
*
* @return the member-value pairs of this annotation
*/
IMemberValuePair[] getMemberValuePairs();
Stream<IMemberValuePair> getMemberValuePairs();
}

View File

@@ -0,0 +1,9 @@
package org.springframework.ide.vscode.commons.java;
public interface IArrayType extends IJavaType {
int dimensions();
IJavaType component();
}

View File

@@ -0,0 +1,5 @@
package org.springframework.ide.vscode.commons.java;
public interface IClassType extends IJavaType {
}

View File

@@ -1,33 +1,33 @@
/*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.vscode.commons.java;
import java.nio.file.Path;
import java.util.Collection;
/**
* Classpath for a Java artifact
*
* @author Kris De Volder
* @author Alex Boyko
*
*/
public interface IClasspath {
/**
* Classpath entries paths
*
* @return collection of classpath entries in a form file/folder paths
* @throws Exception
*/
Collection<Path> getClasspathEntries() throws Exception;
}
/*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.vscode.commons.java;
import java.nio.file.Path;
import java.util.stream.Stream;
/**
* Classpath for a Java artifact
*
* @author Kris De Volder
* @author Alex Boyko
*
*/
public interface IClasspath {
/**
* Classpath entries paths
*
* @return collection of classpath entries in a form file/folder paths
* @throws Exception
*/
Stream<Path> getClasspathEntries() throws Exception;
}

View File

@@ -0,0 +1,7 @@
package org.springframework.ide.vscode.commons.java;
public interface IJavaType {
String name();
}

View File

@@ -1,5 +1,7 @@
package org.springframework.ide.vscode.commons.java;
import java.util.stream.Stream;
public interface IMethod extends IMember {
/**
@@ -20,28 +22,34 @@ public interface IMethod extends IMember {
* @return the type signature of the return value of this method, void for constructors
* @see Signature
*/
String getReturnType();
IJavaType getReturnType();
// /**
// * Returns the signature of this method. This includes the signatures for the
// * parameter types and return type, but does not include the method name,
// * exception types, or type parameters.
// * <p>
// * For example, a source method declared as <code>public void foo(String text, int length)</code>
// * would return <code>"(QString;I)V"</code>.
// * </p>
// * <p>
// * The type signatures embedded in the method signature may be either unresolved
// * (for source types) or resolved (for binary types), and either basic (for
// * basic types) or rich (for parameterized types). See {@link Signature} for
// * details.
// * </p>
// *
// * @return the signature of this method
// * @exception JavaModelException if this element does not exist or if an
// * exception occurs while accessing its corresponding resource.
// * @see Signature
// */
// String getSignature();
/**
* Returns the signature of this method. This includes the signatures for the
* parameter types and return type, but does not include the method name,
* exception types, or type parameters.
* <p>
* For example, a source method declared as <code>public void foo(String text, int length)</code>
* would return <code>"(QString;I)V"</code>.
* </p>
* <p>
* The type signatures embedded in the method signature may be either unresolved
* (for source types) or resolved (for binary types), and either basic (for
* basic types) or rich (for parameterized types). See {@link Signature} for
* details.
* </p>
*
* @return the signature of this method
* @exception JavaModelException if this element does not exist or if an
* exception occurs while accessing its corresponding resource.
* @see Signature
* Returns parameter types of this method
* @return
*/
String getSignature();
Stream<IJavaType> parameters();
}

View File

@@ -0,0 +1,11 @@
package org.springframework.ide.vscode.commons.java;
import java.util.stream.Stream;
public interface IParameterizedType extends IJavaType {
IJavaType owner();
Stream<IJavaType> arguments();
}

View File

@@ -0,0 +1,21 @@
package org.springframework.ide.vscode.commons.java;
public interface IPrimitiveType extends IJavaType {
static IPrimitiveType INT = () -> "I";
static IPrimitiveType BOOLEAN = () -> "Z";
static IPrimitiveType CHAR = () -> "C";
static IPrimitiveType FLOAT = () -> "F";
static IPrimitiveType BYTE = () -> "B";
static IPrimitiveType DOUBLE = () -> "D";
static IPrimitiveType LONG = () -> "J";
static IPrimitiveType SHORT = () -> "S";
}

View File

@@ -13,6 +13,8 @@
*******************************************************************************/
package org.springframework.ide.vscode.commons.java;
import java.util.stream.Stream;
/**
* Replaces eclipse JDT IType.
*/
@@ -56,7 +58,7 @@ public interface IType extends IMember {
*
* @return the fields declared by this type
*/
IField[] getFields();
Stream<IField> getFields();
/**
* Returns the method with the specified name and parameter types
@@ -76,7 +78,7 @@ public interface IType extends IMember {
* @param parameterTypeSignatures the given parameter types
* @return the method with the specified name and parameter types in this type
*/
IMethod getMethod(String name, String[] parameterTypeSignatures);
IMethod getMethod(String name, Stream<IJavaType> parameters);
/**
* Returns the methods and constructors declared by this type.
@@ -88,33 +90,33 @@ public interface IType extends IMember {
*
* @return the methods and constructors declared by this type
*/
IMethod[] getMethods();
Stream<IMethod> getMethods();
/**
* Resolves the given type name within the context of this type (depending on the type hierarchy
* and its imports).
* <p>
* Multiple answers might be found in case there are ambiguous matches.
* </p>
* <p>
* Each matching type name is decomposed as an array of two strings, the first denoting the package
* name (dot-separated) and the second being the type name. The package name is empty if it is the
* default package. The type name is the type qualified name using a '.' enclosing type separator.
* </p>
* <p>
* Returns <code>null</code> if unable to find any matching type.
* </p>
*<p>
* For example, resolution of <code>"Object"</code> would typically return
* <code>{{"java.lang", "Object"}}</code>. Another resolution that returns
* <code>{{"", "X.Inner"}}</code> represents the inner type Inner defined in type X in the
* default package.
* </p>
*
* @param typeName the given type name
* @return the resolved type names or <code>null</code> if unable to find any matching type
* @see #getTypeQualifiedName(char)
*/
String[][] resolveType(String typeName);
// /**
// * Resolves the given type name within the context of this type (depending on the type hierarchy
// * and its imports).
// * <p>
// * Multiple answers might be found in case there are ambiguous matches.
// * </p>
// * <p>
// * Each matching type name is decomposed as an array of two strings, the first denoting the package
// * name (dot-separated) and the second being the type name. The package name is empty if it is the
// * default package. The type name is the type qualified name using a '.' enclosing type separator.
// * </p>
// * <p>
// * Returns <code>null</code> if unable to find any matching type.
// * </p>
// *<p>
// * For example, resolution of <code>"Object"</code> would typically return
// * <code>{{"java.lang", "Object"}}</code>. Another resolution that returns
// * <code>{{"", "X.Inner"}}</code> represents the inner type Inner defined in type X in the
// * default package.
// * </p>
// *
// * @param typeName the given type name
// * @return the resolved type names or <code>null</code> if unable to find any matching type
// * @see #getTypeQualifiedName(char)
// */
// String[][] resolveType(String typeName);
}

View File

@@ -0,0 +1,5 @@
package org.springframework.ide.vscode.commons.java;
public interface ITypeVariable extends IJavaType {
}

View File

@@ -0,0 +1,5 @@
package org.springframework.ide.vscode.commons.java;
public interface IUnresolvedTypeVariable extends IJavaType {
}

View File

@@ -0,0 +1,14 @@
package org.springframework.ide.vscode.commons.java;
public interface IVoidType extends IJavaType {
static IVoidType DEFAULT = new IVoidType() {
@Override
public String name() {
return "V";
}
};
}

View File

@@ -0,0 +1,5 @@
package org.springframework.ide.vscode.commons.java;
public interface IWildcardType extends IJavaType {
}

View File

@@ -1,5 +1,7 @@
package org.springframework.ide.vscode.commons.languageserver.reconcile;
import org.springframework.ide.vscode.commons.languageserver.util.DocumentRegion;
/**
* An implementation of {@link ReconcileProblem} that is just a simple data object.
*
@@ -45,4 +47,24 @@ public class ReconcileProblemImpl implements ReconcileProblem {
return getType().getCode();
}
/**
* Attempt to enlarge a empty document region to include a
* character that can be visibly underlined.
*/
protected static DocumentRegion makeVisible(DocumentRegion region) {
DocumentRegion altRegion = region.textAfter(1);
if (!altRegion.isEmpty() && canUnderline(altRegion.charAt(0))) {
return altRegion;
}
altRegion = region.textBefore(1);
if (!altRegion.isEmpty() && canUnderline(altRegion.charAt(0))) {
return altRegion;
}
return region;
}
private static boolean canUnderline(char c) {
return c!='\n'&&c!='\r';
}
}

View File

@@ -17,13 +17,16 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.maven.RepositoryUtils;
import org.apache.maven.artifact.Artifact;
@@ -46,8 +49,13 @@ import org.eclipse.aether.util.graph.transformer.NearestVersionSelector;
import org.eclipse.aether.util.graph.transformer.SimpleOptionalitySelector;
import org.eclipse.aether.util.graph.visitor.CloningDependencyVisitor;
import org.eclipse.aether.util.graph.visitor.FilteringDependencyVisitor;
import org.springframework.ide.vscode.commons.jandex.JandexIndex;
import org.springframework.ide.vscode.commons.util.ExternalCommand;
import org.springframework.ide.vscode.commons.util.ExternalProcess;
import org.springframework.ide.vscode.commons.util.Log;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
/**
* Maven Core functionality
@@ -57,6 +65,10 @@ import org.springframework.ide.vscode.commons.util.ExternalProcess;
*/
public class MavenCore {
public static final String JAVA_IO_TMPDIR = "java.io.tmpdir";
private static final String JAVA_HOME = "java.home";
private static final String JAVA_RUNTIME_VERSION = "java.runtime.version";
private static final String JAVA_BOOT_CLASS_PATH = "sun.boot.class.path";
public static final String CLASSPATH_TXT = "classpath.txt";
public static final String POM_XML = "pom.xml";
@@ -64,6 +76,14 @@ public class MavenCore {
private MavenBridge maven = new MavenBridge();
private Supplier<Optional<JandexIndex>> javaCoreIndex = Suppliers.memoize(() -> {
try {
return Optional.of(new JandexIndex(getJreLibs(), jarFile -> findIndexFile(jarFile)));
} catch (MavenException e) {
return Optional.empty();
}
});
public static MavenCore getInstance() {
if (instance == null) {
instance = new MavenCore();
@@ -78,11 +98,11 @@ public class MavenCore {
* @return set of classpath entries
* @throws IOException
*/
public static Set<Path> readClassPathFile(Path classPathFilePath) throws IOException {
public static Stream<Path> readClassPathFile(Path classPathFilePath) throws IOException {
InputStream in = Files.newInputStream(classPathFilePath);
String text = new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining());
Path dir = classPathFilePath.getParent();
return Arrays.stream(text.split(File.pathSeparator)).map(dir::resolve).collect(Collectors.toSet());
return Arrays.stream(text.split(File.pathSeparator)).map(dir::resolve);
}
/**
@@ -96,7 +116,7 @@ public class MavenCore {
? testProjectPath.resolve("mvnw.cmd") : testProjectPath.resolve("mvnw");
mvnwPath.toFile().setExecutable(true);
ExternalProcess process = new ExternalProcess(testProjectPath.toFile(),
new ExternalCommand(mvnwPath.toAbsolutePath().toString(), "clean", "package"), true);
new ExternalCommand(mvnwPath.toAbsolutePath().toString(), "clean", "package", "-DskipTests"), true);
if (process.getExitValue() != 0) {
throw new RuntimeException("Failed to build test project");
}
@@ -214,4 +234,33 @@ public class MavenCore {
return artifacts;
}
public Stream<Path> getJreLibs() throws MavenException {
String s = (String) maven.createExecutionRequest().getSystemProperties().get(JAVA_BOOT_CLASS_PATH);
return Arrays.stream(s.split(File.pathSeparator)).map(File::new).filter(f -> f.canRead()).map(f -> Paths.get(f.toURI()));
}
private String getJavaRuntimeVersion() throws MavenException {
return maven.createExecutionRequest().getSystemProperties().getProperty(JAVA_RUNTIME_VERSION);
}
private String getJavaHome() throws MavenException {
return maven.createExecutionRequest().getSystemProperties().getProperty(JAVA_HOME);
}
private File findIndexFile(File jarFile) {
String suffix = null;
try {
if (jarFile.toString().startsWith(getJavaHome())) {
suffix = getJavaRuntimeVersion();
}
} catch (MavenException e) {
Log.log(e);
}
return new File(System.getProperty(JAVA_IO_TMPDIR), jarFile.getName() + suffix);
}
public Optional<JandexIndex> getJavaIndexForJreLibs() {
return javaCoreIndex.get();
}
}

View File

@@ -56,8 +56,7 @@ public class MavenJavaProject implements IJavaProject {
@Override
public IType findType(String fqName) {
// TODO Auto-generated method stub
return null;
return classpath.findType(fqName);
}
@Override

View File

@@ -1,54 +1,74 @@
/*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.vscode.commons.maven.java;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.maven.project.MavenProject;
import org.springframework.ide.vscode.commons.java.IClasspath;
import org.springframework.ide.vscode.commons.maven.MavenCore;
/**
* Classpath for a maven project
*
* @author Alex Boyko
*
*/
public class MavenProjectClasspath implements IClasspath {
private MavenCore maven;
private MavenProject project;
public MavenProjectClasspath(MavenProject project) {
this(project, MavenCore.getInstance());
}
MavenProjectClasspath(MavenProject project, MavenCore maven) {
this.maven = maven;
this.project = project;
}
@Override
public Collection<Path> getClasspathEntries() throws Exception {
List<Path> entries = maven.resolveDependencies(project, null).stream().map(artifact -> {
return Paths.get(artifact.getFile().toURI());
}).collect(Collectors.toList());
entries.add(Paths.get(new File(project.getBuild().getOutputDirectory()).toURI()));
entries.add(Paths.get(new File(project.getBuild().getTestOutputDirectory()).toURI()));
return entries;
}
}
/*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.vscode.commons.maven.java;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
import org.apache.maven.project.MavenProject;
import org.springframework.ide.vscode.commons.jandex.JandexIndex;
import org.springframework.ide.vscode.commons.java.IClasspath;
import org.springframework.ide.vscode.commons.java.IType;
import org.springframework.ide.vscode.commons.maven.MavenCore;
import org.springframework.ide.vscode.commons.util.Log;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
/**
* Classpath for a maven project
*
* @author Alex Boyko
*
*/
public class MavenProjectClasspath implements IClasspath {
private MavenCore maven;
private MavenProject project;
private Supplier<JandexIndex> javaIndex;
public MavenProjectClasspath(MavenProject project) {
this(project, MavenCore.getInstance());
}
MavenProjectClasspath(MavenProject project, MavenCore maven) {
this.maven = maven;
this.project = project;
this.javaIndex = Suppliers.memoize(() -> {
Stream<Path> classpathEntries = Stream.empty();
try {
classpathEntries = getClasspathEntries();
} catch (Exception e) {
Log.log(e);
}
return new JandexIndex(classpathEntries, jarFile -> findIndexFile(jarFile), maven.getJavaIndexForJreLibs());
});
}
@Override
public Stream<Path> getClasspathEntries() throws Exception {
return Stream.concat(maven.resolveDependencies(project, null).stream().map(artifact -> {
return Paths.get(artifact.getFile().toURI());
}), Stream.of(Paths.get(new File(project.getBuild().getOutputDirectory()).toURI()),
Paths.get(new File(project.getBuild().getTestOutputDirectory()).toURI())));
}
public IType findType(String fqName) {
return javaIndex.get().findType(fqName);
}
private File findIndexFile(File jarFile) {
return new File(System.getProperty(MavenCore.JAVA_IO_TMPDIR), jarFile.getName() + jarFile.lastModified());
}
}

View File

@@ -1,42 +1,40 @@
/*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.vscode.commons.maven.java.classpathfile;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Set;
import org.springframework.ide.vscode.commons.java.IClasspath;
import org.springframework.ide.vscode.commons.maven.MavenCore;
/**
* Classpath for a project containing classpath text file
*
* @author Alex Boyko
*
*/
public class FileClasspath implements IClasspath {
private Path classpathFilePath;
public FileClasspath(Path classpathFilePath) {
this.classpathFilePath = classpathFilePath;
}
@Override
public Collection<Path> getClasspathEntries() throws Exception {
Set<Path> entries = MavenCore.readClassPathFile(classpathFilePath);
entries.add(classpathFilePath.getParent().resolve("target/classes"));
entries.add(classpathFilePath.getParent().resolve("target/test-classes"));
return entries;
}
}
/*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.vscode.commons.maven.java.classpathfile;
import java.nio.file.Path;
import java.util.stream.Stream;
import org.springframework.ide.vscode.commons.java.IClasspath;
import org.springframework.ide.vscode.commons.maven.MavenCore;
/**
* Classpath for a project containing classpath text file
*
* @author Alex Boyko
*
*/
public class FileClasspath implements IClasspath {
private Path classpathFilePath;
public FileClasspath(Path classpathFilePath) {
this.classpathFilePath = classpathFilePath;
}
@Override
public Stream<Path> getClasspathEntries() throws Exception {
return Stream.concat(MavenCore.readClassPathFile(classpathFilePath),
Stream.of(classpathFilePath.getParent().resolve("target/classes"),
classpathFilePath.getParent().resolve("target/test-classes")));
}
}

View File

@@ -28,9 +28,8 @@ import org.junit.Test;
*/
public class DependencyTreeTest {
@Test
public void mavenTest() throws Exception {
Path testProjectPath = Paths.get(DependencyTreeTest.class.getResource("/empty-boot-project-with-classpath-file").toURI());
private void testMavenClasspath(String projectName) throws Exception {
Path testProjectPath = Paths.get(DependencyTreeTest.class.getResource("/" + projectName).toURI());
MavenCore.buildMavenProject(testProjectPath);
MavenProject project = MavenCore.getInstance().readProject(testProjectPath.resolve(MavenCore.POM_XML).toFile());
@@ -38,8 +37,18 @@ public class DependencyTreeTest {
return Paths.get(artifact.getFile().toURI());
}).collect(Collectors.toSet());;
Set<Path> expectedClasspath = MavenCore.readClassPathFile(testProjectPath.resolve(MavenCore.CLASSPATH_TXT));
Set<Path> expectedClasspath = MavenCore.readClassPathFile(testProjectPath.resolve(MavenCore.CLASSPATH_TXT)).collect(Collectors.toSet());
assertEquals(expectedClasspath, calculatedClassPath);
}
@Test
public void mavenClasspathTest_1() throws Exception {
testMavenClasspath("empty-boot-project-with-classpath-file");
}
@Test
public void mavenClasspathTest_2() throws Exception {
testMavenClasspath("gs-rest-service-cors-boot-1.4.1-with-classpath-file");
}
}

View File

@@ -0,0 +1,65 @@
package org.springframework.ide.vscode.commons.maven;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
import org.junit.Test;
import org.springframework.ide.vscode.commons.java.IMethod;
import org.springframework.ide.vscode.commons.java.IType;
import org.springframework.ide.vscode.commons.java.IVoidType;
import org.springframework.ide.vscode.commons.maven.java.MavenJavaProject;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
public class JavaIndexTest {
private static LoadingCache<String, MavenJavaProject> projectsCache = CacheBuilder.newBuilder().build(new CacheLoader<String, MavenJavaProject>() {
@Override
public MavenJavaProject load(String projectName) throws Exception {
Path testProjectPath = Paths.get(DependencyTreeTest.class.getResource("/" + projectName).toURI());
MavenCore.buildMavenProject(testProjectPath);
return new MavenJavaProject(testProjectPath.resolve(MavenCore.POM_XML).toFile());
}
});
@Test
public void findClassInJar() throws Exception {
MavenJavaProject project = projectsCache.get("gs-rest-service-cors-boot-1.4.1-with-classpath-file");
IType type = project.findType("org.springframework.test.web.client.ExpectedCount");
assertNotNull(type);
}
@Test
public void findClassInOutputFolder() throws Exception {
MavenJavaProject project = projectsCache.get("gs-rest-service-cors-boot-1.4.1-with-classpath-file");
IType type = project.findType("hello.Greeting");
assertNotNull(type);
}
@Test
public void classNotFound() throws Exception {
MavenJavaProject project = projectsCache.get("gs-rest-service-cors-boot-1.4.1-with-classpath-file");
IType type = project.findType("hello.NonExistentClass");
assertNull(type);
}
@Test
public void voidMethodNoParams() throws Exception {
MavenJavaProject project = projectsCache.get("gs-rest-service-cors-boot-1.4.1-with-classpath-file");
IType type = project.findType("java.util.ArrayList");
assertNotNull(type);
IMethod m = type.getMethod("clear", Stream.empty());
assertEquals("clear", m.getElementName());
assertEquals(IVoidType.DEFAULT, m.getReturnType());
assertEquals(0, m.parameters().count());
}
}

View File

@@ -0,0 +1,24 @@
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/

View File

@@ -0,0 +1 @@
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip

View File

@@ -0,0 +1,30 @@
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.1.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'spring-boot'
jar {
baseName = 'gs-rest-service-cors'
version = '0.1.0'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
testCompile("org.springframework.boot:spring-boot-starter-test")
testCompile("org.apache.httpcomponents:httpclient:4.5.2")
}

View File

@@ -0,0 +1,6 @@
#Mon Aug 29 13:08:17 CDT 2016
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.13-bin.zip

View File

@@ -0,0 +1,160 @@
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

View File

@@ -0,0 +1,90 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1,11 @@
---
applications:
- name: rest-service-guides
memory: 256M
instances: 1
random-route: true
domain: cfapps.io
timeout: 180
buildpack: java_buildpack
# For Maven target/gs-rest-service-cors-0.1.0.jar
path: build/libs/gs-rest-service-cors-0.1.0.jar

View File

@@ -0,0 +1,233 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
#
# Look for the Apple JDKs first to preserve the existing behaviour, and then look
# for the new JDKs provided by Oracle.
#
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then
#
# Oracle JDKs
#
export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then
#
# Apple JDKs
#
export JAVA_HOME=`/usr/libexec/java_home`
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Migwn, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
fi
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
local basedir=$(pwd)
local wdir=$(pwd)
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
wdir=$(cd "$wdir/.."; pwd)
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)}
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} "$@"

View File

@@ -0,0 +1,145 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
set MAVEN_CMD_LINE_ARGS=%*
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar""
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS%
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

View File

@@ -0,0 +1,64 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>gs-rest-service-cors</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>build-classpath</id>
<phase>generate-sources</phase>
<goals>
<goal>build-classpath</goal>
</goals>
</execution>
</executions>
<configuration>
<outputFile>classpath.txt</outputFile>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,9 @@
$(document).ready(function() {
$.ajax({
url: "http://localhost:8080/greeting"
}).then(function(data, status, jqxhr) {
$('.greeting-id').append(data.id);
$('.greeting-content').append(data.content);
console.log(jqxhr);
});
});

View File

@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html>
<head>
<title>Hello CORS</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="hello.js"></script>
</head>
<body>
<div>
<p class="greeting-id">The ID is </p>
<p class="greeting-content">The content is </p>
</div>
</body>
</html>

View File

@@ -0,0 +1,27 @@
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000");
}
};
}
}

View File

@@ -0,0 +1,25 @@
package hello;
public class Greeting {
private final long id;
private final String content;
public Greeting() {
this.id = -1;
this.content = "";
}
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}

View File

@@ -0,0 +1,29 @@
package hello;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@CrossOrigin(origins = "http://localhost:9000")
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) {
System.out.println("==== in greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
@GetMapping("/greeting-javaconfig")
public Greeting greetingWithJavaconfig(@RequestParam(required=false, defaultValue="World") String name) {
System.out.println("==== in greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
}

View File

@@ -0,0 +1,49 @@
package hello;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class GreetingIntegrationTests {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void corsWithAnnotation() {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ORIGIN, "http://localhost:9000");
HttpEntity<?> requestEntity = new HttpEntity(headers);
ResponseEntity<Greeting> entity = this.restTemplate.exchange("/greeting", HttpMethod.GET, requestEntity, Greeting.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("http://localhost:9000", entity.getHeaders().getAccessControlAllowOrigin());
Greeting greeting = entity.getBody();
assertEquals("Hello, World!", greeting.getContent());
}
@Test
public void corsWithJavaconfig() {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ORIGIN, "http://localhost:9000");
HttpEntity<?> requestEntity = new HttpEntity(headers);
ResponseEntity<Greeting> entity = this.restTemplate.exchange("/greeting-javaconfig", HttpMethod.GET, requestEntity, Greeting.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("http://localhost:9000", entity.getHeaders().getAccessControlAllowOrigin());
Greeting greeting = entity.getBody();
assertEquals("Hello, World!", greeting.getContent());
}
}

View File

@@ -1,3 +1,5 @@
/.classpath
/.project
**/classpath.txt
**/.project
**/.settings/*.*

View File

@@ -48,6 +48,7 @@ public class ProjectsHarness {
Path testProjectPath = getProjectPath(name);
switch (type) {
case MAVEN:
MavenCore.buildMavenProject(testProjectPath);
return new MavenJavaProject(testProjectPath.resolve(MavenCore.POM_XML).toFile());
case CLASSPATH_TXT:
MavenCore.buildMavenProject(testProjectPath);

View File

@@ -0,0 +1 @@
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip

View File

@@ -0,0 +1,236 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
#
# Look for the Apple JDKs first to preserve the existing behaviour, and then look
# for the new JDKs provided by Oracle.
#
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then
#
# Oracle JDKs
#
export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then
#
# Apple JDKs
#
export JAVA_HOME=`/usr/libexec/java_home`
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Migwn, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
local basedir=$(pwd)
local wdir=$(pwd)
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
wdir=$(cd "$wdir/.."; pwd)
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)}
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
# avoid using MAVEN_CMD_LINE_ARGS below since that would loose parameter escaping in $@
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

View File

@@ -0,0 +1,146 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
set MAVEN_CMD_LINE_ARGS=%MAVEN_CONFIG% %*
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR=""%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar""
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
# avoid using MAVEN_CMD_LINE_ARGS below since that would loose parameter escaping in %*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

View File

@@ -0,0 +1,101 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>sts-4231</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>sts-4231</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.BUILD-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Brixton.M1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>

View File

@@ -0,0 +1,12 @@
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Sts4231Application {
public static void main(String[] args) {
SpringApplication.run(Sts4231Application.class, args);
}
}

View File

@@ -0,0 +1,18 @@
package com.example;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Sts4231Application.class)
@WebAppConfiguration
public class Sts4231ApplicationTests {
@Test
public void contextLoads() {
}
}

View File

@@ -0,0 +1 @@
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip

View File

@@ -0,0 +1,236 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
#
# Look for the Apple JDKs first to preserve the existing behaviour, and then look
# for the new JDKs provided by Oracle.
#
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then
#
# Oracle JDKs
#
export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then
#
# Apple JDKs
#
export JAVA_HOME=`/usr/libexec/java_home`
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Migwn, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
local basedir=$(pwd)
local wdir=$(pwd)
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
wdir=$(cd "$wdir/.."; pwd)
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)}
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
# avoid using MAVEN_CMD_LINE_ARGS below since that would loose parameter escaping in $@
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

View File

@@ -0,0 +1,146 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
set MAVEN_CMD_LINE_ARGS=%MAVEN_CONFIG% %*
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR=""%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar""
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
# avoid using MAVEN_CMD_LINE_ARGS below since that would loose parameter escaping in %*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

View File

@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo-with-resource-prop</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,12 @@
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoWithResourcePropApplication {
public static void main(String[] args) {
SpringApplication.run(DemoWithResourcePropApplication.class, args);
}
}

View File

@@ -0,0 +1,30 @@
package com.example;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WelcomeController {
@Autowired
private WelcomeProperties welcome;
@RequestMapping(value="/", produces="text/plain")
public Resource welcome() {
return welcome.getResource();
}
/**
* Shows some debug infos.
*/
@RequestMapping("/debug")
public String debug() throws IOException {
Resource rsrc = welcome.getResource();
return rsrc.getURI().toString();
}
}

View File

@@ -0,0 +1,31 @@
package com.example;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties("my.welcome")
public class WelcomeProperties {
private Resource resource;
private String path;
public Resource getResource() {
return resource;
}
public void setResource(Resource resource) {
this.resource = resource;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}

View File

@@ -0,0 +1,15 @@
{
"hints": [
{
"name": "my.welcome.path",
"providers": [
{
"name": "handle-as",
"parameters": {
"target": "org.springframework.core.io.Resource"
}
}
]
}
]
}

View File

@@ -0,0 +1,3 @@
my:
welcome:
resource: classpath:txt/welcome.txt

View File

@@ -0,0 +1,9 @@
Welcome to the Resource Demo App
--------------------------------
This app demonstrates how to use a configuration property of type
'Resource' to point to a resource loaded from your classpath.
If you are seeing the contents of this file then it is working.
This file is a resource on your classpath :-)

View File

@@ -0,0 +1 @@
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip

View File

@@ -0,0 +1,236 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
#
# Look for the Apple JDKs first to preserve the existing behaviour, and then look
# for the new JDKs provided by Oracle.
#
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then
#
# Oracle JDKs
#
export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then
#
# Apple JDKs
#
export JAVA_HOME=`/usr/libexec/java_home`
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Migwn, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
local basedir=$(pwd)
local wdir=$(pwd)
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
wdir=$(cd "$wdir/.."; pwd)
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)}
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
# avoid using MAVEN_CMD_LINE_ARGS below since that would loose parameter escaping in $@
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

View File

@@ -0,0 +1,146 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
set MAVEN_CMD_LINE_ARGS=%MAVEN_CONFIG% %*
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR=""%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar""
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
# avoid using MAVEN_CMD_LINE_ARGS below since that would loose parameter escaping in %*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

View File

@@ -13,14 +13,10 @@ package org.springframework.ide.vscode.application.properties;
import org.springframework.ide.vscode.application.properties.metadata.SpringPropertyIndexProvider;
import org.springframework.ide.vscode.application.properties.metadata.types.TypeUtilProvider;
import org.springframework.ide.vscode.application.properties.reconcile.SpringPropertiesReconcileEngine;
import org.springframework.ide.vscode.commons.languageserver.reconcile.BadWordReconcileEngine;
import org.springframework.ide.vscode.commons.languageserver.reconcile.IReconcileEngine;
import org.springframework.ide.vscode.commons.languageserver.util.SimpleLanguageServer;
import org.springframework.ide.vscode.commons.languageserver.util.SimpleTextDocumentService;
import org.springframework.ide.vscode.commons.languageserver.util.TextDocument;
import org.springframework.ide.vscode.java.properties.antlr.parser.AntlrParser;
import org.springframework.ide.vscode.java.properties.parser.ParseResults;
import org.springframework.ide.vscode.java.properties.parser.Parser;
import io.typefox.lsapi.TextDocumentSyncKind;
import io.typefox.lsapi.impl.ServerCapabilitiesImpl;
@@ -33,13 +29,6 @@ import io.typefox.lsapi.impl.ServerCapabilitiesImpl;
*/
public class ApplicationPropertiesLanguageServer extends SimpleLanguageServer {
private static final String SYNTAX_ERROR_HEADER_MSG = "Syntax Error: ";
private static final String YNTAX_ERROR_MSG__UNEXPECTED_END_OF_INPUT = "Unexpected end of input, value identifier is expected";
private static final String SYNTAX_ERROR_MSG__UNEXPECTED_END_OF_LINE = "Unexpected end of line, value identifier is expected";
private ParseResults parseResults;
private Parser parser;
private SpringPropertyIndexProvider indexProvider;
private TypeUtilProvider typeUtilProvider;
@@ -47,7 +36,6 @@ public class ApplicationPropertiesLanguageServer extends SimpleLanguageServer {
public ApplicationPropertiesLanguageServer(SpringPropertyIndexProvider indexProvider, TypeUtilProvider typeUtilProvider) {
this.indexProvider = indexProvider;
this.typeUtilProvider = typeUtilProvider;
this.parser = new AntlrParser();
SimpleTextDocumentService documents = getTextDocumentService();
IReconcileEngine reconcileEngine = getReconcileEngine();
@@ -55,37 +43,7 @@ public class ApplicationPropertiesLanguageServer extends SimpleLanguageServer {
TextDocument doc = params.getDocument();
validateWith(doc, reconcileEngine);
});
// documents.onDidChangeContent(params -> {
// System.out.println("Document changed: "+params);
// TextDocument doc = params.getDocument();
// parseResults = parser.parse(doc.getText());
// validateDocument(documents, doc);
// });
}
// private void validateDocument(SimpleTextDocumentService documents, TextDocument doc) {
// documents.publishDiagnostics(doc, parseResults.syntaxErrors.stream().map(problem -> {
// DiagnosticImpl diagnostic = new DiagnosticImpl();
// diagnostic.setMessage(createSyntaxErrorMessage(problem.getMessage()));
// diagnostic.setCode(problem.getCode());
// diagnostic.setSeverity(DiagnosticSeverity.Error);
// diagnostic.setSource("java-properties");
// diagnostic.setRange(doc.toRange(problem.getOffset(), problem.getLength()));
// return diagnostic;
// }).collect(Collectors.toList()));
// }
//
// private static String createSyntaxErrorMessage(String parserMessage) {
// String message = parserMessage;
// if (parserMessage.contains("extraneous input '\\n' expecting")) {
// message = SYNTAX_ERROR_MSG__UNEXPECTED_END_OF_LINE;
// } else if (parserMessage.contains("mismatched input '<EOF>' expecting")) {
// message = YNTAX_ERROR_MSG__UNEXPECTED_END_OF_INPUT;
// }
// return SYNTAX_ERROR_HEADER_MSG + message;
// }
@Override
protected ServerCapabilitiesImpl getServerCapabilities() {

View File

@@ -60,25 +60,27 @@ public class SpringPropertiesReconcileEngine implements IReconcileEngine {
"(\\s|\\\\\\s)*,(\\s|\\\\\\s)*"
);
// private static final Pattern SPACES = Pattern.compile(
// "(\\s|\\\\\\s)*"
// );
/**
* Regexp that matches a whitespace, including escaped whitespace
*/
// private static final Pattern ASSIGN = SpringPropertiesCompletionEngine.ASSIGN;
private static final Pattern SPACES = Pattern.compile(
"(\\s|\\\\\\s)*"
);
private SpringPropertyIndexProvider fIndexProvider;
private TypeUtilProvider typeUtilProvider;
private final DelimitedListReconciler commaListReconciler = new DelimitedListReconciler(COMMA, this::reconcileType);
private Parser parser = new AntlrParser();
private boolean recordSyntaxErrors = false;
public SpringPropertiesReconcileEngine(SpringPropertyIndexProvider provider, TypeUtilProvider typeUtilProvider) {
this.fIndexProvider = provider;
this.typeUtilProvider = typeUtilProvider;
this(provider, typeUtilProvider, true);
}
public SpringPropertiesReconcileEngine(SpringPropertyIndexProvider provider, TypeUtilProvider typeUtilProvider, boolean recordSyntaxErrors) {
this.fIndexProvider = provider;
this.typeUtilProvider = typeUtilProvider;
this.recordSyntaxErrors = recordSyntaxErrors;
}
public void reconcile(IDocument doc, IProblemCollector problemCollector) {
FuzzyMap<PropertyInfo> index = fIndexProvider.getIndex(doc);
problemCollector.beginCollecting();
@@ -86,10 +88,12 @@ public class SpringPropertiesReconcileEngine implements IReconcileEngine {
ParseResults results = parser.parse(doc.get());
DuplicateNameChecker duplicateNameChecker = new DuplicateNameChecker(problemCollector);
results.syntaxErrors.forEach(syntaxError -> {
problemCollector.accept(problem(PROP_SYNTAX_ERROR, syntaxError.getMessage(), syntaxError.getOffset(),
syntaxError.getLength()));
});
if (recordSyntaxErrors) {
results.syntaxErrors.forEach(syntaxError -> {
problemCollector.accept(problem(PROP_SYNTAX_ERROR, syntaxError.getMessage(), syntaxError.getOffset(),
syntaxError.getLength()));
});
}
if (index==null || index.isEmpty()) {
//don't report errors when index is empty, simply don't check (otherwise we will just reprot
@@ -136,6 +140,14 @@ public class SpringPropertiesReconcileEngine implements IReconcileEngine {
}
}
public void setRecordSyntaxErrors(boolean recordSyntaxErrors) {
this.recordSyntaxErrors = recordSyntaxErrors;
}
public boolean isRecordSyntaxErrors() {
return recordSyntaxErrors ;
}
protected SpringPropertyProblem problemDeprecated(DocumentRegion region, PropertyInfo property) {
SpringPropertyProblem p = problem(PROP_DEPRECATED,
TypeUtil.deprecatedPropertyMessage(
@@ -163,18 +175,8 @@ public class SpringPropertiesReconcileEngine implements IReconcileEngine {
}
private void reconcileType(IDocument doc, Type expectType, Node value, IProblemCollector problems) {
// DocumentRegion escapedValue = getAssignedValue(doc, regions, i);
// if (escapedValue==null) {
// int charPos = DocumentUtil.lastNonWhitespaceCharOfRegion(doc, regions[i]);
// if (charPos>=0) {
// problems.accept(problem(SpringPropertiesProblemType.PROP_VALUE_TYPE_MISMATCH,
// "Expecting '"+typeUtil.niceTypeName(expectType)+"'",
// charPos, 1));
// }
// } else {
// reconcileType(escapedValue, expectType, problems);
// }
reconcileType(createRegion(doc, value), expectType,
// Trim start and end spaces from the value node
reconcileType(createRegion(doc, value).trimStart(SPACES).trimEnd(SPACES), expectType,
problems);
}
@@ -188,7 +190,7 @@ public class SpringPropertiesReconcileEngine implements IReconcileEngine {
}
return new DocumentRegion(doc, value.getOffset(), value.getOffset() + length);
}
private void reconcileType(DocumentRegion region, Type expectType, IProblemCollector problems) {
TypeUtil typeUtil = typeUtilProvider.getTypeUtil(region.getDocument());
ValueParser parser = typeUtil.getValueParser(expectType);
@@ -209,23 +211,6 @@ public class SpringPropertiesReconcileEngine implements IReconcileEngine {
}
}
// private DocumentRegion getAssignedValue(IDocument doc, ITypedRegion[] regions, int i) {
// int valueRegionIndex = i+1;
// if (valueRegionIndex<regions.length) {
// String valueRegionType = regions[valueRegionIndex].getType();
// DocumentRegion valueRegion = new DocumentRegion(doc, regions[valueRegionIndex]);
// if (IPropertiesFilePartitions.PROPERTY_VALUE.equals(valueRegionType)) {
// //Need to remove the 'ASSIGN' bit from the start
// valueRegion = valueRegion.trimStart(ASSIGN).trimEnd(SPACES);
// //region text includes
// // potential padding with whitespace.
// // the ':' or '=' (if its there).
// return valueRegion;
// }
// }
// return null;
// }
private String suggestSimilar(PropertyInfo similarEntry, CharSequence validPrefix, CharSequence fullName) {
int matchedChars = validPrefix.length();
int wrongChars = fullName.length()-matchedChars;
@@ -236,18 +221,4 @@ public class SpringPropertiesReconcileEngine implements IReconcileEngine {
}
}
/**
* Check that there is an assignment char directly following the given region.
*/
// private boolean isAssigned(IDocument doc, IRegion r) {
// try {
// char c = doc.getChar(r.getOffset()+r.getLength());
// //Note either a '=' or a ':' can be used to assign properties.
// return isAssign(c);
// } catch (BadLocationException e) {
// //happens if looking for assignment char outside the document
// return false;
// }
// }
}

View File

@@ -23,6 +23,9 @@ public class SpringPropertyProblem extends ReconcileProblemImpl {
}
public static SpringPropertyProblem problem(ApplicationPropertiesProblemType type, String msg, DocumentRegion region) {
if (region.isEmpty()) {
region = makeVisible(region);
}
return new SpringPropertyProblem(type, msg, region.getStart(), region.getLength());
}

View File

@@ -213,13 +213,13 @@ public class ApplicationPropertiesEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testPredefinedProject() throws Exception {
@Test public void testPredefinedProject() throws Exception {
IJavaProject p = createPredefinedMavenProject("tricky-getters-boot-1.3.1-app");
IType type = p.findType("demo.DemoApplication");
assertNotNull(type);
}
@Ignore @Test public void testEnableApt() throws Throwable {
@Test public void testEnableApt() throws Throwable {
MavenJavaProject p = createPredefinedMavenProject("boot-1.2.0-properties-live-metadta");
//Check some assumptions about the initial state of the test project (if these checks fail then
@@ -285,7 +285,7 @@ public class ApplicationPropertiesEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testReconcilePojoArray() throws Exception {
@Test public void testReconcilePojoArray() throws Exception {
IJavaProject p = createPredefinedMavenProject("boot-1.2.1-app-properties-list-of-pojo");
useProject(p);
@@ -499,7 +499,7 @@ public class ApplicationPropertiesEditorTest extends AbstractPropsEditorTest {
);
}
@Ignore @Test public void testEnumPropertyReconciling() throws Exception {
@Test public void testEnumPropertyReconciling() throws Exception {
IJavaProject p = createPredefinedMavenProject("enums-boot-1.3.2-app");
@@ -540,7 +540,7 @@ public class ApplicationPropertiesEditorTest extends AbstractPropsEditorTest {
assertCompletionsVariations("foo.name-colors.something=G<*>", "foo.name-colors.something=GREEN<*>");
}
@Ignore @Test public void testEnumMapValueReconciling() throws Exception {
@Test public void testEnumMapValueReconciling() throws Exception {
IJavaProject p = createPredefinedMavenProject("enums-boot-1.3.2-app");
useProject(p);
@@ -597,7 +597,7 @@ public class ApplicationPropertiesEditorTest extends AbstractPropsEditorTest {
);
}
@Ignore @Test public void testEnumMapKeyReconciling() throws Exception {
@Test public void testEnumMapKeyReconciling() throws Exception {
IJavaProject p = createPredefinedMavenProject("enums-boot-1.3.2-app");
useProject(p);
@@ -652,7 +652,7 @@ public class ApplicationPropertiesEditorTest extends AbstractPropsEditorTest {
assertCompletionsVariations("foo.data.col<*>", "foo.data.color-children.<*>");
}
@Ignore @Test public void testPojoReconciling() throws Exception {
@Test public void testPojoReconciling() throws Exception {
IJavaProject p = createPredefinedMavenProject("enums-boot-1.3.2-app");
useProject(p);
@@ -753,7 +753,7 @@ public class ApplicationPropertiesEditorTest extends AbstractPropsEditorTest {
);
}
@Ignore @Test public void testEnumsInLowerCaseReconciling() throws Exception {
@Test public void testEnumsInLowerCaseReconciling() throws Exception {
IJavaProject p = createPredefinedMavenProject("enums-boot-1.3.2-app");
useProject(p);
@@ -787,7 +787,7 @@ public class ApplicationPropertiesEditorTest extends AbstractPropsEditorTest {
editor = newEditor(
"foo.color-data.red.next=green\n" +
"foo.color-data.red.next=not a color\n" +
"foo.color-data.green.next=not a color\n" +
"foo.color-data.red.bogus=green\n" +
"foo.color-data.red.name=Rood\n"
);
@@ -860,32 +860,38 @@ public class ApplicationPropertiesEditorTest extends AbstractPropsEditorTest {
assertCompletion("relaxedColor=b<*>", "relaxedColor=blue<*>");
}
@Ignore @Test public void testReconcileDeprecatedProperty() throws Exception {
/*
* TODO: Remove editor.setText(contents) after the call to deprecate(...) once property index listener mechanism is in place
*/
@Test public void testReconcileDeprecatedProperty() throws Exception {
data("error.path", "java.lang.String", null, "Path of the error controller.");
Editor editor = newEditor(
"# a comment\n"+
"error.path=foo\n"
);
String contents = "# a comment\n"
+ "error.path=foo\n";
Editor editor = newEditor(contents);
deprecate("error.path", "server.error.path", null);
editor.setText(contents);
editor.assertProblems(
"error.path|Deprecated: Use 'server.error.path'"
//no other problems
);
deprecate("error.path", "server.error.path", "This is old.");
editor.setText(contents);
editor.assertProblems(
"error.path|Deprecated: Use 'server.error.path' instead. Reason: This is old."
//no other problems
);
deprecate("error.path", null, "This is old.");
editor.setText(contents);
editor.assertProblems(
"error.path|Deprecated: This is old."
//no other problems
);
deprecate("error.path", null, null);
editor.setText(contents);
editor.assertProblems(
"error.path|Deprecated!"
//no other problems
@@ -948,7 +954,7 @@ public class ApplicationPropertiesEditorTest extends AbstractPropsEditorTest {
);
}
@Ignore @Test public void testDeprecatedBeanPropertyReconcile() throws Exception {
@Test public void testDeprecatedBeanPropertyReconcile() throws Exception {
IJavaProject p = createPredefinedMavenProject("tricky-getters-boot-1.3.1-app");
useProject(p);
data("foo", "demo.Deprecater", null, "A Bean with deprecated properties");
@@ -1151,7 +1157,7 @@ public class ApplicationPropertiesEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void test_STS_3335_reconcile_list_nested_in_Map_of_String() throws Exception {
@Test public void test_STS_3335_reconcile_list_nested_in_Map_of_String() throws Exception {
Editor editor;
useProject(createPredefinedMavenProject("boot-1.3.3-sts-4335"));
@@ -1382,7 +1388,7 @@ public class ApplicationPropertiesEditorTest extends AbstractPropsEditorTest {
editor.assertLinkTargets("java.lang.String", "java.lang.String");
}
@Ignore @Test public void testCommaListReconcile() throws Exception {
@Test public void testCommaListReconcile() throws Exception {
Editor editor;
IJavaProject p = createPredefinedMavenProject("enums-boot-1.3.2-app");
@@ -1391,13 +1397,13 @@ public class ApplicationPropertiesEditorTest extends AbstractPropsEditorTest {
data("my.colors", "java.util.List<demo.Color>", null, "Ooh! nice colors!");
editor = newEditor(
"#comment\n" +
"my.colors=RED, green, not-a-color , BLUE"
);
editor.assertProblems(
"not-a-color|demo.Color"
);
// editor = newEditor(
// "#comment\n" +
// "my.colors=RED, green, not-a-color , BLUE"
// );
// editor.assertProblems(
// "not-a-color|demo.Color"
// );
editor = newEditor(
"my.colors=\\\n" +
@@ -1553,6 +1559,16 @@ public class ApplicationPropertiesEditorTest extends AbstractPropsEditorTest {
@Override
protected SimpleLanguageServer newLanguageServer() {
return new ApplicationPropertiesLanguageServer(md.getIndexProvider(), typeUtilProvider);
// return new ApplicationPropertiesLanguageServer(md.getIndexProvider(), typeUtilProvider) {
//
// @Override
// protected IReconcileEngine getReconcileEngine() {
// SpringPropertiesReconcileEngine reconcileEngine = (SpringPropertiesReconcileEngine) super.getReconcileEngine();
// reconcileEngine.setRecordSyntaxErrors(false);
// return reconcileEngine;
// }
//
// };
}
/**

View File

@@ -109,7 +109,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
@Ignore @Test public void testHoverInfoForEnumValueInMapKey() throws Exception {
Editor editor;
IJavaProject project = createPredefinedMavenProject("boot13");
IJavaProject project = createPredefinedMavenProject("empty-boot-1.3.0-app");
useProject(project);
//This test will fail if source jars haven't been downloaded.
@@ -141,7 +141,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testHoverInfoForEnumValueInMapKeyCompletion() throws Exception {
IJavaProject project = createPredefinedMavenProject("boot13");
IJavaProject project = createPredefinedMavenProject("empty-boot-1.3.0-app");
useProject(project);
//This test will fail if source jars haven't been downloaded.
@@ -198,7 +198,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
@Ignore @Test public void testUserDefinedHoversandLinkTargets() throws Exception {
useProject(createPredefinedMavenProject("demo-enum"));
useProject(createPredefinedMavenProject("enums-boot-1.3.2-app"));
data("foo.link-tester", "demo.LinkTestSubject", null, "for testing different Pojo link cases");
Editor editor = newEditor(
"#A comment at the start\n" +
@@ -225,7 +225,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
@Ignore @Test public void testHyperlinkTargets() throws Exception {
System.out.println(">>> testHyperlinkTargets");
IJavaProject p = createPredefinedMavenProject("demo");
IJavaProject p = createPredefinedMavenProject("tricky-getters-boot-1.3.1-app");
useProject(p);
Editor editor = newEditor(
@@ -273,7 +273,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
);
}
@Ignore @Test public void test_STS_4140_StringArrayReconciling() throws Exception {
@Test public void test_STS_4140_StringArrayReconciling() throws Exception {
defaultTestData();
Editor editor;
@@ -331,7 +331,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
);
}
@Ignore @Test public void testReconcileIntegerScalar() throws Exception {
@Test public void testReconcileIntegerScalar() throws Exception {
data("server.port", "java.lang.Integer", null, "Port of server");
data("server.threads", "java.lang.Integer", null, "Number of threads for server threadpool");
Editor editor = newEditor(
@@ -346,7 +346,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
);
}
@Ignore @Test public void testReconcileExpectMapping() throws Exception {
@Test public void testReconcileExpectMapping() throws Exception {
defaultTestData();
Editor editor = newEditor(
"server:\n" +
@@ -358,7 +358,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
);
}
@Ignore @Test public void testReconcileExpectScalar() throws Exception {
@Test public void testReconcileExpectScalar() throws Exception {
defaultTestData();
Editor editor = newEditor(
"server:\n" +
@@ -371,7 +371,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
);
}
@Ignore @Test public void testReconcileCamelCaseBasic() throws Exception {
@Test public void testReconcileCamelCaseBasic() throws Exception {
Editor editor;
data("something.with-many-parts", "java.lang.Integer", "For testing tolerance of camelCase", null);
data("something.with-parts.and-more", "java.lang.Integer", "For testing tolerance of camelCase", null);
@@ -435,10 +435,10 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
);
}
@Ignore @Test public void testReconcileCamelCaseBeanProp() throws Exception {
@Test public void testReconcileCamelCaseBeanProp() throws Exception {
Editor editor;
IJavaProject p = createPredefinedMavenProject("demo");
IJavaProject p = createPredefinedMavenProject("tricky-getters-boot-1.3.1-app");
useProject(p);
data("demo.bean", "demo.CamelCaser", "For testing tolerance of camelCase", null);
@@ -492,7 +492,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testContentAssistCamelCaseBeanProp() throws Exception {
IJavaProject p = createPredefinedMavenProject("demo");
IJavaProject p = createPredefinedMavenProject("tricky-getters-boot-1.3.1-app");
useProject(p);
data("demo.bean", "demo.CamelCaser", "For testing tolerance of camelCase", null);
@@ -542,8 +542,8 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testReconcileBeanPropName() throws Exception {
IJavaProject p = createPredefinedMavenProject("demo-list-of-pojo");
@Test public void testReconcileBeanPropName() throws Exception {
IJavaProject p = createPredefinedMavenProject("boot-1.2.1-app-properties-list-of-pojo");
useProject(p);
assertNotNull(p.findType("demo.Foo"));
data("some-foo", "demo.Foo", null, "some Foo pojo property");
@@ -562,7 +562,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
);
}
@Ignore @Test public void testIgnoreSpringExpression() throws Exception {
@Test public void testIgnoreSpringExpression() throws Exception {
defaultTestData();
Editor editor = newEditor(
"server:\n" +
@@ -574,8 +574,8 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
);
}
@Ignore @Test public void testReconcilePojoArray() throws Exception {
IJavaProject p = createPredefinedMavenProject("demo-list-of-pojo");
@Test public void testReconcilePojoArray() throws Exception {
IJavaProject p = createPredefinedMavenProject("boot-1.2.1-app-properties-list-of-pojo");
useProject(p);
assertNotNull(p.findType("demo.Foo"));
@@ -627,7 +627,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testReconcileSequenceGotAtomicType() throws Exception {
@Test public void testReconcileSequenceGotAtomicType() throws Exception {
defaultTestData();
Editor editor = newEditor(
"liquibase:\n" +
@@ -639,7 +639,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
);
}
@Ignore @Test public void testReconcileSequenceGotMapType() throws Exception {
@Test public void testReconcileSequenceGotMapType() throws Exception {
data("the-map", "java.util.Map<java.lang.String,java.lang.String>", null, "Nice mappy");
Editor editor = newEditor(
"the-map:\n" +
@@ -651,8 +651,8 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
);
}
@Ignore @Test public void testEnumPropertyReconciling() throws Exception {
IJavaProject p = createPredefinedMavenProject("demo-enum");
@Test public void testEnumPropertyReconciling() throws Exception {
IJavaProject p = createPredefinedMavenProject("enums-boot-1.3.2-app");
useProject(p);
assertNotNull(p.findType("demo.Color"));
@@ -676,8 +676,8 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
);
editor.assertProblems(
"bad: BLUE|Expecting a 'demo.Color[RED, GREEN, BLUE]' but got a 'Mapping' node",
"Bogus|Expecting a 'demo.Color[RED, GREEN, BLUE]' but got 'Bogus'"
"bad: BLUE| but got a 'Mapping' node",
"Bogus| but got 'Bogus'"
);
}
@@ -1007,7 +1007,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testContentAssistPropertyWithPojoType() throws Exception {
useProject(createPredefinedMavenProject("demo-enum"));
useProject(createPredefinedMavenProject("enums-boot-1.3.2-app"));
//Try in-place completion
assertCompletion(
@@ -1034,7 +1034,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testContentAssistPropertyWithEnumType() throws Exception {
useProject(createPredefinedMavenProject("demo-enum"));
useProject(createPredefinedMavenProject("enums-boot-1.3.2-app"));
//Try in-place completion
assertCompletion(
@@ -1094,7 +1094,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testCompletionForExistingBeanPropertiesAreDemoted() throws Exception {
useProject(createPredefinedMavenProject("demo-enum"));
useProject(createPredefinedMavenProject("enums-boot-1.3.2-app"));
assertCompletions(
"foo:\n" +
" data:\n" +
@@ -1529,7 +1529,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testEnumValueCompletion() throws Exception {
useProject(createPredefinedMavenProject("demo-enum"));
useProject(createPredefinedMavenProject("enums-boot-1.3.2-app"));
data("foo.color", "demo.Color", null, "A foonky colour");
assertCompletion("foo.c<*>",
@@ -1551,7 +1551,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testEnumMapValueCompletion() throws Exception {
useProject(createPredefinedMavenProject("demo-enum"));
useProject(createPredefinedMavenProject("enums-boot-1.3.2-app"));
assertCompletions(
"foo:\n" +
@@ -1583,8 +1583,8 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
);
}
@Ignore @Test public void testEnumMapValueReconciling() throws Exception {
useProject(createPredefinedMavenProject("demo-enum"));
@Test public void testEnumMapValueReconciling() throws Exception {
useProject(createPredefinedMavenProject("enums-boot-1.3.2-app"));
data("foo.name-colors", "java.util.Map<java.lang.String,demo.Color>", null, "Map with colors in its values");
Editor editor;
@@ -1616,7 +1616,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testEnumMapKeyCompletion() throws Exception {
useProject(createPredefinedMavenProject("demo-enum"));
useProject(createPredefinedMavenProject("enums-boot-1.3.2-app"));
data("foo.color-names", "java.util.Map<demo.Color,java.lang.String>", null, "Map with colors in its keys");
data("foo.color-data", "java.util.Map<demo.Color,demo.ColorData>", null, "Map with colors in its keys, and pojo in values");
@@ -1729,8 +1729,8 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testPojoReconciling() throws Exception {
useProject(createPredefinedMavenProject("demo-enum"));
@Test public void testPojoReconciling() throws Exception {
useProject(createPredefinedMavenProject("enums-boot-1.3.2-app"));
Editor editor = newEditor(
"foo:\n" +
@@ -1774,8 +1774,8 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
" - <*>");
}
@Ignore @Test public void testEnumsInLowerCaseReconciling() throws Exception {
useProject(createPredefinedMavenProject("demo-enum"));
@Test public void testEnumsInLowerCaseReconciling() throws Exception {
useProject(createPredefinedMavenProject("enums-boot-1.3.2-app"));
data("simple.pants.size", "demo.ClothingSize", null, "The simple pant's size");
@@ -1834,7 +1834,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testEnumsInLowerCaseContentAssist() throws Exception {
IJavaProject p = createPredefinedMavenProject("demo-enum");
IJavaProject p = createPredefinedMavenProject("enums-boot-1.3.2-app");
useProject(p);
assertNotNull(p.findType("demo.ClothingSize"));
@@ -1914,7 +1914,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testPojoInListCompletion() throws Exception {
useProject(createPredefinedMavenProject("demo-enum"));
useProject(createPredefinedMavenProject("enums-boot-1.3.2-app"));
assertCompletion(
"foo:\n" +
@@ -2089,7 +2089,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
);
}
@Ignore @Test public void testMultiProfileYamlReconcile() throws Exception {
@Test public void testMultiProfileYamlReconcile() throws Exception {
Editor editor;
//See https://issuetracker.springsource.com/browse/STS-4144
defaultTestData();
@@ -2119,7 +2119,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
);
}
@Ignore @Test public void testReconcileArrayOfPrimitiveType() throws Exception {
@Test public void testReconcileArrayOfPrimitiveType() throws Exception {
data("my.array", "int[]", null, "A primitive array");
data("my.boxarray", "int[]", null, "An array of boxed primitives");
data("my.list", "java.util.List<java.lang.Integer>", null, "A list of boxed types");
@@ -2161,13 +2161,13 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
@Ignore @Test public void test_STS4231() throws Exception {
//Should the 'predefined' project need to be recreated... use the commented code below:
// BootProjectTestHarness projectHarness = new BootProjectTestHarness(ResourcesPlugin.getWorkspace());
// IJavaProject project = projectHarness.createBootProject("sts-4231",
// IJavaProject project = projectHarness.createBootProject("boot-1.3.0-app-sts-4231",
// bootVersionAtLeast("1.3.0"),
// withStarters("web", "cloud-config-server")
// );
//For more robust test use predefined project which is not so much a moving target:
IJavaProject project = createPredefinedMavenProject("sts-4231");
IJavaProject project = createPredefinedMavenProject("boot-1.3.0-app-sts-4231");
useProject(project);
assertCompletionsDisplayString(
@@ -2228,7 +2228,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void test_STS_4254_MapStringObjectReconciling() throws Exception {
@Test public void test_STS_4254_MapStringObjectReconciling() throws Exception {
Editor editor;
data("info", "java.util.Map<java.lang.String,java.lang.Object>", null, "Info for the actuator's info endpoint.");
@@ -2264,7 +2264,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
);
}
@Ignore @Test public void test_STS_4254_MapStringStringReconciling() throws Exception {
@Test public void test_STS_4254_MapStringStringReconciling() throws Exception {
Editor editor;
data("info", "java.util.Map<java.lang.String,java.lang.String>", null, "Info for the actuator's info endpoint.");
@@ -2294,7 +2294,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void test_STS_4254_MapStringIntegerReconciling() throws Exception {
@Test public void test_STS_4254_MapStringIntegerReconciling() throws Exception {
Editor editor;
data("info", "java.util.Map<java.lang.String,java.lang.Integer>", null, "Info for the actuator's info endpoint.");
@@ -2345,33 +2345,43 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
);
}
@Ignore @Test public void testDeprecatedReconcileProperty() throws Exception {
/*
* TODO: Remove editor.setText(contents) after the call to deprecate(...) once property index listener mechanism is in place
*/
@Test public void testDeprecatedReconcileProperty() throws Exception {
data("error.path", "java.lang.String", null, "Path of the error controller.");
Editor editor = newEditor(
"# a comment\n"+
String contents = "# a comment\n"+
"error:\n"+
" path: foo\n"
" path: foo\n";
Editor editor = newEditor(
contents
);
deprecate("error.path", "server.error.path", null);
editor.setText(contents);
editor.assertProblems(
"path|'error.path' is Deprecated: Use 'server.error.path'"
//no other problems
);
deprecate("error.path", "server.error.path", "This is old.");
editor.setText(contents);
editor.assertProblems(
"path|'error.path' is Deprecated: Use 'server.error.path' instead. Reason: This is old."
//no other problems
);
deprecate("error.path", null, "This is old.");
editor.setText(contents);
editor.assertProblems(
"path|'error.path' is Deprecated: This is old."
//no other problems
);
deprecate("error.path", null, null);
editor.setText(contents);
editor.assertProblems(
"path|'error.path' is Deprecated!"
//no other problems
@@ -2418,7 +2428,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testDeprecatedBeanPropertyHoverInfo() throws Exception {
IJavaProject jp = createPredefinedMavenProject("demo");
IJavaProject jp = createPredefinedMavenProject("tricky-getters-boot-1.3.1-app");
useProject(jp);
data("foo", "demo.Deprecater", null, "A bean with deprecated property.");
Editor editor = newEditor(
@@ -2430,8 +2440,8 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
editor.assertHoverContains("name", "<b>Deprecated!</b>");
}
@Ignore @Test public void testDeprecatedBeanPropertyReconcile() throws Exception {
IJavaProject jp = createPredefinedMavenProject("demo");
@Test public void testDeprecatedBeanPropertyReconcile() throws Exception {
IJavaProject jp = createPredefinedMavenProject("tricky-getters-boot-1.3.1-app");
useProject(jp);
data("foo", "demo.Deprecater", null, "A Bean with deprecated properties");
@@ -2464,7 +2474,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testDeprecatedBeanPropertyCompletions() throws Exception {
IJavaProject jp = createPredefinedMavenProject("demo");
IJavaProject jp = createPredefinedMavenProject("tricky-getters-boot-1.3.1-app");
useProject(jp);
data("foo", "demo.Deprecater", null, "A Bean with deprecated properties");
@@ -2788,7 +2798,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
}
@Ignore @Test public void testReconcileDuplicateProperties() throws Exception {
@Test public void testReconcileDuplicateProperties() throws Exception {
defaultTestData();
Editor editor = newEditor(
"spring:\n" +
@@ -2803,7 +2813,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
);
}
@Ignore @Test public void testReconcileDuplicatePropertiesNested() throws Exception {
@Test public void testReconcileDuplicatePropertiesNested() throws Exception {
data("foo.person.name", "String", null, "Name of person");
data("foo.person.family", "String", null, "Family name of person");
Editor editor = newEditor(
@@ -2819,8 +2829,8 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
);
}
@Ignore @Test public void testReconcileDuplicatePropertiesInBean() throws Exception {
useProject(createPredefinedMavenProject("demo-enum"));
@Test public void testReconcileDuplicatePropertiesInBean() throws Exception {
useProject(createPredefinedMavenProject("enums-boot-1.3.2-app"));
data("some.color", "demo.ColorData", null, "Some info about a color.");
Editor editor = newEditor(
"some:\n" +
@@ -2903,7 +2913,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
@Ignore @Test public void testPropertyValueHintCompletions() throws Exception {
//Test that 'value hints' work when property name is associated with 'value' hints.
// via boot metadata.
useProject(createPredefinedMavenProject("boot13"));
useProject(createPredefinedMavenProject("empty-boot-1.3.0-app"));
assertCompletionsDisplayString(
"spring:\n" +
@@ -2917,7 +2927,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testPropertyListHintCompletions() throws Exception {
useProject(createPredefinedMavenProject("boot13"));
useProject(createPredefinedMavenProject("empty-boot-1.3.0-app"));
assertCompletion(
"management:\n" +
@@ -2947,7 +2957,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testPropertyMapValueCompletions() throws Exception {
useProject(createPredefinedMavenProject("boot13"));
useProject(createPredefinedMavenProject("empty-boot-1.3.0-app"));
assertCompletionsDisplayString(
"logging:\n" +
@@ -2965,7 +2975,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testPropertyMapKeyCompletions() throws Exception {
useProject(createPredefinedMavenProject("boot13"));
useProject(createPredefinedMavenProject("empty-boot-1.3.0-app"));
assertCompletionWithLabel(
"logging:\n" +
" level:\n" +
@@ -2980,7 +2990,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testEscapeStringValueStartingWithStar() throws Exception {
useProject(createPredefinedMavenProject("boot13"));
useProject(createPredefinedMavenProject("empty-boot-1.3.0-app"));
assertCompletions(
"endpoints:\n"+
" cors:\n"+
@@ -3039,7 +3049,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
CachingValueProvider.TIMEOUT = Duration.ofSeconds(20); // the provider can't be reliably tested if its not allowed to
// fetch all its values (even though in 'production' you
// wouldn't want it to block the UI thread for this long.
useProject(createPredefinedMavenProject("boot13"));
useProject(createPredefinedMavenProject("empty-boot-1.3.0-app"));
//Finds a package:
assertCompletionWithLabel(
"logging:\n" +
@@ -3070,7 +3080,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
@Ignore @Test public void testSimpleResourceCompletion() throws Exception {
CachingValueProvider.TIMEOUT = Duration.ofSeconds(20);
useProject(createPredefinedMavenProject("boot13"));
useProject(createPredefinedMavenProject("empty-boot-1.3.0-app"));
data("my.nice.resource", "org.springframework.core.io.Resource", null, "A very nice resource.");
@@ -3114,7 +3124,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
@Ignore @Test public void testClasspathResourceCompletion() throws Exception {
CachingValueProvider.TIMEOUT = Duration.ofSeconds(20);
useProject(createPredefinedMavenProject("boot13"));
useProject(createPredefinedMavenProject("empty-boot-1.3.0-app"));
data("my.nice.resource", "org.springframework.core.io.Resource", null, "A very nice resource.");
data("my.nice.list", "java.util.List<org.springframework.core.io.Resource>", null, "A nice list of resources.");
@@ -3229,7 +3239,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
@Ignore @Test public void testClassReferenceCompletion() throws Exception {
CachingValueProvider.TIMEOUT = Duration.ofSeconds(20);
useProject(createPredefinedMavenProject("boot13_with_mongo"));
useProject(createPredefinedMavenProject("empty-boot-1.3.0-with-mongo"));
assertCompletion(
"spring:\n" +
@@ -3270,7 +3280,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
);
//Test what happens when 'target' type isn't on the classpath:
useProject(createPredefinedMavenProject("boot13"));
useProject(createPredefinedMavenProject("empty-boot-1.3.0-app"));
assertCompletionsDisplayString(
"spring:\n" +
" data:\n" +
@@ -3283,7 +3293,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
@Ignore @Test public void testClassReferenceInValueLink() throws Exception {
Editor editor;
useProject(createPredefinedMavenProject("boot13_with_mongo"));
useProject(createPredefinedMavenProject("empty-boot-1.3.0-with-mongo"));
editor = newEditor(
"spring:\n" +
@@ -3313,9 +3323,9 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
editor.assertLinkTargets("java.lang.String", "java.lang.String");
}
@Ignore @Test public void test_STS_3335_reconcile_list_nested_in_Map_of_String() throws Exception {
@Test public void test_STS_3335_reconcile_list_nested_in_Map_of_String() throws Exception {
Editor editor;
useProject(createPredefinedMavenProject("demo-sts-4335"));
useProject(createPredefinedMavenProject("boot-1.3.3-sts-4335"));
editor = newEditor(
"test-map:\n" +
@@ -3342,7 +3352,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
@Ignore @Test public void test_STS_3335_completions_list_nested_in_Map_of_String() throws Exception {
useProject(createPredefinedMavenProject("demo-sts-4335"));
useProject(createPredefinedMavenProject("boot-1.3.3-sts-4335"));
assertCompletions(
"test-map:\n" +
@@ -3391,7 +3401,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testBootBug5905() throws Exception {
useProject(createPredefinedMavenProject("demo-with-resource-prop"));
useProject(createPredefinedMavenProject("boot-1.3.3-app-with-resource-prop"));
//Check the metadata reflects the 'handle-as':
PropertyInfo metadata = getIndexProvider().getIndex(null).get("my.welcome.path");
@@ -3412,7 +3422,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testEnumJavaDocShownInValueContentAssist() throws Exception {
useProject(createPredefinedMavenProject("demo-enum"));
useProject(createPredefinedMavenProject("enums-boot-1.3.2-app"));
data("my.background", "demo.Color", null, "Color to use as default background.");
assertCompletionWithInfoHover(
@@ -3426,7 +3436,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
}
@Ignore @Test public void testEnumJavaDocShownInValueHover() throws Exception {
useProject(createPredefinedMavenProject("demo-enum"));
useProject(createPredefinedMavenProject("enums-boot-1.3.2-app"));
data("my.background", "demo.Color", null, "Color to use as default background.");
Editor editor;
@@ -3446,7 +3456,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
@Ignore @Test public void testHyperLinkEnumValue() throws Exception {
Editor editor;
useProject(createPredefinedMavenProject("demo-enum"));
useProject(createPredefinedMavenProject("enums-boot-1.3.2-app"));
data("my.background", "demo.Color", null, "Color to use as default background.");
editor = newEditor(
@@ -3464,7 +3474,7 @@ public class ApplicationYamlEditorTest extends AbstractPropsEditorTest {
@Ignore @Test public void testHyperLinkEnumValueInMapKey() throws Exception {
Editor editor;
useProject(createPredefinedMavenProject("demo-enum"));
useProject(createPredefinedMavenProject("enums-boot-1.3.2-app"));
data("my.color.map", "java.util.Map<demo.Color,java.lang.String>", null, "Pretty names for the colors.");
editor = newEditor(