Moved commons and concourse editor to 'headless-services'

This commit is contained in:
Kris De Volder
2017-04-06 16:27:12 -07:00
parent 3abf189512
commit bf8f8cffa9
608 changed files with 600 additions and 51 deletions

View File

@@ -1,17 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>commons-parent</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>

View File

@@ -1,2 +0,0 @@
eclipse.preferences.version=1
encoding/<project>=UTF-8

View File

@@ -1,4 +0,0 @@
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1

View File

@@ -1,26 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

View File

@@ -1,29 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>commons-cf</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.springframework.ide.eclipse.core.springbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.springframework.ide.eclipse.core.springnature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>

View File

@@ -1,4 +0,0 @@
eclipse.preferences.version=1
encoding//src/main/java=UTF-8
encoding//src/test/java=UTF-8
encoding/<project>=UTF-8

View File

@@ -1,5 +0,0 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.8

View File

@@ -1,4 +0,0 @@
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1

View File

@@ -1,39 +0,0 @@
<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>
<artifactId>commons-cf</artifactId>
<name>commons-cf</name>
<description>Common code related to 'accessing Cloud Foundry'</description>
<parent>
<groupId>org.springframework.ide.vscode</groupId>
<artifactId>commons-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.ide.vscode</groupId>
<artifactId>commons-util</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.cloudfoundry</groupId>
<artifactId>cloudfoundry-client-reactor</artifactId>
<version>${cloudfoundry-client-version}</version>
</dependency>
<dependency>
<groupId>org.cloudfoundry</groupId>
<artifactId>cloudfoundry-operations</artifactId>
<version>${cloudfoundry-client-version}</version>
</dependency>
<!-- Test harness -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -1,15 +0,0 @@
/*******************************************************************************
* 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.cloudfoundry.client;
public interface CFBuildpack {
String getName();
}

View File

@@ -1,57 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.cloudfoundry.client;
/**
* Package-private.
* <p/>
* Use {@link CFEntities} public API to create instance
*
*/
class CFBuildpackImpl implements CFBuildpack {
private final String name;
public CFBuildpackImpl(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CFBuildpackImpl other = (CFBuildpackImpl) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}

View File

@@ -1,17 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.cloudfoundry.client;
public interface CFDomain {
String getName();
}

View File

@@ -1,52 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.cloudfoundry.client;
class CFDomainImpl implements CFDomain {
private final String name;
public CFDomainImpl(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CFDomainImpl other = (CFDomainImpl) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}

View File

@@ -1,35 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.cloudfoundry.client;
/**
* Factory to create CF "Entities" like CF services, buildpacks, etc..
*/
public class CFEntities {
public static CFBuildpack createBuildpack(String name) {
return new CFBuildpackImpl(name);
}
public static CFServiceInstance createServiceInstance(String name, String service, String plan,
String documentationUrl, String description, String dashboardUrl) {
return new CFServiceInstanceImpl(name, service, plan, documentationUrl, description, dashboardUrl);
}
public static CFServiceInstance createServiceInstance(String name, String service, String plan) {
return new CFServiceInstanceImpl(name, service, plan, /* doc url */ null, /* description */ null,
/* dasboard Url */ null);
}
public static CFDomain createDomain(String name) {
return new CFDomainImpl(name);
}
}

View File

@@ -1,15 +0,0 @@
/*******************************************************************************
* 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.cloudfoundry.client;
public interface CFEntity {
String getName();
}

View File

@@ -1,27 +0,0 @@
/*******************************************************************************
* 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.cloudfoundry.client;
import org.springframework.ide.vscode.commons.util.ExceptionUtil;
/**
* Static methods to recognize specific types of exceptions CF client
* may throw.
*
* @author Kris De Volder
*/
public class CFExceptions {
public static boolean isSSLCertificateFailure(Exception e) {
Throwable cause = ExceptionUtil.getDeepestCause(e);
return cause.getClass().getName().equals("sun.security.provider.certpath.SunCertPathBuilderException");
}
}

View File

@@ -1,24 +0,0 @@
/*******************************************************************************
* 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.cloudfoundry.client;
public interface CFServiceInstance extends CFEntity {
String getName();
String getService();
String getPlan();
String getDescription();
String getDocumentationUrl();
String getDashboardUrl();
//TODO: last operation info?
}

View File

@@ -1,123 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.cloudfoundry.client;
/**
* Package-private.
* <p/>
* Use {@link CFEntities} public API to create instance
*
*/
class CFServiceInstanceImpl implements CFServiceInstance {
private String service;
private String plan;
private String name;
private String documentationUrl;
private String description;
private String dashboardUrl;
public CFServiceInstanceImpl(String name, String service, String plan, String documentationUrl, String description,
String dashboardUrl) {
this.name = name;
this.service = service;
this.plan = plan;
this.documentationUrl = documentationUrl;
this.description = description;
this.dashboardUrl = dashboardUrl;
}
@Override
public String getService() {
return service;
}
@Override
public String getPlan() {
return plan;
}
@Override
public String getName() {
return name;
}
@Override
public String getDocumentationUrl() {
return documentationUrl;
}
@Override
public String getDescription() {
return description;
}
@Override
public String getDashboardUrl() {
return dashboardUrl;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dashboardUrl == null) ? 0 : dashboardUrl.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((documentationUrl == null) ? 0 : documentationUrl.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((plan == null) ? 0 : plan.hashCode());
result = prime * result + ((service == null) ? 0 : service.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CFServiceInstanceImpl other = (CFServiceInstanceImpl) obj;
if (dashboardUrl == null) {
if (other.dashboardUrl != null)
return false;
} else if (!dashboardUrl.equals(other.dashboardUrl))
return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (documentationUrl == null) {
if (other.documentationUrl != null)
return false;
} else if (!documentationUrl.equals(other.documentationUrl))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (plan == null) {
if (other.plan != null)
return false;
} else if (!plan.equals(other.plan))
return false;
if (service == null) {
if (other.service != null)
return false;
} else if (!service.equals(other.service))
return false;
return true;
}
}

View File

@@ -1,22 +0,0 @@
/*******************************************************************************
* Copyright (c) 2015, 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.cloudfoundry.client;
import java.util.List;
public interface ClientRequests {
List<CFBuildpack> getBuildpacks() throws Exception;
List<CFServiceInstance> getServices() throws Exception;
List<CFDomain> getDomains() throws Exception;
}

View File

@@ -1,28 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.cloudfoundry.client;
import java.time.Duration;
public class ClientTimeouts {
public static final ClientTimeouts DEFAULT_TIMEOUTS = new ClientTimeouts();
private static final Duration GET_SERVICES_TIMEOUT = Duration.ofSeconds(60);
public Duration getServicesTimeout() {
return GET_SERVICES_TIMEOUT;
}
public Duration getBuildpacksTimeout() {
return Duration.ofSeconds(10);
}
}

View File

@@ -1,17 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.cloudfoundry.client;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.CFClientParams;
public interface CloudFoundryClientFactory {
ClientRequests getClient(CFClientParams params, ClientTimeouts timeouts) throws Exception;
}

View File

@@ -1,27 +0,0 @@
/*******************************************************************************
* 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.cloudfoundry.client;
public enum LoginMethod {
PASSWORD,
TEMPORARY_CODE;
public String getLabel() {
String[] pieces = name().split("_");
StringBuilder label = new StringBuilder();
for (int i = 0; i < pieces.length; i++) {
if (i>0) {
label.append(" ");
}
label.append(pieces[i].toLowerCase());
}
return label.toString();
}
}

View File

@@ -1,25 +0,0 @@
/*******************************************************************************
* 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.cloudfoundry.client;
public class RequestErrorHandler {
/**
*
* @param e
* @return true if request error should be treated as an error and thrown. False error
* should be ignored.
*/
public boolean throwError(Throwable e) {
return true;
}
}

View File

@@ -1,67 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.cloudfoundry.client.cftarget;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.concurrent.Callable;
import org.cloudfoundry.uaa.UaaException;
import org.springframework.ide.vscode.commons.util.ExceptionUtil;
import reactor.ipc.netty.channel.AbortedException;
/**
* This is a stateful callable context that is "aware" of CF errors, and is not
* suitable for reuse as it may cache errors
*
*/
public class CFCallableContext {
private final CFParamsProviderMessages paramsProviderMessages;
private Exception lastConnectionError;
public CFCallableContext(CFParamsProviderMessages paramsProviderMessages) {
this.paramsProviderMessages = paramsProviderMessages;
}
public <T> T checkConnection(Callable<T> callable) throws Exception {
this.lastConnectionError = null;
try {
return callable.call();
} catch (Exception e) {
throw convertToCfVscodeError(e);
}
}
protected Exception convertToCfVscodeError(Exception e) {
this.lastConnectionError = getConnectionError(e);
// return the "converted" error if it is available
if (this.lastConnectionError != null) {
return this.lastConnectionError;
}
return e;
}
protected Exception getConnectionError(Exception e) {
Throwable deepestCause = ExceptionUtil.getDeepestCause(e);
if (deepestCause instanceof UaaException || deepestCause instanceof AbortedException
|| deepestCause instanceof SocketException || deepestCause instanceof UnknownHostException) {
return new ConnectionException(this.paramsProviderMessages.noNetworkConnection());
}
return null;
}
public boolean hasConnectionError() {
return this.lastConnectionError != null;
}
}

View File

@@ -1,164 +0,0 @@
/*******************************************************************************
* 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.cloudfoundry.client.cftarget;
import java.net.URI;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.CFCredentials.CFCredentialType;
import org.springframework.ide.vscode.commons.util.Assert;
/**
* All the parameters needed to create a CF client.
*
* @author Kris De Volder
*/
public class CFClientParams {
private static final Logger logger = Logger.getLogger(CFClientParams.class.getName());
private final String apiUrl;
private final String username;
private CFCredentials credentials;
private final boolean skipSslValidation;
private String orgName; // optional
private String spaceName; // optional
public CFClientParams(String apiUrl,
String username,
CFCredentials credentials,
String orgName,
String spaceName,
boolean skipSslValidation
) {
Assert.isNotNull(apiUrl);
Assert.isNotNull(credentials);
if (credentials.getType() == CFCredentialType.PASSWORD) {
Assert.isNotNull(username);
}
this.apiUrl = apiUrl;
this.username = username;
this.credentials = credentials;
this.skipSslValidation = skipSslValidation;
this.orgName = orgName;
this.spaceName = spaceName;
}
public CFClientParams(String apiUrl, String username, CFCredentials credentials, boolean skipSslValidation) {
this(apiUrl, username, credentials, null /* no org */,
null /* no space */, skipSslValidation);
}
public CFCredentials getCredentials() {
return credentials;
}
public String getUsername() {
return username;
}
public boolean skipSslValidation() {
return skipSslValidation;
}
public String getApiUrl() {
return apiUrl;
}
public String getOrgName() {
return orgName;
}
public void setOrgName(String orgName) {
this.orgName = orgName;
}
public String getSpaceName() {
return spaceName;
}
public void setSpaceName(String spaceName) {
this.spaceName = spaceName;
}
public String getHost() {
try {
URI uri = new URI(getApiUrl());
return uri.getHost();
} catch (Exception e) {
logger.log(Level.SEVERE, e.getMessage(), e);
}
return null;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((apiUrl == null) ? 0 : apiUrl.hashCode());
result = prime * result + ((credentials == null) ? 0 : credentials.hashCode());
result = prime * result + ((orgName == null) ? 0 : orgName.hashCode());
result = prime * result + (skipSslValidation ? 1231 : 1237);
result = prime * result + ((spaceName == null) ? 0 : spaceName.hashCode());
result = prime * result + ((username == null) ? 0 : username.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CFClientParams other = (CFClientParams) obj;
if (apiUrl == null) {
if (other.apiUrl != null)
return false;
} else if (!apiUrl.equals(other.apiUrl))
return false;
if (credentials == null) {
if (other.credentials != null)
return false;
} else if (!credentials.equals(other.credentials))
return false;
if (orgName == null) {
if (other.orgName != null)
return false;
} else if (!orgName.equals(other.orgName))
return false;
if (skipSslValidation != other.skipSslValidation)
return false;
if (spaceName == null) {
if (other.spaceName != null)
return false;
} else if (!spaceName.equals(other.spaceName))
return false;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
@Override
public String toString() {
return "CFClientParams [apiUrl=" + apiUrl + ", username=" + username + ", credentials=" + credentials
+ ", skipSslValidation=" + skipSslValidation + ", orgName=" + orgName + ", spaceName=" + spaceName
+ "]";
}
}

View File

@@ -1,132 +0,0 @@
/*******************************************************************************
* 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.cloudfoundry.client.cftarget;
import org.springframework.ide.vscode.commons.cloudfoundry.client.LoginMethod;
import org.springframework.ide.vscode.commons.util.Assert;
public class CFCredentials {
public enum CFCredentialType {
PASSWORD,
TEMPORARY_CODE,
REFRESH_TOKEN;
public LoginMethod toLoginMethod() {
switch (this) {
case PASSWORD:
return LoginMethod.PASSWORD;
case TEMPORARY_CODE:
return LoginMethod.TEMPORARY_CODE;
default:
return null;
}
}
}
private final CFCredentialType type;
private final String secret;
/**
* Deprecated, use fromLogin instead
*/
@Deprecated
public static CFCredentials fromPassword(String password) {
return fromLogin(LoginMethod.PASSWORD, password);
}
public static CFCredentials fromLogin(LoginMethod method, String secret) {
CFCredentialType type;
switch (method) {
case PASSWORD:
type = CFCredentialType.PASSWORD;
break;
case TEMPORARY_CODE:
type = CFCredentialType.TEMPORARY_CODE;
break;
default:
throw new IllegalStateException("Bug! Missing switch case?");
}
return new CFCredentials(type, secret);
}
public static CFCredentials fromRefreshToken(String refreshToken) {
Assert.isNotNull(refreshToken);
return new CFCredentials(CFCredentialType.REFRESH_TOKEN, refreshToken);
}
public String getSecret() {
return secret;
}
/////////////////////////////////////////////////////////////////////////
/**
* Private constuctor, use static `fromXXX` factory methods instead.
*/
private CFCredentials(CFCredentialType type, String secret) {
this.type = type;
this.secret = secret;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((secret == null) ? 0 : secret.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CFCredentials other = (CFCredentials) obj;
if (secret == null) {
if (other.secret != null)
return false;
} else if (!secret.equals(other.secret))
return false;
if (type != other.type)
return false;
return true;
}
@Override
public String toString() {
return "CFCredentials [type=" + type + ", secret=" + hidePassword(type, secret) + "]";
}
private String hidePassword(CFCredentialType type, String password) {
if (password==null) {
return null;
}
return (type==CFCredentialType.PASSWORD || type==CFCredentialType.REFRESH_TOKEN)
? "****"
: password;
}
public CFCredentialType getType() {
return type;
}
public static CFCredentials fromSsoToken(String ssoToken) {
return CFCredentials.fromLogin(LoginMethod.TEMPORARY_CODE, ssoToken);
}
}

View File

@@ -1,28 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.cloudfoundry.client.cftarget;
/**
* Messages that are specific to a particular parameter provider
*
*/
public interface CFParamsProviderMessages {
String noTargetsFound();
String unauthorised();
String noNetworkConnection();
String noOrgSpace();
}

View File

@@ -1,141 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.cloudfoundry.client.cftarget;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import org.springframework.ide.vscode.commons.cloudfoundry.client.CFBuildpack;
import org.springframework.ide.vscode.commons.cloudfoundry.client.CFDomain;
import org.springframework.ide.vscode.commons.cloudfoundry.client.CFServiceInstance;
import org.springframework.ide.vscode.commons.cloudfoundry.client.ClientRequests;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
/**
*
* Wrapper around a {@link ClientRequests} that may contain cached information
* like buildpacks
*
*/
public class CFTarget {
private final CFClientParams params;
private final ClientRequests requests;
private final String targetName;
/*
* Cached information
*/
private LoadingCache<String, List<CFBuildpack>> buildpacksCache;
private LoadingCache<String, List<CFServiceInstance>> servicesCache;
private LoadingCache<String, List<CFDomain>> domainCache;
private CFCallableContext callableContext;
public CFTarget(String targetName, CFClientParams params, ClientRequests requests,
CFCallableContext callableContext) {
this.params = params;
this.requests = requests;
this.targetName = targetName;
this.callableContext = callableContext;
initCache(requests);
}
private void initCache(ClientRequests requests) {
CacheLoader<String, List<CFServiceInstance>> servicesLoader = new CacheLoader<String, List<CFServiceInstance>>() {
@Override
public List<CFServiceInstance> load(String key) throws Exception {
/* Cache of services does not use keys, as the whole cache
* gets wiped clean on any new call to CF.
*/
return runAndCheckForFailure(() -> requests.getServices());
}
};
this.servicesCache = CacheBuilder.newBuilder()
.expireAfterAccess(CFTargetCache.SERVICES_EXPIRATION, TimeUnit.SECONDS).build(servicesLoader);
CacheLoader<String, List<CFBuildpack>> buildpacksLoader = new CacheLoader<String, List<CFBuildpack>>() {
@Override
public List<CFBuildpack> load(String key) throws Exception {
/* Cache does not use keys, as the whole cache
* gets wiped clean on any new call to CF.
*/
return runAndCheckForFailure(() -> requests.getBuildpacks());
}
};
this.buildpacksCache = CacheBuilder.newBuilder()
.expireAfterAccess(CFTargetCache.TARGET_EXPIRATION, TimeUnit.HOURS).build(buildpacksLoader);
CacheLoader<String, List<CFDomain>> domainLoader = new CacheLoader<String, List<CFDomain>>() {
@Override
public List<CFDomain> load(String key) throws Exception {
return runAndCheckForFailure(() -> requests.getDomains());
}
};
this.domainCache = CacheBuilder.newBuilder()
.expireAfterAccess(CFTargetCache.TARGET_EXPIRATION, TimeUnit.HOURS).build(domainLoader);
}
protected <T> T runAndCheckForFailure(Callable<T> callable) throws Exception {
return callableContext.checkConnection(callable);
}
public boolean hasConnectionError() {
return callableContext.hasConnectionError();
}
public CFClientParams getParams() {
return params;
}
public List<CFBuildpack> getBuildpacks() throws Exception {
// Use the target name as the "key" , since Guava cache doesn't allow null keys
// However, the key is not really used when fetching buildpacks, as we are not caching
// buildpacks per target here. This class only represents ONE target, so it will only
// ever have one key
String key = getName();
return this.buildpacksCache.get(key);
}
public List<CFServiceInstance> getServices() throws Exception {
/* services don't use keys, as they get wiped clean on each refresh
* . That said, the cache doesn't allow a null key, so use the target name as the "key"
*
*/
String key = getName();
return this.servicesCache.get(key);
}
public List<CFDomain> getDomains() throws Exception {
String key = getName();
return this.domainCache.get(key);
}
public ClientRequests getClientRequests() {
return requests;
}
public String getName() {
return this.targetName;
}
@Override
public String toString() {
return "CFClientTarget [params=" + params + ", targetName=" + targetName + "]";
}
}

View File

@@ -1,112 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.cloudfoundry.client.cftarget;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.springframework.ide.vscode.commons.cloudfoundry.client.ClientTimeouts;
import org.springframework.ide.vscode.commons.cloudfoundry.client.CloudFoundryClientFactory;
import org.springframework.ide.vscode.commons.util.Assert;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
public class CFTargetCache {
private final ClientParamsProvider paramsProvider;
private final CloudFoundryClientFactory clientFactory;
private final ClientTimeouts timeouts;
private final LoadingCache<ClientParamsCacheKey, CFTarget> cache;
private final CFCallableContext cacheCallableContext;
public static final long SERVICES_EXPIRATION = 10;
public static final long TARGET_EXPIRATION = 1;
public CFTargetCache(ClientParamsProvider paramsProvider, CloudFoundryClientFactory clientFactory,
ClientTimeouts timeouts) {
Assert.isLegal(paramsProvider != null,
"A Cloud Foundry client parameters provider must be set when creating a target cache.");
this.paramsProvider = paramsProvider;
this.clientFactory = clientFactory;
this.timeouts = timeouts;
this.cacheCallableContext = new CFCallableContext(paramsProvider.getMessages());
CacheLoader<ClientParamsCacheKey, CFTarget> loader = new CacheLoader<ClientParamsCacheKey, CFTarget>() {
@Override
public CFTarget load(ClientParamsCacheKey params) throws Exception {
return create(params.fullParams);
}
};
cache = CacheBuilder.newBuilder().maximumSize(1).expireAfterAccess(TARGET_EXPIRATION, TimeUnit.HOURS)
.build(loader);
}
/**
* @return non-null list of targets, or throws exception if no targets found
* @throws NoTargetsException
* if no targets found
* @throws Exception
* for any other error encountered
*/
public synchronized List<CFTarget> getOrCreate() throws NoTargetsException, Exception {
return cacheCallableContext.checkConnection(() -> doGetOrCreate());
}
protected synchronized List<CFTarget> doGetOrCreate() throws NoTargetsException, Exception {
List<CFClientParams> allParams = paramsProvider.getParams();
List<CFTarget> targets = new ArrayList<>();
if (allParams != null) {
for (CFClientParams params : allParams) {
ClientParamsCacheKey key = ClientParamsCacheKey.from(params);
CFTarget target = cache.get(key);
if (target != null) {
// If any CF errors occurred in the target, refresh once
if (target.hasConnectionError()) {
cache.refresh(key);
target = cache.get(key);
}
targets.add(target);
}
}
}
return targets;
}
protected CFTarget create(CFClientParams params) throws Exception {
/*
* Must pass a NEW callable context. Cannot be
* the same as the target cache callable context, as
* contexts may contain error state
*/
return new CFTarget(getTargetName(params), params, clientFactory.getClient(params, timeouts),
new CFCallableContext(paramsProvider.getMessages()));
}
protected static String getTargetName(CFClientParams params) {
return labelFromCfApi(params.getApiUrl());
}
protected static String labelFromCfApi(String cfApiUrl) {
if (cfApiUrl.startsWith("https://")) {
return cfApiUrl.substring("https://".length());
} else if (cfApiUrl.startsWith("http://")) {
return cfApiUrl.substring("http://".length());
} else {
return cfApiUrl;
}
}
}

View File

@@ -1,116 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.cloudfoundry.client.cftarget;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import org.springframework.ide.vscode.commons.util.StringUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Provides existing Cloud Foundry client params, like target and credentials,
* from the CLI config.json in the file system.
*
*
*/
public class CfCliParamsProvider implements ClientParamsProvider {
public static final String TARGET = "Target";
public static final String REFRESH_TOKEN = "RefreshToken";
public static final String ORGANIZATION_FIELDS = "OrganizationFields";
public static final String SPACE_FIELDS = "SpaceFields";
public static final String NAME = "Name";
public static final String SSL_DISABLED = "SSLDisabled";
private CfCliProviderMessages cfCliProviderMessages = new CfCliProviderMessages();
/*
* (non-Javadoc)
*
* @see org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.
* ClientParamsProvider#getParams()
*/
@Override
public List<CFClientParams> getParams() throws NoTargetsException, ExecutionException {
List<CFClientParams> params = new ArrayList<>();
try {
File file = getConfigJsonFile();
if (file != null) {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> userData = mapper.readValue(file, Map.class);
if (userData != null) {
String refreshToken = (String) userData.get(REFRESH_TOKEN);
// Only support connecting to CF via refresh token for now
if (isRefreshTokenSet(refreshToken)) {
CFCredentials credentials = CFCredentials.fromRefreshToken(refreshToken);
boolean sslDisabled = (Boolean) userData.get(SSL_DISABLED);
String target = (String) userData.get(TARGET);
Map<String, Object> orgFields = (Map<String, Object>) userData.get(ORGANIZATION_FIELDS);
Map<String, Object> spaceFields = (Map<String, Object>) userData.get(SPACE_FIELDS);
if (target != null && orgFields != null && spaceFields != null) {
String orgName = (String) orgFields.get(NAME);
String spaceName = (String) spaceFields.get(NAME);
if (!StringUtil.hasText(orgName) || !StringUtil.hasText(spaceName)) {
throw new NoTargetsException(getMessages().noOrgSpace());
}
params.add(new CFClientParams(target, null, credentials, orgName, spaceName, sslDisabled));
}
}
}
}
} catch (IOException | InterruptedException e) {
throw new ExecutionException(e);
}
if (params.isEmpty()) {
throw new NoTargetsException(getMessages().noTargetsFound());
} else {
return params;
}
}
private boolean isRefreshTokenSet(String token) {
return StringUtil.hasText(token);
}
private File getConfigJsonFile() throws IOException, InterruptedException {
String homeDir = getHomeDir();
if (homeDir != null) {
if (!homeDir.endsWith("/")) {
homeDir += '/';
}
String filePath = homeDir + ".cf/config.json";
File file = new File(filePath);
if (file.exists() && file.canRead()) {
return file;
}
}
return null;
}
private String getHomeDir() throws IOException, InterruptedException {
return System.getProperty("user.home");
}
@Override
public CFParamsProviderMessages getMessages() {
return cfCliProviderMessages;
}
}

View File

@@ -1,44 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.cloudfoundry.client.cftarget;
public final class CfCliProviderMessages implements CFParamsProviderMessages {
/*
* Important: be sure to use ':' to separate the initial part of the message
* with a longer portion. The vscode content assist will parse around the
* first ':' and the second segment will appear as a doc string that can be
* longer
*/
public static final String NO_CLI_TARGETS_FOUND_MESSAGE = "No Cloud Foundry targets found: Use cf CLI to login";
public static final String NO_NETWORK_CONNECTION = "No connection to Cloud Foundry: Use cf CLI to login or verify network connection";
public static final String NO_ORG_SPACE = "No org/space selected: Use CF CLI to login";
@Override
public String noTargetsFound() {
return NO_CLI_TARGETS_FOUND_MESSAGE;
}
@Override
public String unauthorised() {
return NO_NETWORK_CONNECTION;
}
@Override
public String noNetworkConnection() {
return NO_NETWORK_CONNECTION;
}
@Override
public String noOrgSpace() {
return NO_ORG_SPACE;
}
}

View File

@@ -1,81 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.cloudfoundry.client.cftarget;
/**
*
* A key for CF targets that uses {@link CFClientParams} values, EXCEPT for
* credentials, as the key value.
*
*/
public class ClientParamsCacheKey {
public final CFClientParams fullParams;
/**
* Use static API to create: {@link #from(CFClientParams)}
* @param fullParams
*/
private ClientParamsCacheKey(CFClientParams fullParams) {
this.fullParams = fullParams;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((fullParams.getApiUrl() == null) ? 0 : fullParams.getApiUrl().hashCode());
result = prime * result + ((fullParams.getOrgName() == null) ? 0 : fullParams.getOrgName().hashCode());
result = prime * result + (fullParams.skipSslValidation() ? 1231 : 1237);
result = prime * result + ((fullParams.getSpaceName() == null) ? 0 : fullParams.getSpaceName().hashCode());
result = prime * result + ((fullParams.getUsername() == null) ? 0 : fullParams.getUsername().hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ClientParamsCacheKey other = (ClientParamsCacheKey) obj;
if (fullParams.getApiUrl() == null) {
if (other.fullParams.getApiUrl() != null)
return false;
} else if (!fullParams.getApiUrl().equals(other.fullParams.getApiUrl()))
return false;
if (fullParams.getOrgName() == null) {
if (other.fullParams.getOrgName() != null)
return false;
} else if (!fullParams.getOrgName().equals(other.fullParams.getOrgName()))
return false;
if (fullParams.skipSslValidation() != other.fullParams.skipSslValidation())
return false;
if (fullParams.getSpaceName() == null) {
if (other.fullParams.getSpaceName() != null)
return false;
} else if (!fullParams.getSpaceName().equals(other.fullParams.getSpaceName()))
return false;
if (fullParams.getUsername() == null) {
if (other.fullParams.getUsername() != null)
return false;
} else if (!fullParams.getUsername().equals(other.fullParams.getUsername()))
return false;
return true;
}
public static ClientParamsCacheKey from(CFClientParams params) {
return new ClientParamsCacheKey(params);
}
}

View File

@@ -1,27 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.cloudfoundry.client.cftarget;
import java.util.List;
import java.util.concurrent.ExecutionException;
public interface ClientParamsProvider {
/**
*
* @return non-null list of VALID params to connect to Cloud Foundry
* @throws NoTargetsException if failure to resolve any params for Cloud Foundry
* @throws ExecutionException if failure occurs while resolving params
*/
List<CFClientParams> getParams() throws NoTargetsException, ExecutionException;
CFParamsProviderMessages getMessages();
}

View File

@@ -1,24 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.cloudfoundry.client.cftarget;
public class ConnectionException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public ConnectionException(String message) {
super(message);
}
}

View File

@@ -1,24 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.cloudfoundry.client.cftarget;
public class NoTargetsException extends Exception {
public NoTargetsException(String message) {
super(message);
}
/**
*
*/
private static final long serialVersionUID = 1L;
}

View File

@@ -1,143 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.cloudfoundry.client.v2;
import java.time.Duration;
import java.util.Optional;
import org.cloudfoundry.client.CloudFoundryClient;
import org.cloudfoundry.reactor.ConnectionContext;
import org.cloudfoundry.reactor.DefaultConnectionContext;
import org.cloudfoundry.reactor.ProxyConfiguration;
import org.cloudfoundry.reactor.TokenProvider;
import org.cloudfoundry.reactor.client.ReactorCloudFoundryClient;
import org.cloudfoundry.reactor.doppler.ReactorDopplerClient;
import org.cloudfoundry.reactor.tokenprovider.OneTimePasscodeTokenProvider;
import org.cloudfoundry.reactor.tokenprovider.PasswordGrantTokenProvider;
import org.cloudfoundry.reactor.tokenprovider.RefreshTokenGrantTokenProvider;
import org.cloudfoundry.reactor.uaa.ReactorUaaClient;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.CFClientParams;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.CFCredentials;
public class CFClientProvider {
final ConnectionContext connection;
final TokenProvider tokenProvider;
//Note the three client objects below are 'stateless' wrappers and it would be
// fine to recreate as needed instead of store them
final CloudFoundryClient client;
final ReactorUaaClient uaaClient;
final ReactorDopplerClient doppler;
private ProxyConfiguration getProxy(String host) {
// TODO: enable proxy support for vscode. The code below retrieves proxy via Eclipse proxy service thus
// not applicable when this is used outside of Eclipse
// try {
// if (StringUtils.hasText(host)) {
// URL url = new URL("https://"+host);
// // In certain cases, the activator would have stopped and the plugin may
// // no longer be available. Usually onl happens on shutdown.
// BootDashActivator plugin = BootDashActivator.getDefault();
// if (plugin != null) {
// IProxyService proxyService = plugin.getProxyService();
// if (proxyService != null) {
// IProxyData[] selectedProxies = proxyService.select(url.toURI());
//
// // No proxy configured or not found
// if (selectedProxies == null || selectedProxies.length == 0) {
// return null;
// }
//
// IProxyData data = selectedProxies[0];
// int proxyPort = data.getPort();
// String proxyHost = data.getHost();
// String user = data.getUserId();
// String password = data.getPassword();
// if (proxyHost!=null) {
// return ProxyConfiguration.builder()
// .host(proxyHost)
// .port(proxyPort==-1?Optional.empty():Optional.of(proxyPort))
// .username(Optional.ofNullable(user))
// .password(Optional.ofNullable(password))
// .build();
//// return proxyHost != null ? new HttpProxyConfiguration(proxyHost, proxyPort,
//// data.isRequiresAuthentication(), user, password) : null;
// }
// }
// }
// }
// } catch (Exception e) {
// Log.log(e);
// }
return null;
}
public CFClientProvider(CFClientParams params) {
long sslTimeout = Long.getLong("sts.bootdash.cf.client.ssl.handshake.timeout", 60); //TODO: make a preference for this?
Optional<Boolean> keepAlive = getBooleanSystemProp("http.keepAlive");
CloudFoundryClientCache.debug("cf client keepAlive = "+keepAlive);
connection = DefaultConnectionContext.builder()
.proxyConfiguration(Optional.ofNullable(getProxy(params.getHost())))
.apiHost(params.getHost())
.sslHandshakeTimeout(Duration.ofSeconds(sslTimeout))
.keepAlive(keepAlive)
.skipSslValidation(params.skipSslValidation())
.build();
tokenProvider = createTokenProvider(params);
client = ReactorCloudFoundryClient.builder()
.connectionContext(connection)
.tokenProvider(tokenProvider)
.build();
uaaClient = ReactorUaaClient.builder()
.connectionContext(connection)
.tokenProvider(tokenProvider)
.build();
doppler = ReactorDopplerClient.builder()
.connectionContext(connection)
.tokenProvider(tokenProvider)
.build();
}
private TokenProvider createTokenProvider(CFClientParams params) {
CFCredentials creds = params.getCredentials();
switch (creds.getType()) {
case PASSWORD:
return PasswordGrantTokenProvider.builder()
.username(params.getUsername())
.password(creds.getSecret())
.build();
case REFRESH_TOKEN:
return RefreshTokenGrantTokenProvider.builder()
.token(creds.getSecret())
.build();
case TEMPORARY_CODE:
return OneTimePasscodeTokenProvider.builder()
.passcode(creds.getSecret())
.build();
default:
throw new IllegalStateException("BUG! Missing switch case?");
}
}
private Optional<Boolean> getBooleanSystemProp(String name) {
String str = System.getProperty(name);
if (str!=null) {
return Optional.of(Boolean.valueOf(str));
}
return Optional.empty();
}
}

View File

@@ -1,50 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016, 2017 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.cloudfoundry.client.v2;
import org.cloudfoundry.operations.buildpacks.Buildpack;
import org.cloudfoundry.operations.domains.Domain;
import org.cloudfoundry.operations.services.ServiceInstanceSummary;
import org.cloudfoundry.operations.services.ServiceInstanceType;
import org.springframework.ide.vscode.commons.cloudfoundry.client.CFBuildpack;
import org.springframework.ide.vscode.commons.cloudfoundry.client.CFDomain;
import org.springframework.ide.vscode.commons.cloudfoundry.client.CFEntities;
import org.springframework.ide.vscode.commons.cloudfoundry.client.CFServiceInstance;
/**
* Various helper methods to 'wrap' objects returned by CF client into our own
* types, so that we do not directly expose library types to our code.
*
* @author Kris De Volder
*/
public class CFWrappingV2 {
public static CFBuildpack wrap(Buildpack buildpack) {
String name = buildpack.getName();
return CFEntities.createBuildpack(name);
}
public static CFDomain wrap(Domain domain) {
String name = domain.getName();
return CFEntities.createDomain(name);
}
public static CFServiceInstance wrap(ServiceInstanceSummary serviceInstance) {
String name = serviceInstance.getName();
String plan = serviceInstance.getPlan();
String service = serviceInstance.getType() == ServiceInstanceType.USER_PROVIDED ? "user-provided"
: serviceInstance.getService();
return CFEntities.createServiceInstance(name, service, plan);
}
}

View File

@@ -1,94 +0,0 @@
/*******************************************************************************
* 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.cloudfoundry.client.v2;
/**
* Manages a set of CancelationTokens.
*
* @author Kris De Volder
*/
public class CancelationTokens {
private String DEBUG = null;
//Note: we don't actually have to keep a set of tokens explicitly.
// The tokens use a 'id' which is incremented on each new token.
//So it is easy to cancel all existing tokens based on a their
//id simply by remembering the 'id' where the cancelation
//occurred. All ids 'older' than the current id are 'canceled'.
/**
* An uncancelable token that can be used by operations that don't
* need cancelation support.
*/
public static final CancelationToken NULL = new CancelationToken() {
@Override
public boolean isCanceled() {
return false;
}
};
private final Object SYNC = CancelationTokens.this;
private int canceledAllBefore = 0;
private int nextId = 0;
public CancelationTokens() {
}
public CancelationTokens(String debug) {
this.DEBUG = debug;
}
public interface CancelationToken {
boolean isCanceled();
}
public synchronized CancelationToken create() {
CancelationToken token = new ManagedToken();
debug("creating cancelation token: "+token);
return token;
}
private class ManagedToken implements CancelationToken {
private int id;
private ManagedToken() {
synchronized (SYNC) {
this.id = nextId++;
}
}
public boolean isCanceled() {
synchronized (SYNC) {
boolean isCanceled = id < canceledAllBefore;
debug("isCanceled? ["+id+"] => "+isCanceled);
return isCanceled;
}
}
@Override
public String toString() {
return "CancelToken("+id+")";
}
}
public synchronized void cancelAll() {
canceledAllBefore = nextId;
debug("CancelationTokens < "+canceledAllBefore+" are Canceled");
}
private void debug(String string) {
if (DEBUG!=null) {
System.out.println(DEBUG+": "+string);
}
}
}

View File

@@ -1,77 +0,0 @@
/*******************************************************************************
* 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.cloudfoundry.client.v2;
import java.util.concurrent.TimeUnit;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.CFClientParams;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.ClientParamsCacheKey;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
/**
* TODO: Remove this class when the 'thread leak bug' in V2 client is fixed.
*
* At the moment each time {@link SpringCloudFoundryClient} is create a
* threadpool is created by the client and it is never cleaned up. The only way
* we have to mitigate this leak is to try and create as few clients as
* possible.
* <p>
* So we have a permanent cache of clients here that is reused.
* <p>
* When the bug is fixed then this should no longer be necessary and we can
* removed this cache and just create the client as needed.
*
* @author Kris De Volder
*/
public class CloudFoundryClientCache {
private static final boolean DEBUG = false;
public static final long EXPIRATION = 1;
static void debug(String string) {
if (DEBUG) {
System.out.println(string);
}
}
private final LoadingCache<ClientParamsCacheKey, CFClientProvider> cache;
private int clientCount = 0;
public CloudFoundryClientCache() {
CacheLoader<ClientParamsCacheKey, CFClientProvider> loader = new CacheLoader<ClientParamsCacheKey, CFClientProvider>() {
@Override
public CFClientProvider load(ClientParamsCacheKey params) throws Exception {
clientCount++;
debug("Creating client [" + clientCount + "]: " + params);
return create(params.fullParams);
}
};
cache = CacheBuilder.newBuilder().maximumSize(1).expireAfterAccess(EXPIRATION, TimeUnit.HOURS)
.build(loader);
}
public synchronized CFClientProvider getOrCreate(CFClientParams params) throws Exception {
return create(params);
// Disable cache as corrupted clients may be kept due to connection or auth errors
// return cache.get(ClientParamsCacheKey.from(params));
}
protected CFClientProvider create(CFClientParams params) {
return new CFClientProvider(params);
}
}

View File

@@ -1,156 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016, 2017 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.cloudfoundry.client.v2;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.cloudfoundry.client.CloudFoundryClient;
import org.cloudfoundry.operations.CloudFoundryOperations;
import org.cloudfoundry.operations.DefaultCloudFoundryOperations;
import org.springframework.ide.vscode.commons.cloudfoundry.client.CFBuildpack;
import org.springframework.ide.vscode.commons.cloudfoundry.client.CFDomain;
import org.springframework.ide.vscode.commons.cloudfoundry.client.CFServiceInstance;
import org.springframework.ide.vscode.commons.cloudfoundry.client.ClientRequests;
import org.springframework.ide.vscode.commons.cloudfoundry.client.ClientTimeouts;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.CFClientParams;
import org.springframework.ide.vscode.commons.util.ExceptionUtil;
import com.google.common.collect.ImmutableList;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* @author Kris De Volder
* @author Nieraj Singh
*/
public class DefaultClientRequestsV2 implements ClientRequests {
private static final Logger logger = Logger.getLogger(DefaultClientRequestsV2.class.getName());
private static final boolean DEBUG = false;
private CloudFoundryClient _client ;
private CloudFoundryOperations _operations;
private final ClientTimeouts timeouts;
public DefaultClientRequestsV2(CloudFoundryClientCache clients, CFClientParams params, ClientTimeouts timeouts) {
CFClientProvider provider = getFromCache(clients, params);
this._client = provider.client;
this._operations = DefaultCloudFoundryOperations.builder()
.cloudFoundryClient(_client)
.dopplerClient(provider.doppler)
.uaaClient(provider.uaaClient)
.organization(params.getOrgName())
.space(params.getSpaceName())
.build();
// timeouts must never be null
this.timeouts = timeouts != null ? timeouts : ClientTimeouts.DEFAULT_TIMEOUTS;
}
private CFClientProvider getFromCache(CloudFoundryClientCache clients, CFClientParams params) {
CFClientProvider provider = null;
try {
provider = clients.getOrCreate(params);
} catch (Exception e) {
throw new IllegalArgumentException("Failed to create a v2 CF Java client using params: " + params, e);
}
return provider;
}
@Override
public List<CFServiceInstance> getServices() throws Exception {
return ReactorUtils.get(timeouts.getServicesTimeout(), CancelationTokens.NULL,
log("operations.services.listIntances",
_operations
.services()
.listInstances()
.map(CFWrappingV2::wrap)
.collectList()
.map(ImmutableList::copyOf)
)
);
}
@Override
public List<CFDomain> getDomains() throws Exception {
return ReactorUtils.get(timeouts.getBuildpacksTimeout(), CancelationTokens.NULL,
log("operations.domains.list",
_operations
.domains()
.list()
.map(CFWrappingV2::wrap)
.collectList()
.map(ImmutableList::copyOf)
)
);
}
@Override
public List<CFBuildpack> getBuildpacks() throws Exception {
return ReactorUtils.get(timeouts.getBuildpacksTimeout(), CancelationTokens.NULL,
log("operations.buildpacks.list",
_operations
.buildpacks()
.list()
.map(CFWrappingV2::wrap)
.collectList()
.map(ImmutableList::copyOf)
)
);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
//// calls to client and operations with 'logging'.
private <T> Flux<T> log(String msg, Flux<T> flux) {
if (DEBUG) {
return flux
.doOnSubscribe((sub) -> debug(">>> "+msg))
.doOnComplete(() -> {
debug("<<< "+msg+" OK");
})
.doOnCancel(() -> {
debug("<<< "+msg+" CANCEL");
})
.doOnError((error) -> {
debug("<<< "+msg+" ERROR: "+ExceptionUtil.getMessage(error));
});
} else {
return flux;
}
}
private <T> Mono<T> log(String msg, Mono<T> mono) {
if (DEBUG) {
return mono
.doOnSubscribe((sub) -> debug(">>> "+msg))
.doOnCancel(() -> debug("<<< "+msg+" CANCEL"))
.doOnSuccess((data) -> {
debug("<<< "+msg+" OK");
})
.doOnError((error) -> {
debug("<<< "+msg+" ERROR: "+ExceptionUtil.getMessage(error));
});
} else {
return mono;
}
}
private void debug(String msg) {
logger.log(Level.INFO, msg);
}
}

View File

@@ -1,43 +0,0 @@
/*******************************************************************************
* 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.cloudfoundry.client.v2;
import org.springframework.ide.vscode.commons.cloudfoundry.client.ClientRequests;
import org.springframework.ide.vscode.commons.cloudfoundry.client.ClientTimeouts;
import org.springframework.ide.vscode.commons.cloudfoundry.client.CloudFoundryClientFactory;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.CFClientParams;
public class DefaultCloudFoundryClientFactoryV2 implements CloudFoundryClientFactory {
public static final CloudFoundryClientFactory INSTANCE = new DefaultCloudFoundryClientFactoryV2();
/**
* Use 'INSTANCE' constant instead. This class is a singleton.
*/
private DefaultCloudFoundryClientFactoryV2() {
}
private CloudFoundryClientCache cache = new CloudFoundryClientCache();
/*
* (non-Javadoc)
*
* @see org.springframework.ide.vscode.commons.cloudfoundry.client.v2.
* CloudFoundryClientFactory#getClient(org.springframework.ide.vscode.
* commons.cloudfoundry.client.cftarget.CFClientParams,
* org.springframework.ide.vscode.commons.cloudfoundry.client.v2.
* RequestTimeouts)
*/
@Override
public ClientRequests getClient(CFClientParams params, ClientTimeouts timeouts) throws Exception {
return new DefaultClientRequestsV2(cache, params, timeouts);
}
}

View File

@@ -1,295 +0,0 @@
/*******************************************************************************
* 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.cloudfoundry.client.v2;
import java.io.IOException;
import java.time.Duration;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import org.reactivestreams.Publisher;
import org.springframework.ide.vscode.commons.cloudfoundry.client.v2.CancelationTokens.CancelationToken;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;
/**
* @author Kris De Volder
*/
public class ReactorUtils {
private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(45); // reflects default timeout of Mono.block in reactor 2.x.
public static boolean DUMP_STACK_ON_TIMEOUT = false;
// TODO: uncommented when cancellation is handled in vscode
// /**
// * Convert a {@link CancelationToken} into a Mono that raises
// * an {@link OperationCanceledException} when the token is canceled.
// */
// public static <T> Mono<T> toMono(CancelationToken cancelToken) {
// return Mono.delay(Duration.ofSeconds(1))
// .then((ping) ->
// cancelToken.isCanceled()
// ? Mono.<T>error(new OperationCanceledException())
// : Mono.empty()
// )
// .repeatWhenEmpty((x) -> x);
// }
/**
* Similar to Mono.get but logs a more traceable version of the exception to Eclipse's error
* log before 'rethrowing' it.
* <p>
* This is useful because the actual exception is pretty hard to trace. It doesn't even 'point'
* to the line where 'get' was called.
*/
public static <T> T get(Mono<T> mono) throws Exception {
try {
return mono.block(DEFAULT_TIMEOUT);
} catch (Exception e) {
dumpStacks();
throw new IOException(e);
}
}
/**
* Similar to Mono.get but logs a more traceable version of the exception to Eclipse's error
* log before 'rethrowing' it.
* <p>
* This is useful because the actual exception is pretty hard to trace. It doesn't even 'point'
* to the line where 'get' was called.
*/
public static <T> T get(Duration timeout, CancelationToken cancelationToken, Mono<T> mono) throws Exception {
try {
return mono
// TODO: uncomment when cancellation properly supported in vscode
// Mono
// .first(mono,
// toMono(cancelationToken))
// .otherwise(errorFilter(cancelationToken))
.block(timeout);
} catch (Exception e) {
dumpStacks();
throw new IOException(e);
}
}
public static <T> List<T> get(Duration t, Mono<List<T>> m) throws IOException {
try {
return m.block(t);
} catch (Exception e) {
dumpStacks();
throw new IOException(e);
}
}
private static void dumpStacks() {
if (DUMP_STACK_ON_TIMEOUT) {
System.out.println(getStackDumps().toString());
}
}
/**
* A 'filter' to use as a Mono.otherwise hanlder. It transforms any exception into {@link OperationCanceledException}
* when cancelationToken has been canceled.
*/
private static <T> Function<Throwable, Mono<T>> errorFilter(CancelationToken cancelationToken) {
// return (Throwable e) -> cancelationToken.isCanceled()?Mono.error(new OperationCanceledException()):Mono.error(e);
return (Throwable e) -> Mono.error(e);
}
/**
* Deprecated because this is really the same as Mono.justOrEmpty, so use that instead.
*/
@Deprecated
public static <T> Mono<T> just(T it) {
return it == null ? Mono.empty() : Mono.just(it);
}
/**
* @return A function that can be passed to Mono.otherwise to convert a specific exception type into
* Mono.empty().
*/
public static <T> Function<Throwable, Mono<T>> suppressException(Class<? extends Throwable> exceptionType) {
return (Throwable caught) -> {
if (exceptionType.isAssignableFrom(caught.getClass())) {
return Mono.empty();
} else {
return Mono.error(caught);
}
};
}
/**
* Build a Mono<Void> that executes a given number of Mono<Void> one after the
* other.
*/
@SafeVarargs
public static Mono<Void> sequence(Mono<Void>... tasks) {
Mono<Void> seq = Mono.empty();
for (Mono<Void> t : tasks) {
seq = seq.then(t);
}
return seq;
}
/**
* Execute a bunch of mono in parallel. All monos are executed to completion (rather than canceled early
* when one of them fails)
* <p>
* When at least one operation has failed then, upon completion or failure of the last Mono we guarantee that at least
* one of the exceptions is propagated.
*/
public static Mono<Void> safeMerge(Flux<Mono<Void>> operations, int concurrency) {
AtomicReference<Throwable> failure = new AtomicReference<>(null);
return Flux.merge(
operations
.map((Mono<Void> op) -> {
return op.otherwise((e) -> {
failure.compareAndSet(null, e);
return Mono.empty();
});
}),
concurrency //limit concurrency otherwise troubles (flooding/choking request broker?)
)
.then(() -> {
Throwable error = failure.get();
if (error!=null) {
return Mono.error(error);
} else {
return Mono.empty();
}
});
}
/**
* Attach a timestamp to each element in a Stream
*/
public static <T> Flux<Tuple2<T,Long>> timestamp(Flux<T> stream) {
return stream.map((e) -> Tuples.of(e, System.currentTimeMillis()));
}
/**
* Sorts the elements in a flux in a moving time window. I.e. this assumes element order may be
* scrambled but the scrambling has a certain 'time localilty' to it. So we only need to consider
* sorting of elements that arrive 'close to eachother'.
* <p>
* WARNING: The returned flux is intended for a single subscriber. It only maintains a
* single buffer for sorting stream elements. This buffer is consumed when elements
* are released to any subscriber. Therefore if one subscriber received a element it is gone
* from the buffer and will not be delivered to the other subscribers.
*
* @param stream The stream to be sorted
* @param comparator Compare function to sort with
* @param bufferTime The 'window' of time beyond which we don't need to compare elements.
*/
public static <T> Flux<T> sort(Flux<T> stream, Comparator<T> comparator, Duration bufferTime) {
class SorterAccumulator {
final PriorityQueue<Tuple2<T, Long>> holdingPen = new PriorityQueue<>((Tuple2<T, Long> o1, Tuple2<T, Long> o2) -> {
return comparator.compare(o1.getT1(), o2.getT1());
});
final Flux<T> released = Flux.fromIterable(() -> new Iterator<T>() {
@Override
public boolean hasNext() {
Tuple2<T, Long> nxt;
synchronized (holdingPen) {
nxt = holdingPen.peek();
}
return nxt!=null && isOldEnough(nxt);
}
private boolean isOldEnough(Tuple2<T, Long> nxt) {
long age = System.currentTimeMillis() - nxt.getT2();
return age > bufferTime.toMillis();
}
@Override
public T next() {
synchronized (holdingPen) {
return holdingPen.remove().getT1();
}
}
});
public SorterAccumulator next(Flux<Tuple2<T, Long>> window) {
window.subscribe((e) -> {
synchronized (holdingPen) {
holdingPen.add(e);
}
});
return this;
}
public Flux<T> getReleased() {
return released;
}
public Publisher<? extends T> drain() {
return Flux.fromIterable(holdingPen)
.map(Tuple2::getT1);
}
}
SorterAccumulator sorter = new SorterAccumulator();
return timestamp(stream)
.window(bufferTime)
.scan(sorter, SorterAccumulator::next)
.concatMap(SorterAccumulator::getReleased)
.concatWith(sorter.drain());
}
protected static StringBuffer getStackDumps() {
StringBuffer sb = new StringBuffer();
Map<Thread, StackTraceElement[]> traces = Thread.getAllStackTraces();
for (Map.Entry<Thread, StackTraceElement[]> entry : traces.entrySet()) {
sb.append(entry.getKey().toString());
sb.append("\n");
for (StackTraceElement element : entry.getValue()) {
sb.append(" ");
sb.append(element.toString());
sb.append("\n");
}
sb.append("\n");
}
return sb;
}
/**
* Connect a mono to a CompletableFuture so that the result of the mono
* can be retrieved from the {@link CompletableFuture} by calling it's 'get'
* method.
*/
public static <T> void completeWith(CompletableFuture<T> future, Mono<T> mono) {
mono.doOnNext((T v) -> {
future.complete(v);
})
.doOnError((Throwable e) -> {
future.completeExceptionally(e);
})
.subscribeOn(Schedulers.elastic())
.subscribe();
}
}

View File

@@ -1,146 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.cloudfoundry.client;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
import java.net.UnknownHostException;
import java.util.concurrent.Callable;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.CFParamsProviderMessages;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.CFTarget;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.CFTargetCache;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.CfCliProviderMessages;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.ConnectionException;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.NoTargetsException;
import org.springframework.ide.vscode.commons.util.ExceptionUtil;
import com.google.common.collect.ImmutableList;
public class CFClientTest {
MockCfCli cloudfoundry = new MockCfCli();
ClientTimeouts timeouts = new ClientTimeouts();
CFTargetCache targetCache;
CFParamsProviderMessages expectedMessages = new CfCliProviderMessages();
@Before
public void setup() throws Exception {
targetCache = new CFTargetCache(cloudfoundry.paramsProvider, cloudfoundry.factory, timeouts);
}
@Test
public void testNoTarget() throws Exception {
when(cloudfoundry.paramsProvider.getParams())
.thenThrow(new NoTargetsException(expectedMessages.noTargetsFound()));
assertError(() -> targetCache.getOrCreate(), NoTargetsException.class, expectedMessages.noTargetsFound());
}
@Test
public void testOneTarget() throws Exception {
CFTarget target = targetCache.getOrCreate().get(0);
assertNotNull(target);
assertEquals(MockCfCli.DEFAULT_PARAMS, target.getParams());
}
@Test
public void testUnknownHostServices() throws Exception {
ClientRequests client = cloudfoundry.client;
when(client.getServices()).thenThrow(new UnknownHostException("api.run.pivotal.io"));
CFTarget target = targetCache.getOrCreate().get(0);
assertError(() -> target.getServices(), ConnectionException.class, expectedMessages.noNetworkConnection());
}
@Test
public void testUnknownHostBuildpacks() throws Exception {
ClientRequests client = cloudfoundry.client;
when(client.getBuildpacks()).thenThrow(new UnknownHostException("api.run.pivotal.io"));
CFTarget target = targetCache.getOrCreate().get(0);
assertError(() -> target.getBuildpacks(), ConnectionException.class, expectedMessages.noNetworkConnection());
}
@Test
public void testUnknownHostDomains() throws Exception {
ClientRequests client = cloudfoundry.client;
when(client.getDomains()).thenThrow(new UnknownHostException("api.run.pivotal.io"));
CFTarget target = targetCache.getOrCreate().get(0);
assertError(() -> target.getDomains(), ConnectionException.class, expectedMessages.noNetworkConnection());
}
@Test
public void testBuildpacksFromTarget() throws Exception {
ClientRequests client = cloudfoundry.client;
CFBuildpack buildpack = Mockito.mock(CFBuildpack.class);
when(buildpack.getName()).thenReturn("java_buildpack");
when(client.getBuildpacks()).thenReturn(ImmutableList.of(buildpack));
CFTarget target = targetCache.getOrCreate().get(0);
assertEquals("java_buildpack", target.getBuildpacks().get(0).getName());
}
@Test
public void testDomainsFromTarget() throws Exception {
ClientRequests client = cloudfoundry.client;
CFDomain domain = Mockito.mock(CFDomain.class);
when(domain.getName()).thenReturn("cfapps.io");
when(client.getDomains()).thenReturn(ImmutableList.of(domain));
CFTarget target = targetCache.getOrCreate().get(0);
assertEquals("cfapps.io", target.getDomains().get(0).getName());
}
@Test
public void testServicesFromTarget() throws Exception {
ClientRequests client = cloudfoundry.client;
CFServiceInstance service = Mockito.mock(CFServiceInstance.class);
when(service.getName()).thenReturn("appdb");
when(service.getPlan()).thenReturn("spark");
when(service.getService()).thenReturn("cleardb");
when(client.getServices()).thenReturn(ImmutableList.of(service));
CFTarget target = targetCache.getOrCreate().get(0);
assertEquals("appdb", target.getServices().get(0).getName());
assertEquals("spark", target.getServices().get(0).getPlan());
assertEquals("cleardb", target.getServices().get(0).getService());
}
@Test
public void testNoServicesFromTarget() throws Exception {
ClientRequests client = cloudfoundry.client;
when(client.getServices()).thenReturn(ImmutableList.of());
CFTarget target = targetCache.getOrCreate().get(0);
assertTrue(target.getServices().isEmpty());
}
protected void assertError(Callable<?> callable, Class<? extends Throwable> expected, String expectedMessage)
throws Exception {
Throwable error = null;
try {
callable.call();
} catch (Exception e) {
error = ExceptionUtil.getDeepestCause(e);
}
assertEquals(expected, error.getClass());
assertTrue(ExceptionUtil.getMessageNoAppendedInformation(error).contains(expectedMessage));
}
}

View File

@@ -1,61 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.cloudfoundry.client;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.mockito.Mockito;
import org.springframework.ide.vscode.commons.cloudfoundry.client.ClientRequests;
import org.springframework.ide.vscode.commons.cloudfoundry.client.CloudFoundryClientFactory;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.CFClientParams;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.CFCredentials;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.CfCliProviderMessages;
import org.springframework.ide.vscode.commons.cloudfoundry.client.cftarget.ClientParamsProvider;
import org.springframework.ide.vscode.commons.util.ExceptionUtil;
import com.google.common.collect.ImmutableList;
public class MockCfCli {
public final static CFClientParams DEFAULT_PARAMS = new CFClientParams("test.io", "testuser",
CFCredentials.fromRefreshToken("refreshtoken"), false);
public final CloudFoundryClientFactory factory = mock(CloudFoundryClientFactory.class);
public final ClientRequests client = mock(ClientRequests.class);
public final ClientParamsProvider paramsProvider = mock(ClientParamsProvider.class);
public final CfCliProviderMessages actualCfCliMessages = new CfCliProviderMessages();
public MockCfCli() {
try {
//program some default behavior into mocks... most tests will use this.
//other tests should 'reset' the mocks and reprogram them as needed.
when(factory.getClient(any(), any())).thenReturn(client);
when(paramsProvider.getParams()).thenReturn(ImmutableList.of(DEFAULT_PARAMS));
when(paramsProvider.getMessages()).thenReturn(actualCfCliMessages);
} catch (Exception e) {
throw ExceptionUtil.unchecked(e);
}
}
/**
* Reset the mocks. Use this if the default's programmed into the mocks don't suite your test case.
* <p>
* Note: you may also choose to call {@link Mockito}.mock directly if you do not want to
* reset all of the mocks.
*/
public void reset() throws Exception {
Mockito.reset(factory, client, paramsProvider);
}
}

View File

@@ -1,31 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

View File

@@ -1,23 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>commons-gradle</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>

View File

@@ -1,5 +0,0 @@
eclipse.preferences.version=1
encoding//src/main/java=UTF-8
encoding//src/test/java=UTF-8
encoding//src/test/resources=UTF-8
encoding/<project>=UTF-8

View File

@@ -1,5 +0,0 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.8

View File

@@ -1,4 +0,0 @@
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1

View File

@@ -1,41 +0,0 @@
<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>
<artifactId>commons-gradle</artifactId>
<name>commons-gradle</name>
<description>Gradle Utilities</description>
<parent>
<groupId>org.springframework.ide.vscode</groupId>
<artifactId>commons-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<properties>
<gradle-tooling.version>3.3</gradle-tooling.version>
</properties>
<repositories>
<repository>
<id>gradle-repo</id>
<name>Gradle Tooling Repo</name>
<url>https://repo.gradle.org/gradle/libs-releases</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.springframework.ide.vscode</groupId>
<artifactId>commons-java</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.gradle</groupId>
<artifactId>gradle-tooling-api</artifactId>
<version>${gradle-tooling.version}</version>
</dependency>
</dependencies>
</project>

View File

@@ -1,86 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.gradle;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.gradle.tooling.GradleConnectionException;
import org.gradle.tooling.GradleConnector;
import org.gradle.tooling.ProjectConnection;
import org.gradle.tooling.internal.consumer.DefaultGradleConnector;
import org.gradle.tooling.model.build.BuildEnvironment;
import org.gradle.tooling.model.eclipse.EclipseProject;
import org.springframework.ide.vscode.commons.util.Assert;
/**
* Gradle API tooling utility
*
* @author Alex Boyko
*
*/
public class GradleCore {
@FunctionalInterface
public interface GradleConfiguration {
void configure(GradleConnector connector);
}
public interface GradleCoreProject {
EclipseProject getProject();
BuildEnvironment getBuildEnvironment();
}
static final String GRADLE_BUILD_FILE = "build.gradle";
private static GradleCore defaultInstance = null;
public static GradleCore getDefault() {
if (defaultInstance == null) {
defaultInstance = new GradleCore();
}
return defaultInstance;
}
private GradleConfiguration configuration;
public GradleCore() {
this.configuration = (connector) -> {};
}
public GradleCore(GradleConfiguration configuration) {
Assert.isNotNull(configuration);
this.configuration = configuration;
}
public <T> T getModel(File projectDir, Class<T> modelType) throws GradleException {
ProjectConnection connection = null;
try {
GradleConnector gradleConnector = GradleConnector.newConnector().forProjectDirectory(projectDir);
/*
* Shut down Gradle daemons right away. Necessary project data is
* queried once and then cached, hence no need need to have the
* daemon running
*/
((DefaultGradleConnector) gradleConnector).daemonMaxIdleTime(1, TimeUnit.SECONDS);
configuration.configure(gradleConnector);
connection = gradleConnector.connect();
return connection.getModel(modelType);
} catch (GradleConnectionException e) {
throw new GradleException(e);
} finally {
if (connection != null) {
connection.close();
}
}
}
}

View File

@@ -1,45 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.gradle;
import java.util.Arrays;
import java.util.stream.Collectors;
/**
* Gradle wrapper exception
*
* @author Alex Boyko
*
*/
public class GradleException extends Exception {
private static final long serialVersionUID = 7958309594787399714L;
private Throwable[] t;
public GradleException() {
super();
}
public GradleException(Throwable... t) {
super();
this.t = t;
}
@Override
public String getMessage() {
if (t != null) {
return String.join("\n", Arrays.stream(t).map(t -> t.getMessage()).collect(Collectors.toList()));
}
return super.getMessage();
}
}

View File

@@ -1,36 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.gradle;
import java.io.File;
import org.springframework.ide.vscode.commons.java.IJavaProject;
/**
* Implementation of Gradle Java project
*
* @author Alex Boyko
*
*/
public class GradleJavaProject implements IJavaProject {
private GradleProjectClasspath classpath;
public GradleJavaProject(GradleCore gradle, File projectDir) throws GradleException {
this.classpath = new GradleProjectClasspath(gradle, projectDir);
}
@Override
public GradleProjectClasspath getClasspath() {
return classpath;
}
}

View File

@@ -1,207 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.gradle;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.gradle.tooling.model.build.BuildEnvironment;
import org.gradle.tooling.model.eclipse.EclipseProject;
import org.springframework.ide.vscode.commons.jandex.JandexClasspath;
import org.springframework.ide.vscode.commons.jandex.JandexIndex;
import org.springframework.ide.vscode.commons.java.IClasspath;
import org.springframework.ide.vscode.commons.java.IJavadocProvider;
import org.springframework.ide.vscode.commons.java.parser.ParserJavadocProvider;
import org.springframework.ide.vscode.commons.javadoc.HtmlJavadocProvider;
import org.springframework.ide.vscode.commons.javadoc.SourceUrlProviderFromSourceContainer;
import org.springframework.ide.vscode.commons.util.Log;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
/**
* Implementation of {@link IClasspath} for Gradle projects
*
* @author Alex Boyko
*
*/
public class GradleProjectClasspath extends JandexClasspath {
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";
private EclipseProject gradleProject;
private Supplier<BuildEnvironment> buildEnvironment;
public GradleProjectClasspath(GradleCore gradle, File projectDir) throws GradleException {
super();
this.gradleProject = gradle.getModel(projectDir, EclipseProject.class);
this.buildEnvironment = Suppliers.memoize(() -> {
try {
return gradle.getModel(projectDir, BuildEnvironment.class);
} catch (GradleException e) {
Log.log(e);
return null;
}
});
}
@Override
protected JandexIndex[] getBaseIndices() {
return new JandexIndex[] { new JandexIndex(getJreLibs().map(path -> path.toFile()).collect(Collectors.toList()),
jarFile -> findIndexFile(jarFile), (classpathResource) -> {
try {
String javaVersion = getJavaRuntimeMinorVersion();
if (javaVersion == null) {
javaVersion = "8";
}
URL javadocUrl = new URL("http://docs.oracle.com/javase/" + javaVersion + "/docs/api/");
return new HtmlJavadocProvider(
(type) -> SourceUrlProviderFromSourceContainer.JAVADOC_FOLDER_URL_SUPPLIER
.sourceUrl(javadocUrl, type));
} catch (MalformedURLException e) {
Log.log(e);
return null;
}
}) };
}
@Override
public Stream<Path> getClasspathEntries() throws Exception {
return Stream.concat(gradleProject.getClasspath().stream().map(dep -> dep.getFile().toPath()),
gradleProject.getProjectDependencies().stream().map(project -> new File(project.getPath()).toPath()));
}
@Override
public Stream<String> getClasspathResources() {
return gradleProject.getSourceDirectories().stream().map(sourceDirectory -> sourceDirectory.getDirectory()).flatMap(folder -> {
try {
return Files.walk(folder.toPath())
.filter(path -> Files.isRegularFile(path))
.map(path -> folder.toPath().relativize(path))
.map(relativePath -> relativePath.toString())
.filter(pathString -> !pathString.endsWith(".java") && !pathString.endsWith(".class"));
} catch (IOException e) {
return Stream.empty();
}
});
}
public Path getOutputFolder() {
return gradleProject.getProjectDirectory().toPath().resolve(gradleProject.getOutputLocation().getPath());
}
public String getName() {
return gradleProject.getName();
}
public boolean exists() {
return gradleProject != null;
}
@Override
protected IJavadocProvider createParserJavadocProvider(File classpathResource) {
if (classpathResource.isDirectory()) {
Optional<File> classpathFolder = gradleProject.getSourceDirectories().stream()
.map(dir -> dir.getDirectory())
.filter(dir -> classpathResource.toPath().startsWith(dir.toPath()))
.findFirst();
if (classpathFolder.isPresent()) {
return new ParserJavadocProvider(type -> {
return SourceUrlProviderFromSourceContainer.SOURCE_FOLDER_URL_SUPPLIER
.sourceUrl(classpathFolder.get().toURI().toURL(), type);
});
}
} else {
}
return null;
}
@Override
protected IJavadocProvider createHtmlJavdocProvider(File classpathResource) {
return null;
}
public String getGradleVersion() throws GradleException {
if (buildEnvironment.get() == null) {
throw new GradleException(new Exception("Cannot find Gradle version"));
} else {
return buildEnvironment.get().getGradle().getGradleVersion();
}
}
public File getGradleHome() throws GradleException {
if (buildEnvironment.get() == null) {
throw new GradleException(new Exception("Cannot find Gradle home folder"));
} else {
return buildEnvironment.get().getGradle().getGradleUserHome();
}
}
public String getJavaRuntimeVersion() {
return System.getProperty(JAVA_RUNTIME_VERSION);
}
public String getJavaRuntimeMinorVersion() {
String fullVersion = getJavaRuntimeVersion();
String[] tokenized = fullVersion.split("\\.");
if (tokenized.length > 1) {
return tokenized[1];
} else {
Log.log("Cannot determine minor version for the Java Runtime Version: " + fullVersion);
return null;
}
}
private String getJavaHome() {
if (buildEnvironment.get() == null) {
return System.getProperty(JAVA_HOME);
} else {
return buildEnvironment.get().getJava().getJavaHome().toString();
}
}
private Stream<Path> getJreLibs() {
String s = System.getProperty(JAVA_BOOT_CLASS_PATH);
return Arrays.stream(s.split(File.pathSeparator))
.map(strPath -> strPath.replace(System.getProperty(JAVA_HOME), getJavaHome()))
.map(File::new)
.filter(f -> f.canRead())
.map(f -> f.toPath());
}
private File findIndexFile(File jarFile) {
String suffix = null;
String javaHome = getJavaHome();
if (javaHome != null) {
int index = javaHome.lastIndexOf('/');
if (index != -1) {
javaHome = javaHome.substring(0, index);
}
}
if (jarFile.toString().startsWith(javaHome)) {
suffix = getJavaRuntimeVersion();
}
return new File(JandexIndex.getIndexFolder().toString(), jarFile.getName() + "-" + suffix + ".jdx");
}
}

View File

@@ -1,62 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.gradle;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.ExecutionException;
import org.springframework.ide.vscode.commons.languageserver.java.IJavaProjectFinderStrategy;
import org.springframework.ide.vscode.commons.util.FileUtils;
import org.springframework.ide.vscode.commons.util.StringUtil;
import org.springframework.ide.vscode.commons.util.text.IDocument;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
/**
* Tests whether document belongs to a Gradle project
*
* @author Alex Boyko
*
*/
public class GradleProjectFinderStrategy implements IJavaProjectFinderStrategy {
private Cache<File, GradleJavaProject> cache = CacheBuilder.newBuilder().build();
private GradleCore gradle;
public GradleProjectFinderStrategy(GradleCore gradle) {
this.gradle = gradle;
}
@Override
public GradleJavaProject find(IDocument d) throws ExecutionException, URISyntaxException {
String uriStr = d.getUri();
if (StringUtil.hasText(uriStr)) {
URI uri = new URI(uriStr);
// TODO: This only work with File uri. Should it work with others
// too?
if (uri.getScheme().equalsIgnoreCase("file")) {
File file = new File(uri).getAbsoluteFile();
File gradlebuild = FileUtils.findFile(file, GradleCore.GRADLE_BUILD_FILE);
if (gradlebuild != null) {
return cache.get(gradlebuild.getParentFile(), () -> {
return new GradleJavaProject(gradle, gradlebuild.getParentFile());
});
}
}
}
return null;
}
}

View File

@@ -1,58 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.gradle;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.Test;
/**
* Tests covering Gradle project data
*
* @author Alex Boyko
*
*/
public class GradleProjectTest {
private GradleJavaProject getGradleProject(String projectName) throws Exception {
Path testProjectPath = Paths.get(GradleProjectTest.class.getResource("/" + projectName).toURI());
return new GradleJavaProject(GradleCore.getDefault(), testProjectPath.toFile());
}
@Test
public void testEclipseGradleProject() throws Exception {
GradleJavaProject project = getGradleProject("empty-gradle-project");
Set<Path> calculatedClassPath = project.getClasspath().getClasspathEntries().collect(Collectors.toSet());
assertEquals(48, calculatedClassPath.size());
}
@Test
public void outputFolder() throws Exception {
GradleJavaProject project = getGradleProject("test-app-1");
assertTrue(project.getClasspath().getOutputFolder().endsWith("bin"));
}
@Test
public void gradleClasspathResource() throws Exception {
GradleJavaProject project = getGradleProject("test-app-1");
List<String> resources = project.getClasspath().getClasspathResources().collect(Collectors.toList());
assertArrayEquals(new String[] {"test-resource-1.txt"}, resources.toArray(new String[resources.size()]));
}
}

View File

@@ -1,25 +0,0 @@
.gradle
/build/
!gradle/wrapper/gradle-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

@@ -1,33 +0,0 @@
buildscript {
ext {
springBootVersion = '1.5.1.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
jar {
baseName = 'empty-boot-1.4.0-web-app'
version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-actuator')
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}

View File

@@ -1,5 +0,0 @@
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

@@ -1,164 +0,0 @@
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# 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
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# 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
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
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" -a "$nonstop" = "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

@@ -1,90 +0,0 @@
@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
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@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=
@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 Windows 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

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

View File

@@ -1,16 +0,0 @@
package com.example;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class EmptyGradleProjectApplicationTests {
@Test
public void contextLoads() {
}
}

View File

@@ -1,28 +0,0 @@
/*
* This build file was generated by the Gradle 'init' task.
*
* This generated file contains a sample Java project to get you started.
* For more details take a look at the Java Quickstart chapter in the Gradle
* user guide available at https://docs.gradle.org/3.3/userguide/tutorial_java_projects.html
*/
// Apply the java plugin to add support for Java
apply plugin: 'java'
// In this section you declare where to find the dependencies of your project
repositories {
// Use jcenter for resolving your dependencies.
// You can declare any Maven/Ivy/file repository here.
jcenter()
}
dependencies {
// The production code uses Guava
compile 'com.google.guava:guava:20.0'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-actuator', version: '1.5.1.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '1.5.1.RELEASE'
// Use JUnit test framework
testCompile 'junit:junit:4.12'
}

View File

@@ -1,6 +0,0 @@
#Tue Feb 07 11:31:46 EST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-bin.zip

View File

@@ -1,172 +0,0 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# 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
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# 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
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
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" -a "$nonstop" = "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
# Escape application args
save ( ) {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

View File

@@ -1,84 +0,0 @@
@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
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@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=
@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 Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_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=%*
: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

@@ -1,20 +0,0 @@
/*
* This settings file was generated by the Gradle 'init' task.
*
* The settings file is used to specify which projects to include in your build.
* In a single project build this file can be empty or even removed.
*
* Detailed information about configuring a multi-project build in Gradle can be found
* in the user guide at https://docs.gradle.org/3.3/userguide/multi_project_builds.html
*/
/*
// To declare projects as part of a multi-project build use the 'include' method
include 'shared'
include 'api'
include 'services:webservice'
*/
rootProject.name = 'test-app-1'
//org.gradle.java.home = '/Library/Java/JavaVirtualMachines/jdk1.7.0_60.jdk/Contents/Home'

View File

@@ -1,8 +0,0 @@
/*
* This Java source file was generated by the Gradle 'init' task.
*/
public class Library {
public boolean someLibraryMethod() {
return true;
}
}

View File

@@ -1,12 +0,0 @@
/*
* This Java source file was generated by the Gradle 'init' task.
*/
import org.junit.Test;
import static org.junit.Assert.*;
public class LibraryTest {
@Test public void testSomeLibraryMethod() {
Library classUnderTest = new Library();
assertTrue("someLibraryMethod should return 'true'", classUnderTest.someLibraryMethod());
}
}

View File

@@ -1,26 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

View File

@@ -1,23 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>commons-java</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>

View File

@@ -1,3 +0,0 @@
eclipse.preferences.version=1
encoding//src/main/java=UTF-8
encoding/<project>=UTF-8

View File

@@ -1,5 +0,0 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.8

View File

@@ -1,4 +0,0 @@
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1

View File

@@ -1,50 +0,0 @@
<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>
<artifactId>commons-java</artifactId>
<name>commons-java</name>
<description>Common code related to 'accessing Java knowledge'</description>
<parent>
<groupId>org.springframework.ide.vscode</groupId>
<artifactId>commons-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<properties>
<!-- roatser version -->
<roaster.version>2.19.2.Final</roaster.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.ide.vscode</groupId>
<artifactId>commons-util</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.jboss</groupId>
<artifactId>jandex</artifactId>
<version>2.0.3.Final</version>
</dependency>
<!-- HTML <-> Markdown conversion -->
<dependency>
<groupId>com.kotcrab.remark</groupId>
<artifactId>remark</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.github.javaparser</groupId>
<artifactId>javaparser-core</artifactId>
<version>2.5.1</version>
</dependency>
<!-- Reactor -->
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
<version>${reactor-version}</version>
</dependency>
</dependencies>
</project>

View File

@@ -1,72 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016-2017 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.jandex;
import java.util.stream.Stream;
import org.jboss.jandex.AnnotationInstance;
import org.springframework.ide.vscode.commons.java.IAnnotation;
import org.springframework.ide.vscode.commons.java.IJavadocProvider;
import org.springframework.ide.vscode.commons.java.IMemberValuePair;
import org.springframework.ide.vscode.commons.javadoc.IJavadoc;
public class AnnotationImpl implements IAnnotation {
private AnnotationInstance annotation;
private IJavadocProvider javadocProvider;
AnnotationImpl(AnnotationInstance annotation, IJavadocProvider javadocProvider) {
this.annotation = annotation;
this.javadocProvider = javadocProvider;
}
@Override
public String getElementName() {
return annotation.name().toString();
}
@Override
public IJavadoc getJavaDoc() {
return javadocProvider == null ? null : javadocProvider.getJavadoc(this);
}
@Override
public boolean exists() {
return true;
}
@Override
public Stream<IMemberValuePair> getMemberValuePairs() {
return annotation.values().stream().map(av -> {
return Wrappers.wrap(av);
});
}
@Override
public String toString() {
return annotation.toString();
}
@Override
public int hashCode() {
return annotation.toString().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof AnnotationImpl) {
return annotation.toString().equals(((AnnotationImpl)obj).annotation.toString());
}
return super.equals(obj);
}
}

View File

@@ -1,41 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016-2017 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.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

@@ -1,28 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016-2017 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.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

@@ -1,93 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016-2017 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.jandex;
import java.util.stream.Stream;
import org.jboss.jandex.FieldInfo;
import org.springframework.ide.vscode.commons.java.Flags;
import org.springframework.ide.vscode.commons.java.IAnnotation;
import org.springframework.ide.vscode.commons.java.IField;
import org.springframework.ide.vscode.commons.java.IJavadocProvider;
import org.springframework.ide.vscode.commons.java.IType;
import org.springframework.ide.vscode.commons.javadoc.IJavadoc;
class FieldImpl implements IField {
private JandexIndex index;
private FieldInfo field;
private IJavadocProvider javadocProvider;
FieldImpl(JandexIndex index, FieldInfo field, IJavadocProvider javadocProvider) {
this.index = index;
this.field = field;
this.javadocProvider = javadocProvider;
}
@Override
public int getFlags() {
return field.flags();
}
@Override
public IType getDeclaringType() {
return Wrappers.wrap(index, field.declaringClass(), javadocProvider);
}
@Override
public String getElementName() {
return field.name();
}
@Override
public IJavadoc getJavaDoc() {
return javadocProvider == null ? null : javadocProvider.getJavadoc(this);
}
@Override
public boolean exists() {
return true;
}
@Override
public Stream<IAnnotation> getAnnotations() {
return field.annotations().stream().map(a -> {
return Wrappers.wrap(a, javadocProvider);
});
}
@Override
public boolean isEnumConstant() {
return Flags.isEnum(field.flags());
}
@Override
public String toString() {
return field.toString();
}
@Override
public int hashCode() {
return field.toString().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof FieldImpl) {
return field.toString().equals(((FieldImpl)obj).field.toString());
}
return super.equals(obj);
}
}

View File

@@ -1,88 +0,0 @@
package org.springframework.ide.vscode.commons.jandex;
import java.io.File;
import java.nio.file.Path;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.ide.vscode.commons.java.IClasspath;
import org.springframework.ide.vscode.commons.java.IJavadocProvider;
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;
import reactor.core.publisher.Flux;
import reactor.util.function.Tuple2;
public abstract class JandexClasspath implements IClasspath {
public static JavadocProviderTypes providerType = JavadocProviderTypes.HTML;
public enum JavadocProviderTypes {
JAVA_PARSER,
HTML
}
private Supplier<JandexIndex> javaIndex;
public JandexClasspath() {
this.javaIndex = Suppliers.memoize(() -> createIndex());
}
protected JandexIndex createIndex() {
Stream<Path> classpathEntries = Stream.empty();
try {
classpathEntries = getClasspathEntries();
} catch (Exception e) {
Log.log(e);
}
return new JandexIndex(classpathEntries.map(p -> p.toFile()).collect(Collectors.toList()), jarFile -> findIndexFile(jarFile), classpathResource -> {
switch (providerType) {
case JAVA_PARSER:
return createParserJavadocProvider(classpathResource);
default:
return createHtmlJavdocProvider(classpathResource);
}
}, getBaseIndices());
}
protected JandexIndex[] getBaseIndices() {
return new JandexIndex[0];
}
public IType findType(String fqName) {
return javaIndex.get().findType(fqName);
}
public Flux<Tuple2<IType, Double>> fuzzySearchTypes(String searchTerm, Predicate<IType> typeFilter) {
return javaIndex.get().fuzzySearchTypes(searchTerm, typeFilter);
}
public Flux<Tuple2<String, Double>> fuzzySearchPackages(String searchTerm) {
return javaIndex.get().fuzzySearchPackages(searchTerm);
}
public Flux<IType> allSubtypesOf(IType type) {
return javaIndex.get().allSubtypesOf(type);
}
private File findIndexFile(File jarFile) {
File indexFolder = getIndexFolder();
if (indexFolder == null) {
return null;
}
return new File(indexFolder.toString(), jarFile.getName() + "-" + jarFile.lastModified() + ".jdx");
}
protected File getIndexFolder() {
return JandexIndex.getIndexFolder();
}
abstract protected IJavadocProvider createParserJavadocProvider(File classpathResource);
abstract protected IJavadocProvider createHtmlJavdocProvider(File classpathResource);
}

View File

@@ -1,316 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016-2017 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.jandex;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.jboss.jandex.ClassInfo;
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.IAnnotation;
import org.springframework.ide.vscode.commons.java.IField;
import org.springframework.ide.vscode.commons.java.IJavadocProvider;
import org.springframework.ide.vscode.commons.java.IMethod;
import org.springframework.ide.vscode.commons.java.IType;
import org.springframework.ide.vscode.commons.javadoc.IJavadoc;
import org.springframework.ide.vscode.commons.util.FuzzyMatcher;
import org.springframework.ide.vscode.commons.util.Log;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;
public class JandexIndex {
private static final String JAVA_IO_TMPDIR = "java.io.tmpdir";
@FunctionalInterface
public static interface IndexFileFinder {
File findIndexFile(File jarFile);
}
@FunctionalInterface
public static interface JavadocProviderFactory {
IJavadocProvider createJavadocProvider(File jarContainer);
}
public static File getIndexFolder() {
File folder = new File(System.getProperty(JAVA_IO_TMPDIR), "jandex");
if (!folder.isDirectory()) {
folder.mkdirs();
}
return folder;
}
private static final IJavadocProvider ABSENT_JAVADOC_PROVIDER = new IJavadocProvider() {
@Override
public IJavadoc getJavadoc(IType type) {
return null;
}
@Override
public IJavadoc getJavadoc(IField field) {
return null;
}
@Override
public IJavadoc getJavadoc(IMethod method) {
return null;
}
@Override
public IJavadoc getJavadoc(IAnnotation method) {
return null;
}
};
private Map<File, Supplier<Optional<IndexView>>> index;
private JavadocProviderFactory javadocProviderFactory;
private Map<File, Supplier<List<Tuple2<String, IType>>>> knownTypes;
private Map<File, Supplier<List<String>>> knownPackages;
private Cache<File, IJavadocProvider> javadocProvidersCache = CacheBuilder.newBuilder().build();
private JandexIndex[] baseIndex;
public void setJvadocProviderFactory(JavadocProviderFactory sourceContainerProvider) {
this.javadocProviderFactory = sourceContainerProvider;
}
public JavadocProviderFactory getJavadocProviderFactory() {
return javadocProviderFactory;
}
public JandexIndex(Collection<File> classpathEntries, IndexFileFinder indexFileFinder,
JavadocProviderFactory javadocProviderFactory, JandexIndex... baseIndex) {
this.baseIndex = baseIndex;
this.index = new ConcurrentHashMap<>();
this.knownTypes = new HashMap<>();
this.knownPackages = new HashMap<>();
this.javadocProviderFactory = javadocProviderFactory;
classpathEntries.forEach(file -> {
index.put(file, Suppliers.memoize(() -> createIndex(file, indexFileFinder)));
knownTypes.put(file, Suppliers.memoize(() -> getKnownTypesStream(file).collect(Collectors.toList())));
knownPackages.put(file, Suppliers.memoize(() -> getKnownPackages(file).collect(Collectors.toList())));
});
}
private Optional<IndexView> createIndex(File file, IndexFileFinder indexFileFinder) {
if (file != null && file.isFile() && file.getName().endsWith(".jar")) {
return indexJar(file, indexFileFinder);
} else if (file != null && file.isDirectory()) {
return indexFolder(file);
} else {
return Optional.empty();
}
}
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) {
File indexFile = indexFileFinder.findIndexFile(file);
if (indexFile != null) {
try {
if (indexFile.createNewFile()) {
try {
return Optional.of(JarIndexer.createJarIndex(file, new Indexer(), indexFile, false, false,
false, System.out, System.err).getIndex());
} catch (IOException e) {
Log.log("Failed to index '" + file + "'", e);
}
} else {
try {
return Optional.of(new IndexReader(new FileInputStream(indexFile)).read());
} catch (IOException e) {
Log.log("Failed to read index file '" + indexFile + "'. Creating new index file.", e);
if (indexFile.delete()) {
return indexJar(file, indexFileFinder);
} else {
Log.log("Failed to read index file '" + indexFile);
}
}
}
} catch (IOException e) {
Log.log("Unable to create index file '" + indexFile + "'");
}
} else {
try {
return Optional.of(JarIndexer
.createJarIndex(file, new Indexer(), file.canWrite(), file.getParentFile().canWrite(), false)
.getIndex());
} catch (IOException e) {
Log.log("Failed to index '" + file + "'", e);
}
}
return Optional.empty();
}
public IType findType(String fqName) {
return getClassByName(DotName.createSimple(fqName));
}
IType getClassByName(DotName fqName) {
// First look for type in the base index array
return (baseIndex == null ? Stream.<IType>empty()
: Arrays.stream(
baseIndex)
.filter(
jandexIndex -> jandexIndex != null)
.map(jandexIndex -> jandexIndex.getClassByName(fqName))).filter(type -> type != null)
.findFirst()
// If not found look at indices owned by this
// JandexIndex instance
.orElseGet(() -> streamOfIndices()
.map(e -> Tuples.of(e.getT1(), e.getT2().getClassByName(fqName)))
.filter(e -> e.getT2() != null).map(e -> createType(e)).findFirst()
.orElse(null));
}
private IType createType(Tuple2<File, ClassInfo> match) {
File classpathResource = match.getT1();
IJavadocProvider javadocProvider = null;
try {
javadocProvider = javadocProvidersCache.get(classpathResource, () -> {
IJavadocProvider provider = null;
if (javadocProviderFactory != null) {
provider = javadocProviderFactory.createJavadocProvider(classpathResource);
}
return provider == null ? ABSENT_JAVADOC_PROVIDER : provider;
});
} catch (ExecutionException e) {
Log.log(e);
}
return Wrappers.wrap(this, match.getT2(), javadocProvider);
}
private Stream<Tuple2<File, IndexView>> streamOfIndices() {
return index.entrySet().parallelStream().map(e -> Tuples.of(e.getKey(), e.getValue().get()))
.filter(t -> t.getT2().isPresent()).map(t -> Tuples.of(t.getT1(), t.getT2().get()));
}
private Stream<Tuple2<String, IType>> getKnownTypesStream(File file) {
Optional<IndexView> indexView = index.get(file).get();
if (indexView.isPresent()) {
return indexView.get().getKnownClasses().parallelStream()
.map(info -> Tuples.of(info.name().toString(), createType(Tuples.of(file, info))));
}
return Stream.empty();
}
private Stream<String> getKnownPackages(File file) {
Optional<IndexView> indexView = index.get(file).get();
if (indexView.isPresent()) {
return indexView.get().getKnownClasses().parallelStream().map(info -> {
String name = info.name().toString();
return name.substring(0, name.lastIndexOf('.'));
}).distinct();
}
return Stream.empty();
}
public Flux<Tuple2<IType, Double>> fuzzySearchTypes(String searchTerm, Predicate<IType> typeFilter) {
Flux<Tuple2<IType, Double>> flux = Flux.fromIterable(knownTypes.values()).publishOn(Schedulers.parallel())
.flatMap(s -> Flux.fromIterable(s.get())).filter(t -> typeFilter == null || typeFilter.test(t.getT2()))
.map(t -> Tuples.of(t.getT2(), FuzzyMatcher.matchScore(searchTerm, t.getT1())))
.filter(t -> t.getT2() != 0.0);
if (baseIndex == null) {
return flux;
} else {
return Flux.merge(flux,
Flux.fromArray(baseIndex).flatMap(index -> index.fuzzySearchTypes(searchTerm, typeFilter)));
}
}
public Flux<Tuple2<String, Double>> fuzzySearchPackages(String searchTerm) {
Flux<Tuple2<String, Double>> flux = Flux.fromIterable(knownPackages.values()).publishOn(Schedulers.parallel())
.flatMap(s -> Flux.fromIterable(s.get()))
.map(pkg -> Tuples.of(pkg, FuzzyMatcher.matchScore(searchTerm, pkg))).filter(t -> t.getT2() != 0.0);
if (baseIndex == null) {
return flux;
} else {
return Flux.merge(flux, Flux.fromArray(baseIndex).flatMap(index -> index.fuzzySearchPackages(searchTerm)));
}
}
public Flux<IType> allSubtypesOf(IType type) {
DotName name = DotName.createSimple(type.getFullyQualifiedName());
Flux<IType> flux = Flux.fromIterable(index.keySet()).publishOn(Schedulers.parallel()).flatMap(file -> {
Optional<IndexView> optional = index.get(file).get();
if (optional.isPresent()) {
return Flux
.fromIterable(type.isInterface() ? optional.get().getAllKnownImplementors(name)
: optional.get().getAllKnownSubclasses(name))
.publishOn(Schedulers.parallel()).map(info -> createType(Tuples.of(file, info)));
} else {
return Flux.empty();
}
});
if (baseIndex == null) {
return flux;
} else {
return Flux.merge(flux, Flux.fromArray(baseIndex).flatMap(index -> index.allSubtypesOf(type)));
}
}
}

View File

@@ -1,113 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016-2017 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.jandex;
import java.util.stream.Stream;
import org.jboss.jandex.MethodInfo;
import org.springframework.ide.vscode.commons.java.IAnnotation;
import org.springframework.ide.vscode.commons.java.IJavaType;
import org.springframework.ide.vscode.commons.java.IJavadocProvider;
import org.springframework.ide.vscode.commons.java.IMethod;
import org.springframework.ide.vscode.commons.java.IType;
import org.springframework.ide.vscode.commons.javadoc.IJavadoc;
public class MethodImpl implements IMethod {
private static final String JANDEX_CONTRUCTOR_NAME = "<init>";
private JandexIndex index;
private MethodInfo method;
private IJavadocProvider javadocProvider;
MethodImpl(JandexIndex index, MethodInfo method, IJavadocProvider javadocProvider) {
this.index = index;
this.method = method;
this.javadocProvider =javadocProvider;
}
@Override
public int getFlags() {
return method.flags();
}
@Override
public boolean isConstructor() {
return method.name().equals(JANDEX_CONTRUCTOR_NAME);
}
@Override
public IType getDeclaringType() {
return Wrappers.wrap(index, method.declaringClass(), javadocProvider);
}
@Override
public String getElementName() {
return isConstructor() ? getDeclaringType().getElementName() : method.name();
}
@Override
public IJavadoc getJavaDoc() {
return javadocProvider == null ? null : javadocProvider.getJavadoc(this);
}
@Override
public boolean exists() {
return true;
}
@Override
public Stream<IAnnotation> getAnnotations() {
return method.annotations().stream().map(a -> Wrappers.wrap(a, javadocProvider));
}
@Override
public IJavaType getReturnType() {
return Wrappers.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);
}
@Override
public int hashCode() {
return method.toString().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof MethodImpl) {
return method.toString().equals(((MethodImpl)obj).method.toString());
}
return super.equals(obj);
}
}

View File

@@ -1,42 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016-2017 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.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

@@ -1,145 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016-2017 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.jandex;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.Type;
import org.springframework.ide.vscode.commons.java.Flags;
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.IJavadocProvider;
import org.springframework.ide.vscode.commons.java.IMethod;
import org.springframework.ide.vscode.commons.java.IType;
import org.springframework.ide.vscode.commons.javadoc.IJavadoc;
class TypeImpl implements IType {
private ClassInfo info;
private JandexIndex index;
private IJavadocProvider javadocProvider;
TypeImpl(JandexIndex index, ClassInfo info, IJavadocProvider javadocProvider) {
this.info = info;
this.index = index;
this.javadocProvider = javadocProvider;
}
@Override
public int getFlags() {
return info.flags();
}
@Override
public IType getDeclaringType() {
DotName enclosingClass = info.enclosingClass();
return enclosingClass == null ? null : index.getClassByName(enclosingClass);
}
@Override
public String getElementName() {
return info.simpleName() == null ? info.name().local() : info.simpleName();
}
@Override
public IJavadoc getJavaDoc() {
return javadocProvider == null ? null : javadocProvider.getJavadoc(this);
}
@Override
public boolean exists() {
return true;
}
@Override
public Stream<IAnnotation> getAnnotations() {
// TODO: check correctness!
List<AnnotationInstance> annotations = info.annotations().get(info.name());
return annotations == null ? Stream.empty() : annotations.stream().map(a -> Wrappers.wrap(a, javadocProvider));
}
@Override
public boolean isClass() {
return true;
}
@Override
public boolean isEnum() {
return Flags.isEnum(info.flags());
}
@Override
public boolean isInterface() {
return Flags.isInterface(info.flags());
}
@Override
public boolean isAnnotation() {
return Flags.isAnnotation(info.flags());
}
@Override
public String getFullyQualifiedName() {
return info.name().toString();
}
@Override
public IField getField(String name) {
return Wrappers.wrap(index, info.field(name), javadocProvider);
}
@Override
public Stream<IField> getFields() {
return info.fields().stream().map(f -> {
return Wrappers.wrap(index, f, javadocProvider);
});
}
@Override
public IMethod getMethod(String name, Stream<IJavaType> parameters) {
List<Type> typeParameters = parameters.map(Wrappers::from).collect(Collectors.toList());
return Wrappers.wrap(index, info.method(name, typeParameters.toArray(new Type[typeParameters.size()])), javadocProvider);
}
@Override
public Stream<IMethod> getMethods() {
return info.methods().stream().map(m -> {
return Wrappers.wrap(index, m, javadocProvider);
});
}
@Override
public String toString() {
return info.toString();
}
@Override
public int hashCode() {
return info.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof TypeImpl) {
return info.equals(((TypeImpl)obj).info);
}
return super.equals(obj);
}
}

View File

@@ -1,28 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016-2017 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.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

@@ -1,45 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016-2017 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.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

@@ -1,28 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016-2017 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.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

@@ -1,28 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016-2017 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.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

@@ -1,154 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016-2017 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.jandex;
import static org.springframework.ide.vscode.commons.util.Assert.isNotNull;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationValue;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.FieldInfo;
import org.jboss.jandex.MethodInfo;
import org.jboss.jandex.PrimitiveType;
import org.jboss.jandex.Type;
import org.jboss.jandex.Type.Kind;
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.IJavadocProvider;
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;
public class Wrappers {
public static IType wrap(JandexIndex index, ClassInfo info, IJavadocProvider javadocProvider) {
if (info == null) {
return null;
}
return new TypeImpl(index, info, javadocProvider);
}
public static IField wrap(JandexIndex index, FieldInfo field, IJavadocProvider javadocProvider) {
if (field == null) {
return null;
}
return new FieldImpl(index, field, javadocProvider);
}
public static IMethod wrap(JandexIndex index, MethodInfo method, IJavadocProvider javadocProvider) {
isNotNull(index);
isNotNull(method);
return new MethodImpl(index, method, javadocProvider);
}
public static IAnnotation wrap(AnnotationInstance annotation, IJavadocProvider javadocProvider) {
isNotNull(annotation);
return new AnnotationImpl(annotation, javadocProvider);
}
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 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")
static Type from(IJavaType type) {
if (type == IPrimitiveType.BOOLEAN) {
return PrimitiveType.BOOLEAN;
} else if (type == IPrimitiveType.BYTE) {
return PrimitiveType.BYTE;
} else if (type == IPrimitiveType.CHAR) {
return PrimitiveType.CHAR;
} else if (type == IPrimitiveType.DOUBLE) {
return PrimitiveType.DOUBLE;
} else if (type == IPrimitiveType.FLOAT) {
return PrimitiveType.FLOAT;
} else if (type == IPrimitiveType.INT) {
return PrimitiveType.INT;
} else if (type == IPrimitiveType.LONG) {
return PrimitiveType.LONG;
} else if (type == IPrimitiveType.SHORT) {
return PrimitiveType.SHORT;
} else if (type == IVoidType.DEFAULT) {
return Type.create(null, Kind.VOID);
} else 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,161 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2014 IBM Corporation and others.
* 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:
* IBM Corporation - initial API and implementation
* Jesper S Moller - Contributions for
* Bug 405066 - [1.8][compiler][codegen] Implement code generation infrastructure for JSR335
* Bug 406982 - [1.8][compiler] Generation of MethodParameters Attribute in classfile
* Andy Clement (GoPivotal, Inc) aclement@gopivotal.com - Contributions for
* Bug 405104 - [1.8][compiler][codegen] Implement support for serializeable lambdas
*******************************************************************************/
package org.springframework.ide.vscode.commons.java;
public interface ClassFileConstants {
int AccDefault = 0;
/*
* Modifiers
*/
int AccPublic = 0x0001;
int AccPrivate = 0x0002;
int AccProtected = 0x0004;
int AccStatic = 0x0008;
int AccFinal = 0x0010;
int AccSynchronized = 0x0020;
int AccVolatile = 0x0040;
int AccBridge = 0x0040;
int AccTransient = 0x0080;
int AccVarargs = 0x0080;
int AccNative = 0x0100;
int AccInterface = 0x0200;
int AccAbstract = 0x0400;
int AccStrictfp = 0x0800;
int AccSynthetic = 0x1000;
int AccAnnotation = 0x2000;
int AccEnum = 0x4000;
/**
* From classfile version 52 (compliance 1.8 up), meaning that a formal parameter is mandated
* by a language specification, so all compilers for the language must emit it.
*/
int AccMandated = 0x8000;
/**
* Other VM flags.
*/
int AccSuper = 0x0020;
// /**
// * Extra flags for types and members attributes (not from the JVMS, should have been defined in ExtraCompilerModifiers).
// */
// int AccAnnotationDefault = ASTNode.Bit18; // indicate presence of an attribute "DefaultValue" (annotation method)
// int AccDeprecated = ASTNode.Bit21; // indicate presence of an attribute "Deprecated"
int Utf8Tag = 1;
int IntegerTag = 3;
int FloatTag = 4;
int LongTag = 5;
int DoubleTag = 6;
int ClassTag = 7;
int StringTag = 8;
int FieldRefTag = 9;
int MethodRefTag = 10;
int InterfaceMethodRefTag = 11;
int NameAndTypeTag = 12;
int MethodHandleTag = 15;
int MethodTypeTag = 16;
int InvokeDynamicTag = 18;
int ConstantMethodRefFixedSize = 5;
int ConstantClassFixedSize = 3;
int ConstantDoubleFixedSize = 9;
int ConstantFieldRefFixedSize = 5;
int ConstantFloatFixedSize = 5;
int ConstantIntegerFixedSize = 5;
int ConstantInterfaceMethodRefFixedSize = 5;
int ConstantLongFixedSize = 9;
int ConstantStringFixedSize = 3;
int ConstantUtf8FixedSize = 3;
int ConstantNameAndTypeFixedSize = 5;
int ConstantMethodHandleFixedSize = 4;
int ConstantMethodTypeFixedSize = 3;
int ConstantInvokeDynamicFixedSize = 5;
// JVMS 4.4.8
int MethodHandleRefKindGetField = 1;
int MethodHandleRefKindGetStatic = 2;
int MethodHandleRefKindPutField = 3;
int MethodHandleRefKindPutStatic = 4;
int MethodHandleRefKindInvokeVirtual = 5;
int MethodHandleRefKindInvokeStatic = 6;
int MethodHandleRefKindInvokeSpecial = 7;
int MethodHandleRefKindNewInvokeSpecial = 8;
int MethodHandleRefKindInvokeInterface = 9;
int MAJOR_VERSION_1_1 = 45;
int MAJOR_VERSION_1_2 = 46;
int MAJOR_VERSION_1_3 = 47;
int MAJOR_VERSION_1_4 = 48;
int MAJOR_VERSION_1_5 = 49;
int MAJOR_VERSION_1_6 = 50;
int MAJOR_VERSION_1_7 = 51;
int MAJOR_VERSION_1_8 = 52;
int MAJOR_VERSION_1_9 = 53; // This might change
int MINOR_VERSION_0 = 0;
int MINOR_VERSION_1 = 1;
int MINOR_VERSION_2 = 2;
int MINOR_VERSION_3 = 3;
int MINOR_VERSION_4 = 4;
// JDK 1.1 -> 1.9, comparable value allowing to check both major/minor version at once 1.4.1 > 1.4.0
// 16 unsigned bits for major, then 16 bits for minor
long JDK1_1 = ((long)ClassFileConstants.MAJOR_VERSION_1_1 << 16) + ClassFileConstants.MINOR_VERSION_3; // 1.1. is 45.3
long JDK1_2 = ((long)ClassFileConstants.MAJOR_VERSION_1_2 << 16) + ClassFileConstants.MINOR_VERSION_0;
long JDK1_3 = ((long)ClassFileConstants.MAJOR_VERSION_1_3 << 16) + ClassFileConstants.MINOR_VERSION_0;
long JDK1_4 = ((long)ClassFileConstants.MAJOR_VERSION_1_4 << 16) + ClassFileConstants.MINOR_VERSION_0;
long JDK1_5 = ((long)ClassFileConstants.MAJOR_VERSION_1_5 << 16) + ClassFileConstants.MINOR_VERSION_0;
long JDK1_6 = ((long)ClassFileConstants.MAJOR_VERSION_1_6 << 16) + ClassFileConstants.MINOR_VERSION_0;
long JDK1_7 = ((long)ClassFileConstants.MAJOR_VERSION_1_7 << 16) + ClassFileConstants.MINOR_VERSION_0;
long JDK1_8 = ((long)ClassFileConstants.MAJOR_VERSION_1_8 << 16) + ClassFileConstants.MINOR_VERSION_0;
long JDK1_9 = ((long)ClassFileConstants.MAJOR_VERSION_1_9 << 16) + ClassFileConstants.MINOR_VERSION_0;
/*
* cldc1.1 is 45.3, but we modify it to be different from JDK1_1.
* In the code gen, we will generate the same target value as JDK1_1
*/
long CLDC_1_1 = ((long)ClassFileConstants.MAJOR_VERSION_1_1 << 16) + ClassFileConstants.MINOR_VERSION_4;
// jdk level used to denote future releases: optional behavior is not enabled for now, but may become so. In order to enable these,
// search for references to this constant, and change it to one of the official JDT constants above.
long JDK_DEFERRED = Long.MAX_VALUE;
int INT_ARRAY = 10;
int BYTE_ARRAY = 8;
int BOOLEAN_ARRAY = 4;
int SHORT_ARRAY = 9;
int CHAR_ARRAY = 5;
int LONG_ARRAY = 11;
int FLOAT_ARRAY = 6;
int DOUBLE_ARRAY = 7;
// Debug attributes
int ATTR_SOURCE = 0x1; // SourceFileAttribute
int ATTR_LINES = 0x2; // LineNumberAttribute
int ATTR_VARS = 0x4; // LocalVariableTableAttribute
int ATTR_STACK_MAP_TABLE = 0x8; // Stack map table attribute
int ATTR_STACK_MAP = 0x10; // Stack map attribute: cldc
int ATTR_TYPE_ANNOTATION = 0x20; // type annotation attribute (jsr 308)
int ATTR_METHOD_PARAMETERS = 0x40; // method parameters attribute (jep 118)
// See java.lang.invoke.LambdaMetafactory constants - option bitflags when calling altMetaFactory()
int FLAG_SERIALIZABLE = 0x01;
int FLAG_MARKERS = 0x02;
int FLAG_BRIDGES = 0x04;
}

View File

@@ -1,473 +0,0 @@
/*******************************************************************************
* Copyright (c) 2000, 2013 IBM Corporation and others.
* 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:
* IBM Corporation - initial API and implementation
* IBM Corporation - added constant AccDefault
* IBM Corporation - added constants AccBridge and AccVarargs for J2SE 1.5
*******************************************************************************/
package org.springframework.ide.vscode.commons.java;
/**
* Utility class for decoding modifier flags in Java elements.
* <p>
* This class provides static methods only.
* </p>
* <p>
* Note that the numeric values of these flags match the ones for class files
* as described in the Java Virtual Machine Specification (except for
* {@link #AccDeprecated}, {@link #AccAnnotationDefault}, and {@link #AccDefaultMethod}).
* </p>
* <p>
* The AST class <code>Modifier</code> provides
* similar functionality as this class, only in the
* <code>org.eclipse.jdt.core.dom</code> package.
* </p>
*
* @see IMember#getFlags()
* @noinstantiate This class is not intended to be instantiated by clients.
*/
public final class Flags {
/**
* Constant representing the absence of any flag.
* @since 3.0
*/
public static final int AccDefault = ClassFileConstants.AccDefault;
/**
* Public access flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccPublic = ClassFileConstants.AccPublic;
/**
* Private access flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccPrivate = ClassFileConstants.AccPrivate;
/**
* Protected access flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccProtected = ClassFileConstants.AccProtected;
/**
* Static access flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccStatic = ClassFileConstants.AccStatic;
/**
* Final access flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccFinal = ClassFileConstants.AccFinal;
/**
* Synchronized access flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccSynchronized = ClassFileConstants.AccSynchronized;
/**
* Volatile property flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccVolatile = ClassFileConstants.AccVolatile;
/**
* Transient property flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccTransient = ClassFileConstants.AccTransient;
/**
* Native property flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccNative = ClassFileConstants.AccNative;
/**
* Interface property flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccInterface = ClassFileConstants.AccInterface;
/**
* Abstract property flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccAbstract = ClassFileConstants.AccAbstract;
/**
* Strictfp property flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccStrictfp = ClassFileConstants.AccStrictfp;
/**
* Super property flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccSuper = ClassFileConstants.AccSuper;
/**
* Synthetic property flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccSynthetic = ClassFileConstants.AccSynthetic;
// /**
// * Deprecated property flag.
// * <p>
// * Note that this flag's value is internal and is not defined in the
// * Virtual Machine specification.
// * </p>
// * @since 2.0
// */
// public static final int AccDeprecated = ClassFileConstants.AccDeprecated;
/**
* Bridge method property flag (added in J2SE 1.5). Used to flag a compiler-generated
* bridge methods.
* See The Java Virtual Machine Specification for more details.
* @since 3.0
*/
public static final int AccBridge = ClassFileConstants.AccBridge;
/**
* Varargs method property flag (added in J2SE 1.5).
* Used to flag variable arity method declarations.
* See The Java Virtual Machine Specification for more details.
* @since 3.0
*/
public static final int AccVarargs = ClassFileConstants.AccVarargs;
/**
* Enum property flag (added in J2SE 1.5).
* See The Java Virtual Machine Specification for more details.
* @since 3.0
*/
public static final int AccEnum = ClassFileConstants.AccEnum;
/**
* Annotation property flag (added in J2SE 1.5).
* See The Java Virtual Machine Specification for more details.
* @since 3.0
*/
public static final int AccAnnotation = ClassFileConstants.AccAnnotation;
// /**
// * Default method property flag.
// * <p>
// * Note that this flag's value is internal and is not defined in the
// * Virtual Machine specification.
// * </p>
// * @since 3.10
// */
// public static final int AccDefaultMethod = ExtraCompilerModifiers.AccDefaultMethod;
//
// /**
// * Annotation method default property flag.
// * Used to flag annotation type methods that declare a default value.
// * <p>
// * Note that this flag's value is internal and is not defined in the
// * Virtual Machine specification.
// * </p>
// * @since 3.10
// */
// public static final int AccAnnotationDefault = ClassFileConstants.AccAnnotationDefault;
/**
* Not instantiable.
*/
private Flags() {
// Not instantiable
}
/**
* Returns whether the given integer includes the <code>abstract</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>abstract</code> modifier is included
*/
public static boolean isAbstract(int flags) {
return (flags & AccAbstract) != 0;
}
// /**
// * Returns whether the given integer includes the indication that the
// * element is deprecated (<code>@deprecated</code> tag in Javadoc comment).
// *
// * @param flags the flags
// * @return <code>true</code> if the element is marked as deprecated
// */
// public static boolean isDeprecated(int flags) {
// return (flags & AccDeprecated) != 0;
// }
/**
* Returns whether the given integer includes the <code>final</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>final</code> modifier is included
*/
public static boolean isFinal(int flags) {
return (flags & AccFinal) != 0;
}
/**
* Returns whether the given integer includes the <code>interface</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>interface</code> modifier is included
* @since 2.0
*/
public static boolean isInterface(int flags) {
return (flags & AccInterface) != 0;
}
/**
* Returns whether the given integer includes the <code>native</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>native</code> modifier is included
*/
public static boolean isNative(int flags) {
return (flags & AccNative) != 0;
}
/**
* Returns whether the given integer does not include one of the
* <code>public</code>, <code>private</code>, or <code>protected</code> flags.
*
* @param flags the flags
* @return <code>true</code> if no visibility flag is set
* @since 3.2
*/
public static boolean isPackageDefault(int flags) {
return (flags & (AccPublic | AccPrivate | AccProtected)) == 0;
}
/**
* Returns whether the given integer includes the <code>private</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>private</code> modifier is included
*/
public static boolean isPrivate(int flags) {
return (flags & AccPrivate) != 0;
}
/**
* Returns whether the given integer includes the <code>protected</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>protected</code> modifier is included
*/
public static boolean isProtected(int flags) {
return (flags & AccProtected) != 0;
}
/**
* Returns whether the given integer includes the <code>public</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>public</code> modifier is included
*/
public static boolean isPublic(int flags) {
return (flags & AccPublic) != 0;
}
/**
* Returns whether the given integer includes the <code>static</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>static</code> modifier is included
*/
public static boolean isStatic(int flags) {
return (flags & AccStatic) != 0;
}
/**
* Returns whether the given integer includes the <code>super</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>super</code> modifier is included
* @since 3.2
*/
public static boolean isSuper(int flags) {
return (flags & AccSuper) != 0;
}
/**
* Returns whether the given integer includes the <code>strictfp</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>strictfp</code> modifier is included
*/
public static boolean isStrictfp(int flags) {
return (flags & AccStrictfp) != 0;
}
/**
* Returns whether the given integer includes the <code>synchronized</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>synchronized</code> modifier is included
*/
public static boolean isSynchronized(int flags) {
return (flags & AccSynchronized) != 0;
}
/**
* Returns whether the given integer includes the indication that the
* element is synthetic.
*
* @param flags the flags
* @return <code>true</code> if the element is marked synthetic
*/
public static boolean isSynthetic(int flags) {
return (flags & AccSynthetic) != 0;
}
/**
* Returns whether the given integer includes the <code>transient</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>transient</code> modifier is included
*/
public static boolean isTransient(int flags) {
return (flags & AccTransient) != 0;
}
/**
* Returns whether the given integer includes the <code>volatile</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>volatile</code> modifier is included
*/
public static boolean isVolatile(int flags) {
return (flags & AccVolatile) != 0;
}
/**
* Returns whether the given integer has the <code>AccBridge</code>
* bit set.
*
* @param flags the flags
* @return <code>true</code> if the <code>AccBridge</code> flag is included
* @see #AccBridge
* @since 3.0
*/
public static boolean isBridge(int flags) {
return (flags & AccBridge) != 0;
}
/**
* Returns whether the given integer has the <code>AccVarargs</code>
* bit set.
*
* @param flags the flags
* @return <code>true</code> if the <code>AccVarargs</code> flag is included
* @see #AccVarargs
* @since 3.0
*/
public static boolean isVarargs(int flags) {
return (flags & AccVarargs) != 0;
}
/**
* Returns whether the given integer has the <code>AccEnum</code>
* bit set.
*
* @param flags the flags
* @return <code>true</code> if the <code>AccEnum</code> flag is included
* @see #AccEnum
* @since 3.0
*/
public static boolean isEnum(int flags) {
return (flags & AccEnum) != 0;
}
/**
* Returns whether the given integer has the <code>AccAnnotation</code>
* bit set.
*
* @param flags the flags
* @return <code>true</code> if the <code>AccAnnotation</code> flag is included
* @see #AccAnnotation
* @since 3.0
*/
public static boolean isAnnotation(int flags) {
return (flags & AccAnnotation) != 0;
}
// /**
// * Returns whether the given integer has the <code>AccDefaultMethod</code>
// * bit set. Note that this flag represents the usage of the 'default' keyword
// * on a method and should not be confused with the 'package' access visibility (which used to be called 'default access').
// *
// * @return <code>true</code> if the <code>AccDefaultMethod</code> flag is included
// * @see #AccDefaultMethod
// * @since 3.10
// */
// public static boolean isDefaultMethod(int flags) {
// return (flags & AccDefaultMethod) != 0;
// }
// /**
// * Returns whether the given integer has the <code>AccAnnnotationDefault</code>
// * bit set.
// *
// * @return <code>true</code> if the <code>AccAnnotationDefault</code> flag is included
// * @see #AccAnnotationDefault
// * @since 3.10
// */
// public static boolean isAnnnotationDefault(int flags) {
// return (flags & AccAnnotationDefault) != 0;
// }
/**
* Returns a standard string describing the given modifier flags.
* Only modifier flags are included in the output; deprecated,
* synthetic, bridge, etc. flags are ignored.
* <p>
* The flags are output in the following order:
* <pre> public protected private
* abstract default static final synchronized native strictfp transient volatile</pre>
* <p>
* This order is consistent with the recommendations in JLS8 ("*Modifier:" rules in chapters 8 and 9).
* </p>
* <p>
* Note that the flags of a method can include the AccVarargs flag that has no standard description. Since the AccVarargs flag has the same value as
* the AccTransient flag (valid for fields only), attempting to get the description of method modifiers with the AccVarargs flag set would result in an
* unexpected description. Clients should ensure that the AccVarargs is not included in the flags of a method as follows:
* <pre>
* IMethod method = ...
* int flags = method.getFlags() & ~Flags.AccVarargs;
* return Flags.toString(flags);
* </pre>
* </p>
* <p>
* Examples results:
* <pre>
* <code>"public static final"</code>
* <code>"private native"</code>
* </pre>
* </p>
*
* @param flags the flags
* @return the standard string representation of the given flags
*/
public static String toString(int flags) {
StringBuffer sb = new StringBuffer();
if (isPublic(flags))
sb.append("public "); //$NON-NLS-1$
if (isProtected(flags))
sb.append("protected "); //$NON-NLS-1$
if (isPrivate(flags))
sb.append("private "); //$NON-NLS-1$
if (isAbstract(flags))
sb.append("abstract "); //$NON-NLS-1$
// if (isDefaultMethod(flags))
// sb.append("default "); //$NON-NLS-1$
if (isStatic(flags))
sb.append("static "); //$NON-NLS-1$
if (isFinal(flags))
sb.append("final "); //$NON-NLS-1$
if (isSynchronized(flags))
sb.append("synchronized "); //$NON-NLS-1$
if (isNative(flags))
sb.append("native "); //$NON-NLS-1$
if (isStrictfp(flags))
sb.append("strictfp "); //$NON-NLS-1$
if (isTransient(flags))
sb.append("transient "); //$NON-NLS-1$
if (isVolatile(flags))
sb.append("volatile "); //$NON-NLS-1$
int len = sb.length();
if (len == 0)
return ""; //$NON-NLS-1$
sb.setLength(len - 1);
return sb.toString();
}
}

View File

@@ -1,19 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 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.util.stream.Stream;
public interface IAnnotatable extends IJavaElement {
Stream<IAnnotation> getAnnotations();
}

Some files were not shown because too many files have changed in this diff Show More