repo_name
stringlengths 7
104
| file_path
stringlengths 13
198
| context
stringlengths 67
7.15k
| import_statement
stringlengths 16
4.43k
| code
stringlengths 40
6.98k
| prompt
stringlengths 227
8.27k
| next_line
stringlengths 8
795
|
---|---|---|---|---|---|---|
dpaukov/combinatoricslib3 | src/test/java/org/paukov/combinatorics3/KPermutationTest.java | // Path: src/main/java/org/paukov/combinatorics3/PermutationGenerator.java
// public enum TreatDuplicatesAs {
// DIFFERENT,
// IDENTICAL
// }
| import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Iterator;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.paukov.combinatorics3.PermutationGenerator.TreatDuplicatesAs; | assertThat(permutations.get(5)).containsExactly(3, 2);
}
@Test
public void test_k_1_of_1_permutation() {
List<List<Integer>> permutations =
Generator.permutation(1)
.k(1)
.stream()
.collect(toList());
assertThat(permutations).hasSize(1);
assertThat(permutations.get(0)).containsOnly(1);
}
@Test
public void test_k_0_of_0_permutation() {
List<List<Integer>> permutations =
Generator.<Integer>permutation()
.k(0)
.stream()
.collect(toList());
assertThat(permutations).isEmpty();
}
@Test
public void test_k_2_of_3_with_duplicates_permutation() {
List<List<String>> permutations =
Generator.permutation("a", "a", "b") | // Path: src/main/java/org/paukov/combinatorics3/PermutationGenerator.java
// public enum TreatDuplicatesAs {
// DIFFERENT,
// IDENTICAL
// }
// Path: src/test/java/org/paukov/combinatorics3/KPermutationTest.java
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Iterator;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.paukov.combinatorics3.PermutationGenerator.TreatDuplicatesAs;
assertThat(permutations.get(5)).containsExactly(3, 2);
}
@Test
public void test_k_1_of_1_permutation() {
List<List<Integer>> permutations =
Generator.permutation(1)
.k(1)
.stream()
.collect(toList());
assertThat(permutations).hasSize(1);
assertThat(permutations.get(0)).containsOnly(1);
}
@Test
public void test_k_0_of_0_permutation() {
List<List<Integer>> permutations =
Generator.<Integer>permutation()
.k(0)
.stream()
.collect(toList());
assertThat(permutations).isEmpty();
}
@Test
public void test_k_2_of_3_with_duplicates_permutation() {
List<List<String>> permutations =
Generator.permutation("a", "a", "b") | .k(2, TreatDuplicatesAs.IDENTICAL) |
dpaukov/combinatoricslib3 | src/test/java/org/paukov/combinatorics3/CartesianProductTest.java | // Path: src/main/java/org/paukov/combinatorics3/Generator.java
// @SafeVarargs
// public static <T> IGenerator<List<T>> cartesianProduct(List<T>... args) {
// return cartesianProduct(Arrays.asList(args));
// }
| import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.paukov.combinatorics3.Generator.cartesianProduct;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test; | package org.paukov.combinatorics3;
public final class CartesianProductTest {
@Test
public void test_cartesian_product_number() { | // Path: src/main/java/org/paukov/combinatorics3/Generator.java
// @SafeVarargs
// public static <T> IGenerator<List<T>> cartesianProduct(List<T>... args) {
// return cartesianProduct(Arrays.asList(args));
// }
// Path: src/test/java/org/paukov/combinatorics3/CartesianProductTest.java
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.paukov.combinatorics3.Generator.cartesianProduct;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
package org.paukov.combinatorics3;
public final class CartesianProductTest {
@Test
public void test_cartesian_product_number() { | List<List<Integer>> cartesianProduct = |
dpaukov/combinatoricslib3 | src/main/java/org/paukov/combinatorics3/PermutationGenerator.java | // Path: src/main/java/org/paukov/combinatorics3/EmptyGenerator.java
// static <T> EmptyGenerator<T> emptyGenerator() {
// @SuppressWarnings("unchecked")
// EmptyGenerator<T> g = (EmptyGenerator<T>) EMPTY;
// return g;
// }
| import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.paukov.combinatorics3.EmptyGenerator.emptyGenerator; | /*
* Combinatorics Library 3
* Copyright 2009-2016 Dmytro Paukov [email protected]
*/
package org.paukov.combinatorics3;
public class PermutationGenerator<T> {
final Collection<T> originalVector;
PermutationGenerator(Collection<T> originalVector) {
this.originalVector = originalVector;
}
public static <T> boolean hasDuplicates(Collection<T> collection) {
if (collection.size() <= 1) {
return false;
}
Set<T> set = new HashSet<>(collection);
return set.size() < collection.size();
}
public IGenerator<List<T>> simple() {
return new SimplePermutationGenerator<>(originalVector, false);
}
public IGenerator<List<T>> simple(TreatDuplicatesAs treatAsIdentical) {
return new SimplePermutationGenerator<>(originalVector,
TreatDuplicatesAs.IDENTICAL.equals(treatAsIdentical));
}
public IGenerator<List<T>> k(int length) {
return new KPermutationGenerator<>(originalVector, length, false);
}
public IGenerator<List<T>> k(int length, TreatDuplicatesAs treatAsIdentical) {
return new KPermutationGenerator<>(originalVector, length,
TreatDuplicatesAs.IDENTICAL.equals(treatAsIdentical));
}
public IGenerator<List<T>> withRepetitions(int permutationLength) {
return originalVector.isEmpty() | // Path: src/main/java/org/paukov/combinatorics3/EmptyGenerator.java
// static <T> EmptyGenerator<T> emptyGenerator() {
// @SuppressWarnings("unchecked")
// EmptyGenerator<T> g = (EmptyGenerator<T>) EMPTY;
// return g;
// }
// Path: src/main/java/org/paukov/combinatorics3/PermutationGenerator.java
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.paukov.combinatorics3.EmptyGenerator.emptyGenerator;
/*
* Combinatorics Library 3
* Copyright 2009-2016 Dmytro Paukov [email protected]
*/
package org.paukov.combinatorics3;
public class PermutationGenerator<T> {
final Collection<T> originalVector;
PermutationGenerator(Collection<T> originalVector) {
this.originalVector = originalVector;
}
public static <T> boolean hasDuplicates(Collection<T> collection) {
if (collection.size() <= 1) {
return false;
}
Set<T> set = new HashSet<>(collection);
return set.size() < collection.size();
}
public IGenerator<List<T>> simple() {
return new SimplePermutationGenerator<>(originalVector, false);
}
public IGenerator<List<T>> simple(TreatDuplicatesAs treatAsIdentical) {
return new SimplePermutationGenerator<>(originalVector,
TreatDuplicatesAs.IDENTICAL.equals(treatAsIdentical));
}
public IGenerator<List<T>> k(int length) {
return new KPermutationGenerator<>(originalVector, length, false);
}
public IGenerator<List<T>> k(int length, TreatDuplicatesAs treatAsIdentical) {
return new KPermutationGenerator<>(originalVector, length,
TreatDuplicatesAs.IDENTICAL.equals(treatAsIdentical));
}
public IGenerator<List<T>> withRepetitions(int permutationLength) {
return originalVector.isEmpty() | ? emptyGenerator() |
birdcage/soundcloud-web-api-android | soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/auth/SoundCloudAuthenticator.java | // Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/SoundCloudAPI.java
// public class SoundCloudAPI {
//
// public static final String SOUNDCLOUD_API_ENDPOINT = "https://api.soundcloud.com/";
//
// private final SoundCloudService service;
//
// private final String clientId;
// private String token;
//
// /**
// * Creates a {@link SoundCloudService}. Serializes with JSON.
// *
// * @param clientId Client ID provided by SoundCloud.
// */
// public SoundCloudAPI(String clientId) {
// this.clientId = clientId;
//
// Gson gson = new GsonBuilder()
// .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
// .registerTypeAdapter(Date.class, new DateTypeAdapter())
// .create();
//
// OkHttpClient client = new OkHttpClient.Builder()
// .addInterceptor(new SoundCloudInterceptor())
// .build();
//
// Retrofit adapter = new Retrofit.Builder()
// .client(client)
// .baseUrl(SOUNDCLOUD_API_ENDPOINT)
// .addConverterFactory(GsonConverterFactory.create(gson))
// .build();
//
// service = adapter.create(SoundCloudService.class);
// }
//
// /**
// * Gives access to a {@link SoundCloudService}.
// *
// * @return The {@link SoundCloudService} created by this {@link SoundCloudAPI}.
// */
// public SoundCloudService getService() {
// return service;
// }
//
// /**
// * Sets the auth token needed by the service in order to make authenticated requests.
// *
// * @param token The OAuth token to use for authenticated requests.
// */
// public void setToken(String token) {
// this.token = token;
// }
//
// private class SoundCloudInterceptor implements Interceptor {
// @Override
// public Response intercept(Interceptor.Chain chain) throws IOException {
//
// Request request = chain.request();
//
// HttpUrl.Builder urlBuilder = request.url().newBuilder();
//
// urlBuilder.addEncodedQueryParameter("client_id", clientId);
// if (token != null) {
// urlBuilder.addEncodedQueryParameter("oauth_token", token);
// }
//
// Request newRequest = request.newBuilder()
// .url(urlBuilder.build())
// .build();
//
// return chain.proceed(newRequest);
// }
// }
// }
//
// Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/auth/models/AuthenticationResponse.java
// public class AuthenticationResponse {
//
// public String access_token;
//
// public String scope;
//
// public String error;
//
// /**
// * Helper method to determine authentication response type.
// *
// * @return The type of the authentication response.
// */
// public ResponseType getType() {
// if (access_token != null) {
// return ResponseType.TOKEN;
// }
//
// if (error != null) {
// return ResponseType.ERROR;
// }
//
// return ResponseType.UNKNOWN;
// }
//
// public enum ResponseType {
// TOKEN,
// ERROR,
// UNKNOWN
// }
//
// @Override
// public String toString() {
// return "AuthenticationResponse{" +
// "access_token='" + access_token + '\'' +
// ", scope='" + scope + '\'' +
// ", error='" + error + '\'' +
// '}';
// }
// }
| import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import com.jlubecki.soundcloud.webapi.android.SoundCloudAPI;
import com.jlubecki.soundcloud.webapi.android.auth.models.AuthenticationResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST; | }
/**
* Describes the method used to give the app permission to make authenticated requests.
*
* @see <a href="https://developers.soundcloud.com/docs/api/reference#connect">Connect
* Reference</a>
* @see <a href="https://developers.soundcloud.com/docs/api/reference#token">OAuth Reference</a>
*/
public class GrantType {
public static final String AUTH_CODE = "authorization_code";
public static final String REFRESH_TOKEN = "refresh_token";
public static final String PASSWORD = "password";
public static final String CLIENT_CREDENTIALS = "client_credentials";
public static final String OAUTH1_TOKEN = "oauth1_token";
}
/**
* Retrofit interface built solely to authenticate SoundCloud.
*/
public interface AuthService {
/**
* Asynchronously obtains an OAuth Token.
*
* @param authMap An {@link Map} defining form-urlencoded auth parameters.
* @return the call that can be run to access the API resource.
*/
@FormUrlEncoded
@POST("oauth2/token") | // Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/SoundCloudAPI.java
// public class SoundCloudAPI {
//
// public static final String SOUNDCLOUD_API_ENDPOINT = "https://api.soundcloud.com/";
//
// private final SoundCloudService service;
//
// private final String clientId;
// private String token;
//
// /**
// * Creates a {@link SoundCloudService}. Serializes with JSON.
// *
// * @param clientId Client ID provided by SoundCloud.
// */
// public SoundCloudAPI(String clientId) {
// this.clientId = clientId;
//
// Gson gson = new GsonBuilder()
// .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
// .registerTypeAdapter(Date.class, new DateTypeAdapter())
// .create();
//
// OkHttpClient client = new OkHttpClient.Builder()
// .addInterceptor(new SoundCloudInterceptor())
// .build();
//
// Retrofit adapter = new Retrofit.Builder()
// .client(client)
// .baseUrl(SOUNDCLOUD_API_ENDPOINT)
// .addConverterFactory(GsonConverterFactory.create(gson))
// .build();
//
// service = adapter.create(SoundCloudService.class);
// }
//
// /**
// * Gives access to a {@link SoundCloudService}.
// *
// * @return The {@link SoundCloudService} created by this {@link SoundCloudAPI}.
// */
// public SoundCloudService getService() {
// return service;
// }
//
// /**
// * Sets the auth token needed by the service in order to make authenticated requests.
// *
// * @param token The OAuth token to use for authenticated requests.
// */
// public void setToken(String token) {
// this.token = token;
// }
//
// private class SoundCloudInterceptor implements Interceptor {
// @Override
// public Response intercept(Interceptor.Chain chain) throws IOException {
//
// Request request = chain.request();
//
// HttpUrl.Builder urlBuilder = request.url().newBuilder();
//
// urlBuilder.addEncodedQueryParameter("client_id", clientId);
// if (token != null) {
// urlBuilder.addEncodedQueryParameter("oauth_token", token);
// }
//
// Request newRequest = request.newBuilder()
// .url(urlBuilder.build())
// .build();
//
// return chain.proceed(newRequest);
// }
// }
// }
//
// Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/auth/models/AuthenticationResponse.java
// public class AuthenticationResponse {
//
// public String access_token;
//
// public String scope;
//
// public String error;
//
// /**
// * Helper method to determine authentication response type.
// *
// * @return The type of the authentication response.
// */
// public ResponseType getType() {
// if (access_token != null) {
// return ResponseType.TOKEN;
// }
//
// if (error != null) {
// return ResponseType.ERROR;
// }
//
// return ResponseType.UNKNOWN;
// }
//
// public enum ResponseType {
// TOKEN,
// ERROR,
// UNKNOWN
// }
//
// @Override
// public String toString() {
// return "AuthenticationResponse{" +
// "access_token='" + access_token + '\'' +
// ", scope='" + scope + '\'' +
// ", error='" + error + '\'' +
// '}';
// }
// }
// Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/auth/SoundCloudAuthenticator.java
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import com.jlubecki.soundcloud.webapi.android.SoundCloudAPI;
import com.jlubecki.soundcloud.webapi.android.auth.models.AuthenticationResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
}
/**
* Describes the method used to give the app permission to make authenticated requests.
*
* @see <a href="https://developers.soundcloud.com/docs/api/reference#connect">Connect
* Reference</a>
* @see <a href="https://developers.soundcloud.com/docs/api/reference#token">OAuth Reference</a>
*/
public class GrantType {
public static final String AUTH_CODE = "authorization_code";
public static final String REFRESH_TOKEN = "refresh_token";
public static final String PASSWORD = "password";
public static final String CLIENT_CREDENTIALS = "client_credentials";
public static final String OAUTH1_TOKEN = "oauth1_token";
}
/**
* Retrofit interface built solely to authenticate SoundCloud.
*/
public interface AuthService {
/**
* Asynchronously obtains an OAuth Token.
*
* @param authMap An {@link Map} defining form-urlencoded auth parameters.
* @return the call that can be run to access the API resource.
*/
@FormUrlEncoded
@POST("oauth2/token") | Call<AuthenticationResponse> authorize(@FieldMap Map<String, String> authMap); |
birdcage/soundcloud-web-api-android | soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/auth/SoundCloudAuthenticator.java | // Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/SoundCloudAPI.java
// public class SoundCloudAPI {
//
// public static final String SOUNDCLOUD_API_ENDPOINT = "https://api.soundcloud.com/";
//
// private final SoundCloudService service;
//
// private final String clientId;
// private String token;
//
// /**
// * Creates a {@link SoundCloudService}. Serializes with JSON.
// *
// * @param clientId Client ID provided by SoundCloud.
// */
// public SoundCloudAPI(String clientId) {
// this.clientId = clientId;
//
// Gson gson = new GsonBuilder()
// .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
// .registerTypeAdapter(Date.class, new DateTypeAdapter())
// .create();
//
// OkHttpClient client = new OkHttpClient.Builder()
// .addInterceptor(new SoundCloudInterceptor())
// .build();
//
// Retrofit adapter = new Retrofit.Builder()
// .client(client)
// .baseUrl(SOUNDCLOUD_API_ENDPOINT)
// .addConverterFactory(GsonConverterFactory.create(gson))
// .build();
//
// service = adapter.create(SoundCloudService.class);
// }
//
// /**
// * Gives access to a {@link SoundCloudService}.
// *
// * @return The {@link SoundCloudService} created by this {@link SoundCloudAPI}.
// */
// public SoundCloudService getService() {
// return service;
// }
//
// /**
// * Sets the auth token needed by the service in order to make authenticated requests.
// *
// * @param token The OAuth token to use for authenticated requests.
// */
// public void setToken(String token) {
// this.token = token;
// }
//
// private class SoundCloudInterceptor implements Interceptor {
// @Override
// public Response intercept(Interceptor.Chain chain) throws IOException {
//
// Request request = chain.request();
//
// HttpUrl.Builder urlBuilder = request.url().newBuilder();
//
// urlBuilder.addEncodedQueryParameter("client_id", clientId);
// if (token != null) {
// urlBuilder.addEncodedQueryParameter("oauth_token", token);
// }
//
// Request newRequest = request.newBuilder()
// .url(urlBuilder.build())
// .build();
//
// return chain.proceed(newRequest);
// }
// }
// }
//
// Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/auth/models/AuthenticationResponse.java
// public class AuthenticationResponse {
//
// public String access_token;
//
// public String scope;
//
// public String error;
//
// /**
// * Helper method to determine authentication response type.
// *
// * @return The type of the authentication response.
// */
// public ResponseType getType() {
// if (access_token != null) {
// return ResponseType.TOKEN;
// }
//
// if (error != null) {
// return ResponseType.ERROR;
// }
//
// return ResponseType.UNKNOWN;
// }
//
// public enum ResponseType {
// TOKEN,
// ERROR,
// UNKNOWN
// }
//
// @Override
// public String toString() {
// return "AuthenticationResponse{" +
// "access_token='" + access_token + '\'' +
// ", scope='" + scope + '\'' +
// ", error='" + error + '\'' +
// '}';
// }
// }
| import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import com.jlubecki.soundcloud.webapi.android.SoundCloudAPI;
import com.jlubecki.soundcloud.webapi.android.auth.models.AuthenticationResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST; | }
/**
* Retrofit interface built solely to authenticate SoundCloud.
*/
public interface AuthService {
/**
* Asynchronously obtains an OAuth Token.
*
* @param authMap An {@link Map} defining form-urlencoded auth parameters.
* @return the call that can be run to access the API resource.
*/
@FormUrlEncoded
@POST("oauth2/token")
Call<AuthenticationResponse> authorize(@FieldMap Map<String, String> authMap);
}
/**
* Gets the Auth Service so a user can call
* {@link AuthService#authorize(Map)}.
*
* @return An instance of a {@link AuthService}.
*/
public final AuthService getAuthService() {
if (service == null) {
OkHttpClient client =
new OkHttpClient.Builder().addInterceptor(new AuthInterceptor()).build();
Retrofit adapter = new Retrofit.Builder() | // Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/SoundCloudAPI.java
// public class SoundCloudAPI {
//
// public static final String SOUNDCLOUD_API_ENDPOINT = "https://api.soundcloud.com/";
//
// private final SoundCloudService service;
//
// private final String clientId;
// private String token;
//
// /**
// * Creates a {@link SoundCloudService}. Serializes with JSON.
// *
// * @param clientId Client ID provided by SoundCloud.
// */
// public SoundCloudAPI(String clientId) {
// this.clientId = clientId;
//
// Gson gson = new GsonBuilder()
// .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
// .registerTypeAdapter(Date.class, new DateTypeAdapter())
// .create();
//
// OkHttpClient client = new OkHttpClient.Builder()
// .addInterceptor(new SoundCloudInterceptor())
// .build();
//
// Retrofit adapter = new Retrofit.Builder()
// .client(client)
// .baseUrl(SOUNDCLOUD_API_ENDPOINT)
// .addConverterFactory(GsonConverterFactory.create(gson))
// .build();
//
// service = adapter.create(SoundCloudService.class);
// }
//
// /**
// * Gives access to a {@link SoundCloudService}.
// *
// * @return The {@link SoundCloudService} created by this {@link SoundCloudAPI}.
// */
// public SoundCloudService getService() {
// return service;
// }
//
// /**
// * Sets the auth token needed by the service in order to make authenticated requests.
// *
// * @param token The OAuth token to use for authenticated requests.
// */
// public void setToken(String token) {
// this.token = token;
// }
//
// private class SoundCloudInterceptor implements Interceptor {
// @Override
// public Response intercept(Interceptor.Chain chain) throws IOException {
//
// Request request = chain.request();
//
// HttpUrl.Builder urlBuilder = request.url().newBuilder();
//
// urlBuilder.addEncodedQueryParameter("client_id", clientId);
// if (token != null) {
// urlBuilder.addEncodedQueryParameter("oauth_token", token);
// }
//
// Request newRequest = request.newBuilder()
// .url(urlBuilder.build())
// .build();
//
// return chain.proceed(newRequest);
// }
// }
// }
//
// Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/auth/models/AuthenticationResponse.java
// public class AuthenticationResponse {
//
// public String access_token;
//
// public String scope;
//
// public String error;
//
// /**
// * Helper method to determine authentication response type.
// *
// * @return The type of the authentication response.
// */
// public ResponseType getType() {
// if (access_token != null) {
// return ResponseType.TOKEN;
// }
//
// if (error != null) {
// return ResponseType.ERROR;
// }
//
// return ResponseType.UNKNOWN;
// }
//
// public enum ResponseType {
// TOKEN,
// ERROR,
// UNKNOWN
// }
//
// @Override
// public String toString() {
// return "AuthenticationResponse{" +
// "access_token='" + access_token + '\'' +
// ", scope='" + scope + '\'' +
// ", error='" + error + '\'' +
// '}';
// }
// }
// Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/auth/SoundCloudAuthenticator.java
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import com.jlubecki.soundcloud.webapi.android.SoundCloudAPI;
import com.jlubecki.soundcloud.webapi.android.auth.models.AuthenticationResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
}
/**
* Retrofit interface built solely to authenticate SoundCloud.
*/
public interface AuthService {
/**
* Asynchronously obtains an OAuth Token.
*
* @param authMap An {@link Map} defining form-urlencoded auth parameters.
* @return the call that can be run to access the API resource.
*/
@FormUrlEncoded
@POST("oauth2/token")
Call<AuthenticationResponse> authorize(@FieldMap Map<String, String> authMap);
}
/**
* Gets the Auth Service so a user can call
* {@link AuthService#authorize(Map)}.
*
* @return An instance of a {@link AuthService}.
*/
public final AuthService getAuthService() {
if (service == null) {
OkHttpClient client =
new OkHttpClient.Builder().addInterceptor(new AuthInterceptor()).build();
Retrofit adapter = new Retrofit.Builder() | .baseUrl(SoundCloudAPI.SOUNDCLOUD_API_ENDPOINT) |
birdcage/soundcloud-web-api-android | soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/query/TrackQuery.java | // Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/models/Track.java
// public enum Filter {
// ALL("all"),
// PUBLIC("public"),
// PRIVATE("private");
//
// private final String filter;
//
// Filter(String filter) {
// this.filter = filter;
// }
//
// @Override
// public String toString() {
// return filter;
// }
// }
//
// Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/models/Track.java
// public enum License {
//
// ALL_RIGHTS_RESERVED("all-rights-reserved"),
// NO_RIGHTS_RESERVED("no-rights-reserved"),
// CC_ATTRIBUTION("cc-by"),
// CC_ATTRIBUTION_NONCOMMERCIAL("cc-by-nc"),
// CC_ATTRIBUTION_NO_DERIVATIVES("cc-by-nd"),
// CC_ATTRIBUTION_SHARE_ALIKE("cc-by-sa"),
// CC_ATTRIBUTION_NONCOMMERCIAL_NO_DERIVATES("cc-by-nc-nd"),
// CC_ATTRIBUTION_NONCOMMERCIAL_SHARE_ALIKE("cc-by-nc-sa");
//
// private final String license;
//
// License(String license) {
// this.license = license;
// }
//
// @Override
// public String toString() {
// return license;
// }
// }
//
// Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/models/Track.java
// public enum Type {
//
// ORIGINAL("original"),
// REMIX("remix"),
// LIVE("live"),
// RECORDING("recording"),
// SPOKEN("spoken"),
// PODCAST("podcast"),
// DEMO("demo"),
// IN_PROGRESS("in progress"),
// STEM("stem"),
// LOOP("loop"),
// SOUND_EFFECT("sound effect"),
// SAMPLE("sample"),
// OTHER("other");
//
// private final String type;
//
// Type(String type) {
// this.type = type;
// }
//
// @Override
// public String toString() {
// return type;
// }
// }
| import static com.jlubecki.soundcloud.webapi.android.models.Track.Filter;
import static com.jlubecki.soundcloud.webapi.android.models.Track.License;
import static com.jlubecki.soundcloud.webapi.android.models.Track.Type;
import android.support.annotation.IntRange;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import java.util.HashMap; | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Jacob Lubecki
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.jlubecki.soundcloud.webapi.android.query;
/**
* Created by Jacob on 9/17/15.
*/
public class TrackQuery extends Query {
private String query;
private String tags; | // Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/models/Track.java
// public enum Filter {
// ALL("all"),
// PUBLIC("public"),
// PRIVATE("private");
//
// private final String filter;
//
// Filter(String filter) {
// this.filter = filter;
// }
//
// @Override
// public String toString() {
// return filter;
// }
// }
//
// Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/models/Track.java
// public enum License {
//
// ALL_RIGHTS_RESERVED("all-rights-reserved"),
// NO_RIGHTS_RESERVED("no-rights-reserved"),
// CC_ATTRIBUTION("cc-by"),
// CC_ATTRIBUTION_NONCOMMERCIAL("cc-by-nc"),
// CC_ATTRIBUTION_NO_DERIVATIVES("cc-by-nd"),
// CC_ATTRIBUTION_SHARE_ALIKE("cc-by-sa"),
// CC_ATTRIBUTION_NONCOMMERCIAL_NO_DERIVATES("cc-by-nc-nd"),
// CC_ATTRIBUTION_NONCOMMERCIAL_SHARE_ALIKE("cc-by-nc-sa");
//
// private final String license;
//
// License(String license) {
// this.license = license;
// }
//
// @Override
// public String toString() {
// return license;
// }
// }
//
// Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/models/Track.java
// public enum Type {
//
// ORIGINAL("original"),
// REMIX("remix"),
// LIVE("live"),
// RECORDING("recording"),
// SPOKEN("spoken"),
// PODCAST("podcast"),
// DEMO("demo"),
// IN_PROGRESS("in progress"),
// STEM("stem"),
// LOOP("loop"),
// SOUND_EFFECT("sound effect"),
// SAMPLE("sample"),
// OTHER("other");
//
// private final String type;
//
// Type(String type) {
// this.type = type;
// }
//
// @Override
// public String toString() {
// return type;
// }
// }
// Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/query/TrackQuery.java
import static com.jlubecki.soundcloud.webapi.android.models.Track.Filter;
import static com.jlubecki.soundcloud.webapi.android.models.Track.License;
import static com.jlubecki.soundcloud.webapi.android.models.Track.Type;
import android.support.annotation.IntRange;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import java.util.HashMap;
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Jacob Lubecki
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.jlubecki.soundcloud.webapi.android.query;
/**
* Created by Jacob on 9/17/15.
*/
public class TrackQuery extends Query {
private String query;
private String tags; | private Filter filter; |
birdcage/soundcloud-web-api-android | soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/query/TrackQuery.java | // Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/models/Track.java
// public enum Filter {
// ALL("all"),
// PUBLIC("public"),
// PRIVATE("private");
//
// private final String filter;
//
// Filter(String filter) {
// this.filter = filter;
// }
//
// @Override
// public String toString() {
// return filter;
// }
// }
//
// Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/models/Track.java
// public enum License {
//
// ALL_RIGHTS_RESERVED("all-rights-reserved"),
// NO_RIGHTS_RESERVED("no-rights-reserved"),
// CC_ATTRIBUTION("cc-by"),
// CC_ATTRIBUTION_NONCOMMERCIAL("cc-by-nc"),
// CC_ATTRIBUTION_NO_DERIVATIVES("cc-by-nd"),
// CC_ATTRIBUTION_SHARE_ALIKE("cc-by-sa"),
// CC_ATTRIBUTION_NONCOMMERCIAL_NO_DERIVATES("cc-by-nc-nd"),
// CC_ATTRIBUTION_NONCOMMERCIAL_SHARE_ALIKE("cc-by-nc-sa");
//
// private final String license;
//
// License(String license) {
// this.license = license;
// }
//
// @Override
// public String toString() {
// return license;
// }
// }
//
// Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/models/Track.java
// public enum Type {
//
// ORIGINAL("original"),
// REMIX("remix"),
// LIVE("live"),
// RECORDING("recording"),
// SPOKEN("spoken"),
// PODCAST("podcast"),
// DEMO("demo"),
// IN_PROGRESS("in progress"),
// STEM("stem"),
// LOOP("loop"),
// SOUND_EFFECT("sound effect"),
// SAMPLE("sample"),
// OTHER("other");
//
// private final String type;
//
// Type(String type) {
// this.type = type;
// }
//
// @Override
// public String toString() {
// return type;
// }
// }
| import static com.jlubecki.soundcloud.webapi.android.models.Track.Filter;
import static com.jlubecki.soundcloud.webapi.android.models.Track.License;
import static com.jlubecki.soundcloud.webapi.android.models.Track.Type;
import android.support.annotation.IntRange;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import java.util.HashMap; | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Jacob Lubecki
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.jlubecki.soundcloud.webapi.android.query;
/**
* Created by Jacob on 9/17/15.
*/
public class TrackQuery extends Query {
private String query;
private String tags;
private Filter filter; | // Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/models/Track.java
// public enum Filter {
// ALL("all"),
// PUBLIC("public"),
// PRIVATE("private");
//
// private final String filter;
//
// Filter(String filter) {
// this.filter = filter;
// }
//
// @Override
// public String toString() {
// return filter;
// }
// }
//
// Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/models/Track.java
// public enum License {
//
// ALL_RIGHTS_RESERVED("all-rights-reserved"),
// NO_RIGHTS_RESERVED("no-rights-reserved"),
// CC_ATTRIBUTION("cc-by"),
// CC_ATTRIBUTION_NONCOMMERCIAL("cc-by-nc"),
// CC_ATTRIBUTION_NO_DERIVATIVES("cc-by-nd"),
// CC_ATTRIBUTION_SHARE_ALIKE("cc-by-sa"),
// CC_ATTRIBUTION_NONCOMMERCIAL_NO_DERIVATES("cc-by-nc-nd"),
// CC_ATTRIBUTION_NONCOMMERCIAL_SHARE_ALIKE("cc-by-nc-sa");
//
// private final String license;
//
// License(String license) {
// this.license = license;
// }
//
// @Override
// public String toString() {
// return license;
// }
// }
//
// Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/models/Track.java
// public enum Type {
//
// ORIGINAL("original"),
// REMIX("remix"),
// LIVE("live"),
// RECORDING("recording"),
// SPOKEN("spoken"),
// PODCAST("podcast"),
// DEMO("demo"),
// IN_PROGRESS("in progress"),
// STEM("stem"),
// LOOP("loop"),
// SOUND_EFFECT("sound effect"),
// SAMPLE("sample"),
// OTHER("other");
//
// private final String type;
//
// Type(String type) {
// this.type = type;
// }
//
// @Override
// public String toString() {
// return type;
// }
// }
// Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/query/TrackQuery.java
import static com.jlubecki.soundcloud.webapi.android.models.Track.Filter;
import static com.jlubecki.soundcloud.webapi.android.models.Track.License;
import static com.jlubecki.soundcloud.webapi.android.models.Track.Type;
import android.support.annotation.IntRange;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import java.util.HashMap;
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Jacob Lubecki
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.jlubecki.soundcloud.webapi.android.query;
/**
* Created by Jacob on 9/17/15.
*/
public class TrackQuery extends Query {
private String query;
private String tags;
private Filter filter; | private License license; |
birdcage/soundcloud-web-api-android | soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/query/TrackQuery.java | // Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/models/Track.java
// public enum Filter {
// ALL("all"),
// PUBLIC("public"),
// PRIVATE("private");
//
// private final String filter;
//
// Filter(String filter) {
// this.filter = filter;
// }
//
// @Override
// public String toString() {
// return filter;
// }
// }
//
// Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/models/Track.java
// public enum License {
//
// ALL_RIGHTS_RESERVED("all-rights-reserved"),
// NO_RIGHTS_RESERVED("no-rights-reserved"),
// CC_ATTRIBUTION("cc-by"),
// CC_ATTRIBUTION_NONCOMMERCIAL("cc-by-nc"),
// CC_ATTRIBUTION_NO_DERIVATIVES("cc-by-nd"),
// CC_ATTRIBUTION_SHARE_ALIKE("cc-by-sa"),
// CC_ATTRIBUTION_NONCOMMERCIAL_NO_DERIVATES("cc-by-nc-nd"),
// CC_ATTRIBUTION_NONCOMMERCIAL_SHARE_ALIKE("cc-by-nc-sa");
//
// private final String license;
//
// License(String license) {
// this.license = license;
// }
//
// @Override
// public String toString() {
// return license;
// }
// }
//
// Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/models/Track.java
// public enum Type {
//
// ORIGINAL("original"),
// REMIX("remix"),
// LIVE("live"),
// RECORDING("recording"),
// SPOKEN("spoken"),
// PODCAST("podcast"),
// DEMO("demo"),
// IN_PROGRESS("in progress"),
// STEM("stem"),
// LOOP("loop"),
// SOUND_EFFECT("sound effect"),
// SAMPLE("sample"),
// OTHER("other");
//
// private final String type;
//
// Type(String type) {
// this.type = type;
// }
//
// @Override
// public String toString() {
// return type;
// }
// }
| import static com.jlubecki.soundcloud.webapi.android.models.Track.Filter;
import static com.jlubecki.soundcloud.webapi.android.models.Track.License;
import static com.jlubecki.soundcloud.webapi.android.models.Track.Type;
import android.support.annotation.IntRange;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import java.util.HashMap; | private String createdAtFrom;
private String createdAtTo;
private String ids;
private String genres;
private String types;
public Builder setQuery(String query) {
this.query = query;
return this;
}
public Builder setTags(String... tagArray) {
this.tags = TextUtils.join(", ", tagArray);
return this;
}
public Builder setFilter(Filter filter) {
this.filter = filter;
return this;
}
public Builder setLicense(License license) {
this.license = license;
return this;
}
| // Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/models/Track.java
// public enum Filter {
// ALL("all"),
// PUBLIC("public"),
// PRIVATE("private");
//
// private final String filter;
//
// Filter(String filter) {
// this.filter = filter;
// }
//
// @Override
// public String toString() {
// return filter;
// }
// }
//
// Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/models/Track.java
// public enum License {
//
// ALL_RIGHTS_RESERVED("all-rights-reserved"),
// NO_RIGHTS_RESERVED("no-rights-reserved"),
// CC_ATTRIBUTION("cc-by"),
// CC_ATTRIBUTION_NONCOMMERCIAL("cc-by-nc"),
// CC_ATTRIBUTION_NO_DERIVATIVES("cc-by-nd"),
// CC_ATTRIBUTION_SHARE_ALIKE("cc-by-sa"),
// CC_ATTRIBUTION_NONCOMMERCIAL_NO_DERIVATES("cc-by-nc-nd"),
// CC_ATTRIBUTION_NONCOMMERCIAL_SHARE_ALIKE("cc-by-nc-sa");
//
// private final String license;
//
// License(String license) {
// this.license = license;
// }
//
// @Override
// public String toString() {
// return license;
// }
// }
//
// Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/models/Track.java
// public enum Type {
//
// ORIGINAL("original"),
// REMIX("remix"),
// LIVE("live"),
// RECORDING("recording"),
// SPOKEN("spoken"),
// PODCAST("podcast"),
// DEMO("demo"),
// IN_PROGRESS("in progress"),
// STEM("stem"),
// LOOP("loop"),
// SOUND_EFFECT("sound effect"),
// SAMPLE("sample"),
// OTHER("other");
//
// private final String type;
//
// Type(String type) {
// this.type = type;
// }
//
// @Override
// public String toString() {
// return type;
// }
// }
// Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/query/TrackQuery.java
import static com.jlubecki.soundcloud.webapi.android.models.Track.Filter;
import static com.jlubecki.soundcloud.webapi.android.models.Track.License;
import static com.jlubecki.soundcloud.webapi.android.models.Track.Type;
import android.support.annotation.IntRange;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import java.util.HashMap;
private String createdAtFrom;
private String createdAtTo;
private String ids;
private String genres;
private String types;
public Builder setQuery(String query) {
this.query = query;
return this;
}
public Builder setTags(String... tagArray) {
this.tags = TextUtils.join(", ", tagArray);
return this;
}
public Builder setFilter(Filter filter) {
this.filter = filter;
return this;
}
public Builder setLicense(License license) {
this.license = license;
return this;
}
| public Builder setTypes(Type... types) { |
birdcage/soundcloud-web-api-android | soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/auth/AuthenticationStrategy.java | // Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/auth/models/AuthenticationResponse.java
// public class AuthenticationResponse {
//
// public String access_token;
//
// public String scope;
//
// public String error;
//
// /**
// * Helper method to determine authentication response type.
// *
// * @return The type of the authentication response.
// */
// public ResponseType getType() {
// if (access_token != null) {
// return ResponseType.TOKEN;
// }
//
// if (error != null) {
// return ResponseType.ERROR;
// }
//
// return ResponseType.UNKNOWN;
// }
//
// public enum ResponseType {
// TOKEN,
// ERROR,
// UNKNOWN
// }
//
// @Override
// public String toString() {
// return "AuthenticationResponse{" +
// "access_token='" + access_token + '\'' +
// ", scope='" + scope + '\'' +
// ", error='" + error + '\'' +
// '}';
// }
// }
| import com.jlubecki.soundcloud.webapi.android.auth.models.AuthenticationResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.support.annotation.NonNull;
import android.util.Log; |
private AuthenticationStrategy(@NonNull Context context, @NonNull List<SoundCloudAuthenticator> authenticators) {
this.context = context;
this.authenticators = authenticators;
}
public boolean beginAuthentication(AuthenticationCallback callback) {
if (shouldCheckNetwork && !networkIsConnected()) return false; // Not connected to the internet.
for(SoundCloudAuthenticator authenticator : authenticators) {
if(authenticator.prepareAuthenticationFlow(callback)) {
this.authenticator = authenticator;
return true; // Prepared successfully. Will execute callback.
}
}
return false;
}
public boolean canAuthenticate(Intent intent) {
return authenticator != null &&
authenticator.canAuthenticate(intent);
}
public void getToken(Intent intent, String clientSecret, final ResponseCallback callback) {
Map<String, String> authMap = authenticator.handleResponse(intent, clientSecret);
if (authMap != null) {
authenticator.getAuthService()
.authorize(authMap) | // Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/auth/models/AuthenticationResponse.java
// public class AuthenticationResponse {
//
// public String access_token;
//
// public String scope;
//
// public String error;
//
// /**
// * Helper method to determine authentication response type.
// *
// * @return The type of the authentication response.
// */
// public ResponseType getType() {
// if (access_token != null) {
// return ResponseType.TOKEN;
// }
//
// if (error != null) {
// return ResponseType.ERROR;
// }
//
// return ResponseType.UNKNOWN;
// }
//
// public enum ResponseType {
// TOKEN,
// ERROR,
// UNKNOWN
// }
//
// @Override
// public String toString() {
// return "AuthenticationResponse{" +
// "access_token='" + access_token + '\'' +
// ", scope='" + scope + '\'' +
// ", error='" + error + '\'' +
// '}';
// }
// }
// Path: soundcloud-api/src/main/java/com/jlubecki/soundcloud/webapi/android/auth/AuthenticationStrategy.java
import com.jlubecki.soundcloud.webapi.android.auth.models.AuthenticationResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.support.annotation.NonNull;
import android.util.Log;
private AuthenticationStrategy(@NonNull Context context, @NonNull List<SoundCloudAuthenticator> authenticators) {
this.context = context;
this.authenticators = authenticators;
}
public boolean beginAuthentication(AuthenticationCallback callback) {
if (shouldCheckNetwork && !networkIsConnected()) return false; // Not connected to the internet.
for(SoundCloudAuthenticator authenticator : authenticators) {
if(authenticator.prepareAuthenticationFlow(callback)) {
this.authenticator = authenticator;
return true; // Prepared successfully. Will execute callback.
}
}
return false;
}
public boolean canAuthenticate(Intent intent) {
return authenticator != null &&
authenticator.canAuthenticate(intent);
}
public void getToken(Intent intent, String clientSecret, final ResponseCallback callback) {
Map<String, String> authMap = authenticator.handleResponse(intent, clientSecret);
if (authMap != null) {
authenticator.getAuthService()
.authorize(authMap) | .enqueue(new Callback<AuthenticationResponse>() { |
Kaljurand/Arvutaja | app/src/ee/ioc/phon/android/arvutaja/provider/QueriesContentProvider.java | // Path: app/src/ee/ioc/phon/android/arvutaja/Log.java
// public class Log {
//
// private static final boolean DEBUG = BuildConfig.DEBUG;
//
// public static final String LOG_TAG = "Arvutaja";
//
// public static void i(String msg) {
// if (DEBUG) android.util.Log.i(LOG_TAG, msg);
// }
//
// public static void e(String msg) {
// if (DEBUG) android.util.Log.e(LOG_TAG, msg);
// }
//
// public static void i(String tag, String msg) {
// if (DEBUG) android.util.Log.i(tag, msg);
// }
//
// public static void e(String tag, String msg) {
// if (DEBUG) android.util.Log.e(tag, msg);
// }
// }
| import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import java.util.Arrays;
import java.util.HashMap;
import ee.ioc.phon.android.arvutaja.Log;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper; | }
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + QUERIES_TABLE_NAME + " ("
+ Query.Columns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Query.Columns.TIMESTAMP + " TIMESTAMP,"
+ Query.Columns.UTTERANCE + " TEXT,"
+ Query.Columns.TRANSLATION + " TEXT,"
+ Query.Columns.EVALUATION + " REAL,"
+ Query.Columns.LANG + " TEXT,"
+ Query.Columns.TARGET_LANG + " TEXT,"
+ Query.Columns.MESSAGE + " TEXT"
+ ");");
db.execSQL("CREATE TABLE " + QEVALS_TABLE_NAME + " ("
+ Qeval.Columns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Qeval.Columns.TIMESTAMP + " TIMESTAMP,"
+ Qeval.Columns.UTTERANCE + " TEXT,"
+ Qeval.Columns.TRANSLATION + " TEXT,"
+ Qeval.Columns.EVALUATION + " REAL,"
+ Qeval.Columns.LANG + " TEXT,"
+ Qeval.Columns.TARGET_LANG + " TEXT,"
+ Qeval.Columns.MESSAGE + " TEXT"
+ ");");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { | // Path: app/src/ee/ioc/phon/android/arvutaja/Log.java
// public class Log {
//
// private static final boolean DEBUG = BuildConfig.DEBUG;
//
// public static final String LOG_TAG = "Arvutaja";
//
// public static void i(String msg) {
// if (DEBUG) android.util.Log.i(LOG_TAG, msg);
// }
//
// public static void e(String msg) {
// if (DEBUG) android.util.Log.e(LOG_TAG, msg);
// }
//
// public static void i(String tag, String msg) {
// if (DEBUG) android.util.Log.i(tag, msg);
// }
//
// public static void e(String tag, String msg) {
// if (DEBUG) android.util.Log.e(tag, msg);
// }
// }
// Path: app/src/ee/ioc/phon/android/arvutaja/provider/QueriesContentProvider.java
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import java.util.Arrays;
import java.util.HashMap;
import ee.ioc.phon.android.arvutaja.Log;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + QUERIES_TABLE_NAME + " ("
+ Query.Columns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Query.Columns.TIMESTAMP + " TIMESTAMP,"
+ Query.Columns.UTTERANCE + " TEXT,"
+ Query.Columns.TRANSLATION + " TEXT,"
+ Query.Columns.EVALUATION + " REAL,"
+ Query.Columns.LANG + " TEXT,"
+ Query.Columns.TARGET_LANG + " TEXT,"
+ Query.Columns.MESSAGE + " TEXT"
+ ");");
db.execSQL("CREATE TABLE " + QEVALS_TABLE_NAME + " ("
+ Qeval.Columns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Qeval.Columns.TIMESTAMP + " TIMESTAMP,"
+ Qeval.Columns.UTTERANCE + " TEXT,"
+ Qeval.Columns.TRANSLATION + " TEXT,"
+ Qeval.Columns.EVALUATION + " REAL,"
+ Qeval.Columns.LANG + " TEXT,"
+ Qeval.Columns.TARGET_LANG + " TEXT,"
+ Qeval.Columns.MESSAGE + " TEXT"
+ ");");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { | Log.i(TAG, "Upgrading database v" + oldVersion + " -> v" + newVersion + ", which will destroy all old data."); |
Kaljurand/Arvutaja | app/src/ee/ioc/phon/android/arvutaja/ShowActivity.java | // Path: app/src/ee/ioc/phon/android/arvutaja/command/Command.java
// public interface Command {
//
// Intent getIntent() throws CommandParseException;
//
// /**
// * <p>Returns a message that helps the user to resolve the situation
// * where the command (intent) cannot be executed because the corresponding
// * activity is not installed.</p>
// *
// * @return suggestion for an activity
// */
// Uri getSuggestion();
//
// String getCommand();
//
// /**
// * <p>Evaluates the expression and returns the result.
// * This method can throw various exceptions.</p>
// *
// * @return evaluation of the expression that was given to the constructor
// */
// Object getOut();
//
//
// /**
// * @return resource ID of the message to show in the UI for this command.
// */
// int getMessage();
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/command/CommandParseException.java
// public class CommandParseException extends Exception {
//
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/command/CommandParser.java
// public class CommandParser {
//
// public static Command getCommand(Context context, String command) throws CommandParseException {
// if (command == null) {
// throw new CommandParseException();
// }
//
// // We check expressions first because some can be mistaken for URIs.
// if (Expr.isCommand(command))
// return new Expr(command);
//
// // In case the command is a URI then we launch ACTION_VIEW.
// if (View.isCommand(command))
// return new View(command);
//
// if (Alarm.isCommand(command))
// return new Alarm(command, context.getString(R.string.alarmExtraMessage));
//
// if (WebSearch.isCommand(command))
// return new WebSearch(command);
//
// if (Dial.isCommand(command))
// return new Dial(command);
//
// if (Search.isCommand(command))
// return new Search(command);
//
// if (Unitconv.isCommand(command))
// return new Unitconv(command);
//
// if (Direction.isCommand(command))
// return new Direction(command);
//
// return new DefaultCommand(command);
// }
//
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/provider/Query.java
// public class Query {
//
// public static final class Columns implements BaseColumns {
//
// public static final Uri CONTENT_URI = Uri.parse("content://" +
// QueriesContentProvider.AUTHORITY +
// "/" +
// QueriesContentProvider.QUERIES_TABLE_NAME);
//
// public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.ee.ioc.phon.android.arvutaja";
//
// public static final String TIMESTAMP = "TIMESTAMP";
// public static final String UTTERANCE = "UTTERANCE";
// public static final String TRANSLATION = "TRANSLATION";
// public static final String EVALUATION = "EVALUATION";
// public static final String LANG = "LANG";
// public static final String TARGET_LANG = "TARGET_LANG";
// public static final String MESSAGE = "MESSAGE";
//
// private Columns() {
// }
// }
// }
| import android.widget.LinearLayout;
import android.widget.TextView;
import ee.ioc.phon.android.arvutaja.command.Command;
import ee.ioc.phon.android.arvutaja.command.CommandParseException;
import ee.ioc.phon.android.arvutaja.command.CommandParser;
import ee.ioc.phon.android.arvutaja.provider.Query;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.format.Time;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton; | /*
* Copyright 2013, Institute of Cybernetics at Tallinn University of Technology
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ee.ioc.phon.android.arvutaja;
/**
* Shows the full DB record:
*
* TIMESTAMP
* UTTERANCE
* LANG
* TRANSLATION (linearization), possibly missing
* EVALUATION, possibly missing
* TARGET_LANG
* VIEW (show which external evaluator would be used, support clicking on it)
* MESSAGE (show error message if present)
*/
public class ShowActivity extends AbstractRecognizerActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.show);
final Uri contentUri = getIntent().getData();
ImageButton bDelete = (ImageButton) findViewById(R.id.bDelete);
bDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
getContentResolver().delete(contentUri, null, null);
finish();
}});
TextView tvMessage = (TextView) findViewById(R.id.tvMessage);
try {
Cursor c = getContentResolver().query(contentUri, null, null, null, null);
if (c.moveToFirst()) {
// Column names are the same for Query and Qeval
// Timestamp | // Path: app/src/ee/ioc/phon/android/arvutaja/command/Command.java
// public interface Command {
//
// Intent getIntent() throws CommandParseException;
//
// /**
// * <p>Returns a message that helps the user to resolve the situation
// * where the command (intent) cannot be executed because the corresponding
// * activity is not installed.</p>
// *
// * @return suggestion for an activity
// */
// Uri getSuggestion();
//
// String getCommand();
//
// /**
// * <p>Evaluates the expression and returns the result.
// * This method can throw various exceptions.</p>
// *
// * @return evaluation of the expression that was given to the constructor
// */
// Object getOut();
//
//
// /**
// * @return resource ID of the message to show in the UI for this command.
// */
// int getMessage();
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/command/CommandParseException.java
// public class CommandParseException extends Exception {
//
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/command/CommandParser.java
// public class CommandParser {
//
// public static Command getCommand(Context context, String command) throws CommandParseException {
// if (command == null) {
// throw new CommandParseException();
// }
//
// // We check expressions first because some can be mistaken for URIs.
// if (Expr.isCommand(command))
// return new Expr(command);
//
// // In case the command is a URI then we launch ACTION_VIEW.
// if (View.isCommand(command))
// return new View(command);
//
// if (Alarm.isCommand(command))
// return new Alarm(command, context.getString(R.string.alarmExtraMessage));
//
// if (WebSearch.isCommand(command))
// return new WebSearch(command);
//
// if (Dial.isCommand(command))
// return new Dial(command);
//
// if (Search.isCommand(command))
// return new Search(command);
//
// if (Unitconv.isCommand(command))
// return new Unitconv(command);
//
// if (Direction.isCommand(command))
// return new Direction(command);
//
// return new DefaultCommand(command);
// }
//
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/provider/Query.java
// public class Query {
//
// public static final class Columns implements BaseColumns {
//
// public static final Uri CONTENT_URI = Uri.parse("content://" +
// QueriesContentProvider.AUTHORITY +
// "/" +
// QueriesContentProvider.QUERIES_TABLE_NAME);
//
// public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.ee.ioc.phon.android.arvutaja";
//
// public static final String TIMESTAMP = "TIMESTAMP";
// public static final String UTTERANCE = "UTTERANCE";
// public static final String TRANSLATION = "TRANSLATION";
// public static final String EVALUATION = "EVALUATION";
// public static final String LANG = "LANG";
// public static final String TARGET_LANG = "TARGET_LANG";
// public static final String MESSAGE = "MESSAGE";
//
// private Columns() {
// }
// }
// }
// Path: app/src/ee/ioc/phon/android/arvutaja/ShowActivity.java
import android.widget.LinearLayout;
import android.widget.TextView;
import ee.ioc.phon.android.arvutaja.command.Command;
import ee.ioc.phon.android.arvutaja.command.CommandParseException;
import ee.ioc.phon.android.arvutaja.command.CommandParser;
import ee.ioc.phon.android.arvutaja.provider.Query;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.format.Time;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
/*
* Copyright 2013, Institute of Cybernetics at Tallinn University of Technology
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ee.ioc.phon.android.arvutaja;
/**
* Shows the full DB record:
*
* TIMESTAMP
* UTTERANCE
* LANG
* TRANSLATION (linearization), possibly missing
* EVALUATION, possibly missing
* TARGET_LANG
* VIEW (show which external evaluator would be used, support clicking on it)
* MESSAGE (show error message if present)
*/
public class ShowActivity extends AbstractRecognizerActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.show);
final Uri contentUri = getIntent().getData();
ImageButton bDelete = (ImageButton) findViewById(R.id.bDelete);
bDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
getContentResolver().delete(contentUri, null, null);
finish();
}});
TextView tvMessage = (TextView) findViewById(R.id.tvMessage);
try {
Cursor c = getContentResolver().query(contentUri, null, null, null, null);
if (c.moveToFirst()) {
// Column names are the same for Query and Qeval
// Timestamp | long timestamp = c.getLong(c.getColumnIndex(Query.Columns.TIMESTAMP)); |
Kaljurand/Arvutaja | app/src/ee/ioc/phon/android/arvutaja/ShowActivity.java | // Path: app/src/ee/ioc/phon/android/arvutaja/command/Command.java
// public interface Command {
//
// Intent getIntent() throws CommandParseException;
//
// /**
// * <p>Returns a message that helps the user to resolve the situation
// * where the command (intent) cannot be executed because the corresponding
// * activity is not installed.</p>
// *
// * @return suggestion for an activity
// */
// Uri getSuggestion();
//
// String getCommand();
//
// /**
// * <p>Evaluates the expression and returns the result.
// * This method can throw various exceptions.</p>
// *
// * @return evaluation of the expression that was given to the constructor
// */
// Object getOut();
//
//
// /**
// * @return resource ID of the message to show in the UI for this command.
// */
// int getMessage();
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/command/CommandParseException.java
// public class CommandParseException extends Exception {
//
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/command/CommandParser.java
// public class CommandParser {
//
// public static Command getCommand(Context context, String command) throws CommandParseException {
// if (command == null) {
// throw new CommandParseException();
// }
//
// // We check expressions first because some can be mistaken for URIs.
// if (Expr.isCommand(command))
// return new Expr(command);
//
// // In case the command is a URI then we launch ACTION_VIEW.
// if (View.isCommand(command))
// return new View(command);
//
// if (Alarm.isCommand(command))
// return new Alarm(command, context.getString(R.string.alarmExtraMessage));
//
// if (WebSearch.isCommand(command))
// return new WebSearch(command);
//
// if (Dial.isCommand(command))
// return new Dial(command);
//
// if (Search.isCommand(command))
// return new Search(command);
//
// if (Unitconv.isCommand(command))
// return new Unitconv(command);
//
// if (Direction.isCommand(command))
// return new Direction(command);
//
// return new DefaultCommand(command);
// }
//
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/provider/Query.java
// public class Query {
//
// public static final class Columns implements BaseColumns {
//
// public static final Uri CONTENT_URI = Uri.parse("content://" +
// QueriesContentProvider.AUTHORITY +
// "/" +
// QueriesContentProvider.QUERIES_TABLE_NAME);
//
// public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.ee.ioc.phon.android.arvutaja";
//
// public static final String TIMESTAMP = "TIMESTAMP";
// public static final String UTTERANCE = "UTTERANCE";
// public static final String TRANSLATION = "TRANSLATION";
// public static final String EVALUATION = "EVALUATION";
// public static final String LANG = "LANG";
// public static final String TARGET_LANG = "TARGET_LANG";
// public static final String MESSAGE = "MESSAGE";
//
// private Columns() {
// }
// }
// }
| import android.widget.LinearLayout;
import android.widget.TextView;
import ee.ioc.phon.android.arvutaja.command.Command;
import ee.ioc.phon.android.arvutaja.command.CommandParseException;
import ee.ioc.phon.android.arvutaja.command.CommandParser;
import ee.ioc.phon.android.arvutaja.provider.Query;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.format.Time;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton; | tvTranslation.setText(translation);
TextView tvTargetLang = (TextView) findViewById(R.id.tvTargetLang);
String targetLang = c.getString(c.getColumnIndex(Query.Columns.TARGET_LANG));
tvTargetLang.setText(targetLang);
TextView tvEvaluation = (TextView) findViewById(R.id.tvEvaluation);
String evaluation = c.getString(c.getColumnIndex(Query.Columns.EVALUATION));
if (evaluation == null || evaluation.length() == 0) {
tvEvaluation.setVisibility(View.GONE);
// If the internal evaluation is missing then show the internal error message (if present)
// Actually, don't show the message because it looks scary and is not localized.
/*
String message = c.getString(c.getColumnIndex(Query.Columns.MESSAGE));
if (message == null || message.length() == 0) {
} else {
tvMessage.setVisibility(View.VISIBLE);
tvMessage.setText(message);
}
*/
} else {
// Otherwise show the internal evaluation
tvEvaluation.setText(evaluation);
}
// Show a link to the external evaluator, or to the Play Store
// if there is not external evaluator.
final TextView tvView = (TextView) findViewById(R.id.tvView);
String message = null;
try { | // Path: app/src/ee/ioc/phon/android/arvutaja/command/Command.java
// public interface Command {
//
// Intent getIntent() throws CommandParseException;
//
// /**
// * <p>Returns a message that helps the user to resolve the situation
// * where the command (intent) cannot be executed because the corresponding
// * activity is not installed.</p>
// *
// * @return suggestion for an activity
// */
// Uri getSuggestion();
//
// String getCommand();
//
// /**
// * <p>Evaluates the expression and returns the result.
// * This method can throw various exceptions.</p>
// *
// * @return evaluation of the expression that was given to the constructor
// */
// Object getOut();
//
//
// /**
// * @return resource ID of the message to show in the UI for this command.
// */
// int getMessage();
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/command/CommandParseException.java
// public class CommandParseException extends Exception {
//
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/command/CommandParser.java
// public class CommandParser {
//
// public static Command getCommand(Context context, String command) throws CommandParseException {
// if (command == null) {
// throw new CommandParseException();
// }
//
// // We check expressions first because some can be mistaken for URIs.
// if (Expr.isCommand(command))
// return new Expr(command);
//
// // In case the command is a URI then we launch ACTION_VIEW.
// if (View.isCommand(command))
// return new View(command);
//
// if (Alarm.isCommand(command))
// return new Alarm(command, context.getString(R.string.alarmExtraMessage));
//
// if (WebSearch.isCommand(command))
// return new WebSearch(command);
//
// if (Dial.isCommand(command))
// return new Dial(command);
//
// if (Search.isCommand(command))
// return new Search(command);
//
// if (Unitconv.isCommand(command))
// return new Unitconv(command);
//
// if (Direction.isCommand(command))
// return new Direction(command);
//
// return new DefaultCommand(command);
// }
//
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/provider/Query.java
// public class Query {
//
// public static final class Columns implements BaseColumns {
//
// public static final Uri CONTENT_URI = Uri.parse("content://" +
// QueriesContentProvider.AUTHORITY +
// "/" +
// QueriesContentProvider.QUERIES_TABLE_NAME);
//
// public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.ee.ioc.phon.android.arvutaja";
//
// public static final String TIMESTAMP = "TIMESTAMP";
// public static final String UTTERANCE = "UTTERANCE";
// public static final String TRANSLATION = "TRANSLATION";
// public static final String EVALUATION = "EVALUATION";
// public static final String LANG = "LANG";
// public static final String TARGET_LANG = "TARGET_LANG";
// public static final String MESSAGE = "MESSAGE";
//
// private Columns() {
// }
// }
// }
// Path: app/src/ee/ioc/phon/android/arvutaja/ShowActivity.java
import android.widget.LinearLayout;
import android.widget.TextView;
import ee.ioc.phon.android.arvutaja.command.Command;
import ee.ioc.phon.android.arvutaja.command.CommandParseException;
import ee.ioc.phon.android.arvutaja.command.CommandParser;
import ee.ioc.phon.android.arvutaja.provider.Query;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.format.Time;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
tvTranslation.setText(translation);
TextView tvTargetLang = (TextView) findViewById(R.id.tvTargetLang);
String targetLang = c.getString(c.getColumnIndex(Query.Columns.TARGET_LANG));
tvTargetLang.setText(targetLang);
TextView tvEvaluation = (TextView) findViewById(R.id.tvEvaluation);
String evaluation = c.getString(c.getColumnIndex(Query.Columns.EVALUATION));
if (evaluation == null || evaluation.length() == 0) {
tvEvaluation.setVisibility(View.GONE);
// If the internal evaluation is missing then show the internal error message (if present)
// Actually, don't show the message because it looks scary and is not localized.
/*
String message = c.getString(c.getColumnIndex(Query.Columns.MESSAGE));
if (message == null || message.length() == 0) {
} else {
tvMessage.setVisibility(View.VISIBLE);
tvMessage.setText(message);
}
*/
} else {
// Otherwise show the internal evaluation
tvEvaluation.setText(evaluation);
}
// Show a link to the external evaluator, or to the Play Store
// if there is not external evaluator.
final TextView tvView = (TextView) findViewById(R.id.tvView);
String message = null;
try { | final Command command = CommandParser.getCommand(this, translation); |
Kaljurand/Arvutaja | app/src/ee/ioc/phon/android/arvutaja/ShowActivity.java | // Path: app/src/ee/ioc/phon/android/arvutaja/command/Command.java
// public interface Command {
//
// Intent getIntent() throws CommandParseException;
//
// /**
// * <p>Returns a message that helps the user to resolve the situation
// * where the command (intent) cannot be executed because the corresponding
// * activity is not installed.</p>
// *
// * @return suggestion for an activity
// */
// Uri getSuggestion();
//
// String getCommand();
//
// /**
// * <p>Evaluates the expression and returns the result.
// * This method can throw various exceptions.</p>
// *
// * @return evaluation of the expression that was given to the constructor
// */
// Object getOut();
//
//
// /**
// * @return resource ID of the message to show in the UI for this command.
// */
// int getMessage();
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/command/CommandParseException.java
// public class CommandParseException extends Exception {
//
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/command/CommandParser.java
// public class CommandParser {
//
// public static Command getCommand(Context context, String command) throws CommandParseException {
// if (command == null) {
// throw new CommandParseException();
// }
//
// // We check expressions first because some can be mistaken for URIs.
// if (Expr.isCommand(command))
// return new Expr(command);
//
// // In case the command is a URI then we launch ACTION_VIEW.
// if (View.isCommand(command))
// return new View(command);
//
// if (Alarm.isCommand(command))
// return new Alarm(command, context.getString(R.string.alarmExtraMessage));
//
// if (WebSearch.isCommand(command))
// return new WebSearch(command);
//
// if (Dial.isCommand(command))
// return new Dial(command);
//
// if (Search.isCommand(command))
// return new Search(command);
//
// if (Unitconv.isCommand(command))
// return new Unitconv(command);
//
// if (Direction.isCommand(command))
// return new Direction(command);
//
// return new DefaultCommand(command);
// }
//
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/provider/Query.java
// public class Query {
//
// public static final class Columns implements BaseColumns {
//
// public static final Uri CONTENT_URI = Uri.parse("content://" +
// QueriesContentProvider.AUTHORITY +
// "/" +
// QueriesContentProvider.QUERIES_TABLE_NAME);
//
// public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.ee.ioc.phon.android.arvutaja";
//
// public static final String TIMESTAMP = "TIMESTAMP";
// public static final String UTTERANCE = "UTTERANCE";
// public static final String TRANSLATION = "TRANSLATION";
// public static final String EVALUATION = "EVALUATION";
// public static final String LANG = "LANG";
// public static final String TARGET_LANG = "TARGET_LANG";
// public static final String MESSAGE = "MESSAGE";
//
// private Columns() {
// }
// }
// }
| import android.widget.LinearLayout;
import android.widget.TextView;
import ee.ioc.phon.android.arvutaja.command.Command;
import ee.ioc.phon.android.arvutaja.command.CommandParseException;
import ee.ioc.phon.android.arvutaja.command.CommandParser;
import ee.ioc.phon.android.arvutaja.provider.Query;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.format.Time;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton; | tvTranslation.setText(translation);
TextView tvTargetLang = (TextView) findViewById(R.id.tvTargetLang);
String targetLang = c.getString(c.getColumnIndex(Query.Columns.TARGET_LANG));
tvTargetLang.setText(targetLang);
TextView tvEvaluation = (TextView) findViewById(R.id.tvEvaluation);
String evaluation = c.getString(c.getColumnIndex(Query.Columns.EVALUATION));
if (evaluation == null || evaluation.length() == 0) {
tvEvaluation.setVisibility(View.GONE);
// If the internal evaluation is missing then show the internal error message (if present)
// Actually, don't show the message because it looks scary and is not localized.
/*
String message = c.getString(c.getColumnIndex(Query.Columns.MESSAGE));
if (message == null || message.length() == 0) {
} else {
tvMessage.setVisibility(View.VISIBLE);
tvMessage.setText(message);
}
*/
} else {
// Otherwise show the internal evaluation
tvEvaluation.setText(evaluation);
}
// Show a link to the external evaluator, or to the Play Store
// if there is not external evaluator.
final TextView tvView = (TextView) findViewById(R.id.tvView);
String message = null;
try { | // Path: app/src/ee/ioc/phon/android/arvutaja/command/Command.java
// public interface Command {
//
// Intent getIntent() throws CommandParseException;
//
// /**
// * <p>Returns a message that helps the user to resolve the situation
// * where the command (intent) cannot be executed because the corresponding
// * activity is not installed.</p>
// *
// * @return suggestion for an activity
// */
// Uri getSuggestion();
//
// String getCommand();
//
// /**
// * <p>Evaluates the expression and returns the result.
// * This method can throw various exceptions.</p>
// *
// * @return evaluation of the expression that was given to the constructor
// */
// Object getOut();
//
//
// /**
// * @return resource ID of the message to show in the UI for this command.
// */
// int getMessage();
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/command/CommandParseException.java
// public class CommandParseException extends Exception {
//
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/command/CommandParser.java
// public class CommandParser {
//
// public static Command getCommand(Context context, String command) throws CommandParseException {
// if (command == null) {
// throw new CommandParseException();
// }
//
// // We check expressions first because some can be mistaken for URIs.
// if (Expr.isCommand(command))
// return new Expr(command);
//
// // In case the command is a URI then we launch ACTION_VIEW.
// if (View.isCommand(command))
// return new View(command);
//
// if (Alarm.isCommand(command))
// return new Alarm(command, context.getString(R.string.alarmExtraMessage));
//
// if (WebSearch.isCommand(command))
// return new WebSearch(command);
//
// if (Dial.isCommand(command))
// return new Dial(command);
//
// if (Search.isCommand(command))
// return new Search(command);
//
// if (Unitconv.isCommand(command))
// return new Unitconv(command);
//
// if (Direction.isCommand(command))
// return new Direction(command);
//
// return new DefaultCommand(command);
// }
//
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/provider/Query.java
// public class Query {
//
// public static final class Columns implements BaseColumns {
//
// public static final Uri CONTENT_URI = Uri.parse("content://" +
// QueriesContentProvider.AUTHORITY +
// "/" +
// QueriesContentProvider.QUERIES_TABLE_NAME);
//
// public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.ee.ioc.phon.android.arvutaja";
//
// public static final String TIMESTAMP = "TIMESTAMP";
// public static final String UTTERANCE = "UTTERANCE";
// public static final String TRANSLATION = "TRANSLATION";
// public static final String EVALUATION = "EVALUATION";
// public static final String LANG = "LANG";
// public static final String TARGET_LANG = "TARGET_LANG";
// public static final String MESSAGE = "MESSAGE";
//
// private Columns() {
// }
// }
// }
// Path: app/src/ee/ioc/phon/android/arvutaja/ShowActivity.java
import android.widget.LinearLayout;
import android.widget.TextView;
import ee.ioc.phon.android.arvutaja.command.Command;
import ee.ioc.phon.android.arvutaja.command.CommandParseException;
import ee.ioc.phon.android.arvutaja.command.CommandParser;
import ee.ioc.phon.android.arvutaja.provider.Query;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.format.Time;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
tvTranslation.setText(translation);
TextView tvTargetLang = (TextView) findViewById(R.id.tvTargetLang);
String targetLang = c.getString(c.getColumnIndex(Query.Columns.TARGET_LANG));
tvTargetLang.setText(targetLang);
TextView tvEvaluation = (TextView) findViewById(R.id.tvEvaluation);
String evaluation = c.getString(c.getColumnIndex(Query.Columns.EVALUATION));
if (evaluation == null || evaluation.length() == 0) {
tvEvaluation.setVisibility(View.GONE);
// If the internal evaluation is missing then show the internal error message (if present)
// Actually, don't show the message because it looks scary and is not localized.
/*
String message = c.getString(c.getColumnIndex(Query.Columns.MESSAGE));
if (message == null || message.length() == 0) {
} else {
tvMessage.setVisibility(View.VISIBLE);
tvMessage.setText(message);
}
*/
} else {
// Otherwise show the internal evaluation
tvEvaluation.setText(evaluation);
}
// Show a link to the external evaluator, or to the Play Store
// if there is not external evaluator.
final TextView tvView = (TextView) findViewById(R.id.tvView);
String message = null;
try { | final Command command = CommandParser.getCommand(this, translation); |
Kaljurand/Arvutaja | app/src/ee/ioc/phon/android/arvutaja/ShowActivity.java | // Path: app/src/ee/ioc/phon/android/arvutaja/command/Command.java
// public interface Command {
//
// Intent getIntent() throws CommandParseException;
//
// /**
// * <p>Returns a message that helps the user to resolve the situation
// * where the command (intent) cannot be executed because the corresponding
// * activity is not installed.</p>
// *
// * @return suggestion for an activity
// */
// Uri getSuggestion();
//
// String getCommand();
//
// /**
// * <p>Evaluates the expression and returns the result.
// * This method can throw various exceptions.</p>
// *
// * @return evaluation of the expression that was given to the constructor
// */
// Object getOut();
//
//
// /**
// * @return resource ID of the message to show in the UI for this command.
// */
// int getMessage();
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/command/CommandParseException.java
// public class CommandParseException extends Exception {
//
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/command/CommandParser.java
// public class CommandParser {
//
// public static Command getCommand(Context context, String command) throws CommandParseException {
// if (command == null) {
// throw new CommandParseException();
// }
//
// // We check expressions first because some can be mistaken for URIs.
// if (Expr.isCommand(command))
// return new Expr(command);
//
// // In case the command is a URI then we launch ACTION_VIEW.
// if (View.isCommand(command))
// return new View(command);
//
// if (Alarm.isCommand(command))
// return new Alarm(command, context.getString(R.string.alarmExtraMessage));
//
// if (WebSearch.isCommand(command))
// return new WebSearch(command);
//
// if (Dial.isCommand(command))
// return new Dial(command);
//
// if (Search.isCommand(command))
// return new Search(command);
//
// if (Unitconv.isCommand(command))
// return new Unitconv(command);
//
// if (Direction.isCommand(command))
// return new Direction(command);
//
// return new DefaultCommand(command);
// }
//
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/provider/Query.java
// public class Query {
//
// public static final class Columns implements BaseColumns {
//
// public static final Uri CONTENT_URI = Uri.parse("content://" +
// QueriesContentProvider.AUTHORITY +
// "/" +
// QueriesContentProvider.QUERIES_TABLE_NAME);
//
// public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.ee.ioc.phon.android.arvutaja";
//
// public static final String TIMESTAMP = "TIMESTAMP";
// public static final String UTTERANCE = "UTTERANCE";
// public static final String TRANSLATION = "TRANSLATION";
// public static final String EVALUATION = "EVALUATION";
// public static final String LANG = "LANG";
// public static final String TARGET_LANG = "TARGET_LANG";
// public static final String MESSAGE = "MESSAGE";
//
// private Columns() {
// }
// }
// }
| import android.widget.LinearLayout;
import android.widget.TextView;
import ee.ioc.phon.android.arvutaja.command.Command;
import ee.ioc.phon.android.arvutaja.command.CommandParseException;
import ee.ioc.phon.android.arvutaja.command.CommandParser;
import ee.ioc.phon.android.arvutaja.provider.Query;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.format.Time;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton; | */
} else {
// Otherwise show the internal evaluation
tvEvaluation.setText(evaluation);
}
// Show a link to the external evaluator, or to the Play Store
// if there is not external evaluator.
final TextView tvView = (TextView) findViewById(R.id.tvView);
String message = null;
try {
final Command command = CommandParser.getCommand(this, translation);
final Intent intent = command.getIntent();
if (getIntentActivities(intent).isEmpty()) {
message = getString(R.string.errorIntentActivityNotPresent);
llInterpretation.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startForeignActivity(new Intent(Intent.ACTION_VIEW, command.getSuggestion()));
}
});
} else {
message = getString(command.getMessage());
llInterpretation.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startForeignActivity(intent);
}
});
} | // Path: app/src/ee/ioc/phon/android/arvutaja/command/Command.java
// public interface Command {
//
// Intent getIntent() throws CommandParseException;
//
// /**
// * <p>Returns a message that helps the user to resolve the situation
// * where the command (intent) cannot be executed because the corresponding
// * activity is not installed.</p>
// *
// * @return suggestion for an activity
// */
// Uri getSuggestion();
//
// String getCommand();
//
// /**
// * <p>Evaluates the expression and returns the result.
// * This method can throw various exceptions.</p>
// *
// * @return evaluation of the expression that was given to the constructor
// */
// Object getOut();
//
//
// /**
// * @return resource ID of the message to show in the UI for this command.
// */
// int getMessage();
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/command/CommandParseException.java
// public class CommandParseException extends Exception {
//
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/command/CommandParser.java
// public class CommandParser {
//
// public static Command getCommand(Context context, String command) throws CommandParseException {
// if (command == null) {
// throw new CommandParseException();
// }
//
// // We check expressions first because some can be mistaken for URIs.
// if (Expr.isCommand(command))
// return new Expr(command);
//
// // In case the command is a URI then we launch ACTION_VIEW.
// if (View.isCommand(command))
// return new View(command);
//
// if (Alarm.isCommand(command))
// return new Alarm(command, context.getString(R.string.alarmExtraMessage));
//
// if (WebSearch.isCommand(command))
// return new WebSearch(command);
//
// if (Dial.isCommand(command))
// return new Dial(command);
//
// if (Search.isCommand(command))
// return new Search(command);
//
// if (Unitconv.isCommand(command))
// return new Unitconv(command);
//
// if (Direction.isCommand(command))
// return new Direction(command);
//
// return new DefaultCommand(command);
// }
//
// }
//
// Path: app/src/ee/ioc/phon/android/arvutaja/provider/Query.java
// public class Query {
//
// public static final class Columns implements BaseColumns {
//
// public static final Uri CONTENT_URI = Uri.parse("content://" +
// QueriesContentProvider.AUTHORITY +
// "/" +
// QueriesContentProvider.QUERIES_TABLE_NAME);
//
// public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.ee.ioc.phon.android.arvutaja";
//
// public static final String TIMESTAMP = "TIMESTAMP";
// public static final String UTTERANCE = "UTTERANCE";
// public static final String TRANSLATION = "TRANSLATION";
// public static final String EVALUATION = "EVALUATION";
// public static final String LANG = "LANG";
// public static final String TARGET_LANG = "TARGET_LANG";
// public static final String MESSAGE = "MESSAGE";
//
// private Columns() {
// }
// }
// }
// Path: app/src/ee/ioc/phon/android/arvutaja/ShowActivity.java
import android.widget.LinearLayout;
import android.widget.TextView;
import ee.ioc.phon.android.arvutaja.command.Command;
import ee.ioc.phon.android.arvutaja.command.CommandParseException;
import ee.ioc.phon.android.arvutaja.command.CommandParser;
import ee.ioc.phon.android.arvutaja.provider.Query;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.format.Time;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
*/
} else {
// Otherwise show the internal evaluation
tvEvaluation.setText(evaluation);
}
// Show a link to the external evaluator, or to the Play Store
// if there is not external evaluator.
final TextView tvView = (TextView) findViewById(R.id.tvView);
String message = null;
try {
final Command command = CommandParser.getCommand(this, translation);
final Intent intent = command.getIntent();
if (getIntentActivities(intent).isEmpty()) {
message = getString(R.string.errorIntentActivityNotPresent);
llInterpretation.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startForeignActivity(new Intent(Intent.ACTION_VIEW, command.getSuggestion()));
}
});
} else {
message = getString(command.getMessage());
llInterpretation.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startForeignActivity(intent);
}
});
} | } catch (CommandParseException e) { |
Sefford/material-in-30-minutes | app/src/main/java/com/sefford/material/sample/common/injection/modules/DevelopmentLoggingModule.java | // Path: app/src/main/java/com/sefford/material/sample/common/logging/DevelopmentLogger.java
// @Singleton
// public class DevelopmentLogger implements Logger {
//
// @Inject
// public DevelopmentLogger() {
// }
//
// @Override
// public void bind(Context context) {
// // Nothing for DevelopmentLogger
// }
//
// @Override
// public void identify(long userId) {
// // This is a Production feature
// }
//
// @Override
// public void e(String logtag, String message) {
// Log.e(logtag, message);
// }
//
// @Override
// public void e(String logtag, String message, Throwable e) {
// Log.e(logtag, message, e);
// }
//
// @Override
// public void d(String logtag, String message) {
// Log.d(logtag, message);
// }
//
// @Override
// public void w(String logtag, String message) {
// Log.w(logtag, message);
// }
//
// @Override
// public void w(String logtag, String message, Throwable e) {
// Log.w(logtag, message, e);
// }
//
// @Override
// public void v(String logtag, String message) {
// Log.v(logtag, message);
// }
//
// @Override
// public void printPerformanceLog(String tag, String element, long start) {
// d(tag, "(" + element + "):" + (System.currentTimeMillis() - start) + "ms");
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/common/logging/Logger.java
// public interface Logger extends Loggable {
//
// void bind(Context context);
//
// void identify(long userId);
//
// void e(String logtag, String message);
//
// void e(String logtag, String message, Throwable e);
//
// void d(String logtag, String message);
//
// void w(String logtag, String message);
//
// void w(String logtag, String message, Throwable e);
//
// void v(String logtag, String message);
//
// void printPerformanceLog(String tag, String element, long start);
// }
| import com.sefford.kor.common.interfaces.Loggable;
import com.sefford.material.sample.common.logging.DevelopmentLogger;
import com.sefford.material.sample.common.logging.Logger;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton; | /*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.common.injection.modules;
/**
* This module handles the Logging system. As this application is not intended for production purposes, handles the
* Development logging module.
* <p/>
* This is copied from other applications which allow the logger to be configured dynamically per BuildConfig.DEBUG
* and uses abstraction to enable logcat or Crashlytics modules.
*/
@Module(library = true,
complete = true)
public class DevelopmentLoggingModule {
@Provides
@Singleton | // Path: app/src/main/java/com/sefford/material/sample/common/logging/DevelopmentLogger.java
// @Singleton
// public class DevelopmentLogger implements Logger {
//
// @Inject
// public DevelopmentLogger() {
// }
//
// @Override
// public void bind(Context context) {
// // Nothing for DevelopmentLogger
// }
//
// @Override
// public void identify(long userId) {
// // This is a Production feature
// }
//
// @Override
// public void e(String logtag, String message) {
// Log.e(logtag, message);
// }
//
// @Override
// public void e(String logtag, String message, Throwable e) {
// Log.e(logtag, message, e);
// }
//
// @Override
// public void d(String logtag, String message) {
// Log.d(logtag, message);
// }
//
// @Override
// public void w(String logtag, String message) {
// Log.w(logtag, message);
// }
//
// @Override
// public void w(String logtag, String message, Throwable e) {
// Log.w(logtag, message, e);
// }
//
// @Override
// public void v(String logtag, String message) {
// Log.v(logtag, message);
// }
//
// @Override
// public void printPerformanceLog(String tag, String element, long start) {
// d(tag, "(" + element + "):" + (System.currentTimeMillis() - start) + "ms");
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/common/logging/Logger.java
// public interface Logger extends Loggable {
//
// void bind(Context context);
//
// void identify(long userId);
//
// void e(String logtag, String message);
//
// void e(String logtag, String message, Throwable e);
//
// void d(String logtag, String message);
//
// void w(String logtag, String message);
//
// void w(String logtag, String message, Throwable e);
//
// void v(String logtag, String message);
//
// void printPerformanceLog(String tag, String element, long start);
// }
// Path: app/src/main/java/com/sefford/material/sample/common/injection/modules/DevelopmentLoggingModule.java
import com.sefford.kor.common.interfaces.Loggable;
import com.sefford.material.sample.common.logging.DevelopmentLogger;
import com.sefford.material.sample.common.logging.Logger;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton;
/*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.common.injection.modules;
/**
* This module handles the Logging system. As this application is not intended for production purposes, handles the
* Development logging module.
* <p/>
* This is copied from other applications which allow the logger to be configured dynamically per BuildConfig.DEBUG
* and uses abstraction to enable logcat or Crashlytics modules.
*/
@Module(library = true,
complete = true)
public class DevelopmentLoggingModule {
@Provides
@Singleton | public Logger provideLogger(DevelopmentLogger logger) { |
Sefford/material-in-30-minutes | app/src/main/java/com/sefford/material/sample/common/injection/modules/DevelopmentLoggingModule.java | // Path: app/src/main/java/com/sefford/material/sample/common/logging/DevelopmentLogger.java
// @Singleton
// public class DevelopmentLogger implements Logger {
//
// @Inject
// public DevelopmentLogger() {
// }
//
// @Override
// public void bind(Context context) {
// // Nothing for DevelopmentLogger
// }
//
// @Override
// public void identify(long userId) {
// // This is a Production feature
// }
//
// @Override
// public void e(String logtag, String message) {
// Log.e(logtag, message);
// }
//
// @Override
// public void e(String logtag, String message, Throwable e) {
// Log.e(logtag, message, e);
// }
//
// @Override
// public void d(String logtag, String message) {
// Log.d(logtag, message);
// }
//
// @Override
// public void w(String logtag, String message) {
// Log.w(logtag, message);
// }
//
// @Override
// public void w(String logtag, String message, Throwable e) {
// Log.w(logtag, message, e);
// }
//
// @Override
// public void v(String logtag, String message) {
// Log.v(logtag, message);
// }
//
// @Override
// public void printPerformanceLog(String tag, String element, long start) {
// d(tag, "(" + element + "):" + (System.currentTimeMillis() - start) + "ms");
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/common/logging/Logger.java
// public interface Logger extends Loggable {
//
// void bind(Context context);
//
// void identify(long userId);
//
// void e(String logtag, String message);
//
// void e(String logtag, String message, Throwable e);
//
// void d(String logtag, String message);
//
// void w(String logtag, String message);
//
// void w(String logtag, String message, Throwable e);
//
// void v(String logtag, String message);
//
// void printPerformanceLog(String tag, String element, long start);
// }
| import com.sefford.kor.common.interfaces.Loggable;
import com.sefford.material.sample.common.logging.DevelopmentLogger;
import com.sefford.material.sample.common.logging.Logger;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton; | /*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.common.injection.modules;
/**
* This module handles the Logging system. As this application is not intended for production purposes, handles the
* Development logging module.
* <p/>
* This is copied from other applications which allow the logger to be configured dynamically per BuildConfig.DEBUG
* and uses abstraction to enable logcat or Crashlytics modules.
*/
@Module(library = true,
complete = true)
public class DevelopmentLoggingModule {
@Provides
@Singleton | // Path: app/src/main/java/com/sefford/material/sample/common/logging/DevelopmentLogger.java
// @Singleton
// public class DevelopmentLogger implements Logger {
//
// @Inject
// public DevelopmentLogger() {
// }
//
// @Override
// public void bind(Context context) {
// // Nothing for DevelopmentLogger
// }
//
// @Override
// public void identify(long userId) {
// // This is a Production feature
// }
//
// @Override
// public void e(String logtag, String message) {
// Log.e(logtag, message);
// }
//
// @Override
// public void e(String logtag, String message, Throwable e) {
// Log.e(logtag, message, e);
// }
//
// @Override
// public void d(String logtag, String message) {
// Log.d(logtag, message);
// }
//
// @Override
// public void w(String logtag, String message) {
// Log.w(logtag, message);
// }
//
// @Override
// public void w(String logtag, String message, Throwable e) {
// Log.w(logtag, message, e);
// }
//
// @Override
// public void v(String logtag, String message) {
// Log.v(logtag, message);
// }
//
// @Override
// public void printPerformanceLog(String tag, String element, long start) {
// d(tag, "(" + element + "):" + (System.currentTimeMillis() - start) + "ms");
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/common/logging/Logger.java
// public interface Logger extends Loggable {
//
// void bind(Context context);
//
// void identify(long userId);
//
// void e(String logtag, String message);
//
// void e(String logtag, String message, Throwable e);
//
// void d(String logtag, String message);
//
// void w(String logtag, String message);
//
// void w(String logtag, String message, Throwable e);
//
// void v(String logtag, String message);
//
// void printPerformanceLog(String tag, String element, long start);
// }
// Path: app/src/main/java/com/sefford/material/sample/common/injection/modules/DevelopmentLoggingModule.java
import com.sefford.kor.common.interfaces.Loggable;
import com.sefford.material.sample.common.logging.DevelopmentLogger;
import com.sefford.material.sample.common.logging.Logger;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton;
/*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.common.injection.modules;
/**
* This module handles the Logging system. As this application is not intended for production purposes, handles the
* Development logging module.
* <p/>
* This is copied from other applications which allow the logger to be configured dynamically per BuildConfig.DEBUG
* and uses abstraction to enable logcat or Crashlytics modules.
*/
@Module(library = true,
complete = true)
public class DevelopmentLoggingModule {
@Provides
@Singleton | public Logger provideLogger(DevelopmentLogger logger) { |
Sefford/material-in-30-minutes | app/src/main/java/com/sefford/material/sample/common/injection/modules/ApplicationModule.java | // Path: app/src/main/java/com/sefford/material/sample/common/ui/activities/BaseActivity.java
// public abstract class BaseActivity extends Activity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// final ObjectGraph originalGraph = ((MaterialApplication) getApplication()).getGraph();
// extend(originalGraph, getExtensions(originalGraph, getIntent().getExtras())).inject(this);
// }
//
// /**
// * Extends and returns the ObjectGraph with ad-hoc extensions or returns the original one for dynamic injection
// *
// * @param graph Original ObjectGraph
// * @param extensions Potential ad-hoc extensions.
// * @return The ObjectGraph
// */
// public ObjectGraph extend(ObjectGraph graph, Object[] extensions) {
// return extensions.length == 0 ? graph : graph.plus(extensions);
// }
//
// /**
// * This allows the child Activities to configure their own extension modules to fit their needs
// *
// * @param originalGraph Original ObjectGraph, in case it requires some decision-making from higher-level compnents
// * @param arguments Configuration arguments of the Activity itself
// * @return Array with extensions
// */
// protected abstract Object[] getExtensions(ObjectGraph originalGraph, Bundle arguments);
// }
//
// Path: app/src/main/java/com/sefford/material/sample/common/ui/application/MaterialApplication.java
// public class MaterialApplication extends Application {
//
//
// /**
// * Object Injection Graph for development/production.
// * <p/>
// * We don't care this is static as the Application will live as long as the execution.
// */
// ObjectGraph objectGraph;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// // Initialize Dagger's Dependency injection object Graph
// objectGraph = initializeGraph();
// objectGraph.inject(this);
// }
//
// ObjectGraph initializeGraph() {
// return ObjectGraph.create(new ApplicationModule(this),
// new DevelopmentLoggingModule());
// }
//
// /**
// * Injection facility for the elements.
// *
// * @param instance Instance of the object to inject dependencies
// * @param <T> Class that will be injected
// */
// public <T> void inject(T instance) {
// objectGraph.inject(instance);
// }
//
// /**
// * Provider facility for the elements.
// *
// * @param type Type of the instance to get
// * @param <T> Class that will be injected
// */
// public <T> T get(Class<T> type) {
// return objectGraph.get(type);
// }
//
// public ObjectGraph getGraph() {
// return objectGraph;
// }
// }
| import android.content.Context;
import com.sefford.material.sample.common.ui.activities.BaseActivity;
import com.sefford.material.sample.common.ui.application.MaterialApplication;
import dagger.Module;
import dagger.Provides;
import javax.inject.Named; | /*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.common.injection.modules;
/**
* Application Module handles all the Application-related elements on the injection graph, in this case
* the wide-app singleton Application context.
* <p/>
* We do not feat about leaking this context, as it is alive for as long as Android keeps the App in memory.
*/
@Module(
includes = {
CoreModule.class,
DevelopmentLoggingModule.class,
},
injects = {
// Application | // Path: app/src/main/java/com/sefford/material/sample/common/ui/activities/BaseActivity.java
// public abstract class BaseActivity extends Activity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// final ObjectGraph originalGraph = ((MaterialApplication) getApplication()).getGraph();
// extend(originalGraph, getExtensions(originalGraph, getIntent().getExtras())).inject(this);
// }
//
// /**
// * Extends and returns the ObjectGraph with ad-hoc extensions or returns the original one for dynamic injection
// *
// * @param graph Original ObjectGraph
// * @param extensions Potential ad-hoc extensions.
// * @return The ObjectGraph
// */
// public ObjectGraph extend(ObjectGraph graph, Object[] extensions) {
// return extensions.length == 0 ? graph : graph.plus(extensions);
// }
//
// /**
// * This allows the child Activities to configure their own extension modules to fit their needs
// *
// * @param originalGraph Original ObjectGraph, in case it requires some decision-making from higher-level compnents
// * @param arguments Configuration arguments of the Activity itself
// * @return Array with extensions
// */
// protected abstract Object[] getExtensions(ObjectGraph originalGraph, Bundle arguments);
// }
//
// Path: app/src/main/java/com/sefford/material/sample/common/ui/application/MaterialApplication.java
// public class MaterialApplication extends Application {
//
//
// /**
// * Object Injection Graph for development/production.
// * <p/>
// * We don't care this is static as the Application will live as long as the execution.
// */
// ObjectGraph objectGraph;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// // Initialize Dagger's Dependency injection object Graph
// objectGraph = initializeGraph();
// objectGraph.inject(this);
// }
//
// ObjectGraph initializeGraph() {
// return ObjectGraph.create(new ApplicationModule(this),
// new DevelopmentLoggingModule());
// }
//
// /**
// * Injection facility for the elements.
// *
// * @param instance Instance of the object to inject dependencies
// * @param <T> Class that will be injected
// */
// public <T> void inject(T instance) {
// objectGraph.inject(instance);
// }
//
// /**
// * Provider facility for the elements.
// *
// * @param type Type of the instance to get
// * @param <T> Class that will be injected
// */
// public <T> T get(Class<T> type) {
// return objectGraph.get(type);
// }
//
// public ObjectGraph getGraph() {
// return objectGraph;
// }
// }
// Path: app/src/main/java/com/sefford/material/sample/common/injection/modules/ApplicationModule.java
import android.content.Context;
import com.sefford.material.sample.common.ui.activities.BaseActivity;
import com.sefford.material.sample.common.ui.application.MaterialApplication;
import dagger.Module;
import dagger.Provides;
import javax.inject.Named;
/*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.common.injection.modules;
/**
* Application Module handles all the Application-related elements on the injection graph, in this case
* the wide-app singleton Application context.
* <p/>
* We do not feat about leaking this context, as it is alive for as long as Android keeps the App in memory.
*/
@Module(
includes = {
CoreModule.class,
DevelopmentLoggingModule.class,
},
injects = {
// Application | MaterialApplication.class, |
Sefford/material-in-30-minutes | app/src/main/java/com/sefford/material/sample/common/injection/modules/ApplicationModule.java | // Path: app/src/main/java/com/sefford/material/sample/common/ui/activities/BaseActivity.java
// public abstract class BaseActivity extends Activity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// final ObjectGraph originalGraph = ((MaterialApplication) getApplication()).getGraph();
// extend(originalGraph, getExtensions(originalGraph, getIntent().getExtras())).inject(this);
// }
//
// /**
// * Extends and returns the ObjectGraph with ad-hoc extensions or returns the original one for dynamic injection
// *
// * @param graph Original ObjectGraph
// * @param extensions Potential ad-hoc extensions.
// * @return The ObjectGraph
// */
// public ObjectGraph extend(ObjectGraph graph, Object[] extensions) {
// return extensions.length == 0 ? graph : graph.plus(extensions);
// }
//
// /**
// * This allows the child Activities to configure their own extension modules to fit their needs
// *
// * @param originalGraph Original ObjectGraph, in case it requires some decision-making from higher-level compnents
// * @param arguments Configuration arguments of the Activity itself
// * @return Array with extensions
// */
// protected abstract Object[] getExtensions(ObjectGraph originalGraph, Bundle arguments);
// }
//
// Path: app/src/main/java/com/sefford/material/sample/common/ui/application/MaterialApplication.java
// public class MaterialApplication extends Application {
//
//
// /**
// * Object Injection Graph for development/production.
// * <p/>
// * We don't care this is static as the Application will live as long as the execution.
// */
// ObjectGraph objectGraph;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// // Initialize Dagger's Dependency injection object Graph
// objectGraph = initializeGraph();
// objectGraph.inject(this);
// }
//
// ObjectGraph initializeGraph() {
// return ObjectGraph.create(new ApplicationModule(this),
// new DevelopmentLoggingModule());
// }
//
// /**
// * Injection facility for the elements.
// *
// * @param instance Instance of the object to inject dependencies
// * @param <T> Class that will be injected
// */
// public <T> void inject(T instance) {
// objectGraph.inject(instance);
// }
//
// /**
// * Provider facility for the elements.
// *
// * @param type Type of the instance to get
// * @param <T> Class that will be injected
// */
// public <T> T get(Class<T> type) {
// return objectGraph.get(type);
// }
//
// public ObjectGraph getGraph() {
// return objectGraph;
// }
// }
| import android.content.Context;
import com.sefford.material.sample.common.ui.activities.BaseActivity;
import com.sefford.material.sample.common.ui.application.MaterialApplication;
import dagger.Module;
import dagger.Provides;
import javax.inject.Named; | /*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.common.injection.modules;
/**
* Application Module handles all the Application-related elements on the injection graph, in this case
* the wide-app singleton Application context.
* <p/>
* We do not feat about leaking this context, as it is alive for as long as Android keeps the App in memory.
*/
@Module(
includes = {
CoreModule.class,
DevelopmentLoggingModule.class,
},
injects = {
// Application
MaterialApplication.class,
// Activities | // Path: app/src/main/java/com/sefford/material/sample/common/ui/activities/BaseActivity.java
// public abstract class BaseActivity extends Activity {
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// final ObjectGraph originalGraph = ((MaterialApplication) getApplication()).getGraph();
// extend(originalGraph, getExtensions(originalGraph, getIntent().getExtras())).inject(this);
// }
//
// /**
// * Extends and returns the ObjectGraph with ad-hoc extensions or returns the original one for dynamic injection
// *
// * @param graph Original ObjectGraph
// * @param extensions Potential ad-hoc extensions.
// * @return The ObjectGraph
// */
// public ObjectGraph extend(ObjectGraph graph, Object[] extensions) {
// return extensions.length == 0 ? graph : graph.plus(extensions);
// }
//
// /**
// * This allows the child Activities to configure their own extension modules to fit their needs
// *
// * @param originalGraph Original ObjectGraph, in case it requires some decision-making from higher-level compnents
// * @param arguments Configuration arguments of the Activity itself
// * @return Array with extensions
// */
// protected abstract Object[] getExtensions(ObjectGraph originalGraph, Bundle arguments);
// }
//
// Path: app/src/main/java/com/sefford/material/sample/common/ui/application/MaterialApplication.java
// public class MaterialApplication extends Application {
//
//
// /**
// * Object Injection Graph for development/production.
// * <p/>
// * We don't care this is static as the Application will live as long as the execution.
// */
// ObjectGraph objectGraph;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// // Initialize Dagger's Dependency injection object Graph
// objectGraph = initializeGraph();
// objectGraph.inject(this);
// }
//
// ObjectGraph initializeGraph() {
// return ObjectGraph.create(new ApplicationModule(this),
// new DevelopmentLoggingModule());
// }
//
// /**
// * Injection facility for the elements.
// *
// * @param instance Instance of the object to inject dependencies
// * @param <T> Class that will be injected
// */
// public <T> void inject(T instance) {
// objectGraph.inject(instance);
// }
//
// /**
// * Provider facility for the elements.
// *
// * @param type Type of the instance to get
// * @param <T> Class that will be injected
// */
// public <T> T get(Class<T> type) {
// return objectGraph.get(type);
// }
//
// public ObjectGraph getGraph() {
// return objectGraph;
// }
// }
// Path: app/src/main/java/com/sefford/material/sample/common/injection/modules/ApplicationModule.java
import android.content.Context;
import com.sefford.material.sample.common.ui.activities.BaseActivity;
import com.sefford.material.sample.common.ui.application.MaterialApplication;
import dagger.Module;
import dagger.Provides;
import javax.inject.Named;
/*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.common.injection.modules;
/**
* Application Module handles all the Application-related elements on the injection graph, in this case
* the wide-app singleton Application context.
* <p/>
* We do not feat about leaking this context, as it is alive for as long as Android keeps the App in memory.
*/
@Module(
includes = {
CoreModule.class,
DevelopmentLoggingModule.class,
},
injects = {
// Application
MaterialApplication.class,
// Activities | BaseActivity.class, |
Sefford/material-in-30-minutes | app/src/main/java/com/sefford/material/sample/common/injection/modules/LocalBusModule.java | // Path: app/src/main/java/com/sefford/material/sample/common/internal/Bus.java
// public class Bus implements Postable, com.sefford.brender.interfaces.Postable {
//
// final EventBus bus;
//
// @Inject
// public Bus(EventBus bus) {
// this.bus = bus;
// }
//
// public void register(Object target) {
// if (!bus.isRegistered(target)) {
// bus.register(target);
// }
// }
//
// public void unregister(Object target) {
// if (bus.isRegistered(target)) {
// bus.unregister(target);
// }
// }
//
// @Override
// public void post(Object message) {
// bus.post(message);
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/contacts/details/ui/activities/ContactDetailsActivity.java
// public class ContactDetailsActivity extends BaseActivity {
//
// public static final String EXTRA_ID = "extra_id";
// public static final String EXTRA_NAME = "extra_name";
// public static final String EXTRA_COLOR = "extra_color";
//
// @Inject
// ContactDetailView view;
// @Inject
// ContactDetailPresenter presenter;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.screen_detail);
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// view.configurePlaceholder(getIntent().getStringExtra(EXTRA_NAME), getIntent().getStringExtra(EXTRA_COLOR));
// view.bind(getWindow().findViewById(android.R.id.content));
// presenter.setId(getIntent().getLongExtra(EXTRA_ID, 0));
// presenter.bind(view);
// }
//
//
// @Override
// protected void onDestroy() {
// super.onDestroy();
// presenter.release();
// }
//
// @Override
// protected Object[] getExtensions(ObjectGraph originalGraph, Bundle arguments) {
// final Object[] extensions = new Object[2];
// extensions[0] = new LocalBusModule();
// extensions[1] = new UiModule();
// return extensions;
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/contacts/list/ui/activities/ContactListActivity.java
// public class ContactListActivity extends BaseActivity {
//
// @Inject
// ContactListView view;
// @Inject
// ContactListPresenter presenter;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.screen_contacts);
// }
//
// @Override
// protected Object[] getExtensions(ObjectGraph originalGraph, Bundle arguments) {
// final Object[] extensions = new Object[2];
// extensions[0] = new LocalBusModule();
// extensions[1] = new UiModule();
// return extensions;
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// view.bind(getWindow().findViewById(android.R.id.content));
// presenter.bind(view);
// }
//
// @Override
// protected void onDestroy() {
// super.onDestroy();
// presenter.release();
// }
// }
| import com.sefford.brender.interfaces.Postable;
import com.sefford.material.sample.common.internal.Bus;
import com.sefford.material.sample.contacts.details.ui.activities.ContactDetailsActivity;
import com.sefford.material.sample.contacts.list.ui.activities.ContactListActivity;
import dagger.Module;
import dagger.Provides;
import javax.inject.Named;
import javax.inject.Singleton; | /*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.common.injection.modules;
/**
* Handles the local, independent bus per screen that communicates the business logic components and its views and
* presenters
*/
@Module(injects = {ContactListActivity.class,
ContactDetailsActivity.class},
library = true,
complete = false)
public class LocalBusModule {
public static final String LOCAL_BUS = "Local";
@Singleton
@Provides
@Named(LOCAL_BUS) | // Path: app/src/main/java/com/sefford/material/sample/common/internal/Bus.java
// public class Bus implements Postable, com.sefford.brender.interfaces.Postable {
//
// final EventBus bus;
//
// @Inject
// public Bus(EventBus bus) {
// this.bus = bus;
// }
//
// public void register(Object target) {
// if (!bus.isRegistered(target)) {
// bus.register(target);
// }
// }
//
// public void unregister(Object target) {
// if (bus.isRegistered(target)) {
// bus.unregister(target);
// }
// }
//
// @Override
// public void post(Object message) {
// bus.post(message);
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/contacts/details/ui/activities/ContactDetailsActivity.java
// public class ContactDetailsActivity extends BaseActivity {
//
// public static final String EXTRA_ID = "extra_id";
// public static final String EXTRA_NAME = "extra_name";
// public static final String EXTRA_COLOR = "extra_color";
//
// @Inject
// ContactDetailView view;
// @Inject
// ContactDetailPresenter presenter;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.screen_detail);
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// view.configurePlaceholder(getIntent().getStringExtra(EXTRA_NAME), getIntent().getStringExtra(EXTRA_COLOR));
// view.bind(getWindow().findViewById(android.R.id.content));
// presenter.setId(getIntent().getLongExtra(EXTRA_ID, 0));
// presenter.bind(view);
// }
//
//
// @Override
// protected void onDestroy() {
// super.onDestroy();
// presenter.release();
// }
//
// @Override
// protected Object[] getExtensions(ObjectGraph originalGraph, Bundle arguments) {
// final Object[] extensions = new Object[2];
// extensions[0] = new LocalBusModule();
// extensions[1] = new UiModule();
// return extensions;
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/contacts/list/ui/activities/ContactListActivity.java
// public class ContactListActivity extends BaseActivity {
//
// @Inject
// ContactListView view;
// @Inject
// ContactListPresenter presenter;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.screen_contacts);
// }
//
// @Override
// protected Object[] getExtensions(ObjectGraph originalGraph, Bundle arguments) {
// final Object[] extensions = new Object[2];
// extensions[0] = new LocalBusModule();
// extensions[1] = new UiModule();
// return extensions;
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// view.bind(getWindow().findViewById(android.R.id.content));
// presenter.bind(view);
// }
//
// @Override
// protected void onDestroy() {
// super.onDestroy();
// presenter.release();
// }
// }
// Path: app/src/main/java/com/sefford/material/sample/common/injection/modules/LocalBusModule.java
import com.sefford.brender.interfaces.Postable;
import com.sefford.material.sample.common.internal.Bus;
import com.sefford.material.sample.contacts.details.ui.activities.ContactDetailsActivity;
import com.sefford.material.sample.contacts.list.ui.activities.ContactListActivity;
import dagger.Module;
import dagger.Provides;
import javax.inject.Named;
import javax.inject.Singleton;
/*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.common.injection.modules;
/**
* Handles the local, independent bus per screen that communicates the business logic components and its views and
* presenters
*/
@Module(injects = {ContactListActivity.class,
ContactDetailsActivity.class},
library = true,
complete = false)
public class LocalBusModule {
public static final String LOCAL_BUS = "Local";
@Singleton
@Provides
@Named(LOCAL_BUS) | public Bus provideLocalBus(Bus bus) { |
Sefford/material-in-30-minutes | app/src/main/java/com/sefford/material/sample/contacts/details/interactors/GetContact.java | // Path: app/src/main/java/com/sefford/material/sample/common/model/Contact.java
// public class Contact implements Comparable<Contact>, Renderable, RepoElement<Long>, Updateable<Contact> {
//
// long id;
// Uri thumb;
// Uri photo;
// String name;
// List<String> phones = new ArrayList<String>();
// List<String> emails = new ArrayList<String>();
// LayoutMode mode = LayoutMode.LIST;
//
// @Override
// public Long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// final Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
// thumb = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
// photo = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<String> getPhones() {
// return phones;
// }
//
// public void setPhones(List<String> phones) {
// this.phones = phones;
// }
//
// public void addPhone(String phone) {
// this.phones.add(phone);
// }
//
// public List<String> getEmails() {
// return emails;
// }
//
// public void setEmails(List<String> emails) {
// this.emails = emails;
// }
//
// public void addEmail(String email) {
// this.emails.add(email);
// }
//
// public Uri getThumbnail() {
// return thumb;
// }
//
// public Uri getPhoto() {
// return photo;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Contact contact = (Contact) o;
//
// if (id != contact.id) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return (int) (id ^ (id >>> 32));
// }
//
// @Override
// public int compareTo(Contact another) {
// return name.compareTo(another.name);
// }
//
// @Override
// public int getRenderableId() {
// if (LayoutMode.LIST.equals(mode)) {
// return R.layout.listitem_contact;
// } else {
// return R.layout.griditem_contact;
// }
// }
//
// @Override
// public Contact update(Contact other) {
// return this;
// }
//
// public void setLayoutMode(LayoutMode layoutMode) {
// this.mode = layoutMode;
// }
//
// public enum LayoutMode {
// LIST,
// GRID,
// STAGGER
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/contacts/details/delegates/GetContactDelegate.java
// public class GetContactDelegate implements CacheDelegate<GetContactResponse, GetContactError> {
//
// static final String NAME = "GetContact(%d)";
//
// final Repository<Long, Contact> repository;
// final long id;
//
// public GetContactDelegate(Repository<Long, Contact> repository, long id) {
// this.repository = repository;
// this.id = id;
// }
//
// @Override
// public boolean isCacheValid() {
// return true;
// }
//
// @Override
// public GetContactResponse execute() throws Exception {
// final Contact contact = repository.get(id);
// final ContactData phones = new ContactData(contact.getPhones(), R.drawable.ic_phone_black, R.layout.listitem_phone);
// final ContactData mails = new ContactData(contact.getEmails(), R.drawable.ic_email_black, R.layout.listitem_mail);
// return new GetContactResponse(contact, phones, mails);
// }
//
// @Override
// public GetContactError composeErrorResponse(Exception error) {
// return new GetContactError();
// }
//
// @Override
// public String getInteractorName() {
// return String.format(NAME, id);
// }
// }
| import com.sefford.kor.common.interfaces.Loggable;
import com.sefford.kor.common.interfaces.Postable;
import com.sefford.kor.interactors.CacheInteractor;
import com.sefford.kor.interactors.Interactor;
import com.sefford.kor.interactors.StandaloneInteractor;
import com.sefford.kor.repositories.interfaces.Repository;
import com.sefford.material.sample.common.model.Contact;
import com.sefford.material.sample.contacts.details.delegates.GetContactDelegate;
import javax.inject.Inject;
import java.util.concurrent.ThreadPoolExecutor; | /*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.contacts.details.interactors;
/**
* Retrieves a a {@link Contact Contact}.
*/
public class GetContact extends StandaloneInteractor<Long> {
final Repository<Long, Contact> repository;
/**
* Creates a new instance of the Standalone Interactor.
*
* @param log Logging facilities
* @param executor Execution element
* @param repository
*/
@Inject
public GetContact(Loggable log, ThreadPoolExecutor executor, Repository<Long, Contact> repository) {
super(log, executor);
this.repository = repository;
}
@Override
protected Interactor instantiateInteractor(Postable bus, Long id) { | // Path: app/src/main/java/com/sefford/material/sample/common/model/Contact.java
// public class Contact implements Comparable<Contact>, Renderable, RepoElement<Long>, Updateable<Contact> {
//
// long id;
// Uri thumb;
// Uri photo;
// String name;
// List<String> phones = new ArrayList<String>();
// List<String> emails = new ArrayList<String>();
// LayoutMode mode = LayoutMode.LIST;
//
// @Override
// public Long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// final Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
// thumb = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
// photo = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<String> getPhones() {
// return phones;
// }
//
// public void setPhones(List<String> phones) {
// this.phones = phones;
// }
//
// public void addPhone(String phone) {
// this.phones.add(phone);
// }
//
// public List<String> getEmails() {
// return emails;
// }
//
// public void setEmails(List<String> emails) {
// this.emails = emails;
// }
//
// public void addEmail(String email) {
// this.emails.add(email);
// }
//
// public Uri getThumbnail() {
// return thumb;
// }
//
// public Uri getPhoto() {
// return photo;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Contact contact = (Contact) o;
//
// if (id != contact.id) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return (int) (id ^ (id >>> 32));
// }
//
// @Override
// public int compareTo(Contact another) {
// return name.compareTo(another.name);
// }
//
// @Override
// public int getRenderableId() {
// if (LayoutMode.LIST.equals(mode)) {
// return R.layout.listitem_contact;
// } else {
// return R.layout.griditem_contact;
// }
// }
//
// @Override
// public Contact update(Contact other) {
// return this;
// }
//
// public void setLayoutMode(LayoutMode layoutMode) {
// this.mode = layoutMode;
// }
//
// public enum LayoutMode {
// LIST,
// GRID,
// STAGGER
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/contacts/details/delegates/GetContactDelegate.java
// public class GetContactDelegate implements CacheDelegate<GetContactResponse, GetContactError> {
//
// static final String NAME = "GetContact(%d)";
//
// final Repository<Long, Contact> repository;
// final long id;
//
// public GetContactDelegate(Repository<Long, Contact> repository, long id) {
// this.repository = repository;
// this.id = id;
// }
//
// @Override
// public boolean isCacheValid() {
// return true;
// }
//
// @Override
// public GetContactResponse execute() throws Exception {
// final Contact contact = repository.get(id);
// final ContactData phones = new ContactData(contact.getPhones(), R.drawable.ic_phone_black, R.layout.listitem_phone);
// final ContactData mails = new ContactData(contact.getEmails(), R.drawable.ic_email_black, R.layout.listitem_mail);
// return new GetContactResponse(contact, phones, mails);
// }
//
// @Override
// public GetContactError composeErrorResponse(Exception error) {
// return new GetContactError();
// }
//
// @Override
// public String getInteractorName() {
// return String.format(NAME, id);
// }
// }
// Path: app/src/main/java/com/sefford/material/sample/contacts/details/interactors/GetContact.java
import com.sefford.kor.common.interfaces.Loggable;
import com.sefford.kor.common.interfaces.Postable;
import com.sefford.kor.interactors.CacheInteractor;
import com.sefford.kor.interactors.Interactor;
import com.sefford.kor.interactors.StandaloneInteractor;
import com.sefford.kor.repositories.interfaces.Repository;
import com.sefford.material.sample.common.model.Contact;
import com.sefford.material.sample.contacts.details.delegates.GetContactDelegate;
import javax.inject.Inject;
import java.util.concurrent.ThreadPoolExecutor;
/*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.contacts.details.interactors;
/**
* Retrieves a a {@link Contact Contact}.
*/
public class GetContact extends StandaloneInteractor<Long> {
final Repository<Long, Contact> repository;
/**
* Creates a new instance of the Standalone Interactor.
*
* @param log Logging facilities
* @param executor Execution element
* @param repository
*/
@Inject
public GetContact(Loggable log, ThreadPoolExecutor executor, Repository<Long, Contact> repository) {
super(log, executor);
this.repository = repository;
}
@Override
protected Interactor instantiateInteractor(Postable bus, Long id) { | return new CacheInteractor(bus, log, new GetContactDelegate(repository, id)); |
Sefford/material-in-30-minutes | app/src/main/java/com/sefford/material/sample/common/ui/application/MaterialApplication.java | // Path: app/src/main/java/com/sefford/material/sample/common/injection/modules/ApplicationModule.java
// @Module(
// includes = {
// CoreModule.class,
// DevelopmentLoggingModule.class,
// },
// injects = {
// // Application
// MaterialApplication.class,
// // Activities
// BaseActivity.class,
// },
// complete = true,
// library = true
// )
// public class ApplicationModule {
//
// public static final String APPLICATION = "app";
//
// final Context context;
//
// public ApplicationModule(Context context) {
// this.context = context;
// }
//
// @Provides
// @Named(APPLICATION)
// public Context provideApplicationContext() {
// return context;
// }
//
// }
//
// Path: app/src/main/java/com/sefford/material/sample/common/injection/modules/DevelopmentLoggingModule.java
// @Module(library = true,
// complete = true)
// public class DevelopmentLoggingModule {
//
// @Provides
// @Singleton
// public Logger provideLogger(DevelopmentLogger logger) {
// return logger;
// }
//
// @Provides
// @Singleton
// public Loggable provideLog(Logger log) {
// return log;
// }
// }
| import android.app.Application;
import com.sefford.material.sample.common.injection.modules.ApplicationModule;
import com.sefford.material.sample.common.injection.modules.DevelopmentLoggingModule;
import dagger.ObjectGraph; | /*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.common.ui.application;
/**
* MaterialApplication application with the initialization of app-wide injection modules.
*/
public class MaterialApplication extends Application {
/**
* Object Injection Graph for development/production.
* <p/>
* We don't care this is static as the Application will live as long as the execution.
*/
ObjectGraph objectGraph;
@Override
public void onCreate() {
super.onCreate();
// Initialize Dagger's Dependency injection object Graph
objectGraph = initializeGraph();
objectGraph.inject(this);
}
ObjectGraph initializeGraph() { | // Path: app/src/main/java/com/sefford/material/sample/common/injection/modules/ApplicationModule.java
// @Module(
// includes = {
// CoreModule.class,
// DevelopmentLoggingModule.class,
// },
// injects = {
// // Application
// MaterialApplication.class,
// // Activities
// BaseActivity.class,
// },
// complete = true,
// library = true
// )
// public class ApplicationModule {
//
// public static final String APPLICATION = "app";
//
// final Context context;
//
// public ApplicationModule(Context context) {
// this.context = context;
// }
//
// @Provides
// @Named(APPLICATION)
// public Context provideApplicationContext() {
// return context;
// }
//
// }
//
// Path: app/src/main/java/com/sefford/material/sample/common/injection/modules/DevelopmentLoggingModule.java
// @Module(library = true,
// complete = true)
// public class DevelopmentLoggingModule {
//
// @Provides
// @Singleton
// public Logger provideLogger(DevelopmentLogger logger) {
// return logger;
// }
//
// @Provides
// @Singleton
// public Loggable provideLog(Logger log) {
// return log;
// }
// }
// Path: app/src/main/java/com/sefford/material/sample/common/ui/application/MaterialApplication.java
import android.app.Application;
import com.sefford.material.sample.common.injection.modules.ApplicationModule;
import com.sefford.material.sample.common.injection.modules.DevelopmentLoggingModule;
import dagger.ObjectGraph;
/*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.common.ui.application;
/**
* MaterialApplication application with the initialization of app-wide injection modules.
*/
public class MaterialApplication extends Application {
/**
* Object Injection Graph for development/production.
* <p/>
* We don't care this is static as the Application will live as long as the execution.
*/
ObjectGraph objectGraph;
@Override
public void onCreate() {
super.onCreate();
// Initialize Dagger's Dependency injection object Graph
objectGraph = initializeGraph();
objectGraph.inject(this);
}
ObjectGraph initializeGraph() { | return ObjectGraph.create(new ApplicationModule(this), |
Sefford/material-in-30-minutes | app/src/main/java/com/sefford/material/sample/common/ui/application/MaterialApplication.java | // Path: app/src/main/java/com/sefford/material/sample/common/injection/modules/ApplicationModule.java
// @Module(
// includes = {
// CoreModule.class,
// DevelopmentLoggingModule.class,
// },
// injects = {
// // Application
// MaterialApplication.class,
// // Activities
// BaseActivity.class,
// },
// complete = true,
// library = true
// )
// public class ApplicationModule {
//
// public static final String APPLICATION = "app";
//
// final Context context;
//
// public ApplicationModule(Context context) {
// this.context = context;
// }
//
// @Provides
// @Named(APPLICATION)
// public Context provideApplicationContext() {
// return context;
// }
//
// }
//
// Path: app/src/main/java/com/sefford/material/sample/common/injection/modules/DevelopmentLoggingModule.java
// @Module(library = true,
// complete = true)
// public class DevelopmentLoggingModule {
//
// @Provides
// @Singleton
// public Logger provideLogger(DevelopmentLogger logger) {
// return logger;
// }
//
// @Provides
// @Singleton
// public Loggable provideLog(Logger log) {
// return log;
// }
// }
| import android.app.Application;
import com.sefford.material.sample.common.injection.modules.ApplicationModule;
import com.sefford.material.sample.common.injection.modules.DevelopmentLoggingModule;
import dagger.ObjectGraph; | /*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.common.ui.application;
/**
* MaterialApplication application with the initialization of app-wide injection modules.
*/
public class MaterialApplication extends Application {
/**
* Object Injection Graph for development/production.
* <p/>
* We don't care this is static as the Application will live as long as the execution.
*/
ObjectGraph objectGraph;
@Override
public void onCreate() {
super.onCreate();
// Initialize Dagger's Dependency injection object Graph
objectGraph = initializeGraph();
objectGraph.inject(this);
}
ObjectGraph initializeGraph() {
return ObjectGraph.create(new ApplicationModule(this), | // Path: app/src/main/java/com/sefford/material/sample/common/injection/modules/ApplicationModule.java
// @Module(
// includes = {
// CoreModule.class,
// DevelopmentLoggingModule.class,
// },
// injects = {
// // Application
// MaterialApplication.class,
// // Activities
// BaseActivity.class,
// },
// complete = true,
// library = true
// )
// public class ApplicationModule {
//
// public static final String APPLICATION = "app";
//
// final Context context;
//
// public ApplicationModule(Context context) {
// this.context = context;
// }
//
// @Provides
// @Named(APPLICATION)
// public Context provideApplicationContext() {
// return context;
// }
//
// }
//
// Path: app/src/main/java/com/sefford/material/sample/common/injection/modules/DevelopmentLoggingModule.java
// @Module(library = true,
// complete = true)
// public class DevelopmentLoggingModule {
//
// @Provides
// @Singleton
// public Logger provideLogger(DevelopmentLogger logger) {
// return logger;
// }
//
// @Provides
// @Singleton
// public Loggable provideLog(Logger log) {
// return log;
// }
// }
// Path: app/src/main/java/com/sefford/material/sample/common/ui/application/MaterialApplication.java
import android.app.Application;
import com.sefford.material.sample.common.injection.modules.ApplicationModule;
import com.sefford.material.sample.common.injection.modules.DevelopmentLoggingModule;
import dagger.ObjectGraph;
/*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.common.ui.application;
/**
* MaterialApplication application with the initialization of app-wide injection modules.
*/
public class MaterialApplication extends Application {
/**
* Object Injection Graph for development/production.
* <p/>
* We don't care this is static as the Application will live as long as the execution.
*/
ObjectGraph objectGraph;
@Override
public void onCreate() {
super.onCreate();
// Initialize Dagger's Dependency injection object Graph
objectGraph = initializeGraph();
objectGraph.inject(this);
}
ObjectGraph initializeGraph() {
return ObjectGraph.create(new ApplicationModule(this), | new DevelopmentLoggingModule()); |
Sefford/material-in-30-minutes | app/src/main/java/com/sefford/material/sample/contacts/list/delegates/GetPhoneContactsDelegate.java | // Path: app/src/main/java/com/sefford/material/sample/contacts/list/errors/GetPhoneContactsError.java
// public class GetPhoneContactsError implements com.sefford.kor.errors.Error {
//
// public GetPhoneContactsError() {
// }
//
// @Override
// public int getStatusCode() {
// return 0;
// }
//
// @Override
// public String getUserError() {
// return null;
// }
//
// @Override
// public String getMessage() {
// return null;
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/common/model/Contact.java
// public class Contact implements Comparable<Contact>, Renderable, RepoElement<Long>, Updateable<Contact> {
//
// long id;
// Uri thumb;
// Uri photo;
// String name;
// List<String> phones = new ArrayList<String>();
// List<String> emails = new ArrayList<String>();
// LayoutMode mode = LayoutMode.LIST;
//
// @Override
// public Long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// final Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
// thumb = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
// photo = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<String> getPhones() {
// return phones;
// }
//
// public void setPhones(List<String> phones) {
// this.phones = phones;
// }
//
// public void addPhone(String phone) {
// this.phones.add(phone);
// }
//
// public List<String> getEmails() {
// return emails;
// }
//
// public void setEmails(List<String> emails) {
// this.emails = emails;
// }
//
// public void addEmail(String email) {
// this.emails.add(email);
// }
//
// public Uri getThumbnail() {
// return thumb;
// }
//
// public Uri getPhoto() {
// return photo;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Contact contact = (Contact) o;
//
// if (id != contact.id) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return (int) (id ^ (id >>> 32));
// }
//
// @Override
// public int compareTo(Contact another) {
// return name.compareTo(another.name);
// }
//
// @Override
// public int getRenderableId() {
// if (LayoutMode.LIST.equals(mode)) {
// return R.layout.listitem_contact;
// } else {
// return R.layout.griditem_contact;
// }
// }
//
// @Override
// public Contact update(Contact other) {
// return this;
// }
//
// public void setLayoutMode(LayoutMode layoutMode) {
// this.mode = layoutMode;
// }
//
// public enum LayoutMode {
// LIST,
// GRID,
// STAGGER
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/contacts/list/responses/GetPhoneContactsResponse.java
// public class GetPhoneContactsResponse implements Response {
//
// final Collection<Contact> contacts;
//
// public GetPhoneContactsResponse(Collection<Contact> contacts) {
// this.contacts = contacts;
// }
//
// public Collection<Contact> getContacts() {
// return contacts;
// }
//
// @Override
// public boolean isSuccess() {
// return true;
// }
//
// @Override
// public boolean isFromNetwork() {
// return false;
// }
// }
| import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import com.sefford.kor.interactors.interfaces.CacheDelegate;
import com.sefford.kor.repositories.interfaces.Repository;
import com.sefford.material.sample.contacts.list.errors.GetPhoneContactsError;
import com.sefford.material.sample.common.model.Contact;
import com.sefford.material.sample.contacts.list.responses.GetPhoneContactsResponse;
import java.util.*; | /*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.contacts.list.delegates;
/**
* Retrieves the Contacts from the Phone provider and returns it on a {@link Contact Contact} form.
*
* Probably not the most elegant algorithm out there, basically queries all the phones and mails from the provider and
* merges them into a single Contact.
*/
public class GetPhoneContactsDelegate implements CacheDelegate<GetPhoneContactsResponse, GetPhoneContactsError> {
final Context context; | // Path: app/src/main/java/com/sefford/material/sample/contacts/list/errors/GetPhoneContactsError.java
// public class GetPhoneContactsError implements com.sefford.kor.errors.Error {
//
// public GetPhoneContactsError() {
// }
//
// @Override
// public int getStatusCode() {
// return 0;
// }
//
// @Override
// public String getUserError() {
// return null;
// }
//
// @Override
// public String getMessage() {
// return null;
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/common/model/Contact.java
// public class Contact implements Comparable<Contact>, Renderable, RepoElement<Long>, Updateable<Contact> {
//
// long id;
// Uri thumb;
// Uri photo;
// String name;
// List<String> phones = new ArrayList<String>();
// List<String> emails = new ArrayList<String>();
// LayoutMode mode = LayoutMode.LIST;
//
// @Override
// public Long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// final Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
// thumb = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
// photo = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<String> getPhones() {
// return phones;
// }
//
// public void setPhones(List<String> phones) {
// this.phones = phones;
// }
//
// public void addPhone(String phone) {
// this.phones.add(phone);
// }
//
// public List<String> getEmails() {
// return emails;
// }
//
// public void setEmails(List<String> emails) {
// this.emails = emails;
// }
//
// public void addEmail(String email) {
// this.emails.add(email);
// }
//
// public Uri getThumbnail() {
// return thumb;
// }
//
// public Uri getPhoto() {
// return photo;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Contact contact = (Contact) o;
//
// if (id != contact.id) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return (int) (id ^ (id >>> 32));
// }
//
// @Override
// public int compareTo(Contact another) {
// return name.compareTo(another.name);
// }
//
// @Override
// public int getRenderableId() {
// if (LayoutMode.LIST.equals(mode)) {
// return R.layout.listitem_contact;
// } else {
// return R.layout.griditem_contact;
// }
// }
//
// @Override
// public Contact update(Contact other) {
// return this;
// }
//
// public void setLayoutMode(LayoutMode layoutMode) {
// this.mode = layoutMode;
// }
//
// public enum LayoutMode {
// LIST,
// GRID,
// STAGGER
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/contacts/list/responses/GetPhoneContactsResponse.java
// public class GetPhoneContactsResponse implements Response {
//
// final Collection<Contact> contacts;
//
// public GetPhoneContactsResponse(Collection<Contact> contacts) {
// this.contacts = contacts;
// }
//
// public Collection<Contact> getContacts() {
// return contacts;
// }
//
// @Override
// public boolean isSuccess() {
// return true;
// }
//
// @Override
// public boolean isFromNetwork() {
// return false;
// }
// }
// Path: app/src/main/java/com/sefford/material/sample/contacts/list/delegates/GetPhoneContactsDelegate.java
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import com.sefford.kor.interactors.interfaces.CacheDelegate;
import com.sefford.kor.repositories.interfaces.Repository;
import com.sefford.material.sample.contacts.list.errors.GetPhoneContactsError;
import com.sefford.material.sample.common.model.Contact;
import com.sefford.material.sample.contacts.list.responses.GetPhoneContactsResponse;
import java.util.*;
/*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.contacts.list.delegates;
/**
* Retrieves the Contacts from the Phone provider and returns it on a {@link Contact Contact} form.
*
* Probably not the most elegant algorithm out there, basically queries all the phones and mails from the provider and
* merges them into a single Contact.
*/
public class GetPhoneContactsDelegate implements CacheDelegate<GetPhoneContactsResponse, GetPhoneContactsError> {
final Context context; | final Repository<Long, Contact> cache; |
Sefford/material-in-30-minutes | app/src/main/java/com/sefford/material/sample/common/ui/activities/BaseActivity.java | // Path: app/src/main/java/com/sefford/material/sample/common/ui/application/MaterialApplication.java
// public class MaterialApplication extends Application {
//
//
// /**
// * Object Injection Graph for development/production.
// * <p/>
// * We don't care this is static as the Application will live as long as the execution.
// */
// ObjectGraph objectGraph;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// // Initialize Dagger's Dependency injection object Graph
// objectGraph = initializeGraph();
// objectGraph.inject(this);
// }
//
// ObjectGraph initializeGraph() {
// return ObjectGraph.create(new ApplicationModule(this),
// new DevelopmentLoggingModule());
// }
//
// /**
// * Injection facility for the elements.
// *
// * @param instance Instance of the object to inject dependencies
// * @param <T> Class that will be injected
// */
// public <T> void inject(T instance) {
// objectGraph.inject(instance);
// }
//
// /**
// * Provider facility for the elements.
// *
// * @param type Type of the instance to get
// * @param <T> Class that will be injected
// */
// public <T> T get(Class<T> type) {
// return objectGraph.get(type);
// }
//
// public ObjectGraph getGraph() {
// return objectGraph;
// }
// }
| import android.app.Activity;
import android.os.Bundle;
import com.sefford.material.sample.common.ui.application.MaterialApplication;
import dagger.ObjectGraph; | /*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.common.ui.activities;
/**
* Base activity with injection facilities
*/
public abstract class BaseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | // Path: app/src/main/java/com/sefford/material/sample/common/ui/application/MaterialApplication.java
// public class MaterialApplication extends Application {
//
//
// /**
// * Object Injection Graph for development/production.
// * <p/>
// * We don't care this is static as the Application will live as long as the execution.
// */
// ObjectGraph objectGraph;
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// // Initialize Dagger's Dependency injection object Graph
// objectGraph = initializeGraph();
// objectGraph.inject(this);
// }
//
// ObjectGraph initializeGraph() {
// return ObjectGraph.create(new ApplicationModule(this),
// new DevelopmentLoggingModule());
// }
//
// /**
// * Injection facility for the elements.
// *
// * @param instance Instance of the object to inject dependencies
// * @param <T> Class that will be injected
// */
// public <T> void inject(T instance) {
// objectGraph.inject(instance);
// }
//
// /**
// * Provider facility for the elements.
// *
// * @param type Type of the instance to get
// * @param <T> Class that will be injected
// */
// public <T> T get(Class<T> type) {
// return objectGraph.get(type);
// }
//
// public ObjectGraph getGraph() {
// return objectGraph;
// }
// }
// Path: app/src/main/java/com/sefford/material/sample/common/ui/activities/BaseActivity.java
import android.app.Activity;
import android.os.Bundle;
import com.sefford.material.sample.common.ui.application.MaterialApplication;
import dagger.ObjectGraph;
/*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.common.ui.activities;
/**
* Base activity with injection facilities
*/
public abstract class BaseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | final ObjectGraph originalGraph = ((MaterialApplication) getApplication()).getGraph(); |
Sefford/material-in-30-minutes | app/src/main/java/com/sefford/material/sample/contacts/details/responses/GetContactResponse.java | // Path: app/src/main/java/com/sefford/material/sample/common/model/Contact.java
// public class Contact implements Comparable<Contact>, Renderable, RepoElement<Long>, Updateable<Contact> {
//
// long id;
// Uri thumb;
// Uri photo;
// String name;
// List<String> phones = new ArrayList<String>();
// List<String> emails = new ArrayList<String>();
// LayoutMode mode = LayoutMode.LIST;
//
// @Override
// public Long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// final Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
// thumb = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
// photo = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<String> getPhones() {
// return phones;
// }
//
// public void setPhones(List<String> phones) {
// this.phones = phones;
// }
//
// public void addPhone(String phone) {
// this.phones.add(phone);
// }
//
// public List<String> getEmails() {
// return emails;
// }
//
// public void setEmails(List<String> emails) {
// this.emails = emails;
// }
//
// public void addEmail(String email) {
// this.emails.add(email);
// }
//
// public Uri getThumbnail() {
// return thumb;
// }
//
// public Uri getPhoto() {
// return photo;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Contact contact = (Contact) o;
//
// if (id != contact.id) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return (int) (id ^ (id >>> 32));
// }
//
// @Override
// public int compareTo(Contact another) {
// return name.compareTo(another.name);
// }
//
// @Override
// public int getRenderableId() {
// if (LayoutMode.LIST.equals(mode)) {
// return R.layout.listitem_contact;
// } else {
// return R.layout.griditem_contact;
// }
// }
//
// @Override
// public Contact update(Contact other) {
// return this;
// }
//
// public void setLayoutMode(LayoutMode layoutMode) {
// this.mode = layoutMode;
// }
//
// public enum LayoutMode {
// LIST,
// GRID,
// STAGGER
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/contacts/details/ui/model/ContactData.java
// public class ContactData implements Renderable {
//
// final List<String> elements;
// final int resource;
// final int renderableId;
//
// public ContactData(List<String> elements, int resource, int renderableId) {
// this.elements = elements;
// this.resource = resource;
// this.renderableId = renderableId;
// }
//
// public List<String> getElements() {
// return elements;
// }
//
// public int getResource() {
// return resource;
// }
//
//
// @Override
// public int getRenderableId() {
// return renderableId;
// }
// }
| import com.sefford.kor.responses.Response;
import com.sefford.material.sample.common.model.Contact;
import com.sefford.material.sample.contacts.details.ui.model.ContactData; | /*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.contacts.details.responses;
/**
* Contact Response with the information to populate the UI.
*/
public class GetContactResponse implements Response {
final Contact contact; | // Path: app/src/main/java/com/sefford/material/sample/common/model/Contact.java
// public class Contact implements Comparable<Contact>, Renderable, RepoElement<Long>, Updateable<Contact> {
//
// long id;
// Uri thumb;
// Uri photo;
// String name;
// List<String> phones = new ArrayList<String>();
// List<String> emails = new ArrayList<String>();
// LayoutMode mode = LayoutMode.LIST;
//
// @Override
// public Long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// final Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
// thumb = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
// photo = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<String> getPhones() {
// return phones;
// }
//
// public void setPhones(List<String> phones) {
// this.phones = phones;
// }
//
// public void addPhone(String phone) {
// this.phones.add(phone);
// }
//
// public List<String> getEmails() {
// return emails;
// }
//
// public void setEmails(List<String> emails) {
// this.emails = emails;
// }
//
// public void addEmail(String email) {
// this.emails.add(email);
// }
//
// public Uri getThumbnail() {
// return thumb;
// }
//
// public Uri getPhoto() {
// return photo;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Contact contact = (Contact) o;
//
// if (id != contact.id) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return (int) (id ^ (id >>> 32));
// }
//
// @Override
// public int compareTo(Contact another) {
// return name.compareTo(another.name);
// }
//
// @Override
// public int getRenderableId() {
// if (LayoutMode.LIST.equals(mode)) {
// return R.layout.listitem_contact;
// } else {
// return R.layout.griditem_contact;
// }
// }
//
// @Override
// public Contact update(Contact other) {
// return this;
// }
//
// public void setLayoutMode(LayoutMode layoutMode) {
// this.mode = layoutMode;
// }
//
// public enum LayoutMode {
// LIST,
// GRID,
// STAGGER
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/contacts/details/ui/model/ContactData.java
// public class ContactData implements Renderable {
//
// final List<String> elements;
// final int resource;
// final int renderableId;
//
// public ContactData(List<String> elements, int resource, int renderableId) {
// this.elements = elements;
// this.resource = resource;
// this.renderableId = renderableId;
// }
//
// public List<String> getElements() {
// return elements;
// }
//
// public int getResource() {
// return resource;
// }
//
//
// @Override
// public int getRenderableId() {
// return renderableId;
// }
// }
// Path: app/src/main/java/com/sefford/material/sample/contacts/details/responses/GetContactResponse.java
import com.sefford.kor.responses.Response;
import com.sefford.material.sample.common.model.Contact;
import com.sefford.material.sample.contacts.details.ui.model.ContactData;
/*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.contacts.details.responses;
/**
* Contact Response with the information to populate the UI.
*/
public class GetContactResponse implements Response {
final Contact contact; | final ContactData phones; |
Sefford/material-in-30-minutes | app/src/main/java/com/sefford/material/sample/common/injection/modules/CoreModule.java | // Path: app/src/main/java/com/sefford/material/sample/common/internal/Bus.java
// public class Bus implements Postable, com.sefford.brender.interfaces.Postable {
//
// final EventBus bus;
//
// @Inject
// public Bus(EventBus bus) {
// this.bus = bus;
// }
//
// public void register(Object target) {
// if (!bus.isRegistered(target)) {
// bus.register(target);
// }
// }
//
// public void unregister(Object target) {
// if (bus.isRegistered(target)) {
// bus.unregister(target);
// }
// }
//
// @Override
// public void post(Object message) {
// bus.post(message);
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/common/model/Contact.java
// public class Contact implements Comparable<Contact>, Renderable, RepoElement<Long>, Updateable<Contact> {
//
// long id;
// Uri thumb;
// Uri photo;
// String name;
// List<String> phones = new ArrayList<String>();
// List<String> emails = new ArrayList<String>();
// LayoutMode mode = LayoutMode.LIST;
//
// @Override
// public Long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// final Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
// thumb = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
// photo = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<String> getPhones() {
// return phones;
// }
//
// public void setPhones(List<String> phones) {
// this.phones = phones;
// }
//
// public void addPhone(String phone) {
// this.phones.add(phone);
// }
//
// public List<String> getEmails() {
// return emails;
// }
//
// public void setEmails(List<String> emails) {
// this.emails = emails;
// }
//
// public void addEmail(String email) {
// this.emails.add(email);
// }
//
// public Uri getThumbnail() {
// return thumb;
// }
//
// public Uri getPhoto() {
// return photo;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Contact contact = (Contact) o;
//
// if (id != contact.id) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return (int) (id ^ (id >>> 32));
// }
//
// @Override
// public int compareTo(Contact another) {
// return name.compareTo(another.name);
// }
//
// @Override
// public int getRenderableId() {
// if (LayoutMode.LIST.equals(mode)) {
// return R.layout.listitem_contact;
// } else {
// return R.layout.griditem_contact;
// }
// }
//
// @Override
// public Contact update(Contact other) {
// return this;
// }
//
// public void setLayoutMode(LayoutMode layoutMode) {
// this.mode = layoutMode;
// }
//
// public enum LayoutMode {
// LIST,
// GRID,
// STAGGER
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/common/repository/ContactRepository.java
// public class ContactRepository extends MemoryRepository<Long, Contact> {
// /**
// * Creates a new instance of Memory repository
// */
// public ContactRepository() {
// super(new HashMap<Long, Contact>());
// }
// }
| import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import android.content.Context;
import android.content.res.Resources;
import com.sefford.brender.interfaces.Postable;
import com.sefford.kor.repositories.interfaces.Repository;
import com.sefford.material.sample.BuildConfig;
import com.sefford.material.sample.common.internal.Bus;
import com.sefford.material.sample.common.model.Contact;
import com.sefford.material.sample.common.repository.ContactRepository;
import dagger.Module;
import dagger.Provides;
import de.greenrobot.event.EventBus;
import javax.inject.Named;
import javax.inject.Singleton; | return new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().availableProcessors() * 2,
120, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
}
@Provides
public EventBus provideEventBus() {
return EventBus.builder().throwSubscriberException(BuildConfig.DEBUG).build();
}
@Provides
public Resources provideResources(@Named(ApplicationModule.APPLICATION) Context context) {
return context.getResources();
}
@Provides
@Singleton
@Named(SYSTEM)
public Bus provideSystemBus(Bus bus) {
return bus;
}
@Provides
@Singleton
@Named(SYSTEM)
public Postable provideSystemPostable(@Named(SYSTEM) Bus bus) {
return bus;
}
@Provides
@Singleton | // Path: app/src/main/java/com/sefford/material/sample/common/internal/Bus.java
// public class Bus implements Postable, com.sefford.brender.interfaces.Postable {
//
// final EventBus bus;
//
// @Inject
// public Bus(EventBus bus) {
// this.bus = bus;
// }
//
// public void register(Object target) {
// if (!bus.isRegistered(target)) {
// bus.register(target);
// }
// }
//
// public void unregister(Object target) {
// if (bus.isRegistered(target)) {
// bus.unregister(target);
// }
// }
//
// @Override
// public void post(Object message) {
// bus.post(message);
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/common/model/Contact.java
// public class Contact implements Comparable<Contact>, Renderable, RepoElement<Long>, Updateable<Contact> {
//
// long id;
// Uri thumb;
// Uri photo;
// String name;
// List<String> phones = new ArrayList<String>();
// List<String> emails = new ArrayList<String>();
// LayoutMode mode = LayoutMode.LIST;
//
// @Override
// public Long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// final Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
// thumb = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
// photo = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<String> getPhones() {
// return phones;
// }
//
// public void setPhones(List<String> phones) {
// this.phones = phones;
// }
//
// public void addPhone(String phone) {
// this.phones.add(phone);
// }
//
// public List<String> getEmails() {
// return emails;
// }
//
// public void setEmails(List<String> emails) {
// this.emails = emails;
// }
//
// public void addEmail(String email) {
// this.emails.add(email);
// }
//
// public Uri getThumbnail() {
// return thumb;
// }
//
// public Uri getPhoto() {
// return photo;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Contact contact = (Contact) o;
//
// if (id != contact.id) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return (int) (id ^ (id >>> 32));
// }
//
// @Override
// public int compareTo(Contact another) {
// return name.compareTo(another.name);
// }
//
// @Override
// public int getRenderableId() {
// if (LayoutMode.LIST.equals(mode)) {
// return R.layout.listitem_contact;
// } else {
// return R.layout.griditem_contact;
// }
// }
//
// @Override
// public Contact update(Contact other) {
// return this;
// }
//
// public void setLayoutMode(LayoutMode layoutMode) {
// this.mode = layoutMode;
// }
//
// public enum LayoutMode {
// LIST,
// GRID,
// STAGGER
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/common/repository/ContactRepository.java
// public class ContactRepository extends MemoryRepository<Long, Contact> {
// /**
// * Creates a new instance of Memory repository
// */
// public ContactRepository() {
// super(new HashMap<Long, Contact>());
// }
// }
// Path: app/src/main/java/com/sefford/material/sample/common/injection/modules/CoreModule.java
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import android.content.Context;
import android.content.res.Resources;
import com.sefford.brender.interfaces.Postable;
import com.sefford.kor.repositories.interfaces.Repository;
import com.sefford.material.sample.BuildConfig;
import com.sefford.material.sample.common.internal.Bus;
import com.sefford.material.sample.common.model.Contact;
import com.sefford.material.sample.common.repository.ContactRepository;
import dagger.Module;
import dagger.Provides;
import de.greenrobot.event.EventBus;
import javax.inject.Named;
import javax.inject.Singleton;
return new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().availableProcessors() * 2,
120, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
}
@Provides
public EventBus provideEventBus() {
return EventBus.builder().throwSubscriberException(BuildConfig.DEBUG).build();
}
@Provides
public Resources provideResources(@Named(ApplicationModule.APPLICATION) Context context) {
return context.getResources();
}
@Provides
@Singleton
@Named(SYSTEM)
public Bus provideSystemBus(Bus bus) {
return bus;
}
@Provides
@Singleton
@Named(SYSTEM)
public Postable provideSystemPostable(@Named(SYSTEM) Bus bus) {
return bus;
}
@Provides
@Singleton | public Repository<Long, Contact> provideContactCache() { |
Sefford/material-in-30-minutes | app/src/main/java/com/sefford/material/sample/common/injection/modules/CoreModule.java | // Path: app/src/main/java/com/sefford/material/sample/common/internal/Bus.java
// public class Bus implements Postable, com.sefford.brender.interfaces.Postable {
//
// final EventBus bus;
//
// @Inject
// public Bus(EventBus bus) {
// this.bus = bus;
// }
//
// public void register(Object target) {
// if (!bus.isRegistered(target)) {
// bus.register(target);
// }
// }
//
// public void unregister(Object target) {
// if (bus.isRegistered(target)) {
// bus.unregister(target);
// }
// }
//
// @Override
// public void post(Object message) {
// bus.post(message);
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/common/model/Contact.java
// public class Contact implements Comparable<Contact>, Renderable, RepoElement<Long>, Updateable<Contact> {
//
// long id;
// Uri thumb;
// Uri photo;
// String name;
// List<String> phones = new ArrayList<String>();
// List<String> emails = new ArrayList<String>();
// LayoutMode mode = LayoutMode.LIST;
//
// @Override
// public Long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// final Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
// thumb = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
// photo = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<String> getPhones() {
// return phones;
// }
//
// public void setPhones(List<String> phones) {
// this.phones = phones;
// }
//
// public void addPhone(String phone) {
// this.phones.add(phone);
// }
//
// public List<String> getEmails() {
// return emails;
// }
//
// public void setEmails(List<String> emails) {
// this.emails = emails;
// }
//
// public void addEmail(String email) {
// this.emails.add(email);
// }
//
// public Uri getThumbnail() {
// return thumb;
// }
//
// public Uri getPhoto() {
// return photo;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Contact contact = (Contact) o;
//
// if (id != contact.id) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return (int) (id ^ (id >>> 32));
// }
//
// @Override
// public int compareTo(Contact another) {
// return name.compareTo(another.name);
// }
//
// @Override
// public int getRenderableId() {
// if (LayoutMode.LIST.equals(mode)) {
// return R.layout.listitem_contact;
// } else {
// return R.layout.griditem_contact;
// }
// }
//
// @Override
// public Contact update(Contact other) {
// return this;
// }
//
// public void setLayoutMode(LayoutMode layoutMode) {
// this.mode = layoutMode;
// }
//
// public enum LayoutMode {
// LIST,
// GRID,
// STAGGER
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/common/repository/ContactRepository.java
// public class ContactRepository extends MemoryRepository<Long, Contact> {
// /**
// * Creates a new instance of Memory repository
// */
// public ContactRepository() {
// super(new HashMap<Long, Contact>());
// }
// }
| import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import android.content.Context;
import android.content.res.Resources;
import com.sefford.brender.interfaces.Postable;
import com.sefford.kor.repositories.interfaces.Repository;
import com.sefford.material.sample.BuildConfig;
import com.sefford.material.sample.common.internal.Bus;
import com.sefford.material.sample.common.model.Contact;
import com.sefford.material.sample.common.repository.ContactRepository;
import dagger.Module;
import dagger.Provides;
import de.greenrobot.event.EventBus;
import javax.inject.Named;
import javax.inject.Singleton; | 120, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
}
@Provides
public EventBus provideEventBus() {
return EventBus.builder().throwSubscriberException(BuildConfig.DEBUG).build();
}
@Provides
public Resources provideResources(@Named(ApplicationModule.APPLICATION) Context context) {
return context.getResources();
}
@Provides
@Singleton
@Named(SYSTEM)
public Bus provideSystemBus(Bus bus) {
return bus;
}
@Provides
@Singleton
@Named(SYSTEM)
public Postable provideSystemPostable(@Named(SYSTEM) Bus bus) {
return bus;
}
@Provides
@Singleton
public Repository<Long, Contact> provideContactCache() { | // Path: app/src/main/java/com/sefford/material/sample/common/internal/Bus.java
// public class Bus implements Postable, com.sefford.brender.interfaces.Postable {
//
// final EventBus bus;
//
// @Inject
// public Bus(EventBus bus) {
// this.bus = bus;
// }
//
// public void register(Object target) {
// if (!bus.isRegistered(target)) {
// bus.register(target);
// }
// }
//
// public void unregister(Object target) {
// if (bus.isRegistered(target)) {
// bus.unregister(target);
// }
// }
//
// @Override
// public void post(Object message) {
// bus.post(message);
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/common/model/Contact.java
// public class Contact implements Comparable<Contact>, Renderable, RepoElement<Long>, Updateable<Contact> {
//
// long id;
// Uri thumb;
// Uri photo;
// String name;
// List<String> phones = new ArrayList<String>();
// List<String> emails = new ArrayList<String>();
// LayoutMode mode = LayoutMode.LIST;
//
// @Override
// public Long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// final Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
// thumb = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
// photo = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public List<String> getPhones() {
// return phones;
// }
//
// public void setPhones(List<String> phones) {
// this.phones = phones;
// }
//
// public void addPhone(String phone) {
// this.phones.add(phone);
// }
//
// public List<String> getEmails() {
// return emails;
// }
//
// public void setEmails(List<String> emails) {
// this.emails = emails;
// }
//
// public void addEmail(String email) {
// this.emails.add(email);
// }
//
// public Uri getThumbnail() {
// return thumb;
// }
//
// public Uri getPhoto() {
// return photo;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Contact contact = (Contact) o;
//
// if (id != contact.id) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return (int) (id ^ (id >>> 32));
// }
//
// @Override
// public int compareTo(Contact another) {
// return name.compareTo(another.name);
// }
//
// @Override
// public int getRenderableId() {
// if (LayoutMode.LIST.equals(mode)) {
// return R.layout.listitem_contact;
// } else {
// return R.layout.griditem_contact;
// }
// }
//
// @Override
// public Contact update(Contact other) {
// return this;
// }
//
// public void setLayoutMode(LayoutMode layoutMode) {
// this.mode = layoutMode;
// }
//
// public enum LayoutMode {
// LIST,
// GRID,
// STAGGER
// }
// }
//
// Path: app/src/main/java/com/sefford/material/sample/common/repository/ContactRepository.java
// public class ContactRepository extends MemoryRepository<Long, Contact> {
// /**
// * Creates a new instance of Memory repository
// */
// public ContactRepository() {
// super(new HashMap<Long, Contact>());
// }
// }
// Path: app/src/main/java/com/sefford/material/sample/common/injection/modules/CoreModule.java
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import android.content.Context;
import android.content.res.Resources;
import com.sefford.brender.interfaces.Postable;
import com.sefford.kor.repositories.interfaces.Repository;
import com.sefford.material.sample.BuildConfig;
import com.sefford.material.sample.common.internal.Bus;
import com.sefford.material.sample.common.model.Contact;
import com.sefford.material.sample.common.repository.ContactRepository;
import dagger.Module;
import dagger.Provides;
import de.greenrobot.event.EventBus;
import javax.inject.Named;
import javax.inject.Singleton;
120, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
}
@Provides
public EventBus provideEventBus() {
return EventBus.builder().throwSubscriberException(BuildConfig.DEBUG).build();
}
@Provides
public Resources provideResources(@Named(ApplicationModule.APPLICATION) Context context) {
return context.getResources();
}
@Provides
@Singleton
@Named(SYSTEM)
public Bus provideSystemBus(Bus bus) {
return bus;
}
@Provides
@Singleton
@Named(SYSTEM)
public Postable provideSystemPostable(@Named(SYSTEM) Bus bus) {
return bus;
}
@Provides
@Singleton
public Repository<Long, Contact> provideContactCache() { | return new ContactRepository(); |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/structview/STGroupRootTreeElement.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.ide.util.treeView.smartTree.TreeElement;
import com.intellij.navigation.ItemPresentation;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType; | package org.antlr.jetbrains.st4plugin.structview;
public class STGroupRootTreeElement extends STGroupStructureViewTreeElement {
public STGroupRootTreeElement(PsiFile psiFile) {
super(psiFile);
}
@NotNull
@Override
public ItemPresentation getPresentation() {
return new STGroupRootItemPresentation((PsiFile) psiElement);
}
@NotNull
@Override
public TreeElement[] getChildren() {
return Arrays.stream(this.psiElement.getChildren()) | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/structview/STGroupRootTreeElement.java
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.ide.util.treeView.smartTree.TreeElement;
import com.intellij.navigation.ItemPresentation;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
package org.antlr.jetbrains.st4plugin.structview;
public class STGroupRootTreeElement extends STGroupStructureViewTreeElement {
public STGroupRootTreeElement(PsiFile psiFile) {
super(psiFile);
}
@NotNull
@Override
public ItemPresentation getPresentation() {
return new STGroupRootItemPresentation((PsiFile) psiElement);
}
@NotNull
@Override
public TreeElement[] getChildren() {
return Arrays.stream(this.psiElement.getChildren()) | .filter(e -> e.getNode().getElementType() == getRuleElementType(STGParser.RULE_group)) |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupFile.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupFileType.java
// public class STGroupFileType extends LanguageFileType implements TemplateLanguageFileType {
// public static final STGroupFileType INSTANCE = new STGroupFileType();
//
// protected STGroupFileType() {
// super(STGroupLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return "stg";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return Icons.STG_FILE;
// }
//
// static class Factory extends FileTypeFactory {
// @Override
// public void createFileTypes(@NotNull FileTypeConsumer consumer) {
// consumer.consume(STGroupFileType.INSTANCE);
// }
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupLanguage.java
// public class STGroupLanguage extends Language {
// public static final STGroupLanguage INSTANCE = new STGroupLanguage();
//
// private STGroupLanguage() {
// super("STGroup");
// }
// }
| import com.intellij.extapi.psi.PsiFileBase;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.FileViewProvider;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.STGroupFileType;
import org.antlr.jetbrains.st4plugin.STGroupLanguage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*; | package org.antlr.jetbrains.st4plugin.psi;
public class STGroupFile extends PsiFileBase {
protected STGroupFile(@NotNull FileViewProvider viewProvider) { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupFileType.java
// public class STGroupFileType extends LanguageFileType implements TemplateLanguageFileType {
// public static final STGroupFileType INSTANCE = new STGroupFileType();
//
// protected STGroupFileType() {
// super(STGroupLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return "stg";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return Icons.STG_FILE;
// }
//
// static class Factory extends FileTypeFactory {
// @Override
// public void createFileTypes(@NotNull FileTypeConsumer consumer) {
// consumer.consume(STGroupFileType.INSTANCE);
// }
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupLanguage.java
// public class STGroupLanguage extends Language {
// public static final STGroupLanguage INSTANCE = new STGroupLanguage();
//
// private STGroupLanguage() {
// super("STGroup");
// }
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupFile.java
import com.intellij.extapi.psi.PsiFileBase;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.FileViewProvider;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.STGroupFileType;
import org.antlr.jetbrains.st4plugin.STGroupLanguage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
package org.antlr.jetbrains.st4plugin.psi;
public class STGroupFile extends PsiFileBase {
protected STGroupFile(@NotNull FileViewProvider viewProvider) { | super(viewProvider, STGroupLanguage.INSTANCE); |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupFile.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupFileType.java
// public class STGroupFileType extends LanguageFileType implements TemplateLanguageFileType {
// public static final STGroupFileType INSTANCE = new STGroupFileType();
//
// protected STGroupFileType() {
// super(STGroupLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return "stg";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return Icons.STG_FILE;
// }
//
// static class Factory extends FileTypeFactory {
// @Override
// public void createFileTypes(@NotNull FileTypeConsumer consumer) {
// consumer.consume(STGroupFileType.INSTANCE);
// }
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupLanguage.java
// public class STGroupLanguage extends Language {
// public static final STGroupLanguage INSTANCE = new STGroupLanguage();
//
// private STGroupLanguage() {
// super("STGroup");
// }
// }
| import com.intellij.extapi.psi.PsiFileBase;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.FileViewProvider;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.STGroupFileType;
import org.antlr.jetbrains.st4plugin.STGroupLanguage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*; | package org.antlr.jetbrains.st4plugin.psi;
public class STGroupFile extends PsiFileBase {
protected STGroupFile(@NotNull FileViewProvider viewProvider) {
super(viewProvider, STGroupLanguage.INSTANCE);
}
@NotNull
@Override
public FileType getFileType() { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupFileType.java
// public class STGroupFileType extends LanguageFileType implements TemplateLanguageFileType {
// public static final STGroupFileType INSTANCE = new STGroupFileType();
//
// protected STGroupFileType() {
// super(STGroupLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return "stg";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return Icons.STG_FILE;
// }
//
// static class Factory extends FileTypeFactory {
// @Override
// public void createFileTypes(@NotNull FileTypeConsumer consumer) {
// consumer.consume(STGroupFileType.INSTANCE);
// }
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupLanguage.java
// public class STGroupLanguage extends Language {
// public static final STGroupLanguage INSTANCE = new STGroupLanguage();
//
// private STGroupLanguage() {
// super("STGroup");
// }
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupFile.java
import com.intellij.extapi.psi.PsiFileBase;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.FileViewProvider;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.STGroupFileType;
import org.antlr.jetbrains.st4plugin.STGroupLanguage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
package org.antlr.jetbrains.st4plugin.psi;
public class STGroupFile extends PsiFileBase {
protected STGroupFile(@NotNull FileViewProvider viewProvider) {
super(viewProvider, STGroupLanguage.INSTANCE);
}
@NotNull
@Override
public FileType getFileType() { | return STGroupFileType.INSTANCE; |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupFile.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupFileType.java
// public class STGroupFileType extends LanguageFileType implements TemplateLanguageFileType {
// public static final STGroupFileType INSTANCE = new STGroupFileType();
//
// protected STGroupFileType() {
// super(STGroupLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return "stg";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return Icons.STG_FILE;
// }
//
// static class Factory extends FileTypeFactory {
// @Override
// public void createFileTypes(@NotNull FileTypeConsumer consumer) {
// consumer.consume(STGroupFileType.INSTANCE);
// }
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupLanguage.java
// public class STGroupLanguage extends Language {
// public static final STGroupLanguage INSTANCE = new STGroupLanguage();
//
// private STGroupLanguage() {
// super("STGroup");
// }
// }
| import com.intellij.extapi.psi.PsiFileBase;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.FileViewProvider;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.STGroupFileType;
import org.antlr.jetbrains.st4plugin.STGroupLanguage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*; | package org.antlr.jetbrains.st4plugin.psi;
public class STGroupFile extends PsiFileBase {
protected STGroupFile(@NotNull FileViewProvider viewProvider) {
super(viewProvider, STGroupLanguage.INSTANCE);
}
@NotNull
@Override
public FileType getFileType() {
return STGroupFileType.INSTANCE;
}
@Override
public String toString() {
return "String Template group file";
}
@Nullable
@Override
public Icon getIcon(int flags) { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupFileType.java
// public class STGroupFileType extends LanguageFileType implements TemplateLanguageFileType {
// public static final STGroupFileType INSTANCE = new STGroupFileType();
//
// protected STGroupFileType() {
// super(STGroupLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return "stg";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return Icons.STG_FILE;
// }
//
// static class Factory extends FileTypeFactory {
// @Override
// public void createFileTypes(@NotNull FileTypeConsumer consumer) {
// consumer.consume(STGroupFileType.INSTANCE);
// }
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupLanguage.java
// public class STGroupLanguage extends Language {
// public static final STGroupLanguage INSTANCE = new STGroupLanguage();
//
// private STGroupLanguage() {
// super("STGroup");
// }
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupFile.java
import com.intellij.extapi.psi.PsiFileBase;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.FileViewProvider;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.STGroupFileType;
import org.antlr.jetbrains.st4plugin.STGroupLanguage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
package org.antlr.jetbrains.st4plugin.psi;
public class STGroupFile extends PsiFileBase {
protected STGroupFile(@NotNull FileViewProvider viewProvider) {
super(viewProvider, STGroupLanguage.INSTANCE);
}
@NotNull
@Override
public FileType getFileType() {
return STGroupFileType.INSTANCE;
}
@Override
public String toString() {
return "String Template group file";
}
@Nullable
@Override
public Icon getIcon(int flags) { | return Icons.STG_FILE; |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/highlight/STSemanticHighlightAnnotator.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public class STTokenTypes {
//
// private static final List<TokenIElementType> TOKEN_ELEMENT_TYPES = PSIElementTypeFactory.getTokenIElementTypes(STLanguage.INSTANCE);
// private static final List<RuleIElementType> RULE_ELEMENT_TYPES = PSIElementTypeFactory.getRuleIElementTypes(STLanguage.INSTANCE);
//
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lang.ASTNode;
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.Annotator;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiTreeUtil;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.antlr.jetbrains.st4plugin.parsing.STParser;
import org.antlr.jetbrains.st4plugin.psi.STTokenTypes;
import org.jetbrains.annotations.NotNull;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.highlight;
/**
* Semantic highlighting for .st files.
*/
public class STSemanticHighlightAnnotator implements Annotator {
private static final TextAttributesKey ST_TAG = createTextAttributesKey("ST_TAG");
public static final TextAttributesKey OPTION = createTextAttributesKey("ST_OPTION", DefaultLanguageHighlighterColors.INSTANCE_METHOD);
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public class STTokenTypes {
//
// private static final List<TokenIElementType> TOKEN_ELEMENT_TYPES = PSIElementTypeFactory.getTokenIElementTypes(STLanguage.INSTANCE);
// private static final List<RuleIElementType> RULE_ELEMENT_TYPES = PSIElementTypeFactory.getRuleIElementTypes(STLanguage.INSTANCE);
//
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/highlight/STSemanticHighlightAnnotator.java
import com.intellij.lang.ASTNode;
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.Annotator;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiTreeUtil;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.antlr.jetbrains.st4plugin.parsing.STParser;
import org.antlr.jetbrains.st4plugin.psi.STTokenTypes;
import org.jetbrains.annotations.NotNull;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.highlight;
/**
* Semantic highlighting for .st files.
*/
public class STSemanticHighlightAnnotator implements Annotator {
private static final TextAttributesKey ST_TAG = createTextAttributesKey("ST_TAG");
public static final TextAttributesKey OPTION = createTextAttributesKey("ST_OPTION", DefaultLanguageHighlighterColors.INSTANCE_METHOD);
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) { | if (element.getNode().getElementType() == STTokenTypes.getTokenElementType(STLexer.ID)) { |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/highlight/STSemanticHighlightAnnotator.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public class STTokenTypes {
//
// private static final List<TokenIElementType> TOKEN_ELEMENT_TYPES = PSIElementTypeFactory.getTokenIElementTypes(STLanguage.INSTANCE);
// private static final List<RuleIElementType> RULE_ELEMENT_TYPES = PSIElementTypeFactory.getRuleIElementTypes(STLanguage.INSTANCE);
//
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lang.ASTNode;
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.Annotator;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiTreeUtil;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.antlr.jetbrains.st4plugin.parsing.STParser;
import org.antlr.jetbrains.st4plugin.psi.STTokenTypes;
import org.jetbrains.annotations.NotNull;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.highlight;
/**
* Semantic highlighting for .st files.
*/
public class STSemanticHighlightAnnotator implements Annotator {
private static final TextAttributesKey ST_TAG = createTextAttributesKey("ST_TAG");
public static final TextAttributesKey OPTION = createTextAttributesKey("ST_OPTION", DefaultLanguageHighlighterColors.INSTANCE_METHOD);
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public class STTokenTypes {
//
// private static final List<TokenIElementType> TOKEN_ELEMENT_TYPES = PSIElementTypeFactory.getTokenIElementTypes(STLanguage.INSTANCE);
// private static final List<RuleIElementType> RULE_ELEMENT_TYPES = PSIElementTypeFactory.getRuleIElementTypes(STLanguage.INSTANCE);
//
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/highlight/STSemanticHighlightAnnotator.java
import com.intellij.lang.ASTNode;
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.Annotator;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiTreeUtil;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.antlr.jetbrains.st4plugin.parsing.STParser;
import org.antlr.jetbrains.st4plugin.psi.STTokenTypes;
import org.jetbrains.annotations.NotNull;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.highlight;
/**
* Semantic highlighting for .st files.
*/
public class STSemanticHighlightAnnotator implements Annotator {
private static final TextAttributesKey ST_TAG = createTextAttributesKey("ST_TAG");
public static final TextAttributesKey OPTION = createTextAttributesKey("ST_OPTION", DefaultLanguageHighlighterColors.INSTANCE_METHOD);
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) { | if (element.getNode().getElementType() == STTokenTypes.getTokenElementType(STLexer.ID)) { |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/highlight/STSemanticHighlightAnnotator.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public class STTokenTypes {
//
// private static final List<TokenIElementType> TOKEN_ELEMENT_TYPES = PSIElementTypeFactory.getTokenIElementTypes(STLanguage.INSTANCE);
// private static final List<RuleIElementType> RULE_ELEMENT_TYPES = PSIElementTypeFactory.getRuleIElementTypes(STLanguage.INSTANCE);
//
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lang.ASTNode;
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.Annotator;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiTreeUtil;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.antlr.jetbrains.st4plugin.parsing.STParser;
import org.antlr.jetbrains.st4plugin.psi.STTokenTypes;
import org.jetbrains.annotations.NotNull;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.highlight;
/**
* Semantic highlighting for .st files.
*/
public class STSemanticHighlightAnnotator implements Annotator {
private static final TextAttributesKey ST_TAG = createTextAttributesKey("ST_TAG");
public static final TextAttributesKey OPTION = createTextAttributesKey("ST_OPTION", DefaultLanguageHighlighterColors.INSTANCE_METHOD);
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) {
if (element.getNode().getElementType() == STTokenTypes.getTokenElementType(STLexer.ID)) {
if (isPrimary(element) || isSubtemplate(element)) {
holder.createInfoAnnotation(element, null)
.setTextAttributes(STGroupSemanticHighlightAnnotator.TEMPLATE_PARAM);
} else if (isOptionId(element)) {
holder.createInfoAnnotation(element, null)
.setTextAttributes(OPTION);
} else if (isCall(element)) {
holder.createInfoAnnotation(element, null)
.setTextAttributes(STGroupSyntaxHighlighter.TEMPLATE_NAME);
}
}
if (isTag(element)) {
// use a white/dark background instead of the default green from injected languages
holder.createInfoAnnotation(element, null)
.setTextAttributes(ST_TAG);
}
| // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public class STTokenTypes {
//
// private static final List<TokenIElementType> TOKEN_ELEMENT_TYPES = PSIElementTypeFactory.getTokenIElementTypes(STLanguage.INSTANCE);
// private static final List<RuleIElementType> RULE_ELEMENT_TYPES = PSIElementTypeFactory.getRuleIElementTypes(STLanguage.INSTANCE);
//
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/highlight/STSemanticHighlightAnnotator.java
import com.intellij.lang.ASTNode;
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.Annotator;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiTreeUtil;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.antlr.jetbrains.st4plugin.parsing.STParser;
import org.antlr.jetbrains.st4plugin.psi.STTokenTypes;
import org.jetbrains.annotations.NotNull;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.highlight;
/**
* Semantic highlighting for .st files.
*/
public class STSemanticHighlightAnnotator implements Annotator {
private static final TextAttributesKey ST_TAG = createTextAttributesKey("ST_TAG");
public static final TextAttributesKey OPTION = createTextAttributesKey("ST_OPTION", DefaultLanguageHighlighterColors.INSTANCE_METHOD);
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) {
if (element.getNode().getElementType() == STTokenTypes.getTokenElementType(STLexer.ID)) {
if (isPrimary(element) || isSubtemplate(element)) {
holder.createInfoAnnotation(element, null)
.setTextAttributes(STGroupSemanticHighlightAnnotator.TEMPLATE_PARAM);
} else if (isOptionId(element)) {
holder.createInfoAnnotation(element, null)
.setTextAttributes(OPTION);
} else if (isCall(element)) {
holder.createInfoAnnotation(element, null)
.setTextAttributes(STGroupSyntaxHighlighter.TEMPLATE_NAME);
}
}
if (isTag(element)) {
// use a white/dark background instead of the default green from injected languages
holder.createInfoAnnotation(element, null)
.setTextAttributes(ST_TAG);
}
| if (element.getNode().getElementType() == getRuleElementType(STParser.RULE_ifstat)) { |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/structview/STGroupRootItemPresentation.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
| import com.intellij.navigation.ItemPresentation;
import com.intellij.psi.PsiFile;
import org.antlr.jetbrains.st4plugin.Icons;
import org.jetbrains.annotations.Nullable;
import javax.swing.*; | package org.antlr.jetbrains.st4plugin.structview;
public class STGroupRootItemPresentation implements ItemPresentation {
private final PsiFile file;
public STGroupRootItemPresentation(PsiFile file) {
this.file = file;
}
@Nullable
@Override
public String getPresentableText() {
return file.getName();
}
@Nullable
@Override
public String getLocationString() {
return null;
}
@Nullable
@Override
public Icon getIcon(boolean unused) { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/structview/STGroupRootItemPresentation.java
import com.intellij.navigation.ItemPresentation;
import com.intellij.psi.PsiFile;
import org.antlr.jetbrains.st4plugin.Icons;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
package org.antlr.jetbrains.st4plugin.structview;
public class STGroupRootItemPresentation implements ItemPresentation {
private final PsiFile file;
public STGroupRootItemPresentation(PsiFile file) {
this.file = file;
}
@Nullable
@Override
public String getPresentableText() {
return file.getName();
}
@Nullable
@Override
public String getLocationString() {
return null;
}
@Nullable
@Override
public Icon getIcon(boolean unused) { | return Icons.STG_FILE; |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/highlight/STGroupSyntaxHighlighter.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupLanguage.java
// public class STGroupLanguage extends Language {
// public static final STGroupLanguage INSTANCE = new STGroupLanguage();
//
// private STGroupLanguage() {
// super("STGroup");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public class STGroupTokenTypes {
//
// private static final List<TokenIElementType> TOKEN_ELEMENT_TYPES = PSIElementTypeFactory.getTokenIElementTypes(STGroupLanguage.INSTANCE);
// private static final List<RuleIElementType> RULE_ELEMENT_TYPES = PSIElementTypeFactory.getRuleIElementTypes(STGroupLanguage.INSTANCE);
//
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lexer.Lexer;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.HighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase;
import com.intellij.psi.tree.IElementType;
import org.antlr.intellij.adaptor.lexer.ANTLRLexerAdaptor;
import org.antlr.intellij.adaptor.lexer.TokenIElementType;
import org.antlr.jetbrains.st4plugin.STGroupLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes;
import org.antlr.v4.runtime.Token;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.highlight;
public class STGroupSyntaxHighlighter extends SyntaxHighlighterBase {
public static final TextAttributesKey TEMPLATE_NAME =
createTextAttributesKey("STGroup_TEMPLATE_NAME", DefaultLanguageHighlighterColors.INSTANCE_METHOD);
public static final TextAttributesKey LINE_COMMENT =
createTextAttributesKey("STGroup_LINE_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT);
public static final TextAttributesKey BLOCK_COMMENT =
createTextAttributesKey("STGroup_BLOCK_COMMENT", DefaultLanguageHighlighterColors.BLOCK_COMMENT);
public static final TextAttributesKey KEYWORD =
createTextAttributesKey("STGroup_KEYWORD", DefaultLanguageHighlighterColors.KEYWORD);
public static final TextAttributesKey STRING =
createTextAttributesKey("STGroup_STRING", DefaultLanguageHighlighterColors.STRING);
private static final List<IElementType> KEYWORDS = Stream.of(
STGLexer.DELIMITERS, STGLexer.IMPORT, STGLexer.DEFAULT, STGLexer.KEY, STGLexer.GROUP | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupLanguage.java
// public class STGroupLanguage extends Language {
// public static final STGroupLanguage INSTANCE = new STGroupLanguage();
//
// private STGroupLanguage() {
// super("STGroup");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public class STGroupTokenTypes {
//
// private static final List<TokenIElementType> TOKEN_ELEMENT_TYPES = PSIElementTypeFactory.getTokenIElementTypes(STGroupLanguage.INSTANCE);
// private static final List<RuleIElementType> RULE_ELEMENT_TYPES = PSIElementTypeFactory.getRuleIElementTypes(STGroupLanguage.INSTANCE);
//
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/highlight/STGroupSyntaxHighlighter.java
import com.intellij.lexer.Lexer;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.HighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase;
import com.intellij.psi.tree.IElementType;
import org.antlr.intellij.adaptor.lexer.ANTLRLexerAdaptor;
import org.antlr.intellij.adaptor.lexer.TokenIElementType;
import org.antlr.jetbrains.st4plugin.STGroupLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes;
import org.antlr.v4.runtime.Token;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.highlight;
public class STGroupSyntaxHighlighter extends SyntaxHighlighterBase {
public static final TextAttributesKey TEMPLATE_NAME =
createTextAttributesKey("STGroup_TEMPLATE_NAME", DefaultLanguageHighlighterColors.INSTANCE_METHOD);
public static final TextAttributesKey LINE_COMMENT =
createTextAttributesKey("STGroup_LINE_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT);
public static final TextAttributesKey BLOCK_COMMENT =
createTextAttributesKey("STGroup_BLOCK_COMMENT", DefaultLanguageHighlighterColors.BLOCK_COMMENT);
public static final TextAttributesKey KEYWORD =
createTextAttributesKey("STGroup_KEYWORD", DefaultLanguageHighlighterColors.KEYWORD);
public static final TextAttributesKey STRING =
createTextAttributesKey("STGroup_STRING", DefaultLanguageHighlighterColors.STRING);
private static final List<IElementType> KEYWORDS = Stream.of(
STGLexer.DELIMITERS, STGLexer.IMPORT, STGLexer.DEFAULT, STGLexer.KEY, STGLexer.GROUP | ).map(STGroupTokenTypes::getTokenElementType).collect(Collectors.toList()); |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/highlight/STGroupSyntaxHighlighter.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupLanguage.java
// public class STGroupLanguage extends Language {
// public static final STGroupLanguage INSTANCE = new STGroupLanguage();
//
// private STGroupLanguage() {
// super("STGroup");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public class STGroupTokenTypes {
//
// private static final List<TokenIElementType> TOKEN_ELEMENT_TYPES = PSIElementTypeFactory.getTokenIElementTypes(STGroupLanguage.INSTANCE);
// private static final List<RuleIElementType> RULE_ELEMENT_TYPES = PSIElementTypeFactory.getRuleIElementTypes(STGroupLanguage.INSTANCE);
//
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lexer.Lexer;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.HighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase;
import com.intellij.psi.tree.IElementType;
import org.antlr.intellij.adaptor.lexer.ANTLRLexerAdaptor;
import org.antlr.intellij.adaptor.lexer.TokenIElementType;
import org.antlr.jetbrains.st4plugin.STGroupLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes;
import org.antlr.v4.runtime.Token;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.highlight;
public class STGroupSyntaxHighlighter extends SyntaxHighlighterBase {
public static final TextAttributesKey TEMPLATE_NAME =
createTextAttributesKey("STGroup_TEMPLATE_NAME", DefaultLanguageHighlighterColors.INSTANCE_METHOD);
public static final TextAttributesKey LINE_COMMENT =
createTextAttributesKey("STGroup_LINE_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT);
public static final TextAttributesKey BLOCK_COMMENT =
createTextAttributesKey("STGroup_BLOCK_COMMENT", DefaultLanguageHighlighterColors.BLOCK_COMMENT);
public static final TextAttributesKey KEYWORD =
createTextAttributesKey("STGroup_KEYWORD", DefaultLanguageHighlighterColors.KEYWORD);
public static final TextAttributesKey STRING =
createTextAttributesKey("STGroup_STRING", DefaultLanguageHighlighterColors.STRING);
private static final List<IElementType> KEYWORDS = Stream.of(
STGLexer.DELIMITERS, STGLexer.IMPORT, STGLexer.DEFAULT, STGLexer.KEY, STGLexer.GROUP | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupLanguage.java
// public class STGroupLanguage extends Language {
// public static final STGroupLanguage INSTANCE = new STGroupLanguage();
//
// private STGroupLanguage() {
// super("STGroup");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public class STGroupTokenTypes {
//
// private static final List<TokenIElementType> TOKEN_ELEMENT_TYPES = PSIElementTypeFactory.getTokenIElementTypes(STGroupLanguage.INSTANCE);
// private static final List<RuleIElementType> RULE_ELEMENT_TYPES = PSIElementTypeFactory.getRuleIElementTypes(STGroupLanguage.INSTANCE);
//
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/highlight/STGroupSyntaxHighlighter.java
import com.intellij.lexer.Lexer;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.HighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase;
import com.intellij.psi.tree.IElementType;
import org.antlr.intellij.adaptor.lexer.ANTLRLexerAdaptor;
import org.antlr.intellij.adaptor.lexer.TokenIElementType;
import org.antlr.jetbrains.st4plugin.STGroupLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes;
import org.antlr.v4.runtime.Token;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.highlight;
public class STGroupSyntaxHighlighter extends SyntaxHighlighterBase {
public static final TextAttributesKey TEMPLATE_NAME =
createTextAttributesKey("STGroup_TEMPLATE_NAME", DefaultLanguageHighlighterColors.INSTANCE_METHOD);
public static final TextAttributesKey LINE_COMMENT =
createTextAttributesKey("STGroup_LINE_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT);
public static final TextAttributesKey BLOCK_COMMENT =
createTextAttributesKey("STGroup_BLOCK_COMMENT", DefaultLanguageHighlighterColors.BLOCK_COMMENT);
public static final TextAttributesKey KEYWORD =
createTextAttributesKey("STGroup_KEYWORD", DefaultLanguageHighlighterColors.KEYWORD);
public static final TextAttributesKey STRING =
createTextAttributesKey("STGroup_STRING", DefaultLanguageHighlighterColors.STRING);
private static final List<IElementType> KEYWORDS = Stream.of(
STGLexer.DELIMITERS, STGLexer.IMPORT, STGLexer.DEFAULT, STGLexer.KEY, STGLexer.GROUP | ).map(STGroupTokenTypes::getTokenElementType).collect(Collectors.toList()); |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/highlight/STGroupSyntaxHighlighter.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupLanguage.java
// public class STGroupLanguage extends Language {
// public static final STGroupLanguage INSTANCE = new STGroupLanguage();
//
// private STGroupLanguage() {
// super("STGroup");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public class STGroupTokenTypes {
//
// private static final List<TokenIElementType> TOKEN_ELEMENT_TYPES = PSIElementTypeFactory.getTokenIElementTypes(STGroupLanguage.INSTANCE);
// private static final List<RuleIElementType> RULE_ELEMENT_TYPES = PSIElementTypeFactory.getRuleIElementTypes(STGroupLanguage.INSTANCE);
//
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lexer.Lexer;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.HighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase;
import com.intellij.psi.tree.IElementType;
import org.antlr.intellij.adaptor.lexer.ANTLRLexerAdaptor;
import org.antlr.intellij.adaptor.lexer.TokenIElementType;
import org.antlr.jetbrains.st4plugin.STGroupLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes;
import org.antlr.v4.runtime.Token;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.highlight;
public class STGroupSyntaxHighlighter extends SyntaxHighlighterBase {
public static final TextAttributesKey TEMPLATE_NAME =
createTextAttributesKey("STGroup_TEMPLATE_NAME", DefaultLanguageHighlighterColors.INSTANCE_METHOD);
public static final TextAttributesKey LINE_COMMENT =
createTextAttributesKey("STGroup_LINE_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT);
public static final TextAttributesKey BLOCK_COMMENT =
createTextAttributesKey("STGroup_BLOCK_COMMENT", DefaultLanguageHighlighterColors.BLOCK_COMMENT);
public static final TextAttributesKey KEYWORD =
createTextAttributesKey("STGroup_KEYWORD", DefaultLanguageHighlighterColors.KEYWORD);
public static final TextAttributesKey STRING =
createTextAttributesKey("STGroup_STRING", DefaultLanguageHighlighterColors.STRING);
private static final List<IElementType> KEYWORDS = Stream.of(
STGLexer.DELIMITERS, STGLexer.IMPORT, STGLexer.DEFAULT, STGLexer.KEY, STGLexer.GROUP
).map(STGroupTokenTypes::getTokenElementType).collect(Collectors.toList());
public static final TextAttributesKey[] NO_ATTRIBUTES = new TextAttributesKey[0];
@NotNull
@Override
public Lexer getHighlightingLexer() { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupLanguage.java
// public class STGroupLanguage extends Language {
// public static final STGroupLanguage INSTANCE = new STGroupLanguage();
//
// private STGroupLanguage() {
// super("STGroup");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public class STGroupTokenTypes {
//
// private static final List<TokenIElementType> TOKEN_ELEMENT_TYPES = PSIElementTypeFactory.getTokenIElementTypes(STGroupLanguage.INSTANCE);
// private static final List<RuleIElementType> RULE_ELEMENT_TYPES = PSIElementTypeFactory.getRuleIElementTypes(STGroupLanguage.INSTANCE);
//
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/highlight/STGroupSyntaxHighlighter.java
import com.intellij.lexer.Lexer;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.HighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase;
import com.intellij.psi.tree.IElementType;
import org.antlr.intellij.adaptor.lexer.ANTLRLexerAdaptor;
import org.antlr.intellij.adaptor.lexer.TokenIElementType;
import org.antlr.jetbrains.st4plugin.STGroupLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes;
import org.antlr.v4.runtime.Token;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.highlight;
public class STGroupSyntaxHighlighter extends SyntaxHighlighterBase {
public static final TextAttributesKey TEMPLATE_NAME =
createTextAttributesKey("STGroup_TEMPLATE_NAME", DefaultLanguageHighlighterColors.INSTANCE_METHOD);
public static final TextAttributesKey LINE_COMMENT =
createTextAttributesKey("STGroup_LINE_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT);
public static final TextAttributesKey BLOCK_COMMENT =
createTextAttributesKey("STGroup_BLOCK_COMMENT", DefaultLanguageHighlighterColors.BLOCK_COMMENT);
public static final TextAttributesKey KEYWORD =
createTextAttributesKey("STGroup_KEYWORD", DefaultLanguageHighlighterColors.KEYWORD);
public static final TextAttributesKey STRING =
createTextAttributesKey("STGroup_STRING", DefaultLanguageHighlighterColors.STRING);
private static final List<IElementType> KEYWORDS = Stream.of(
STGLexer.DELIMITERS, STGLexer.IMPORT, STGLexer.DEFAULT, STGLexer.KEY, STGLexer.GROUP
).map(STGroupTokenTypes::getTokenElementType).collect(Collectors.toList());
public static final TextAttributesKey[] NO_ATTRIBUTES = new TextAttributesKey[0];
@NotNull
@Override
public Lexer getHighlightingLexer() { | return new ANTLRLexerAdaptor(STGroupLanguage.INSTANCE, new STGLexer(null)); |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/highlight/STColorSettingsPage.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
| import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.openapi.options.colors.AttributesDescriptor;
import com.intellij.openapi.options.colors.ColorDescriptor;
import com.intellij.openapi.options.colors.ColorSettingsPage;
import org.antlr.jetbrains.st4plugin.Icons;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.HashMap;
import java.util.Map; | package org.antlr.jetbrains.st4plugin.highlight;
public class STColorSettingsPage implements ColorSettingsPage {
private static final AttributesDescriptor[] DESCRIPTORS = new AttributesDescriptor[]{
new AttributesDescriptor("Template Name", STGroupSyntaxHighlighter.TEMPLATE_NAME),
new AttributesDescriptor("Template Parameter", STGroupSemanticHighlightAnnotator.TEMPLATE_PARAM),
new AttributesDescriptor("String", STGroupSyntaxHighlighter.STRING),
new AttributesDescriptor("Keyword", STGroupSyntaxHighlighter.KEYWORD),
new AttributesDescriptor("Line Comment", STGroupSyntaxHighlighter.LINE_COMMENT),
new AttributesDescriptor("Block Comment", STGroupSyntaxHighlighter.BLOCK_COMMENT),
new AttributesDescriptor("Option", STSemanticHighlightAnnotator.OPTION)
};
@Override
public @Nullable Icon getIcon() { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/highlight/STColorSettingsPage.java
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.openapi.options.colors.AttributesDescriptor;
import com.intellij.openapi.options.colors.ColorDescriptor;
import com.intellij.openapi.options.colors.ColorSettingsPage;
import org.antlr.jetbrains.st4plugin.Icons;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.HashMap;
import java.util.Map;
package org.antlr.jetbrains.st4plugin.highlight;
public class STColorSettingsPage implements ColorSettingsPage {
private static final AttributesDescriptor[] DESCRIPTORS = new AttributesDescriptor[]{
new AttributesDescriptor("Template Name", STGroupSyntaxHighlighter.TEMPLATE_NAME),
new AttributesDescriptor("Template Parameter", STGroupSemanticHighlightAnnotator.TEMPLATE_PARAM),
new AttributesDescriptor("String", STGroupSyntaxHighlighter.STRING),
new AttributesDescriptor("Keyword", STGroupSyntaxHighlighter.KEYWORD),
new AttributesDescriptor("Line Comment", STGroupSyntaxHighlighter.LINE_COMMENT),
new AttributesDescriptor("Block Comment", STGroupSyntaxHighlighter.BLOCK_COMMENT),
new AttributesDescriptor("Option", STSemanticHighlightAnnotator.OPTION)
};
@Override
public @Nullable Icon getIcon() { | return Icons.STG_FILE; |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/highlight/STGroupSemanticHighlightAnnotator.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public class STGroupTokenTypes {
//
// private static final List<TokenIElementType> TOKEN_ELEMENT_TYPES = PSIElementTypeFactory.getTokenIElementTypes(STGroupLanguage.INSTANCE);
// private static final List<RuleIElementType> RULE_ELEMENT_TYPES = PSIElementTypeFactory.getRuleIElementTypes(STGroupLanguage.INSTANCE);
//
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.Annotator;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.psi.PsiElement;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes;
import org.jetbrains.annotations.NotNull;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType; | package org.antlr.jetbrains.st4plugin.highlight;
/**
* Highlights a group's formal args differently from its name.
*/
public class STGroupSemanticHighlightAnnotator implements Annotator {
public static final TextAttributesKey TEMPLATE_PARAM = createTextAttributesKey("STGroup_TEMPLATE_PARAM", DefaultLanguageHighlighterColors.INSTANCE_FIELD);
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public class STGroupTokenTypes {
//
// private static final List<TokenIElementType> TOKEN_ELEMENT_TYPES = PSIElementTypeFactory.getTokenIElementTypes(STGroupLanguage.INSTANCE);
// private static final List<RuleIElementType> RULE_ELEMENT_TYPES = PSIElementTypeFactory.getRuleIElementTypes(STGroupLanguage.INSTANCE);
//
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/highlight/STGroupSemanticHighlightAnnotator.java
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.Annotator;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.psi.PsiElement;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes;
import org.jetbrains.annotations.NotNull;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
package org.antlr.jetbrains.st4plugin.highlight;
/**
* Highlights a group's formal args differently from its name.
*/
public class STGroupSemanticHighlightAnnotator implements Annotator {
public static final TextAttributesKey TEMPLATE_PARAM = createTextAttributesKey("STGroup_TEMPLATE_PARAM", DefaultLanguageHighlighterColors.INSTANCE_FIELD);
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) { | if (element.getNode().getElementType() == STGroupTokenTypes.getTokenElementType(STGLexer.ID)) { |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/highlight/STGroupSemanticHighlightAnnotator.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public class STGroupTokenTypes {
//
// private static final List<TokenIElementType> TOKEN_ELEMENT_TYPES = PSIElementTypeFactory.getTokenIElementTypes(STGroupLanguage.INSTANCE);
// private static final List<RuleIElementType> RULE_ELEMENT_TYPES = PSIElementTypeFactory.getRuleIElementTypes(STGroupLanguage.INSTANCE);
//
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.Annotator;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.psi.PsiElement;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes;
import org.jetbrains.annotations.NotNull;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType; | package org.antlr.jetbrains.st4plugin.highlight;
/**
* Highlights a group's formal args differently from its name.
*/
public class STGroupSemanticHighlightAnnotator implements Annotator {
public static final TextAttributesKey TEMPLATE_PARAM = createTextAttributesKey("STGroup_TEMPLATE_PARAM", DefaultLanguageHighlighterColors.INSTANCE_FIELD);
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) {
if (element.getNode().getElementType() == STGroupTokenTypes.getTokenElementType(STGLexer.ID)) { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public class STGroupTokenTypes {
//
// private static final List<TokenIElementType> TOKEN_ELEMENT_TYPES = PSIElementTypeFactory.getTokenIElementTypes(STGroupLanguage.INSTANCE);
// private static final List<RuleIElementType> RULE_ELEMENT_TYPES = PSIElementTypeFactory.getRuleIElementTypes(STGroupLanguage.INSTANCE);
//
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/highlight/STGroupSemanticHighlightAnnotator.java
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.Annotator;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.psi.PsiElement;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes;
import org.jetbrains.annotations.NotNull;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
package org.antlr.jetbrains.st4plugin.highlight;
/**
* Highlights a group's formal args differently from its name.
*/
public class STGroupSemanticHighlightAnnotator implements Annotator {
public static final TextAttributesKey TEMPLATE_PARAM = createTextAttributesKey("STGroup_TEMPLATE_PARAM", DefaultLanguageHighlighterColors.INSTANCE_FIELD);
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) {
if (element.getNode().getElementType() == STGroupTokenTypes.getTokenElementType(STGLexer.ID)) { | if (element.getParent().getNode().getElementType() == getRuleElementType(STGParser.RULE_formalArg)) { |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/structview/STGroupItemPresentation.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
| import com.intellij.navigation.ItemPresentation;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.v4.runtime.tree.ParseTree;
import org.jetbrains.annotations.Nullable;
import javax.swing.*; | package org.antlr.jetbrains.st4plugin.structview;
public abstract class STGroupItemPresentation implements ItemPresentation {
protected ParseTree node;
public STGroupItemPresentation(ParseTree node) {
this.node = node;
}
@Nullable
@Override
public Icon getIcon(boolean unused) {
if (node.getParent() == null) return null; | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/structview/STGroupItemPresentation.java
import com.intellij.navigation.ItemPresentation;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.v4.runtime.tree.ParseTree;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
package org.antlr.jetbrains.st4plugin.structview;
public abstract class STGroupItemPresentation implements ItemPresentation {
protected ParseTree node;
public STGroupItemPresentation(ParseTree node) {
this.node = node;
}
@Nullable
@Override
public Icon getIcon(boolean unused) {
if (node.getParent() == null) return null; | return Icons.STG_FILE; |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/structview/STGroupTemplateDefItemPresentation.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.lang.ASTNode;
import com.intellij.navigation.ItemPresentation;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.Arrays;
import java.util.stream.Collectors;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.structview;
public class STGroupTemplateDefItemPresentation implements ItemPresentation {
private final ASTWrapperPsiElement psiElement;
public STGroupTemplateDefItemPresentation(ASTWrapperPsiElement psiElement) {
this.psiElement = psiElement;
}
@Nullable
@Override
public String getPresentableText() { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/structview/STGroupTemplateDefItemPresentation.java
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.lang.ASTNode;
import com.intellij.navigation.ItemPresentation;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.Arrays;
import java.util.stream.Collectors;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.structview;
public class STGroupTemplateDefItemPresentation implements ItemPresentation {
private final ASTWrapperPsiElement psiElement;
public STGroupTemplateDefItemPresentation(ASTWrapperPsiElement psiElement) {
this.psiElement = psiElement;
}
@Nullable
@Override
public String getPresentableText() { | ASTNode id = psiElement.getNode().findChildByType(getTokenElementType(STGLexer.ID)); |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/structview/STGroupTemplateDefItemPresentation.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.lang.ASTNode;
import com.intellij.navigation.ItemPresentation;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.Arrays;
import java.util.stream.Collectors;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.structview;
public class STGroupTemplateDefItemPresentation implements ItemPresentation {
private final ASTWrapperPsiElement psiElement;
public STGroupTemplateDefItemPresentation(ASTWrapperPsiElement psiElement) {
this.psiElement = psiElement;
}
@Nullable
@Override
public String getPresentableText() {
ASTNode id = psiElement.getNode().findChildByType(getTokenElementType(STGLexer.ID));
if (id == null) {
return null;
}
StringBuilder text = new StringBuilder(id.getText());
| // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/structview/STGroupTemplateDefItemPresentation.java
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.lang.ASTNode;
import com.intellij.navigation.ItemPresentation;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.Arrays;
import java.util.stream.Collectors;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.structview;
public class STGroupTemplateDefItemPresentation implements ItemPresentation {
private final ASTWrapperPsiElement psiElement;
public STGroupTemplateDefItemPresentation(ASTWrapperPsiElement psiElement) {
this.psiElement = psiElement;
}
@Nullable
@Override
public String getPresentableText() {
ASTNode id = psiElement.getNode().findChildByType(getTokenElementType(STGLexer.ID));
if (id == null) {
return null;
}
StringBuilder text = new StringBuilder(id.getText());
| ASTNode args = psiElement.getNode().findChildByType(getRuleElementType(STGParser.RULE_formalArgs)); |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/structview/STGroupTemplateDefItemPresentation.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.lang.ASTNode;
import com.intellij.navigation.ItemPresentation;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.Arrays;
import java.util.stream.Collectors;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType; | return null;
}
StringBuilder text = new StringBuilder(id.getText());
ASTNode args = psiElement.getNode().findChildByType(getRuleElementType(STGParser.RULE_formalArgs));
if (args != null) {
text.append('(');
ASTNode[] argList = args.getChildren(TokenSet.create(getRuleElementType(STGParser.RULE_formalArg)));
text.append(Arrays.stream(argList).map(ASTNode::getText).collect(Collectors.joining(", ")));
text.append(')');
}
return text.toString();
}
@Nullable
@Override
public String getLocationString() {
return null;
}
@Nullable
@Override
public Icon getIcon(boolean unused) {
if (psiElement.getNode().getElementType() == getRuleElementType(STGParser.RULE_dict)) { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/structview/STGroupTemplateDefItemPresentation.java
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.lang.ASTNode;
import com.intellij.navigation.ItemPresentation;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.Arrays;
import java.util.stream.Collectors;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType;
return null;
}
StringBuilder text = new StringBuilder(id.getText());
ASTNode args = psiElement.getNode().findChildByType(getRuleElementType(STGParser.RULE_formalArgs));
if (args != null) {
text.append('(');
ASTNode[] argList = args.getChildren(TokenSet.create(getRuleElementType(STGParser.RULE_formalArg)));
text.append(Arrays.stream(argList).map(ASTNode::getText).collect(Collectors.joining(", ")));
text.append(')');
}
return text.toString();
}
@Nullable
@Override
public String getLocationString() {
return null;
}
@Nullable
@Override
public Icon getIcon(boolean unused) {
if (psiElement.getNode().getElementType() == getRuleElementType(STGParser.RULE_dict)) { | return Icons.DICT; |
antlr/jetbrains-plugin-st4 | src/test/java/org/antlr/jetbrains/st4plugin/psi/TemplateContentLiteralTextEscaperTest.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupLanguage.java
// public class STGroupLanguage extends Language {
// public static final STGroupLanguage INSTANCE = new STGroupLanguage();
//
// private STGroupLanguage() {
// super("STGroup");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import org.antlr.intellij.adaptor.lexer.PSIElementTypeFactory;
import org.antlr.jetbrains.st4plugin.STGroupLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.internal.stubbing.answers.ThrowsException;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock; | package org.antlr.jetbrains.st4plugin.psi;
public class TemplateContentLiteralTextEscaperTest {
private TemplateContentLiteralTextEscaper escaper;
@BeforeClass
public static void beforeClass() {
PSIElementTypeFactory.defineLanguageIElementTypes( | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupLanguage.java
// public class STGroupLanguage extends Language {
// public static final STGroupLanguage INSTANCE = new STGroupLanguage();
//
// private STGroupLanguage() {
// super("STGroup");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/test/java/org/antlr/jetbrains/st4plugin/psi/TemplateContentLiteralTextEscaperTest.java
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import org.antlr.intellij.adaptor.lexer.PSIElementTypeFactory;
import org.antlr.jetbrains.st4plugin.STGroupLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.internal.stubbing.answers.ThrowsException;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
package org.antlr.jetbrains.st4plugin.psi;
public class TemplateContentLiteralTextEscaperTest {
private TemplateContentLiteralTextEscaper escaper;
@BeforeClass
public static void beforeClass() {
PSIElementTypeFactory.defineLanguageIElementTypes( | STGroupLanguage.INSTANCE, |
antlr/jetbrains-plugin-st4 | src/test/java/org/antlr/jetbrains/st4plugin/psi/TemplateContentLiteralTextEscaperTest.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupLanguage.java
// public class STGroupLanguage extends Language {
// public static final STGroupLanguage INSTANCE = new STGroupLanguage();
//
// private STGroupLanguage() {
// super("STGroup");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import org.antlr.intellij.adaptor.lexer.PSIElementTypeFactory;
import org.antlr.jetbrains.st4plugin.STGroupLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.internal.stubbing.answers.ThrowsException;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock; |
TemplateContentElement template = parse(templateText);
escaper = new TemplateContentLiteralTextEscaper(template);
TextRange rangeInsideHost = TextRange.create(1, templateText.length() - 1);
StringBuilder outBuilder = new StringBuilder();
// When
escaper.decode(rangeInsideHost, outBuilder);
// Then
assertEquals("format=\"cap\";", outBuilder.toString());
assertEquals(1, escaper.getOffsetInHost(0, rangeInsideHost)); // f
assertEquals(2, escaper.getOffsetInHost(1, rangeInsideHost)); // o
assertEquals(3, escaper.getOffsetInHost(2, rangeInsideHost)); // r
assertEquals(9, escaper.getOffsetInHost(7, rangeInsideHost)); // "
assertEquals(10, escaper.getOffsetInHost(8, rangeInsideHost)); // c
assertEquals(14, escaper.getOffsetInHost(11, rangeInsideHost)); // "
assertEquals(15, escaper.getOffsetInHost(12, rangeInsideHost)); // ;
}
private TemplateContentElement parse(String raw) {
TemplateContentElement template = mock(TemplateContentElement.class, new ThrowsException(new UnsupportedOperationException()));
ASTNode astNode = mock(ASTNode.class);
doReturn(raw).when(template).getText();
doReturn(astNode).when(template).getNode();
doReturn(astNode).when(astNode).getFirstChildNode(); | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupLanguage.java
// public class STGroupLanguage extends Language {
// public static final STGroupLanguage INSTANCE = new STGroupLanguage();
//
// private STGroupLanguage() {
// super("STGroup");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/test/java/org/antlr/jetbrains/st4plugin/psi/TemplateContentLiteralTextEscaperTest.java
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import org.antlr.intellij.adaptor.lexer.PSIElementTypeFactory;
import org.antlr.jetbrains.st4plugin.STGroupLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.internal.stubbing.answers.ThrowsException;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
TemplateContentElement template = parse(templateText);
escaper = new TemplateContentLiteralTextEscaper(template);
TextRange rangeInsideHost = TextRange.create(1, templateText.length() - 1);
StringBuilder outBuilder = new StringBuilder();
// When
escaper.decode(rangeInsideHost, outBuilder);
// Then
assertEquals("format=\"cap\";", outBuilder.toString());
assertEquals(1, escaper.getOffsetInHost(0, rangeInsideHost)); // f
assertEquals(2, escaper.getOffsetInHost(1, rangeInsideHost)); // o
assertEquals(3, escaper.getOffsetInHost(2, rangeInsideHost)); // r
assertEquals(9, escaper.getOffsetInHost(7, rangeInsideHost)); // "
assertEquals(10, escaper.getOffsetInHost(8, rangeInsideHost)); // c
assertEquals(14, escaper.getOffsetInHost(11, rangeInsideHost)); // "
assertEquals(15, escaper.getOffsetInHost(12, rangeInsideHost)); // ;
}
private TemplateContentElement parse(String raw) {
TemplateContentElement template = mock(TemplateContentElement.class, new ThrowsException(new UnsupportedOperationException()));
ASTNode astNode = mock(ASTNode.class);
doReturn(raw).when(template).getText();
doReturn(astNode).when(template).getNode();
doReturn(astNode).when(astNode).getFirstChildNode(); | doReturn(getTokenElementType(STGLexer.STRING)).when(astNode).getElementType(); |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/psi/TemplateContentLiteralTextEscaper.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.openapi.util.TextRange;
import com.intellij.psi.LiteralTextEscaper;
import com.intellij.psi.PsiLanguageInjectionHost;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.jetbrains.annotations.NotNull;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.psi;
/**
* Removes escaped quotes from subtemplates when parsing them as {@link org.antlr.jetbrains.st4plugin.STLanguage}
* files.
*/
class TemplateContentLiteralTextEscaper extends LiteralTextEscaper<PsiLanguageInjectionHost> {
private int[] offsetsFromDecodedToHost = new int[0];
public TemplateContentLiteralTextEscaper(TemplateContentElement templateContentElement) {
super(templateContentElement);
}
@Override
public boolean decode(@NotNull TextRange rangeInsideHost, @NotNull StringBuilder outChars) {
String subTemplate = rangeInsideHost.substring(myHost.getText());
| // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/TemplateContentLiteralTextEscaper.java
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.LiteralTextEscaper;
import com.intellij.psi.PsiLanguageInjectionHost;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.jetbrains.annotations.NotNull;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.psi;
/**
* Removes escaped quotes from subtemplates when parsing them as {@link org.antlr.jetbrains.st4plugin.STLanguage}
* files.
*/
class TemplateContentLiteralTextEscaper extends LiteralTextEscaper<PsiLanguageInjectionHost> {
private int[] offsetsFromDecodedToHost = new int[0];
public TemplateContentLiteralTextEscaper(TemplateContentElement templateContentElement) {
super(templateContentElement);
}
@Override
public boolean decode(@NotNull TextRange rangeInsideHost, @NotNull StringBuilder outChars) {
String subTemplate = rangeInsideHost.substring(myHost.getText());
| if (myHost.getNode().getFirstChildNode().getElementType() == getTokenElementType(STGLexer.STRING) |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/highlight/STGroupBraceMatcher.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lang.BracePair;
import com.intellij.lang.PairedBraceMatcher;
import com.intellij.psi.PsiFile;
import com.intellij.psi.tree.IElementType;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.highlight;
public class STGroupBraceMatcher implements PairedBraceMatcher {
private static final BracePair[] PAIRS = { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/highlight/STGroupBraceMatcher.java
import com.intellij.lang.BracePair;
import com.intellij.lang.PairedBraceMatcher;
import com.intellij.psi.PsiFile;
import com.intellij.psi.tree.IElementType;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.highlight;
public class STGroupBraceMatcher implements PairedBraceMatcher {
private static final BracePair[] PAIRS = { | new BracePair(getTokenElementType(STGLexer.LBRACK), getTokenElementType(STGLexer.RBRACK), true), |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/folding/STGroupFoldingBuilder.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupFile.java
// public class STGroupFile extends PsiFileBase {
//
// protected STGroupFile(@NotNull FileViewProvider viewProvider) {
// super(viewProvider, STGroupLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public FileType getFileType() {
// return STGroupFileType.INSTANCE;
// }
//
// @Override
// public String toString() {
// return "String Template group file";
// }
//
// @Nullable
// @Override
// public Icon getIcon(int flags) {
// return Icons.STG_FILE;
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lang.ASTNode;
import com.intellij.lang.folding.CustomFoldingBuilder;
import com.intellij.lang.folding.FoldingDescriptor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiTreeUtil;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.antlr.jetbrains.st4plugin.psi.STGroupFile;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.folding;
public class STGroupFoldingBuilder extends CustomFoldingBuilder {
@Override
protected void buildLanguageFoldRegions(@NotNull List<FoldingDescriptor> descriptors,
@NotNull PsiElement root,
@NotNull Document document,
boolean quick) { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupFile.java
// public class STGroupFile extends PsiFileBase {
//
// protected STGroupFile(@NotNull FileViewProvider viewProvider) {
// super(viewProvider, STGroupLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public FileType getFileType() {
// return STGroupFileType.INSTANCE;
// }
//
// @Override
// public String toString() {
// return "String Template group file";
// }
//
// @Nullable
// @Override
// public Icon getIcon(int flags) {
// return Icons.STG_FILE;
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/folding/STGroupFoldingBuilder.java
import com.intellij.lang.ASTNode;
import com.intellij.lang.folding.CustomFoldingBuilder;
import com.intellij.lang.folding.FoldingDescriptor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiTreeUtil;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.antlr.jetbrains.st4plugin.psi.STGroupFile;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.folding;
public class STGroupFoldingBuilder extends CustomFoldingBuilder {
@Override
protected void buildLanguageFoldRegions(@NotNull List<FoldingDescriptor> descriptors,
@NotNull PsiElement root,
@NotNull Document document,
boolean quick) { | if (!(root instanceof STGroupFile)) { |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/folding/STGroupFoldingBuilder.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupFile.java
// public class STGroupFile extends PsiFileBase {
//
// protected STGroupFile(@NotNull FileViewProvider viewProvider) {
// super(viewProvider, STGroupLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public FileType getFileType() {
// return STGroupFileType.INSTANCE;
// }
//
// @Override
// public String toString() {
// return "String Template group file";
// }
//
// @Nullable
// @Override
// public Icon getIcon(int flags) {
// return Icons.STG_FILE;
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lang.ASTNode;
import com.intellij.lang.folding.CustomFoldingBuilder;
import com.intellij.lang.folding.FoldingDescriptor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiTreeUtil;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.antlr.jetbrains.st4plugin.psi.STGroupFile;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.folding;
public class STGroupFoldingBuilder extends CustomFoldingBuilder {
@Override
protected void buildLanguageFoldRegions(@NotNull List<FoldingDescriptor> descriptors,
@NotNull PsiElement root,
@NotNull Document document,
boolean quick) {
if (!(root instanceof STGroupFile)) {
return;
}
foldTemplates(descriptors, root);
foldDicts(descriptors, root);
foldComments(descriptors, root);
}
private void foldTemplates(List<FoldingDescriptor> descriptors, PsiElement root) {
PsiTreeUtil.processElements(root, element -> { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupFile.java
// public class STGroupFile extends PsiFileBase {
//
// protected STGroupFile(@NotNull FileViewProvider viewProvider) {
// super(viewProvider, STGroupLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public FileType getFileType() {
// return STGroupFileType.INSTANCE;
// }
//
// @Override
// public String toString() {
// return "String Template group file";
// }
//
// @Nullable
// @Override
// public Icon getIcon(int flags) {
// return Icons.STG_FILE;
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/folding/STGroupFoldingBuilder.java
import com.intellij.lang.ASTNode;
import com.intellij.lang.folding.CustomFoldingBuilder;
import com.intellij.lang.folding.FoldingDescriptor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiTreeUtil;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.antlr.jetbrains.st4plugin.psi.STGroupFile;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.folding;
public class STGroupFoldingBuilder extends CustomFoldingBuilder {
@Override
protected void buildLanguageFoldRegions(@NotNull List<FoldingDescriptor> descriptors,
@NotNull PsiElement root,
@NotNull Document document,
boolean quick) {
if (!(root instanceof STGroupFile)) {
return;
}
foldTemplates(descriptors, root);
foldDicts(descriptors, root);
foldComments(descriptors, root);
}
private void foldTemplates(List<FoldingDescriptor> descriptors, PsiElement root) {
PsiTreeUtil.processElements(root, element -> { | if (element.getNode().getElementType() == getRuleElementType(STGParser.RULE_templateContent)) { |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/folding/STGroupFoldingBuilder.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupFile.java
// public class STGroupFile extends PsiFileBase {
//
// protected STGroupFile(@NotNull FileViewProvider viewProvider) {
// super(viewProvider, STGroupLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public FileType getFileType() {
// return STGroupFileType.INSTANCE;
// }
//
// @Override
// public String toString() {
// return "String Template group file";
// }
//
// @Nullable
// @Override
// public Icon getIcon(int flags) {
// return Icons.STG_FILE;
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lang.ASTNode;
import com.intellij.lang.folding.CustomFoldingBuilder;
import com.intellij.lang.folding.FoldingDescriptor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiTreeUtil;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.antlr.jetbrains.st4plugin.psi.STGroupFile;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.folding;
public class STGroupFoldingBuilder extends CustomFoldingBuilder {
@Override
protected void buildLanguageFoldRegions(@NotNull List<FoldingDescriptor> descriptors,
@NotNull PsiElement root,
@NotNull Document document,
boolean quick) {
if (!(root instanceof STGroupFile)) {
return;
}
foldTemplates(descriptors, root);
foldDicts(descriptors, root);
foldComments(descriptors, root);
}
private void foldTemplates(List<FoldingDescriptor> descriptors, PsiElement root) {
PsiTreeUtil.processElements(root, element -> {
if (element.getNode().getElementType() == getRuleElementType(STGParser.RULE_templateContent)) {
ASTNode bigString = element.getNode().findChildByType(TokenSet.create( | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupFile.java
// public class STGroupFile extends PsiFileBase {
//
// protected STGroupFile(@NotNull FileViewProvider viewProvider) {
// super(viewProvider, STGroupLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public FileType getFileType() {
// return STGroupFileType.INSTANCE;
// }
//
// @Override
// public String toString() {
// return "String Template group file";
// }
//
// @Nullable
// @Override
// public Icon getIcon(int flags) {
// return Icons.STG_FILE;
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/folding/STGroupFoldingBuilder.java
import com.intellij.lang.ASTNode;
import com.intellij.lang.folding.CustomFoldingBuilder;
import com.intellij.lang.folding.FoldingDescriptor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiTreeUtil;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.antlr.jetbrains.st4plugin.psi.STGroupFile;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.folding;
public class STGroupFoldingBuilder extends CustomFoldingBuilder {
@Override
protected void buildLanguageFoldRegions(@NotNull List<FoldingDescriptor> descriptors,
@NotNull PsiElement root,
@NotNull Document document,
boolean quick) {
if (!(root instanceof STGroupFile)) {
return;
}
foldTemplates(descriptors, root);
foldDicts(descriptors, root);
foldComments(descriptors, root);
}
private void foldTemplates(List<FoldingDescriptor> descriptors, PsiElement root) {
PsiTreeUtil.processElements(root, element -> {
if (element.getNode().getElementType() == getRuleElementType(STGParser.RULE_templateContent)) {
ASTNode bigString = element.getNode().findChildByType(TokenSet.create( | getTokenElementType(STGLexer.BIGSTRING), |
antlr/jetbrains-plugin-st4 | src/test/java/org/antlr/jetbrains/st4plugin/structview/STGroupTemplateDefItemPresentationTest.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupFileType.java
// public class STGroupFileType extends LanguageFileType implements TemplateLanguageFileType {
// public static final STGroupFileType INSTANCE = new STGroupFileType();
//
// protected STGroupFileType() {
// super(STGroupLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return "stg";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return Icons.STG_FILE;
// }
//
// static class Factory extends FileTypeFactory {
// @Override
// public void createFileTypes(@NotNull FileTypeConsumer consumer) {
// consumer.consume(STGroupFileType.INSTANCE);
// }
// }
// }
| import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.testFramework.fixtures.CodeInsightFixtureTestCase;
import javax.swing.Icon;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.STGroupFileType;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.jetbrains.annotations.NotNull; | package org.antlr.jetbrains.st4plugin.structview;
public class STGroupTemplateDefItemPresentationTest extends CodeInsightFixtureTestCase {
public void testIssue37() {
// Given
ASTWrapperPsiElement template = parseTemplate("A() ::= ");
STGroupTemplateDefItemPresentation presentation = new STGroupTemplateDefItemPresentation(template);
// When
Icon icon = presentation.getIcon(false);
// Then | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupFileType.java
// public class STGroupFileType extends LanguageFileType implements TemplateLanguageFileType {
// public static final STGroupFileType INSTANCE = new STGroupFileType();
//
// protected STGroupFileType() {
// super(STGroupLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return "stg";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return Icons.STG_FILE;
// }
//
// static class Factory extends FileTypeFactory {
// @Override
// public void createFileTypes(@NotNull FileTypeConsumer consumer) {
// consumer.consume(STGroupFileType.INSTANCE);
// }
// }
// }
// Path: src/test/java/org/antlr/jetbrains/st4plugin/structview/STGroupTemplateDefItemPresentationTest.java
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.testFramework.fixtures.CodeInsightFixtureTestCase;
import javax.swing.Icon;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.STGroupFileType;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.jetbrains.annotations.NotNull;
package org.antlr.jetbrains.st4plugin.structview;
public class STGroupTemplateDefItemPresentationTest extends CodeInsightFixtureTestCase {
public void testIssue37() {
// Given
ASTWrapperPsiElement template = parseTemplate("A() ::= ");
STGroupTemplateDefItemPresentation presentation = new STGroupTemplateDefItemPresentation(template);
// When
Icon icon = presentation.getIcon(false);
// Then | assertSame(template.getNode().getElementType(), getRuleElementType(STGParser.RULE_template)); |
antlr/jetbrains-plugin-st4 | src/test/java/org/antlr/jetbrains/st4plugin/structview/STGroupTemplateDefItemPresentationTest.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupFileType.java
// public class STGroupFileType extends LanguageFileType implements TemplateLanguageFileType {
// public static final STGroupFileType INSTANCE = new STGroupFileType();
//
// protected STGroupFileType() {
// super(STGroupLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return "stg";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return Icons.STG_FILE;
// }
//
// static class Factory extends FileTypeFactory {
// @Override
// public void createFileTypes(@NotNull FileTypeConsumer consumer) {
// consumer.consume(STGroupFileType.INSTANCE);
// }
// }
// }
| import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.testFramework.fixtures.CodeInsightFixtureTestCase;
import javax.swing.Icon;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.STGroupFileType;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.jetbrains.annotations.NotNull; | package org.antlr.jetbrains.st4plugin.structview;
public class STGroupTemplateDefItemPresentationTest extends CodeInsightFixtureTestCase {
public void testIssue37() {
// Given
ASTWrapperPsiElement template = parseTemplate("A() ::= ");
STGroupTemplateDefItemPresentation presentation = new STGroupTemplateDefItemPresentation(template);
// When
Icon icon = presentation.getIcon(false);
// Then
assertSame(template.getNode().getElementType(), getRuleElementType(STGParser.RULE_template)); | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupFileType.java
// public class STGroupFileType extends LanguageFileType implements TemplateLanguageFileType {
// public static final STGroupFileType INSTANCE = new STGroupFileType();
//
// protected STGroupFileType() {
// super(STGroupLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return "stg";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return Icons.STG_FILE;
// }
//
// static class Factory extends FileTypeFactory {
// @Override
// public void createFileTypes(@NotNull FileTypeConsumer consumer) {
// consumer.consume(STGroupFileType.INSTANCE);
// }
// }
// }
// Path: src/test/java/org/antlr/jetbrains/st4plugin/structview/STGroupTemplateDefItemPresentationTest.java
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.testFramework.fixtures.CodeInsightFixtureTestCase;
import javax.swing.Icon;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.STGroupFileType;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.jetbrains.annotations.NotNull;
package org.antlr.jetbrains.st4plugin.structview;
public class STGroupTemplateDefItemPresentationTest extends CodeInsightFixtureTestCase {
public void testIssue37() {
// Given
ASTWrapperPsiElement template = parseTemplate("A() ::= ");
STGroupTemplateDefItemPresentation presentation = new STGroupTemplateDefItemPresentation(template);
// When
Icon icon = presentation.getIcon(false);
// Then
assertSame(template.getNode().getElementType(), getRuleElementType(STGParser.RULE_template)); | assertEquals(Icons.BIGSTRING, icon); |
antlr/jetbrains-plugin-st4 | src/test/java/org/antlr/jetbrains/st4plugin/structview/STGroupTemplateDefItemPresentationTest.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupFileType.java
// public class STGroupFileType extends LanguageFileType implements TemplateLanguageFileType {
// public static final STGroupFileType INSTANCE = new STGroupFileType();
//
// protected STGroupFileType() {
// super(STGroupLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return "stg";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return Icons.STG_FILE;
// }
//
// static class Factory extends FileTypeFactory {
// @Override
// public void createFileTypes(@NotNull FileTypeConsumer consumer) {
// consumer.consume(STGroupFileType.INSTANCE);
// }
// }
// }
| import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.testFramework.fixtures.CodeInsightFixtureTestCase;
import javax.swing.Icon;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.STGroupFileType;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.jetbrains.annotations.NotNull; |
STGroupTemplateDefItemPresentation presentation = new STGroupTemplateDefItemPresentation(template);
// When
Icon icon = presentation.getIcon(false);
String text = presentation.getPresentableText();
// Then
assertEquals(Icons.BIGSTRING_NONL, icon);
assertEquals("bigStringNoNl(foo, bar)", text);
}
public void testTemplateAlias() {
// Given
ASTWrapperPsiElement template = parseTemplate("foo ::= bar");
STGroupTemplateDefItemPresentation presentation = new STGroupTemplateDefItemPresentation(template);
// When
Icon icon = presentation.getIcon(false);
String text = presentation.getPresentableText();
// Then
assertEquals(Icons.BIGSTRING, icon);
assertEquals("foo", text);
}
@NotNull
private ASTWrapperPsiElement parseTemplate(String content) {
PsiFile file = PsiFileFactory.getInstance(myFixture.getProject()) | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupFileType.java
// public class STGroupFileType extends LanguageFileType implements TemplateLanguageFileType {
// public static final STGroupFileType INSTANCE = new STGroupFileType();
//
// protected STGroupFileType() {
// super(STGroupLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return "stg";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return Icons.STG_FILE;
// }
//
// static class Factory extends FileTypeFactory {
// @Override
// public void createFileTypes(@NotNull FileTypeConsumer consumer) {
// consumer.consume(STGroupFileType.INSTANCE);
// }
// }
// }
// Path: src/test/java/org/antlr/jetbrains/st4plugin/structview/STGroupTemplateDefItemPresentationTest.java
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.testFramework.fixtures.CodeInsightFixtureTestCase;
import javax.swing.Icon;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.STGroupFileType;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.jetbrains.annotations.NotNull;
STGroupTemplateDefItemPresentation presentation = new STGroupTemplateDefItemPresentation(template);
// When
Icon icon = presentation.getIcon(false);
String text = presentation.getPresentableText();
// Then
assertEquals(Icons.BIGSTRING_NONL, icon);
assertEquals("bigStringNoNl(foo, bar)", text);
}
public void testTemplateAlias() {
// Given
ASTWrapperPsiElement template = parseTemplate("foo ::= bar");
STGroupTemplateDefItemPresentation presentation = new STGroupTemplateDefItemPresentation(template);
// When
Icon icon = presentation.getIcon(false);
String text = presentation.getPresentableText();
// Then
assertEquals(Icons.BIGSTRING, icon);
assertEquals("foo", text);
}
@NotNull
private ASTWrapperPsiElement parseTemplate(String content) {
PsiFile file = PsiFileFactory.getInstance(myFixture.getProject()) | .createFileFromText("a.stg", STGroupFileType.INSTANCE, content); |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/psi/STLanguageInjector.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STLanguage.java
// public class STLanguage extends Language {
//
// public static final STLanguage INSTANCE = new STLanguage();
//
// private STLanguage() {
// super("ST");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/parsing/LexerAdaptor.java
// public static final char DELIMITERS_PREFIX = '\u0001';
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.InjectedLanguagePlaces;
import com.intellij.psi.LanguageInjector;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiLanguageInjectionHost;
import com.intellij.psi.tree.TokenSet;
import org.antlr.jetbrains.st4plugin.STLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.jetbrains.annotations.NotNull;
import static org.antlr.jetbrains.st4plugin.parsing.LexerAdaptor.DELIMITERS_PREFIX;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.psi;
/**
* Inject the {@link STLanguage} in {@link org.antlr.jetbrains.st4plugin.STGroupLanguage} subtemplates.
*/
public class STLanguageInjector implements LanguageInjector {
@Override
public void getLanguagesToInject(@NotNull PsiLanguageInjectionHost host,
@NotNull InjectedLanguagePlaces injectionPlacesRegistrar) {
if (host instanceof TemplateContentElement) {
PsiElement firstChild = host.getFirstChild();
String delimiters = detectDelimiters(host);
if (firstChild != null | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STLanguage.java
// public class STLanguage extends Language {
//
// public static final STLanguage INSTANCE = new STLanguage();
//
// private STLanguage() {
// super("ST");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/parsing/LexerAdaptor.java
// public static final char DELIMITERS_PREFIX = '\u0001';
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STLanguageInjector.java
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.InjectedLanguagePlaces;
import com.intellij.psi.LanguageInjector;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiLanguageInjectionHost;
import com.intellij.psi.tree.TokenSet;
import org.antlr.jetbrains.st4plugin.STLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.jetbrains.annotations.NotNull;
import static org.antlr.jetbrains.st4plugin.parsing.LexerAdaptor.DELIMITERS_PREFIX;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.psi;
/**
* Inject the {@link STLanguage} in {@link org.antlr.jetbrains.st4plugin.STGroupLanguage} subtemplates.
*/
public class STLanguageInjector implements LanguageInjector {
@Override
public void getLanguagesToInject(@NotNull PsiLanguageInjectionHost host,
@NotNull InjectedLanguagePlaces injectionPlacesRegistrar) {
if (host instanceof TemplateContentElement) {
PsiElement firstChild = host.getFirstChild();
String delimiters = detectDelimiters(host);
if (firstChild != null | && (firstChild.getNode().getElementType() == getTokenElementType(STGLexer.BIGSTRING) || firstChild.getNode().getElementType() == getTokenElementType(STGLexer.BIGSTRING_NO_NL)) |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/psi/STLanguageInjector.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STLanguage.java
// public class STLanguage extends Language {
//
// public static final STLanguage INSTANCE = new STLanguage();
//
// private STLanguage() {
// super("ST");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/parsing/LexerAdaptor.java
// public static final char DELIMITERS_PREFIX = '\u0001';
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.InjectedLanguagePlaces;
import com.intellij.psi.LanguageInjector;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiLanguageInjectionHost;
import com.intellij.psi.tree.TokenSet;
import org.antlr.jetbrains.st4plugin.STLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.jetbrains.annotations.NotNull;
import static org.antlr.jetbrains.st4plugin.parsing.LexerAdaptor.DELIMITERS_PREFIX;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.psi;
/**
* Inject the {@link STLanguage} in {@link org.antlr.jetbrains.st4plugin.STGroupLanguage} subtemplates.
*/
public class STLanguageInjector implements LanguageInjector {
@Override
public void getLanguagesToInject(@NotNull PsiLanguageInjectionHost host,
@NotNull InjectedLanguagePlaces injectionPlacesRegistrar) {
if (host instanceof TemplateContentElement) {
PsiElement firstChild = host.getFirstChild();
String delimiters = detectDelimiters(host);
if (firstChild != null
&& (firstChild.getNode().getElementType() == getTokenElementType(STGLexer.BIGSTRING) || firstChild.getNode().getElementType() == getTokenElementType(STGLexer.BIGSTRING_NO_NL))
&& host.getTextLength() > 4) {
TextRange textRange = TextRange.create(2, host.getTextLength() - 2); | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STLanguage.java
// public class STLanguage extends Language {
//
// public static final STLanguage INSTANCE = new STLanguage();
//
// private STLanguage() {
// super("ST");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/parsing/LexerAdaptor.java
// public static final char DELIMITERS_PREFIX = '\u0001';
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STLanguageInjector.java
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.InjectedLanguagePlaces;
import com.intellij.psi.LanguageInjector;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiLanguageInjectionHost;
import com.intellij.psi.tree.TokenSet;
import org.antlr.jetbrains.st4plugin.STLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.jetbrains.annotations.NotNull;
import static org.antlr.jetbrains.st4plugin.parsing.LexerAdaptor.DELIMITERS_PREFIX;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.psi;
/**
* Inject the {@link STLanguage} in {@link org.antlr.jetbrains.st4plugin.STGroupLanguage} subtemplates.
*/
public class STLanguageInjector implements LanguageInjector {
@Override
public void getLanguagesToInject(@NotNull PsiLanguageInjectionHost host,
@NotNull InjectedLanguagePlaces injectionPlacesRegistrar) {
if (host instanceof TemplateContentElement) {
PsiElement firstChild = host.getFirstChild();
String delimiters = detectDelimiters(host);
if (firstChild != null
&& (firstChild.getNode().getElementType() == getTokenElementType(STGLexer.BIGSTRING) || firstChild.getNode().getElementType() == getTokenElementType(STGLexer.BIGSTRING_NO_NL))
&& host.getTextLength() > 4) {
TextRange textRange = TextRange.create(2, host.getTextLength() - 2); | injectionPlacesRegistrar.addPlace(STLanguage.INSTANCE, textRange, delimiters, null); |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/psi/STLanguageInjector.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STLanguage.java
// public class STLanguage extends Language {
//
// public static final STLanguage INSTANCE = new STLanguage();
//
// private STLanguage() {
// super("ST");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/parsing/LexerAdaptor.java
// public static final char DELIMITERS_PREFIX = '\u0001';
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.InjectedLanguagePlaces;
import com.intellij.psi.LanguageInjector;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiLanguageInjectionHost;
import com.intellij.psi.tree.TokenSet;
import org.antlr.jetbrains.st4plugin.STLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.jetbrains.annotations.NotNull;
import static org.antlr.jetbrains.st4plugin.parsing.LexerAdaptor.DELIMITERS_PREFIX;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.psi;
/**
* Inject the {@link STLanguage} in {@link org.antlr.jetbrains.st4plugin.STGroupLanguage} subtemplates.
*/
public class STLanguageInjector implements LanguageInjector {
@Override
public void getLanguagesToInject(@NotNull PsiLanguageInjectionHost host,
@NotNull InjectedLanguagePlaces injectionPlacesRegistrar) {
if (host instanceof TemplateContentElement) {
PsiElement firstChild = host.getFirstChild();
String delimiters = detectDelimiters(host);
if (firstChild != null
&& (firstChild.getNode().getElementType() == getTokenElementType(STGLexer.BIGSTRING) || firstChild.getNode().getElementType() == getTokenElementType(STGLexer.BIGSTRING_NO_NL))
&& host.getTextLength() > 4) {
TextRange textRange = TextRange.create(2, host.getTextLength() - 2);
injectionPlacesRegistrar.addPlace(STLanguage.INSTANCE, textRange, delimiters, null);
} else if (firstChild != null
&& firstChild.getNode().getElementType() == getTokenElementType(STGLexer.STRING)
&& host.getTextLength() > 2) {
TextRange textRange = TextRange.create(1, host.getTextLength() - 1);
injectionPlacesRegistrar.addPlace(STLanguage.INSTANCE, textRange, delimiters, null);
}
}
}
/**
* If the STGroup file contains a {@code delimiters "x", "y"} section, we pass those delimiters as a special
* prefix to the lexer. The lexer will then detect this prefix and reconfigure itself to support the new
* delimiters.
*/
private String detectDelimiters(@NotNull PsiLanguageInjectionHost host) {
ASTNode root = host.getContainingFile().getFirstChild().getNode();
| // Path: src/main/java/org/antlr/jetbrains/st4plugin/STLanguage.java
// public class STLanguage extends Language {
//
// public static final STLanguage INSTANCE = new STLanguage();
//
// private STLanguage() {
// super("ST");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/parsing/LexerAdaptor.java
// public static final char DELIMITERS_PREFIX = '\u0001';
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STLanguageInjector.java
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.InjectedLanguagePlaces;
import com.intellij.psi.LanguageInjector;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiLanguageInjectionHost;
import com.intellij.psi.tree.TokenSet;
import org.antlr.jetbrains.st4plugin.STLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.jetbrains.annotations.NotNull;
import static org.antlr.jetbrains.st4plugin.parsing.LexerAdaptor.DELIMITERS_PREFIX;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.psi;
/**
* Inject the {@link STLanguage} in {@link org.antlr.jetbrains.st4plugin.STGroupLanguage} subtemplates.
*/
public class STLanguageInjector implements LanguageInjector {
@Override
public void getLanguagesToInject(@NotNull PsiLanguageInjectionHost host,
@NotNull InjectedLanguagePlaces injectionPlacesRegistrar) {
if (host instanceof TemplateContentElement) {
PsiElement firstChild = host.getFirstChild();
String delimiters = detectDelimiters(host);
if (firstChild != null
&& (firstChild.getNode().getElementType() == getTokenElementType(STGLexer.BIGSTRING) || firstChild.getNode().getElementType() == getTokenElementType(STGLexer.BIGSTRING_NO_NL))
&& host.getTextLength() > 4) {
TextRange textRange = TextRange.create(2, host.getTextLength() - 2);
injectionPlacesRegistrar.addPlace(STLanguage.INSTANCE, textRange, delimiters, null);
} else if (firstChild != null
&& firstChild.getNode().getElementType() == getTokenElementType(STGLexer.STRING)
&& host.getTextLength() > 2) {
TextRange textRange = TextRange.create(1, host.getTextLength() - 1);
injectionPlacesRegistrar.addPlace(STLanguage.INSTANCE, textRange, delimiters, null);
}
}
}
/**
* If the STGroup file contains a {@code delimiters "x", "y"} section, we pass those delimiters as a special
* prefix to the lexer. The lexer will then detect this prefix and reconfigure itself to support the new
* delimiters.
*/
private String detectDelimiters(@NotNull PsiLanguageInjectionHost host) {
ASTNode root = host.getContainingFile().getFirstChild().getNode();
| if (root.getElementType() == getRuleElementType(STGParser.RULE_group)) { |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/psi/STLanguageInjector.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STLanguage.java
// public class STLanguage extends Language {
//
// public static final STLanguage INSTANCE = new STLanguage();
//
// private STLanguage() {
// super("ST");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/parsing/LexerAdaptor.java
// public static final char DELIMITERS_PREFIX = '\u0001';
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.InjectedLanguagePlaces;
import com.intellij.psi.LanguageInjector;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiLanguageInjectionHost;
import com.intellij.psi.tree.TokenSet;
import org.antlr.jetbrains.st4plugin.STLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.jetbrains.annotations.NotNull;
import static org.antlr.jetbrains.st4plugin.parsing.LexerAdaptor.DELIMITERS_PREFIX;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.psi;
/**
* Inject the {@link STLanguage} in {@link org.antlr.jetbrains.st4plugin.STGroupLanguage} subtemplates.
*/
public class STLanguageInjector implements LanguageInjector {
@Override
public void getLanguagesToInject(@NotNull PsiLanguageInjectionHost host,
@NotNull InjectedLanguagePlaces injectionPlacesRegistrar) {
if (host instanceof TemplateContentElement) {
PsiElement firstChild = host.getFirstChild();
String delimiters = detectDelimiters(host);
if (firstChild != null
&& (firstChild.getNode().getElementType() == getTokenElementType(STGLexer.BIGSTRING) || firstChild.getNode().getElementType() == getTokenElementType(STGLexer.BIGSTRING_NO_NL))
&& host.getTextLength() > 4) {
TextRange textRange = TextRange.create(2, host.getTextLength() - 2);
injectionPlacesRegistrar.addPlace(STLanguage.INSTANCE, textRange, delimiters, null);
} else if (firstChild != null
&& firstChild.getNode().getElementType() == getTokenElementType(STGLexer.STRING)
&& host.getTextLength() > 2) {
TextRange textRange = TextRange.create(1, host.getTextLength() - 1);
injectionPlacesRegistrar.addPlace(STLanguage.INSTANCE, textRange, delimiters, null);
}
}
}
/**
* If the STGroup file contains a {@code delimiters "x", "y"} section, we pass those delimiters as a special
* prefix to the lexer. The lexer will then detect this prefix and reconfigure itself to support the new
* delimiters.
*/
private String detectDelimiters(@NotNull PsiLanguageInjectionHost host) {
ASTNode root = host.getContainingFile().getFirstChild().getNode();
if (root.getElementType() == getRuleElementType(STGParser.RULE_group)) {
ASTNode delimitersStatement = root.findChildByType(getRuleElementType(STGParser.RULE_delimiters));
if (delimitersStatement != null) {
ASTNode[] strings = delimitersStatement.getChildren(TokenSet.create(getTokenElementType(STGLexer.STRING)));
if (strings.length == 2 && strings[0].getTextLength() == 3 && strings[1].getTextLength() == 3) { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STLanguage.java
// public class STLanguage extends Language {
//
// public static final STLanguage INSTANCE = new STLanguage();
//
// private STLanguage() {
// super("ST");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/parsing/LexerAdaptor.java
// public static final char DELIMITERS_PREFIX = '\u0001';
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STGParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STGroupTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STGLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STLanguageInjector.java
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.InjectedLanguagePlaces;
import com.intellij.psi.LanguageInjector;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiLanguageInjectionHost;
import com.intellij.psi.tree.TokenSet;
import org.antlr.jetbrains.st4plugin.STLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STGLexer;
import org.antlr.jetbrains.st4plugin.parsing.STGParser;
import org.jetbrains.annotations.NotNull;
import static org.antlr.jetbrains.st4plugin.parsing.LexerAdaptor.DELIMITERS_PREFIX;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STGroupTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.psi;
/**
* Inject the {@link STLanguage} in {@link org.antlr.jetbrains.st4plugin.STGroupLanguage} subtemplates.
*/
public class STLanguageInjector implements LanguageInjector {
@Override
public void getLanguagesToInject(@NotNull PsiLanguageInjectionHost host,
@NotNull InjectedLanguagePlaces injectionPlacesRegistrar) {
if (host instanceof TemplateContentElement) {
PsiElement firstChild = host.getFirstChild();
String delimiters = detectDelimiters(host);
if (firstChild != null
&& (firstChild.getNode().getElementType() == getTokenElementType(STGLexer.BIGSTRING) || firstChild.getNode().getElementType() == getTokenElementType(STGLexer.BIGSTRING_NO_NL))
&& host.getTextLength() > 4) {
TextRange textRange = TextRange.create(2, host.getTextLength() - 2);
injectionPlacesRegistrar.addPlace(STLanguage.INSTANCE, textRange, delimiters, null);
} else if (firstChild != null
&& firstChild.getNode().getElementType() == getTokenElementType(STGLexer.STRING)
&& host.getTextLength() > 2) {
TextRange textRange = TextRange.create(1, host.getTextLength() - 1);
injectionPlacesRegistrar.addPlace(STLanguage.INSTANCE, textRange, delimiters, null);
}
}
}
/**
* If the STGroup file contains a {@code delimiters "x", "y"} section, we pass those delimiters as a special
* prefix to the lexer. The lexer will then detect this prefix and reconfigure itself to support the new
* delimiters.
*/
private String detectDelimiters(@NotNull PsiLanguageInjectionHost host) {
ASTNode root = host.getContainingFile().getFirstChild().getNode();
if (root.getElementType() == getRuleElementType(STGParser.RULE_group)) {
ASTNode delimitersStatement = root.findChildByType(getRuleElementType(STGParser.RULE_delimiters));
if (delimitersStatement != null) {
ASTNode[] strings = delimitersStatement.getChildren(TokenSet.create(getTokenElementType(STGLexer.STRING)));
if (strings.length == 2 && strings[0].getTextLength() == 3 && strings[1].getTextLength() == 3) { | return "" + DELIMITERS_PREFIX + strings[0].getText().charAt(1) + strings[1].getText().charAt(1); |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/structview/STGroupStructureViewTreeElement.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
| import com.intellij.ide.structureView.StructureViewTreeElement;
import com.intellij.ide.util.treeView.smartTree.SortableTreeElement;
import com.intellij.ide.util.treeView.smartTree.TreeElement;
import com.intellij.navigation.ItemPresentation;
import com.intellij.psi.NavigatablePsiElement;
import org.antlr.jetbrains.st4plugin.Icons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*; | package org.antlr.jetbrains.st4plugin.structview;
public abstract class STGroupStructureViewTreeElement
implements StructureViewTreeElement, ItemPresentation, SortableTreeElement {
protected NavigatablePsiElement psiElement;
public STGroupStructureViewTreeElement(NavigatablePsiElement psiElement) {
this.psiElement = psiElement;
}
@Nullable
@Override
public Icon getIcon(boolean unused) { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/structview/STGroupStructureViewTreeElement.java
import com.intellij.ide.structureView.StructureViewTreeElement;
import com.intellij.ide.util.treeView.smartTree.SortableTreeElement;
import com.intellij.ide.util.treeView.smartTree.TreeElement;
import com.intellij.navigation.ItemPresentation;
import com.intellij.psi.NavigatablePsiElement;
import org.antlr.jetbrains.st4plugin.Icons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
package org.antlr.jetbrains.st4plugin.structview;
public abstract class STGroupStructureViewTreeElement
implements StructureViewTreeElement, ItemPresentation, SortableTreeElement {
protected NavigatablePsiElement psiElement;
public STGroupStructureViewTreeElement(NavigatablePsiElement psiElement) {
this.psiElement = psiElement;
}
@Nullable
@Override
public Icon getIcon(boolean unused) { | return Icons.STG_FILE; |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/folding/STFoldingBuilder.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STFile.java
// public class STFile extends PsiFileBase {
//
// protected STFile(@NotNull FileViewProvider viewProvider) {
// super(viewProvider, STLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public FileType getFileType() {
// return STFileType.INSTANCE;
// }
//
// @Override
// public String toString() {
// return "String Template file";
// }
//
// @Nullable
// @Override
// public Icon getIcon(int flags) {
// return Icons.STG_FILE;
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lang.ASTNode;
import com.intellij.lang.folding.CustomFoldingBuilder;
import com.intellij.lang.folding.FoldingDescriptor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.antlr.jetbrains.st4plugin.parsing.STParser;
import org.antlr.jetbrains.st4plugin.psi.STFile;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.folding;
public class STFoldingBuilder extends CustomFoldingBuilder {
@Override
protected void buildLanguageFoldRegions(@NotNull List<FoldingDescriptor> descriptors,
@NotNull PsiElement root,
@NotNull Document document,
boolean quick) { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STFile.java
// public class STFile extends PsiFileBase {
//
// protected STFile(@NotNull FileViewProvider viewProvider) {
// super(viewProvider, STLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public FileType getFileType() {
// return STFileType.INSTANCE;
// }
//
// @Override
// public String toString() {
// return "String Template file";
// }
//
// @Nullable
// @Override
// public Icon getIcon(int flags) {
// return Icons.STG_FILE;
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/folding/STFoldingBuilder.java
import com.intellij.lang.ASTNode;
import com.intellij.lang.folding.CustomFoldingBuilder;
import com.intellij.lang.folding.FoldingDescriptor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.antlr.jetbrains.st4plugin.parsing.STParser;
import org.antlr.jetbrains.st4plugin.psi.STFile;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.folding;
public class STFoldingBuilder extends CustomFoldingBuilder {
@Override
protected void buildLanguageFoldRegions(@NotNull List<FoldingDescriptor> descriptors,
@NotNull PsiElement root,
@NotNull Document document,
boolean quick) { | if (!(root instanceof STFile)) { |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/folding/STFoldingBuilder.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STFile.java
// public class STFile extends PsiFileBase {
//
// protected STFile(@NotNull FileViewProvider viewProvider) {
// super(viewProvider, STLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public FileType getFileType() {
// return STFileType.INSTANCE;
// }
//
// @Override
// public String toString() {
// return "String Template file";
// }
//
// @Nullable
// @Override
// public Icon getIcon(int flags) {
// return Icons.STG_FILE;
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lang.ASTNode;
import com.intellij.lang.folding.CustomFoldingBuilder;
import com.intellij.lang.folding.FoldingDescriptor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.antlr.jetbrains.st4plugin.parsing.STParser;
import org.antlr.jetbrains.st4plugin.psi.STFile;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.folding;
public class STFoldingBuilder extends CustomFoldingBuilder {
@Override
protected void buildLanguageFoldRegions(@NotNull List<FoldingDescriptor> descriptors,
@NotNull PsiElement root,
@NotNull Document document,
boolean quick) {
if (!(root instanceof STFile)) {
return;
}
foldRegions(descriptors, root);
foldIf(descriptors, root);
}
private void foldRegions(List<FoldingDescriptor> descriptors, PsiElement root) {
PsiTreeUtil.processElements(root, element -> { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STFile.java
// public class STFile extends PsiFileBase {
//
// protected STFile(@NotNull FileViewProvider viewProvider) {
// super(viewProvider, STLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public FileType getFileType() {
// return STFileType.INSTANCE;
// }
//
// @Override
// public String toString() {
// return "String Template file";
// }
//
// @Nullable
// @Override
// public Icon getIcon(int flags) {
// return Icons.STG_FILE;
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/folding/STFoldingBuilder.java
import com.intellij.lang.ASTNode;
import com.intellij.lang.folding.CustomFoldingBuilder;
import com.intellij.lang.folding.FoldingDescriptor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.antlr.jetbrains.st4plugin.parsing.STParser;
import org.antlr.jetbrains.st4plugin.psi.STFile;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.folding;
public class STFoldingBuilder extends CustomFoldingBuilder {
@Override
protected void buildLanguageFoldRegions(@NotNull List<FoldingDescriptor> descriptors,
@NotNull PsiElement root,
@NotNull Document document,
boolean quick) {
if (!(root instanceof STFile)) {
return;
}
foldRegions(descriptors, root);
foldIf(descriptors, root);
}
private void foldRegions(List<FoldingDescriptor> descriptors, PsiElement root) {
PsiTreeUtil.processElements(root, element -> { | if (element.getNode().getElementType() == getRuleElementType(STParser.RULE_region)) { |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/folding/STFoldingBuilder.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STFile.java
// public class STFile extends PsiFileBase {
//
// protected STFile(@NotNull FileViewProvider viewProvider) {
// super(viewProvider, STLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public FileType getFileType() {
// return STFileType.INSTANCE;
// }
//
// @Override
// public String toString() {
// return "String Template file";
// }
//
// @Nullable
// @Override
// public Icon getIcon(int flags) {
// return Icons.STG_FILE;
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lang.ASTNode;
import com.intellij.lang.folding.CustomFoldingBuilder;
import com.intellij.lang.folding.FoldingDescriptor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.antlr.jetbrains.st4plugin.parsing.STParser;
import org.antlr.jetbrains.st4plugin.psi.STFile;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType; | return;
}
foldRegions(descriptors, root);
foldIf(descriptors, root);
}
private void foldRegions(List<FoldingDescriptor> descriptors, PsiElement root) {
PsiTreeUtil.processElements(root, element -> {
if (element.getNode().getElementType() == getRuleElementType(STParser.RULE_region)) {
descriptors.add(new FoldingDescriptor(element, element.getTextRange()));
}
return true;
});
}
private void foldIf(List<FoldingDescriptor> descriptors, PsiElement root) {
PsiTreeUtil.processElements(root, element -> {
if (element.getNode().getElementType() == getRuleElementType(STParser.RULE_ifstat)) {
descriptors.add(new FoldingDescriptor(element, element.getTextRange()));
}
return true;
});
}
@Override
protected String getLanguagePlaceholderText(@NotNull ASTNode node, @NotNull TextRange range) {
if (node.getElementType() == getRuleElementType(STParser.RULE_region)) { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STFile.java
// public class STFile extends PsiFileBase {
//
// protected STFile(@NotNull FileViewProvider viewProvider) {
// super(viewProvider, STLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public FileType getFileType() {
// return STFileType.INSTANCE;
// }
//
// @Override
// public String toString() {
// return "String Template file";
// }
//
// @Nullable
// @Override
// public Icon getIcon(int flags) {
// return Icons.STG_FILE;
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/folding/STFoldingBuilder.java
import com.intellij.lang.ASTNode;
import com.intellij.lang.folding.CustomFoldingBuilder;
import com.intellij.lang.folding.FoldingDescriptor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.antlr.jetbrains.st4plugin.parsing.STParser;
import org.antlr.jetbrains.st4plugin.psi.STFile;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getRuleElementType;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType;
return;
}
foldRegions(descriptors, root);
foldIf(descriptors, root);
}
private void foldRegions(List<FoldingDescriptor> descriptors, PsiElement root) {
PsiTreeUtil.processElements(root, element -> {
if (element.getNode().getElementType() == getRuleElementType(STParser.RULE_region)) {
descriptors.add(new FoldingDescriptor(element, element.getTextRange()));
}
return true;
});
}
private void foldIf(List<FoldingDescriptor> descriptors, PsiElement root) {
PsiTreeUtil.processElements(root, element -> {
if (element.getNode().getElementType() == getRuleElementType(STParser.RULE_ifstat)) {
descriptors.add(new FoldingDescriptor(element, element.getTextRange()));
}
return true;
});
}
@Override
protected String getLanguagePlaceholderText(@NotNull ASTNode node, @NotNull TextRange range) {
if (node.getElementType() == getRuleElementType(STParser.RULE_region)) { | ASTNode id = node.findChildByType(getTokenElementType(STLexer.ID)); |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/highlight/STBraceMatcher.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lang.BracePair;
import com.intellij.lang.PairedBraceMatcher;
import com.intellij.psi.PsiFile;
import com.intellij.psi.tree.IElementType;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.highlight;
public class STBraceMatcher implements PairedBraceMatcher {
private static final BracePair[] PAIRS = { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/highlight/STBraceMatcher.java
import com.intellij.lang.BracePair;
import com.intellij.lang.PairedBraceMatcher;
import com.intellij.psi.PsiFile;
import com.intellij.psi.tree.IElementType;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.highlight;
public class STBraceMatcher implements PairedBraceMatcher {
private static final BracePair[] PAIRS = { | new BracePair(getTokenElementType(STLexer.LBRACK), getTokenElementType(STLexer.RBRACK), true), |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/highlight/STSyntaxHighlighter.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STLanguage.java
// public class STLanguage extends Language {
//
// public static final STLanguage INSTANCE = new STLanguage();
//
// private STLanguage() {
// super("ST");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public class STTokenTypes {
//
// private static final List<TokenIElementType> TOKEN_ELEMENT_TYPES = PSIElementTypeFactory.getTokenIElementTypes(STLanguage.INSTANCE);
// private static final List<RuleIElementType> RULE_ELEMENT_TYPES = PSIElementTypeFactory.getRuleIElementTypes(STLanguage.INSTANCE);
//
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lexer.Lexer;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.HighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase;
import com.intellij.psi.tree.IElementType;
import org.antlr.intellij.adaptor.lexer.ANTLRLexerAdaptor;
import org.antlr.jetbrains.st4plugin.STLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.antlr.jetbrains.st4plugin.psi.STTokenTypes;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.highlight;
public class STSyntaxHighlighter extends SyntaxHighlighterBase {
public static final TextAttributesKey STGroup_TEMPLATE_TEXT =
createTextAttributesKey("STGroup_TEMPLATE_TEXT", DefaultLanguageHighlighterColors.TEMPLATE_LANGUAGE_COLOR);
private static final List<IElementType> KEYWORDS = Stream.of(
STLexer.IF, STLexer.ELSE, STLexer.END, STLexer.TRUE,
STLexer.FALSE, STLexer.ELSEIF, STLexer.ENDIF, STLexer.SUPER | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STLanguage.java
// public class STLanguage extends Language {
//
// public static final STLanguage INSTANCE = new STLanguage();
//
// private STLanguage() {
// super("ST");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public class STTokenTypes {
//
// private static final List<TokenIElementType> TOKEN_ELEMENT_TYPES = PSIElementTypeFactory.getTokenIElementTypes(STLanguage.INSTANCE);
// private static final List<RuleIElementType> RULE_ELEMENT_TYPES = PSIElementTypeFactory.getRuleIElementTypes(STLanguage.INSTANCE);
//
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/highlight/STSyntaxHighlighter.java
import com.intellij.lexer.Lexer;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.HighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase;
import com.intellij.psi.tree.IElementType;
import org.antlr.intellij.adaptor.lexer.ANTLRLexerAdaptor;
import org.antlr.jetbrains.st4plugin.STLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.antlr.jetbrains.st4plugin.psi.STTokenTypes;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.highlight;
public class STSyntaxHighlighter extends SyntaxHighlighterBase {
public static final TextAttributesKey STGroup_TEMPLATE_TEXT =
createTextAttributesKey("STGroup_TEMPLATE_TEXT", DefaultLanguageHighlighterColors.TEMPLATE_LANGUAGE_COLOR);
private static final List<IElementType> KEYWORDS = Stream.of(
STLexer.IF, STLexer.ELSE, STLexer.END, STLexer.TRUE,
STLexer.FALSE, STLexer.ELSEIF, STLexer.ENDIF, STLexer.SUPER | ).map(STTokenTypes::getTokenElementType).collect(Collectors.toList()); |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/highlight/STSyntaxHighlighter.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STLanguage.java
// public class STLanguage extends Language {
//
// public static final STLanguage INSTANCE = new STLanguage();
//
// private STLanguage() {
// super("ST");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public class STTokenTypes {
//
// private static final List<TokenIElementType> TOKEN_ELEMENT_TYPES = PSIElementTypeFactory.getTokenIElementTypes(STLanguage.INSTANCE);
// private static final List<RuleIElementType> RULE_ELEMENT_TYPES = PSIElementTypeFactory.getRuleIElementTypes(STLanguage.INSTANCE);
//
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lexer.Lexer;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.HighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase;
import com.intellij.psi.tree.IElementType;
import org.antlr.intellij.adaptor.lexer.ANTLRLexerAdaptor;
import org.antlr.jetbrains.st4plugin.STLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.antlr.jetbrains.st4plugin.psi.STTokenTypes;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.highlight;
public class STSyntaxHighlighter extends SyntaxHighlighterBase {
public static final TextAttributesKey STGroup_TEMPLATE_TEXT =
createTextAttributesKey("STGroup_TEMPLATE_TEXT", DefaultLanguageHighlighterColors.TEMPLATE_LANGUAGE_COLOR);
private static final List<IElementType> KEYWORDS = Stream.of(
STLexer.IF, STLexer.ELSE, STLexer.END, STLexer.TRUE,
STLexer.FALSE, STLexer.ELSEIF, STLexer.ENDIF, STLexer.SUPER | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STLanguage.java
// public class STLanguage extends Language {
//
// public static final STLanguage INSTANCE = new STLanguage();
//
// private STLanguage() {
// super("ST");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public class STTokenTypes {
//
// private static final List<TokenIElementType> TOKEN_ELEMENT_TYPES = PSIElementTypeFactory.getTokenIElementTypes(STLanguage.INSTANCE);
// private static final List<RuleIElementType> RULE_ELEMENT_TYPES = PSIElementTypeFactory.getRuleIElementTypes(STLanguage.INSTANCE);
//
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/highlight/STSyntaxHighlighter.java
import com.intellij.lexer.Lexer;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.HighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase;
import com.intellij.psi.tree.IElementType;
import org.antlr.intellij.adaptor.lexer.ANTLRLexerAdaptor;
import org.antlr.jetbrains.st4plugin.STLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.antlr.jetbrains.st4plugin.psi.STTokenTypes;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.highlight;
public class STSyntaxHighlighter extends SyntaxHighlighterBase {
public static final TextAttributesKey STGroup_TEMPLATE_TEXT =
createTextAttributesKey("STGroup_TEMPLATE_TEXT", DefaultLanguageHighlighterColors.TEMPLATE_LANGUAGE_COLOR);
private static final List<IElementType> KEYWORDS = Stream.of(
STLexer.IF, STLexer.ELSE, STLexer.END, STLexer.TRUE,
STLexer.FALSE, STLexer.ELSEIF, STLexer.ENDIF, STLexer.SUPER | ).map(STTokenTypes::getTokenElementType).collect(Collectors.toList()); |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/highlight/STSyntaxHighlighter.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STLanguage.java
// public class STLanguage extends Language {
//
// public static final STLanguage INSTANCE = new STLanguage();
//
// private STLanguage() {
// super("ST");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public class STTokenTypes {
//
// private static final List<TokenIElementType> TOKEN_ELEMENT_TYPES = PSIElementTypeFactory.getTokenIElementTypes(STLanguage.INSTANCE);
// private static final List<RuleIElementType> RULE_ELEMENT_TYPES = PSIElementTypeFactory.getRuleIElementTypes(STLanguage.INSTANCE);
//
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lexer.Lexer;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.HighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase;
import com.intellij.psi.tree.IElementType;
import org.antlr.intellij.adaptor.lexer.ANTLRLexerAdaptor;
import org.antlr.jetbrains.st4plugin.STLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.antlr.jetbrains.st4plugin.psi.STTokenTypes;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.highlight;
public class STSyntaxHighlighter extends SyntaxHighlighterBase {
public static final TextAttributesKey STGroup_TEMPLATE_TEXT =
createTextAttributesKey("STGroup_TEMPLATE_TEXT", DefaultLanguageHighlighterColors.TEMPLATE_LANGUAGE_COLOR);
private static final List<IElementType> KEYWORDS = Stream.of(
STLexer.IF, STLexer.ELSE, STLexer.END, STLexer.TRUE,
STLexer.FALSE, STLexer.ELSEIF, STLexer.ENDIF, STLexer.SUPER
).map(STTokenTypes::getTokenElementType).collect(Collectors.toList());
@NotNull
@Override
public Lexer getHighlightingLexer() { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STLanguage.java
// public class STLanguage extends Language {
//
// public static final STLanguage INSTANCE = new STLanguage();
//
// private STLanguage() {
// super("ST");
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public class STTokenTypes {
//
// private static final List<TokenIElementType> TOKEN_ELEMENT_TYPES = PSIElementTypeFactory.getTokenIElementTypes(STLanguage.INSTANCE);
// private static final List<RuleIElementType> RULE_ELEMENT_TYPES = PSIElementTypeFactory.getRuleIElementTypes(STLanguage.INSTANCE);
//
// public static RuleIElementType getRuleElementType(@MagicConstant(valuesFromClass = STParser.class) int ruleIndex) {
// return RULE_ELEMENT_TYPES.get(ruleIndex);
// }
//
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/highlight/STSyntaxHighlighter.java
import com.intellij.lexer.Lexer;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.HighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase;
import com.intellij.psi.tree.IElementType;
import org.antlr.intellij.adaptor.lexer.ANTLRLexerAdaptor;
import org.antlr.jetbrains.st4plugin.STLanguage;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.antlr.jetbrains.st4plugin.psi.STTokenTypes;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.highlight;
public class STSyntaxHighlighter extends SyntaxHighlighterBase {
public static final TextAttributesKey STGroup_TEMPLATE_TEXT =
createTextAttributesKey("STGroup_TEMPLATE_TEXT", DefaultLanguageHighlighterColors.TEMPLATE_LANGUAGE_COLOR);
private static final List<IElementType> KEYWORDS = Stream.of(
STLexer.IF, STLexer.ELSE, STLexer.END, STLexer.TRUE,
STLexer.FALSE, STLexer.ELSEIF, STLexer.ENDIF, STLexer.SUPER
).map(STTokenTypes::getTokenElementType).collect(Collectors.toList());
@NotNull
@Override
public Lexer getHighlightingLexer() { | return new ANTLRLexerAdaptor(STLanguage.INSTANCE, new STLexer(null)); |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/psi/STFile.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STFileType.java
// public class STFileType extends LanguageFileType implements TemplateLanguageFileType {
// public static final STFileType INSTANCE = new STFileType();
//
// protected STFileType() {
// super(STLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "StringTemplate v4 template file";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "StringTemplate v4 template file";
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return "st";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return Icons.STG_FILE;
// }
//
// static class Factory extends FileTypeFactory {
// @Override
// public void createFileTypes(@NotNull FileTypeConsumer consumer) {
// consumer.consume(STFileType.INSTANCE);
// }
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STLanguage.java
// public class STLanguage extends Language {
//
// public static final STLanguage INSTANCE = new STLanguage();
//
// private STLanguage() {
// super("ST");
// }
// }
| import com.intellij.extapi.psi.PsiFileBase;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.FileViewProvider;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.STFileType;
import org.antlr.jetbrains.st4plugin.STLanguage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*; | package org.antlr.jetbrains.st4plugin.psi;
public class STFile extends PsiFileBase {
protected STFile(@NotNull FileViewProvider viewProvider) { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STFileType.java
// public class STFileType extends LanguageFileType implements TemplateLanguageFileType {
// public static final STFileType INSTANCE = new STFileType();
//
// protected STFileType() {
// super(STLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "StringTemplate v4 template file";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "StringTemplate v4 template file";
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return "st";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return Icons.STG_FILE;
// }
//
// static class Factory extends FileTypeFactory {
// @Override
// public void createFileTypes(@NotNull FileTypeConsumer consumer) {
// consumer.consume(STFileType.INSTANCE);
// }
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STLanguage.java
// public class STLanguage extends Language {
//
// public static final STLanguage INSTANCE = new STLanguage();
//
// private STLanguage() {
// super("ST");
// }
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STFile.java
import com.intellij.extapi.psi.PsiFileBase;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.FileViewProvider;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.STFileType;
import org.antlr.jetbrains.st4plugin.STLanguage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
package org.antlr.jetbrains.st4plugin.psi;
public class STFile extends PsiFileBase {
protected STFile(@NotNull FileViewProvider viewProvider) { | super(viewProvider, STLanguage.INSTANCE); |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/psi/STFile.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STFileType.java
// public class STFileType extends LanguageFileType implements TemplateLanguageFileType {
// public static final STFileType INSTANCE = new STFileType();
//
// protected STFileType() {
// super(STLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "StringTemplate v4 template file";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "StringTemplate v4 template file";
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return "st";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return Icons.STG_FILE;
// }
//
// static class Factory extends FileTypeFactory {
// @Override
// public void createFileTypes(@NotNull FileTypeConsumer consumer) {
// consumer.consume(STFileType.INSTANCE);
// }
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STLanguage.java
// public class STLanguage extends Language {
//
// public static final STLanguage INSTANCE = new STLanguage();
//
// private STLanguage() {
// super("ST");
// }
// }
| import com.intellij.extapi.psi.PsiFileBase;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.FileViewProvider;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.STFileType;
import org.antlr.jetbrains.st4plugin.STLanguage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*; | package org.antlr.jetbrains.st4plugin.psi;
public class STFile extends PsiFileBase {
protected STFile(@NotNull FileViewProvider viewProvider) {
super(viewProvider, STLanguage.INSTANCE);
}
@NotNull
@Override
public FileType getFileType() { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STFileType.java
// public class STFileType extends LanguageFileType implements TemplateLanguageFileType {
// public static final STFileType INSTANCE = new STFileType();
//
// protected STFileType() {
// super(STLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "StringTemplate v4 template file";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "StringTemplate v4 template file";
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return "st";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return Icons.STG_FILE;
// }
//
// static class Factory extends FileTypeFactory {
// @Override
// public void createFileTypes(@NotNull FileTypeConsumer consumer) {
// consumer.consume(STFileType.INSTANCE);
// }
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STLanguage.java
// public class STLanguage extends Language {
//
// public static final STLanguage INSTANCE = new STLanguage();
//
// private STLanguage() {
// super("ST");
// }
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STFile.java
import com.intellij.extapi.psi.PsiFileBase;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.FileViewProvider;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.STFileType;
import org.antlr.jetbrains.st4plugin.STLanguage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
package org.antlr.jetbrains.st4plugin.psi;
public class STFile extends PsiFileBase {
protected STFile(@NotNull FileViewProvider viewProvider) {
super(viewProvider, STLanguage.INSTANCE);
}
@NotNull
@Override
public FileType getFileType() { | return STFileType.INSTANCE; |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/psi/STFile.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STFileType.java
// public class STFileType extends LanguageFileType implements TemplateLanguageFileType {
// public static final STFileType INSTANCE = new STFileType();
//
// protected STFileType() {
// super(STLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "StringTemplate v4 template file";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "StringTemplate v4 template file";
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return "st";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return Icons.STG_FILE;
// }
//
// static class Factory extends FileTypeFactory {
// @Override
// public void createFileTypes(@NotNull FileTypeConsumer consumer) {
// consumer.consume(STFileType.INSTANCE);
// }
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STLanguage.java
// public class STLanguage extends Language {
//
// public static final STLanguage INSTANCE = new STLanguage();
//
// private STLanguage() {
// super("ST");
// }
// }
| import com.intellij.extapi.psi.PsiFileBase;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.FileViewProvider;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.STFileType;
import org.antlr.jetbrains.st4plugin.STLanguage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*; | package org.antlr.jetbrains.st4plugin.psi;
public class STFile extends PsiFileBase {
protected STFile(@NotNull FileViewProvider viewProvider) {
super(viewProvider, STLanguage.INSTANCE);
}
@NotNull
@Override
public FileType getFileType() {
return STFileType.INSTANCE;
}
@Override
public String toString() {
return "String Template file";
}
@Nullable
@Override
public Icon getIcon(int flags) { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/Icons.java
// public class Icons {
// public static final Icon STG_FILE = IconLoader.getIcon("/icons/st.png");
// public static final Icon BIGSTRING = IconLoader.getIcon("/icons/bigstring.png");
// public static final Icon BIGSTRING_NONL = IconLoader.getIcon("/icons/bigstring-nonl.png");
// public static final Icon STRING = IconLoader.getIcon("/icons/string.png");
// public static final Icon DICT = IconLoader.getIcon("/icons/dict.png");
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STFileType.java
// public class STFileType extends LanguageFileType implements TemplateLanguageFileType {
// public static final STFileType INSTANCE = new STFileType();
//
// protected STFileType() {
// super(STLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "StringTemplate v4 template file";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "StringTemplate v4 template file";
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return "st";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return Icons.STG_FILE;
// }
//
// static class Factory extends FileTypeFactory {
// @Override
// public void createFileTypes(@NotNull FileTypeConsumer consumer) {
// consumer.consume(STFileType.INSTANCE);
// }
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/STLanguage.java
// public class STLanguage extends Language {
//
// public static final STLanguage INSTANCE = new STLanguage();
//
// private STLanguage() {
// super("ST");
// }
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STFile.java
import com.intellij.extapi.psi.PsiFileBase;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.psi.FileViewProvider;
import org.antlr.jetbrains.st4plugin.Icons;
import org.antlr.jetbrains.st4plugin.STFileType;
import org.antlr.jetbrains.st4plugin.STLanguage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
package org.antlr.jetbrains.st4plugin.psi;
public class STFile extends PsiFileBase {
protected STFile(@NotNull FileViewProvider viewProvider) {
super(viewProvider, STLanguage.INSTANCE);
}
@NotNull
@Override
public FileType getFileType() {
return STFileType.INSTANCE;
}
@Override
public String toString() {
return "String Template file";
}
@Nullable
@Override
public Icon getIcon(int flags) { | return Icons.STG_FILE; |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/highlight/STEditorHighlighterProvider.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupFileType.java
// public class STGroupFileType extends LanguageFileType implements TemplateLanguageFileType {
// public static final STGroupFileType INSTANCE = new STGroupFileType();
//
// protected STGroupFileType() {
// super(STGroupLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return "stg";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return Icons.STG_FILE;
// }
//
// static class Factory extends FileTypeFactory {
// @Override
// public void createFileTypes(@NotNull FileTypeConsumer consumer) {
// consumer.consume(STGroupFileType.INSTANCE);
// }
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lang.Language;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.ex.util.LayerDescriptor;
import com.intellij.openapi.editor.ex.util.LayeredLexerEditorHighlighter;
import com.intellij.openapi.editor.highlighter.EditorHighlighter;
import com.intellij.openapi.fileTypes.EditorHighlighterProvider;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.templateLanguages.TemplateDataLanguageMappings;
import org.antlr.jetbrains.st4plugin.STGroupFileType;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.highlight;
public class STEditorHighlighterProvider implements EditorHighlighterProvider {
@Override
public EditorHighlighter getEditorHighlighter(@Nullable Project project, @NotNull FileType fileType, @Nullable VirtualFile virtualFile, @NotNull EditorColorsScheme colors) {
return new STEditorHighlighter(virtualFile, project, fileType, colors);
}
}
/**
* Highlights the "outer language", i.e. the target language.
* The target language can be configured in the Template Data Languages settings.
*/
class STEditorHighlighter extends LayeredLexerEditorHighlighter {
public STEditorHighlighter(@Nullable VirtualFile virtualFile,
@Nullable Project project,
@NotNull FileType fileType,
@NotNull EditorColorsScheme scheme) { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupFileType.java
// public class STGroupFileType extends LanguageFileType implements TemplateLanguageFileType {
// public static final STGroupFileType INSTANCE = new STGroupFileType();
//
// protected STGroupFileType() {
// super(STGroupLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return "stg";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return Icons.STG_FILE;
// }
//
// static class Factory extends FileTypeFactory {
// @Override
// public void createFileTypes(@NotNull FileTypeConsumer consumer) {
// consumer.consume(STGroupFileType.INSTANCE);
// }
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/highlight/STEditorHighlighterProvider.java
import com.intellij.lang.Language;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.ex.util.LayerDescriptor;
import com.intellij.openapi.editor.ex.util.LayeredLexerEditorHighlighter;
import com.intellij.openapi.editor.highlighter.EditorHighlighter;
import com.intellij.openapi.fileTypes.EditorHighlighterProvider;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.templateLanguages.TemplateDataLanguageMappings;
import org.antlr.jetbrains.st4plugin.STGroupFileType;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.highlight;
public class STEditorHighlighterProvider implements EditorHighlighterProvider {
@Override
public EditorHighlighter getEditorHighlighter(@Nullable Project project, @NotNull FileType fileType, @Nullable VirtualFile virtualFile, @NotNull EditorColorsScheme colors) {
return new STEditorHighlighter(virtualFile, project, fileType, colors);
}
}
/**
* Highlights the "outer language", i.e. the target language.
* The target language can be configured in the Template Data Languages settings.
*/
class STEditorHighlighter extends LayeredLexerEditorHighlighter {
public STEditorHighlighter(@Nullable VirtualFile virtualFile,
@Nullable Project project,
@NotNull FileType fileType,
@NotNull EditorColorsScheme scheme) { | super(fileType == STGroupFileType.INSTANCE ? new STGroupSyntaxHighlighter() : new STSyntaxHighlighter(), scheme); |
antlr/jetbrains-plugin-st4 | src/main/java/org/antlr/jetbrains/st4plugin/highlight/STEditorHighlighterProvider.java | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupFileType.java
// public class STGroupFileType extends LanguageFileType implements TemplateLanguageFileType {
// public static final STGroupFileType INSTANCE = new STGroupFileType();
//
// protected STGroupFileType() {
// super(STGroupLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return "stg";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return Icons.STG_FILE;
// }
//
// static class Factory extends FileTypeFactory {
// @Override
// public void createFileTypes(@NotNull FileTypeConsumer consumer) {
// consumer.consume(STGroupFileType.INSTANCE);
// }
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
| import com.intellij.lang.Language;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.ex.util.LayerDescriptor;
import com.intellij.openapi.editor.ex.util.LayeredLexerEditorHighlighter;
import com.intellij.openapi.editor.highlighter.EditorHighlighter;
import com.intellij.openapi.fileTypes.EditorHighlighterProvider;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.templateLanguages.TemplateDataLanguageMappings;
import org.antlr.jetbrains.st4plugin.STGroupFileType;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType; | package org.antlr.jetbrains.st4plugin.highlight;
public class STEditorHighlighterProvider implements EditorHighlighterProvider {
@Override
public EditorHighlighter getEditorHighlighter(@Nullable Project project, @NotNull FileType fileType, @Nullable VirtualFile virtualFile, @NotNull EditorColorsScheme colors) {
return new STEditorHighlighter(virtualFile, project, fileType, colors);
}
}
/**
* Highlights the "outer language", i.e. the target language.
* The target language can be configured in the Template Data Languages settings.
*/
class STEditorHighlighter extends LayeredLexerEditorHighlighter {
public STEditorHighlighter(@Nullable VirtualFile virtualFile,
@Nullable Project project,
@NotNull FileType fileType,
@NotNull EditorColorsScheme scheme) {
super(fileType == STGroupFileType.INSTANCE ? new STGroupSyntaxHighlighter() : new STSyntaxHighlighter(), scheme);
if (project != null && virtualFile != null) {
Language language = TemplateDataLanguageMappings.getInstance(project).getMapping(virtualFile);
if (language != null) {
SyntaxHighlighter outerHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(language.getAssociatedFileType(), project, virtualFile);
if (outerHighlighter != null) { | // Path: src/main/java/org/antlr/jetbrains/st4plugin/STGroupFileType.java
// public class STGroupFileType extends LanguageFileType implements TemplateLanguageFileType {
// public static final STGroupFileType INSTANCE = new STGroupFileType();
//
// protected STGroupFileType() {
// super(STGroupLanguage.INSTANCE);
// }
//
// @NotNull
// @Override
// public String getName() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDescription() {
// return "StringTemplate v4 template group file";
// }
//
// @NotNull
// @Override
// public String getDefaultExtension() {
// return "stg";
// }
//
// @Nullable
// @Override
// public Icon getIcon() {
// return Icons.STG_FILE;
// }
//
// static class Factory extends FileTypeFactory {
// @Override
// public void createFileTypes(@NotNull FileTypeConsumer consumer) {
// consumer.consume(STGroupFileType.INSTANCE);
// }
// }
// }
//
// Path: src/main/java/org/antlr/jetbrains/st4plugin/psi/STTokenTypes.java
// public static TokenIElementType getTokenElementType(@MagicConstant(valuesFromClass = STLexer.class) int ruleIndex) {
// return TOKEN_ELEMENT_TYPES.get(ruleIndex);
// }
// Path: src/main/java/org/antlr/jetbrains/st4plugin/highlight/STEditorHighlighterProvider.java
import com.intellij.lang.Language;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.ex.util.LayerDescriptor;
import com.intellij.openapi.editor.ex.util.LayeredLexerEditorHighlighter;
import com.intellij.openapi.editor.highlighter.EditorHighlighter;
import com.intellij.openapi.fileTypes.EditorHighlighterProvider;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.templateLanguages.TemplateDataLanguageMappings;
import org.antlr.jetbrains.st4plugin.STGroupFileType;
import org.antlr.jetbrains.st4plugin.parsing.STLexer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static org.antlr.jetbrains.st4plugin.psi.STTokenTypes.getTokenElementType;
package org.antlr.jetbrains.st4plugin.highlight;
public class STEditorHighlighterProvider implements EditorHighlighterProvider {
@Override
public EditorHighlighter getEditorHighlighter(@Nullable Project project, @NotNull FileType fileType, @Nullable VirtualFile virtualFile, @NotNull EditorColorsScheme colors) {
return new STEditorHighlighter(virtualFile, project, fileType, colors);
}
}
/**
* Highlights the "outer language", i.e. the target language.
* The target language can be configured in the Template Data Languages settings.
*/
class STEditorHighlighter extends LayeredLexerEditorHighlighter {
public STEditorHighlighter(@Nullable VirtualFile virtualFile,
@Nullable Project project,
@NotNull FileType fileType,
@NotNull EditorColorsScheme scheme) {
super(fileType == STGroupFileType.INSTANCE ? new STGroupSyntaxHighlighter() : new STSyntaxHighlighter(), scheme);
if (project != null && virtualFile != null) {
Language language = TemplateDataLanguageMappings.getInstance(project).getMapping(virtualFile);
if (language != null) {
SyntaxHighlighter outerHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(language.getAssociatedFileType(), project, virtualFile);
if (outerHighlighter != null) { | registerLayer(getTokenElementType(STLexer.TEXT), new LayerDescriptor(outerHighlighter, "")); |
ferstl/pedantic-pom-enforcers | src/test/java/com/github/ferstl/maven/pomenforcers/model/ModelTest.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/XmlUtils.java
// public final class XmlUtils {
//
// /**
// * Parses the given file into an XML {@link Document}.
// * @param file The file to parse.
// * @return The created XML {@link Document}.
// */
// public static Document parseXml(File file) {
// if (!file.exists()) {
// throw new IllegalArgumentException("File " + file + " does not exist.");
// }
// try {
// DocumentBuilder docBuilder = createDocumentBuilder();
// return docBuilder.parse(file);
// } catch (SAXException | IOException e) {
// throw new IllegalStateException("Unable to parse XML file " + file, e);
// }
// }
//
// /**
// * Returns the XML {@link Element} matching the given XPath expression.
// * @param expression XPath expression.
// * @param document XML document to search for the element.
// * @return The matching XML {@link Element}.
// */
// public static Element evaluateXPathAsElement(String expression, Document document) {
// return evaluateXpath(expression, document, XPathConstants.NODE);
// }
//
// /**
// * Returns the XML {@link NodeList} matching the given XPath expression.
// * @param expression XPath expression.
// * @param document XML document to search for the node list.
// * @return The matching XML {@link NodeList}.
// */
// public static NodeList evaluateXPathAsNodeList(String expression, Document document) {
// return evaluateXpath(expression, document, XPathConstants.NODESET);
// }
//
// /**
// * Creates a XML document with the given root element and the given {@link NodeList} as content.
// * @param root The root element of the XML document.
// * @param content Content of the XML document.
// * @return The created XML document.
// */
// public static Document createDocument(String root, NodeList content) {
// DocumentBuilder docBuilder = createDocumentBuilder();
// Document document = docBuilder.newDocument();
// Element rootElement = document.createElement(root);
// document.appendChild(rootElement);
//
// for (int i = 0; i < content.getLength(); i++) {
// Node item = content.item(i);
// item = document.adoptNode(item.cloneNode(true));
// rootElement.appendChild(item);
// }
// return document;
// }
//
// @SuppressWarnings("unchecked")
// private static <T> T evaluateXpath(String expression, Document document, QName dataType) {
// try {
// XPath xpath = createXPath();
// XPathExpression compiledExpression = xpath.compile(expression);
// return (T) compiledExpression.evaluate(document, dataType);
// } catch (XPathExpressionException e) {
// throw new IllegalArgumentException("Cannot evaluate XPath expression '" + expression + "'");
// }
// }
//
// private static XPath createXPath() {
// return XPathFactory.newInstance().newXPath();
// }
//
// private static DocumentBuilder createDocumentBuilder() {
// try {
// return DocumentBuilderFactory.newInstance().newDocumentBuilder();
// } catch (ParserConfigurationException e) {
// throw new IllegalStateException("Cannot create document builder", e);
// }
// }
//
// private XmlUtils() {}
// }
| import java.io.File;
import javax.xml.bind.Binder;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import com.github.ferstl.maven.pomenforcers.util.XmlUtils;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat; | /*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers.model;
public class ModelTest {
@Test
public void test() throws Exception { | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/XmlUtils.java
// public final class XmlUtils {
//
// /**
// * Parses the given file into an XML {@link Document}.
// * @param file The file to parse.
// * @return The created XML {@link Document}.
// */
// public static Document parseXml(File file) {
// if (!file.exists()) {
// throw new IllegalArgumentException("File " + file + " does not exist.");
// }
// try {
// DocumentBuilder docBuilder = createDocumentBuilder();
// return docBuilder.parse(file);
// } catch (SAXException | IOException e) {
// throw new IllegalStateException("Unable to parse XML file " + file, e);
// }
// }
//
// /**
// * Returns the XML {@link Element} matching the given XPath expression.
// * @param expression XPath expression.
// * @param document XML document to search for the element.
// * @return The matching XML {@link Element}.
// */
// public static Element evaluateXPathAsElement(String expression, Document document) {
// return evaluateXpath(expression, document, XPathConstants.NODE);
// }
//
// /**
// * Returns the XML {@link NodeList} matching the given XPath expression.
// * @param expression XPath expression.
// * @param document XML document to search for the node list.
// * @return The matching XML {@link NodeList}.
// */
// public static NodeList evaluateXPathAsNodeList(String expression, Document document) {
// return evaluateXpath(expression, document, XPathConstants.NODESET);
// }
//
// /**
// * Creates a XML document with the given root element and the given {@link NodeList} as content.
// * @param root The root element of the XML document.
// * @param content Content of the XML document.
// * @return The created XML document.
// */
// public static Document createDocument(String root, NodeList content) {
// DocumentBuilder docBuilder = createDocumentBuilder();
// Document document = docBuilder.newDocument();
// Element rootElement = document.createElement(root);
// document.appendChild(rootElement);
//
// for (int i = 0; i < content.getLength(); i++) {
// Node item = content.item(i);
// item = document.adoptNode(item.cloneNode(true));
// rootElement.appendChild(item);
// }
// return document;
// }
//
// @SuppressWarnings("unchecked")
// private static <T> T evaluateXpath(String expression, Document document, QName dataType) {
// try {
// XPath xpath = createXPath();
// XPathExpression compiledExpression = xpath.compile(expression);
// return (T) compiledExpression.evaluate(document, dataType);
// } catch (XPathExpressionException e) {
// throw new IllegalArgumentException("Cannot evaluate XPath expression '" + expression + "'");
// }
// }
//
// private static XPath createXPath() {
// return XPathFactory.newInstance().newXPath();
// }
//
// private static DocumentBuilder createDocumentBuilder() {
// try {
// return DocumentBuilderFactory.newInstance().newDocumentBuilder();
// } catch (ParserConfigurationException e) {
// throw new IllegalStateException("Cannot create document builder", e);
// }
// }
//
// private XmlUtils() {}
// }
// Path: src/test/java/com/github/ferstl/maven/pomenforcers/model/ModelTest.java
import java.io.File;
import javax.xml.bind.Binder;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import com.github.ferstl.maven.pomenforcers.util.XmlUtils;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
/*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers.model;
public class ModelTest {
@Test
public void test() throws Exception { | Document pom = XmlUtils.parseXml(new File("src/test/projects/example-project/pom.xml")); |
ferstl/pedantic-pom-enforcers | src/test/java/com/github/ferstl/maven/pomenforcers/PedanticDependencyScopeEnforcerTest.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/DependencyScope.java
// public enum DependencyScope {
//
// IMPORT("import"),
// COMPILE("compile"),
// PROVIDED("provided"),
// RUNTIME("runtime"),
// SYSTEM("system"),
// TEST("test");
//
// private static final Map<String, DependencyScope> dependencyScopeMap;
//
// static {
// dependencyScopeMap = new LinkedHashMap<>();
// for (DependencyScope scope : values()) {
// dependencyScopeMap.put(scope.getScopeName(), scope);
// }
// }
//
// public static DependencyScope getByScopeName(String scopeName) {
// requireNonNull(scopeName, "Scope name is null.");
//
// DependencyScope scope = dependencyScopeMap.get(scopeName);
// if (scope == null) {
// throw new IllegalArgumentException("Dependency scope'" + scopeName + "' does not exist.");
// }
//
// return scope;
// }
//
// private final String scopeName;
//
// DependencyScope(String name) {
// this.scopeName = name;
// }
//
// public String getScopeName() {
// return this.scopeName;
// }
// }
| import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.codehaus.plexus.util.StringUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import com.github.ferstl.maven.pomenforcers.model.DependencyScope;
import com.google.common.base.Joiner;
import com.google.common.collect.Collections2;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
| /*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers;
/**
* JUnit tests for {@link PedanticDependencyScopeEnforcer}.
*/
@RunWith(Theories.class)
public class PedanticDependencyScopeEnforcerTest extends AbstractPedanticEnforcerTest<PedanticDependencyScopeEnforcer> {
/**
* Creates test data for each possible dependency scope. The data will be used as theory to test the enforcer rule
* with different settings. This prevents writing a test method for each dependency scope.
*/
@DataPoints
public static RuleConfiguration[] ruleConfigurations() throws Exception {
| // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/DependencyScope.java
// public enum DependencyScope {
//
// IMPORT("import"),
// COMPILE("compile"),
// PROVIDED("provided"),
// RUNTIME("runtime"),
// SYSTEM("system"),
// TEST("test");
//
// private static final Map<String, DependencyScope> dependencyScopeMap;
//
// static {
// dependencyScopeMap = new LinkedHashMap<>();
// for (DependencyScope scope : values()) {
// dependencyScopeMap.put(scope.getScopeName(), scope);
// }
// }
//
// public static DependencyScope getByScopeName(String scopeName) {
// requireNonNull(scopeName, "Scope name is null.");
//
// DependencyScope scope = dependencyScopeMap.get(scopeName);
// if (scope == null) {
// throw new IllegalArgumentException("Dependency scope'" + scopeName + "' does not exist.");
// }
//
// return scope;
// }
//
// private final String scopeName;
//
// DependencyScope(String name) {
// this.scopeName = name;
// }
//
// public String getScopeName() {
// return this.scopeName;
// }
// }
// Path: src/test/java/com/github/ferstl/maven/pomenforcers/PedanticDependencyScopeEnforcerTest.java
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.codehaus.plexus.util.StringUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import com.github.ferstl.maven.pomenforcers.model.DependencyScope;
import com.google.common.base.Joiner;
import com.google.common.collect.Collections2;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers;
/**
* JUnit tests for {@link PedanticDependencyScopeEnforcer}.
*/
@RunWith(Theories.class)
public class PedanticDependencyScopeEnforcerTest extends AbstractPedanticEnforcerTest<PedanticDependencyScopeEnforcer> {
/**
* Creates test data for each possible dependency scope. The data will be used as theory to test the enforcer rule
* with different settings. This prevents writing a test method for each dependency scope.
*/
@DataPoints
public static RuleConfiguration[] ruleConfigurations() throws Exception {
| List<RuleConfiguration> ruleConfig = new ArrayList<>(2 * DependencyScope.values().length);
|
ferstl/pedantic-pom-enforcers | src/test/java/com/github/ferstl/maven/pomenforcers/util/EnforcerRuleUtilsTest.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/EnforcerRuleUtils.java
// public static String evaluateProperties(String input, EnforcerRuleHelper helper) {
// if (!Strings.isNullOrEmpty(input)) {
// Matcher matcher = PROPERTY_PATTERN.matcher(input);
// StringBuffer substituted = new StringBuffer();
// while (matcher.find()) {
// String property = matcher.group();
// matcher.appendReplacement(substituted, evaluateStringProperty(property, helper));
// }
// matcher.appendTail(substituted);
// return substituted.toString();
// }
// return input;
// }
| import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper;
import org.junit.Before;
import org.junit.Test;
import static com.github.ferstl.maven.pomenforcers.util.EnforcerRuleUtils.evaluateProperties;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; | /*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers.util;
public class EnforcerRuleUtilsTest {
private EnforcerRuleHelper mockHelper;
@Before
public void setup() throws Exception {
this.mockHelper = mock(EnforcerRuleHelper.class);
when(this.mockHelper.evaluate(anyString())).thenReturn("test");
}
@Test
public void testEvaluateProperties() { | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/EnforcerRuleUtils.java
// public static String evaluateProperties(String input, EnforcerRuleHelper helper) {
// if (!Strings.isNullOrEmpty(input)) {
// Matcher matcher = PROPERTY_PATTERN.matcher(input);
// StringBuffer substituted = new StringBuffer();
// while (matcher.find()) {
// String property = matcher.group();
// matcher.appendReplacement(substituted, evaluateStringProperty(property, helper));
// }
// matcher.appendTail(substituted);
// return substituted.toString();
// }
// return input;
// }
// Path: src/test/java/com/github/ferstl/maven/pomenforcers/util/EnforcerRuleUtilsTest.java
import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper;
import org.junit.Before;
import org.junit.Test;
import static com.github.ferstl.maven.pomenforcers.util.EnforcerRuleUtils.evaluateProperties;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers.util;
public class EnforcerRuleUtilsTest {
private EnforcerRuleHelper mockHelper;
@Before
public void setup() throws Exception {
this.mockHelper = mock(EnforcerRuleHelper.class);
when(this.mockHelper.evaluate(anyString())).thenReturn("test");
}
@Test
public void testEvaluateProperties() { | assertThat(evaluateProperties("foo-${user.name}-bar", this.mockHelper), is("foo-test-bar")); |
ferstl/pedantic-pom-enforcers | src/main/java/com/github/ferstl/maven/pomenforcers/model/functions/StringToArtifactTransformer.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/ArtifactModel.java
// public class ArtifactModel {
//
// private static final Joiner TO_STRING_JOINER = Joiner.on(":").useForNull("");
// private static final String WILDCARD = "*";
// private static final char WILDCARD_CHAR = WILDCARD.charAt(0);
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String groupId;
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String artifactId;
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String version;
//
// ArtifactModel() {
// }
//
// public ArtifactModel(String groupId, String artifactId, String version) {
// // Make sure that wildcards are valid
// determineWildcardMode(groupId);
// determineWildcardMode(artifactId);
//
// this.groupId = groupId;
// this.artifactId = artifactId;
// this.version = version;
//
// }
//
// public ArtifactModel(String groupId, String artifactId) {
// this(groupId, artifactId, null);
// }
//
// public String getGroupId() {
// return this.groupId;
// }
//
// public String getArtifactId() {
// return this.artifactId;
// }
//
// public String getVersion() {
// return this.version;
// }
//
// public boolean matches(ArtifactModel pattern) {
// if (pattern == this) {
// return true;
// }
//
// if (pattern == null) {
// return false;
// }
//
// return match(this.groupId, pattern.groupId)
// && match(this.artifactId, pattern.artifactId);
// }
//
// @Override
// public String toString() {
// return TO_STRING_JOINER.join(
// this.groupId,
// this.artifactId,
// this.version);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (!(obj instanceof ArtifactModel)) {
// return false;
// }
//
// ArtifactModel other = (ArtifactModel) obj;
// return equal(this.groupId, other.groupId)
// && equal(this.artifactId, other.artifactId);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(this.groupId, this.artifactId);
// }
//
// private static WildcardMode determineWildcardMode(String string) {
// if (string == null) {
// return WildcardMode.NONE;
// }
//
// int wildcardCount = 0;
// for (int i = 0; i < string.length(); i++) {
// if (string.charAt(i) == WILDCARD_CHAR) {
// wildcardCount++;
// }
// }
//
// if (wildcardCount == 0) {
// return WildcardMode.NONE;
// } else if (wildcardCount == 1 && string.length() == 1) {
// return WildcardMode.FULL;
// } else if (wildcardCount == 1 && string.startsWith(WILDCARD)) {
// return WildcardMode.LEADING;
// } else if (wildcardCount == 1 && string.endsWith(WILDCARD)) {
// return WildcardMode.TRAILING;
// } else if (wildcardCount == 2 && string.startsWith(WILDCARD) && string.endsWith(WILDCARD)) {
// return WildcardMode.CONTAINS;
// } else {
// throw new IllegalArgumentException("Invalid wildcard pattern '" + string + "'");
// }
// }
//
// private static boolean match(String string, String pattern) {
// switch (determineWildcardMode(pattern)) {
// case NONE:
// return string.equals(pattern);
// case LEADING:
// return string.endsWith(pattern.substring(1));
// case TRAILING:
// return string.startsWith(pattern.substring(0, pattern.length() - 1));
// case CONTAINS:
// return string.contains(pattern.substring(1, pattern.length() - 1));
// case FULL:
// return true;
// default:
// return false;
// }
// }
//
// private enum WildcardMode {
// NONE, LEADING, TRAILING, CONTAINS, FULL
// }
// }
| import java.util.ArrayList;
import com.github.ferstl.maven.pomenforcers.model.ArtifactModel;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists; | /*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers.model.functions;
public final class StringToArtifactTransformer {
private static final Splitter COLON_SPLITTER = Splitter.on(":");
| // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/ArtifactModel.java
// public class ArtifactModel {
//
// private static final Joiner TO_STRING_JOINER = Joiner.on(":").useForNull("");
// private static final String WILDCARD = "*";
// private static final char WILDCARD_CHAR = WILDCARD.charAt(0);
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String groupId;
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String artifactId;
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String version;
//
// ArtifactModel() {
// }
//
// public ArtifactModel(String groupId, String artifactId, String version) {
// // Make sure that wildcards are valid
// determineWildcardMode(groupId);
// determineWildcardMode(artifactId);
//
// this.groupId = groupId;
// this.artifactId = artifactId;
// this.version = version;
//
// }
//
// public ArtifactModel(String groupId, String artifactId) {
// this(groupId, artifactId, null);
// }
//
// public String getGroupId() {
// return this.groupId;
// }
//
// public String getArtifactId() {
// return this.artifactId;
// }
//
// public String getVersion() {
// return this.version;
// }
//
// public boolean matches(ArtifactModel pattern) {
// if (pattern == this) {
// return true;
// }
//
// if (pattern == null) {
// return false;
// }
//
// return match(this.groupId, pattern.groupId)
// && match(this.artifactId, pattern.artifactId);
// }
//
// @Override
// public String toString() {
// return TO_STRING_JOINER.join(
// this.groupId,
// this.artifactId,
// this.version);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (!(obj instanceof ArtifactModel)) {
// return false;
// }
//
// ArtifactModel other = (ArtifactModel) obj;
// return equal(this.groupId, other.groupId)
// && equal(this.artifactId, other.artifactId);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(this.groupId, this.artifactId);
// }
//
// private static WildcardMode determineWildcardMode(String string) {
// if (string == null) {
// return WildcardMode.NONE;
// }
//
// int wildcardCount = 0;
// for (int i = 0; i < string.length(); i++) {
// if (string.charAt(i) == WILDCARD_CHAR) {
// wildcardCount++;
// }
// }
//
// if (wildcardCount == 0) {
// return WildcardMode.NONE;
// } else if (wildcardCount == 1 && string.length() == 1) {
// return WildcardMode.FULL;
// } else if (wildcardCount == 1 && string.startsWith(WILDCARD)) {
// return WildcardMode.LEADING;
// } else if (wildcardCount == 1 && string.endsWith(WILDCARD)) {
// return WildcardMode.TRAILING;
// } else if (wildcardCount == 2 && string.startsWith(WILDCARD) && string.endsWith(WILDCARD)) {
// return WildcardMode.CONTAINS;
// } else {
// throw new IllegalArgumentException("Invalid wildcard pattern '" + string + "'");
// }
// }
//
// private static boolean match(String string, String pattern) {
// switch (determineWildcardMode(pattern)) {
// case NONE:
// return string.equals(pattern);
// case LEADING:
// return string.endsWith(pattern.substring(1));
// case TRAILING:
// return string.startsWith(pattern.substring(0, pattern.length() - 1));
// case CONTAINS:
// return string.contains(pattern.substring(1, pattern.length() - 1));
// case FULL:
// return true;
// default:
// return false;
// }
// }
//
// private enum WildcardMode {
// NONE, LEADING, TRAILING, CONTAINS, FULL
// }
// }
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/functions/StringToArtifactTransformer.java
import java.util.ArrayList;
import com.github.ferstl.maven.pomenforcers.model.ArtifactModel;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
/*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers.model.functions;
public final class StringToArtifactTransformer {
private static final Splitter COLON_SPLITTER = Splitter.on(":");
| public static ArtifactModel toArtifactModel(String input) { |
ferstl/pedantic-pom-enforcers | src/main/java/com/github/ferstl/maven/pomenforcers/PedanticModuleOrderEnforcer.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/CommaSeparatorUtils.java
// public final class CommaSeparatorUtils {
//
// private static final Splitter COMMA_SPLITTER = Splitter.on(",").trimResults().omitEmptyStrings();
//
// public static void splitAndAddToCollection(String commaSeparatedItems, Collection<String> collection) {
// splitAndAddToCollection(commaSeparatedItems, collection, Function.identity());
// }
//
// public static <T> void splitAndAddToCollection(String commaSeparatedItems, Collection<T> collection, Function<String, T> transformer) {
// Iterable<String> items = COMMA_SPLITTER.split(commaSeparatedItems);
// // Don't touch the collection if there is nothing to add.
// if (items.iterator().hasNext()) {
// collection.clear();
// }
// StreamSupport.stream(items.spliterator(), false)
// .map(transformer)
// .collect(toCollection(() -> collection));
// }
//
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/EnforcerRuleUtils.java
// public final class EnforcerRuleUtils {
//
// private static final Pattern PROPERTY_PATTERN = Pattern.compile("\\$\\{.*?}");
//
// public static MavenProject getMavenProject(EnforcerRuleHelper helper) {
// try {
// return (MavenProject) helper.evaluate("${project}");
// } catch (ExpressionEvaluationException e) {
// throw new IllegalStateException("Unable to get maven project", e);
// }
// }
//
// public static String evaluateProperties(String input, EnforcerRuleHelper helper) {
// if (!Strings.isNullOrEmpty(input)) {
// Matcher matcher = PROPERTY_PATTERN.matcher(input);
// StringBuffer substituted = new StringBuffer();
// while (matcher.find()) {
// String property = matcher.group();
// matcher.appendReplacement(substituted, evaluateStringProperty(property, helper));
// }
// matcher.appendTail(substituted);
// return substituted.toString();
// }
// return input;
// }
//
// private static String evaluateStringProperty(String property, EnforcerRuleHelper helper) {
// try {
// return (String) helper.evaluate(property);
// } catch (ExpressionEvaluationException e) {
// throw new IllegalArgumentException("Unable to resolve property " + property);
// } catch (ClassCastException e) {
// throw new IllegalArgumentException("Property " + property + " does not evaluate to a String");
// }
// }
//
// private EnforcerRuleUtils() {
// }
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/ErrorReport.java
// public static <T> String toList(Collection<T> collection) {
// return toList(collection, Function.identity());
// }
| import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.apache.maven.project.MavenProject;
import com.github.ferstl.maven.pomenforcers.util.CommaSeparatorUtils;
import com.github.ferstl.maven.pomenforcers.util.EnforcerRuleUtils;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import static com.github.ferstl.maven.pomenforcers.ErrorReport.toList;
| /*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers;
/**
* This enforcer makes sure that your <code>modules</code> section is sorted
* alphabetically. Modules that should occur at a specific position in the
* <code><modules></code> section can be ignored.
* <pre>
* ### Example
* <rules>
* <moduleOrder implementation="com.github.ferstl.maven.pomenforcers.PedanticModuleOrderEnforcer">
* <!-- These modules may occur at any place in the modules section -->
* <ignoredModules>dist-deb,dist-rpm</ignoredModules>
* </moduleOrder>
* </rules>
* </pre>
*
* @id {@link PedanticEnforcerRule#MODULE_ORDER}
* @since 1.0.0
*/
public class PedanticModuleOrderEnforcer extends AbstractPedanticEnforcer {
/**
* All modules in this set won't be checked for the correct order.
*/
private final Set<String> ignoredModules;
public PedanticModuleOrderEnforcer() {
this.ignoredModules = Sets.newLinkedHashSet();
}
/**
* Comma-separated list of ignored modules. All modules in this list may occur at any place in the
* <code>modules</code> section.
*
* @param ignoredModules Comma-separated list of ignored modules.
* @configParam
* @since 1.0.0
*/
public void setIgnoredModules(String ignoredModules) {
| // Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/CommaSeparatorUtils.java
// public final class CommaSeparatorUtils {
//
// private static final Splitter COMMA_SPLITTER = Splitter.on(",").trimResults().omitEmptyStrings();
//
// public static void splitAndAddToCollection(String commaSeparatedItems, Collection<String> collection) {
// splitAndAddToCollection(commaSeparatedItems, collection, Function.identity());
// }
//
// public static <T> void splitAndAddToCollection(String commaSeparatedItems, Collection<T> collection, Function<String, T> transformer) {
// Iterable<String> items = COMMA_SPLITTER.split(commaSeparatedItems);
// // Don't touch the collection if there is nothing to add.
// if (items.iterator().hasNext()) {
// collection.clear();
// }
// StreamSupport.stream(items.spliterator(), false)
// .map(transformer)
// .collect(toCollection(() -> collection));
// }
//
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/EnforcerRuleUtils.java
// public final class EnforcerRuleUtils {
//
// private static final Pattern PROPERTY_PATTERN = Pattern.compile("\\$\\{.*?}");
//
// public static MavenProject getMavenProject(EnforcerRuleHelper helper) {
// try {
// return (MavenProject) helper.evaluate("${project}");
// } catch (ExpressionEvaluationException e) {
// throw new IllegalStateException("Unable to get maven project", e);
// }
// }
//
// public static String evaluateProperties(String input, EnforcerRuleHelper helper) {
// if (!Strings.isNullOrEmpty(input)) {
// Matcher matcher = PROPERTY_PATTERN.matcher(input);
// StringBuffer substituted = new StringBuffer();
// while (matcher.find()) {
// String property = matcher.group();
// matcher.appendReplacement(substituted, evaluateStringProperty(property, helper));
// }
// matcher.appendTail(substituted);
// return substituted.toString();
// }
// return input;
// }
//
// private static String evaluateStringProperty(String property, EnforcerRuleHelper helper) {
// try {
// return (String) helper.evaluate(property);
// } catch (ExpressionEvaluationException e) {
// throw new IllegalArgumentException("Unable to resolve property " + property);
// } catch (ClassCastException e) {
// throw new IllegalArgumentException("Property " + property + " does not evaluate to a String");
// }
// }
//
// private EnforcerRuleUtils() {
// }
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/ErrorReport.java
// public static <T> String toList(Collection<T> collection) {
// return toList(collection, Function.identity());
// }
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/PedanticModuleOrderEnforcer.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.apache.maven.project.MavenProject;
import com.github.ferstl.maven.pomenforcers.util.CommaSeparatorUtils;
import com.github.ferstl.maven.pomenforcers.util.EnforcerRuleUtils;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import static com.github.ferstl.maven.pomenforcers.ErrorReport.toList;
/*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers;
/**
* This enforcer makes sure that your <code>modules</code> section is sorted
* alphabetically. Modules that should occur at a specific position in the
* <code><modules></code> section can be ignored.
* <pre>
* ### Example
* <rules>
* <moduleOrder implementation="com.github.ferstl.maven.pomenforcers.PedanticModuleOrderEnforcer">
* <!-- These modules may occur at any place in the modules section -->
* <ignoredModules>dist-deb,dist-rpm</ignoredModules>
* </moduleOrder>
* </rules>
* </pre>
*
* @id {@link PedanticEnforcerRule#MODULE_ORDER}
* @since 1.0.0
*/
public class PedanticModuleOrderEnforcer extends AbstractPedanticEnforcer {
/**
* All modules in this set won't be checked for the correct order.
*/
private final Set<String> ignoredModules;
public PedanticModuleOrderEnforcer() {
this.ignoredModules = Sets.newLinkedHashSet();
}
/**
* Comma-separated list of ignored modules. All modules in this list may occur at any place in the
* <code>modules</code> section.
*
* @param ignoredModules Comma-separated list of ignored modules.
* @configParam
* @since 1.0.0
*/
public void setIgnoredModules(String ignoredModules) {
| CommaSeparatorUtils.splitAndAddToCollection(ignoredModules, this.ignoredModules);
|
ferstl/pedantic-pom-enforcers | src/main/java/com/github/ferstl/maven/pomenforcers/PedanticModuleOrderEnforcer.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/CommaSeparatorUtils.java
// public final class CommaSeparatorUtils {
//
// private static final Splitter COMMA_SPLITTER = Splitter.on(",").trimResults().omitEmptyStrings();
//
// public static void splitAndAddToCollection(String commaSeparatedItems, Collection<String> collection) {
// splitAndAddToCollection(commaSeparatedItems, collection, Function.identity());
// }
//
// public static <T> void splitAndAddToCollection(String commaSeparatedItems, Collection<T> collection, Function<String, T> transformer) {
// Iterable<String> items = COMMA_SPLITTER.split(commaSeparatedItems);
// // Don't touch the collection if there is nothing to add.
// if (items.iterator().hasNext()) {
// collection.clear();
// }
// StreamSupport.stream(items.spliterator(), false)
// .map(transformer)
// .collect(toCollection(() -> collection));
// }
//
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/EnforcerRuleUtils.java
// public final class EnforcerRuleUtils {
//
// private static final Pattern PROPERTY_PATTERN = Pattern.compile("\\$\\{.*?}");
//
// public static MavenProject getMavenProject(EnforcerRuleHelper helper) {
// try {
// return (MavenProject) helper.evaluate("${project}");
// } catch (ExpressionEvaluationException e) {
// throw new IllegalStateException("Unable to get maven project", e);
// }
// }
//
// public static String evaluateProperties(String input, EnforcerRuleHelper helper) {
// if (!Strings.isNullOrEmpty(input)) {
// Matcher matcher = PROPERTY_PATTERN.matcher(input);
// StringBuffer substituted = new StringBuffer();
// while (matcher.find()) {
// String property = matcher.group();
// matcher.appendReplacement(substituted, evaluateStringProperty(property, helper));
// }
// matcher.appendTail(substituted);
// return substituted.toString();
// }
// return input;
// }
//
// private static String evaluateStringProperty(String property, EnforcerRuleHelper helper) {
// try {
// return (String) helper.evaluate(property);
// } catch (ExpressionEvaluationException e) {
// throw new IllegalArgumentException("Unable to resolve property " + property);
// } catch (ClassCastException e) {
// throw new IllegalArgumentException("Property " + property + " does not evaluate to a String");
// }
// }
//
// private EnforcerRuleUtils() {
// }
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/ErrorReport.java
// public static <T> String toList(Collection<T> collection) {
// return toList(collection, Function.identity());
// }
| import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.apache.maven.project.MavenProject;
import com.github.ferstl.maven.pomenforcers.util.CommaSeparatorUtils;
import com.github.ferstl.maven.pomenforcers.util.EnforcerRuleUtils;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import static com.github.ferstl.maven.pomenforcers.ErrorReport.toList;
| /*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers;
/**
* This enforcer makes sure that your <code>modules</code> section is sorted
* alphabetically. Modules that should occur at a specific position in the
* <code><modules></code> section can be ignored.
* <pre>
* ### Example
* <rules>
* <moduleOrder implementation="com.github.ferstl.maven.pomenforcers.PedanticModuleOrderEnforcer">
* <!-- These modules may occur at any place in the modules section -->
* <ignoredModules>dist-deb,dist-rpm</ignoredModules>
* </moduleOrder>
* </rules>
* </pre>
*
* @id {@link PedanticEnforcerRule#MODULE_ORDER}
* @since 1.0.0
*/
public class PedanticModuleOrderEnforcer extends AbstractPedanticEnforcer {
/**
* All modules in this set won't be checked for the correct order.
*/
private final Set<String> ignoredModules;
public PedanticModuleOrderEnforcer() {
this.ignoredModules = Sets.newLinkedHashSet();
}
/**
* Comma-separated list of ignored modules. All modules in this list may occur at any place in the
* <code>modules</code> section.
*
* @param ignoredModules Comma-separated list of ignored modules.
* @configParam
* @since 1.0.0
*/
public void setIgnoredModules(String ignoredModules) {
CommaSeparatorUtils.splitAndAddToCollection(ignoredModules, this.ignoredModules);
}
@Override
protected PedanticEnforcerRule getDescription() {
return PedanticEnforcerRule.MODULE_ORDER;
}
@Override
protected void accept(PedanticEnforcerVisitor visitor) {
visitor.visit(this);
}
@Override
protected void doEnforce(ErrorReport report) {
| // Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/CommaSeparatorUtils.java
// public final class CommaSeparatorUtils {
//
// private static final Splitter COMMA_SPLITTER = Splitter.on(",").trimResults().omitEmptyStrings();
//
// public static void splitAndAddToCollection(String commaSeparatedItems, Collection<String> collection) {
// splitAndAddToCollection(commaSeparatedItems, collection, Function.identity());
// }
//
// public static <T> void splitAndAddToCollection(String commaSeparatedItems, Collection<T> collection, Function<String, T> transformer) {
// Iterable<String> items = COMMA_SPLITTER.split(commaSeparatedItems);
// // Don't touch the collection if there is nothing to add.
// if (items.iterator().hasNext()) {
// collection.clear();
// }
// StreamSupport.stream(items.spliterator(), false)
// .map(transformer)
// .collect(toCollection(() -> collection));
// }
//
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/EnforcerRuleUtils.java
// public final class EnforcerRuleUtils {
//
// private static final Pattern PROPERTY_PATTERN = Pattern.compile("\\$\\{.*?}");
//
// public static MavenProject getMavenProject(EnforcerRuleHelper helper) {
// try {
// return (MavenProject) helper.evaluate("${project}");
// } catch (ExpressionEvaluationException e) {
// throw new IllegalStateException("Unable to get maven project", e);
// }
// }
//
// public static String evaluateProperties(String input, EnforcerRuleHelper helper) {
// if (!Strings.isNullOrEmpty(input)) {
// Matcher matcher = PROPERTY_PATTERN.matcher(input);
// StringBuffer substituted = new StringBuffer();
// while (matcher.find()) {
// String property = matcher.group();
// matcher.appendReplacement(substituted, evaluateStringProperty(property, helper));
// }
// matcher.appendTail(substituted);
// return substituted.toString();
// }
// return input;
// }
//
// private static String evaluateStringProperty(String property, EnforcerRuleHelper helper) {
// try {
// return (String) helper.evaluate(property);
// } catch (ExpressionEvaluationException e) {
// throw new IllegalArgumentException("Unable to resolve property " + property);
// } catch (ClassCastException e) {
// throw new IllegalArgumentException("Property " + property + " does not evaluate to a String");
// }
// }
//
// private EnforcerRuleUtils() {
// }
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/ErrorReport.java
// public static <T> String toList(Collection<T> collection) {
// return toList(collection, Function.identity());
// }
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/PedanticModuleOrderEnforcer.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.apache.maven.project.MavenProject;
import com.github.ferstl.maven.pomenforcers.util.CommaSeparatorUtils;
import com.github.ferstl.maven.pomenforcers.util.EnforcerRuleUtils;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import static com.github.ferstl.maven.pomenforcers.ErrorReport.toList;
/*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers;
/**
* This enforcer makes sure that your <code>modules</code> section is sorted
* alphabetically. Modules that should occur at a specific position in the
* <code><modules></code> section can be ignored.
* <pre>
* ### Example
* <rules>
* <moduleOrder implementation="com.github.ferstl.maven.pomenforcers.PedanticModuleOrderEnforcer">
* <!-- These modules may occur at any place in the modules section -->
* <ignoredModules>dist-deb,dist-rpm</ignoredModules>
* </moduleOrder>
* </rules>
* </pre>
*
* @id {@link PedanticEnforcerRule#MODULE_ORDER}
* @since 1.0.0
*/
public class PedanticModuleOrderEnforcer extends AbstractPedanticEnforcer {
/**
* All modules in this set won't be checked for the correct order.
*/
private final Set<String> ignoredModules;
public PedanticModuleOrderEnforcer() {
this.ignoredModules = Sets.newLinkedHashSet();
}
/**
* Comma-separated list of ignored modules. All modules in this list may occur at any place in the
* <code>modules</code> section.
*
* @param ignoredModules Comma-separated list of ignored modules.
* @configParam
* @since 1.0.0
*/
public void setIgnoredModules(String ignoredModules) {
CommaSeparatorUtils.splitAndAddToCollection(ignoredModules, this.ignoredModules);
}
@Override
protected PedanticEnforcerRule getDescription() {
return PedanticEnforcerRule.MODULE_ORDER;
}
@Override
protected void accept(PedanticEnforcerVisitor visitor) {
visitor.visit(this);
}
@Override
protected void doEnforce(ErrorReport report) {
| MavenProject project = EnforcerRuleUtils.getMavenProject(getHelper());
|
ferstl/pedantic-pom-enforcers | src/main/java/com/github/ferstl/maven/pomenforcers/PedanticModuleOrderEnforcer.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/CommaSeparatorUtils.java
// public final class CommaSeparatorUtils {
//
// private static final Splitter COMMA_SPLITTER = Splitter.on(",").trimResults().omitEmptyStrings();
//
// public static void splitAndAddToCollection(String commaSeparatedItems, Collection<String> collection) {
// splitAndAddToCollection(commaSeparatedItems, collection, Function.identity());
// }
//
// public static <T> void splitAndAddToCollection(String commaSeparatedItems, Collection<T> collection, Function<String, T> transformer) {
// Iterable<String> items = COMMA_SPLITTER.split(commaSeparatedItems);
// // Don't touch the collection if there is nothing to add.
// if (items.iterator().hasNext()) {
// collection.clear();
// }
// StreamSupport.stream(items.spliterator(), false)
// .map(transformer)
// .collect(toCollection(() -> collection));
// }
//
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/EnforcerRuleUtils.java
// public final class EnforcerRuleUtils {
//
// private static final Pattern PROPERTY_PATTERN = Pattern.compile("\\$\\{.*?}");
//
// public static MavenProject getMavenProject(EnforcerRuleHelper helper) {
// try {
// return (MavenProject) helper.evaluate("${project}");
// } catch (ExpressionEvaluationException e) {
// throw new IllegalStateException("Unable to get maven project", e);
// }
// }
//
// public static String evaluateProperties(String input, EnforcerRuleHelper helper) {
// if (!Strings.isNullOrEmpty(input)) {
// Matcher matcher = PROPERTY_PATTERN.matcher(input);
// StringBuffer substituted = new StringBuffer();
// while (matcher.find()) {
// String property = matcher.group();
// matcher.appendReplacement(substituted, evaluateStringProperty(property, helper));
// }
// matcher.appendTail(substituted);
// return substituted.toString();
// }
// return input;
// }
//
// private static String evaluateStringProperty(String property, EnforcerRuleHelper helper) {
// try {
// return (String) helper.evaluate(property);
// } catch (ExpressionEvaluationException e) {
// throw new IllegalArgumentException("Unable to resolve property " + property);
// } catch (ClassCastException e) {
// throw new IllegalArgumentException("Property " + property + " does not evaluate to a String");
// }
// }
//
// private EnforcerRuleUtils() {
// }
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/ErrorReport.java
// public static <T> String toList(Collection<T> collection) {
// return toList(collection, Function.identity());
// }
| import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.apache.maven.project.MavenProject;
import com.github.ferstl.maven.pomenforcers.util.CommaSeparatorUtils;
import com.github.ferstl.maven.pomenforcers.util.EnforcerRuleUtils;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import static com.github.ferstl.maven.pomenforcers.ErrorReport.toList;
| @Override
protected void doEnforce(ErrorReport report) {
MavenProject project = EnforcerRuleUtils.getMavenProject(getHelper());
// Do nothing if the project is not a parent project
if (!isPomProject(project)) {
return;
}
// Remove all modules to be ignored.
List<String> declaredModules = new ArrayList<>(getProjectModel().getModules());
declaredModules.removeAll(this.ignoredModules);
// Enforce the module order
Ordering<String> moduleOrdering = Ordering.natural();
if (!moduleOrdering.isOrdered(declaredModules)) {
reportError(report, declaredModules, moduleOrdering.immutableSortedCopy(declaredModules));
}
}
private boolean isPomProject(MavenProject project) {
return "pom".equals(project.getPackaging());
}
private void reportError(ErrorReport report, Collection<String> declaredModules, Collection<String> orderedModules) {
report.addLine("You have to sort your modules alphabetically:")
.emptyLine()
.addDiff(declaredModules, orderedModules, "Actual Order", "Required Order");
if (!this.ignoredModules.isEmpty()) {
report.emptyLine()
.addLine("You may place these modules anywhere in your <modules> section:")
| // Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/CommaSeparatorUtils.java
// public final class CommaSeparatorUtils {
//
// private static final Splitter COMMA_SPLITTER = Splitter.on(",").trimResults().omitEmptyStrings();
//
// public static void splitAndAddToCollection(String commaSeparatedItems, Collection<String> collection) {
// splitAndAddToCollection(commaSeparatedItems, collection, Function.identity());
// }
//
// public static <T> void splitAndAddToCollection(String commaSeparatedItems, Collection<T> collection, Function<String, T> transformer) {
// Iterable<String> items = COMMA_SPLITTER.split(commaSeparatedItems);
// // Don't touch the collection if there is nothing to add.
// if (items.iterator().hasNext()) {
// collection.clear();
// }
// StreamSupport.stream(items.spliterator(), false)
// .map(transformer)
// .collect(toCollection(() -> collection));
// }
//
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/EnforcerRuleUtils.java
// public final class EnforcerRuleUtils {
//
// private static final Pattern PROPERTY_PATTERN = Pattern.compile("\\$\\{.*?}");
//
// public static MavenProject getMavenProject(EnforcerRuleHelper helper) {
// try {
// return (MavenProject) helper.evaluate("${project}");
// } catch (ExpressionEvaluationException e) {
// throw new IllegalStateException("Unable to get maven project", e);
// }
// }
//
// public static String evaluateProperties(String input, EnforcerRuleHelper helper) {
// if (!Strings.isNullOrEmpty(input)) {
// Matcher matcher = PROPERTY_PATTERN.matcher(input);
// StringBuffer substituted = new StringBuffer();
// while (matcher.find()) {
// String property = matcher.group();
// matcher.appendReplacement(substituted, evaluateStringProperty(property, helper));
// }
// matcher.appendTail(substituted);
// return substituted.toString();
// }
// return input;
// }
//
// private static String evaluateStringProperty(String property, EnforcerRuleHelper helper) {
// try {
// return (String) helper.evaluate(property);
// } catch (ExpressionEvaluationException e) {
// throw new IllegalArgumentException("Unable to resolve property " + property);
// } catch (ClassCastException e) {
// throw new IllegalArgumentException("Property " + property + " does not evaluate to a String");
// }
// }
//
// private EnforcerRuleUtils() {
// }
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/ErrorReport.java
// public static <T> String toList(Collection<T> collection) {
// return toList(collection, Function.identity());
// }
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/PedanticModuleOrderEnforcer.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.apache.maven.project.MavenProject;
import com.github.ferstl.maven.pomenforcers.util.CommaSeparatorUtils;
import com.github.ferstl.maven.pomenforcers.util.EnforcerRuleUtils;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import static com.github.ferstl.maven.pomenforcers.ErrorReport.toList;
@Override
protected void doEnforce(ErrorReport report) {
MavenProject project = EnforcerRuleUtils.getMavenProject(getHelper());
// Do nothing if the project is not a parent project
if (!isPomProject(project)) {
return;
}
// Remove all modules to be ignored.
List<String> declaredModules = new ArrayList<>(getProjectModel().getModules());
declaredModules.removeAll(this.ignoredModules);
// Enforce the module order
Ordering<String> moduleOrdering = Ordering.natural();
if (!moduleOrdering.isOrdered(declaredModules)) {
reportError(report, declaredModules, moduleOrdering.immutableSortedCopy(declaredModules));
}
}
private boolean isPomProject(MavenProject project) {
return "pom".equals(project.getPackaging());
}
private void reportError(ErrorReport report, Collection<String> declaredModules, Collection<String> orderedModules) {
report.addLine("You have to sort your modules alphabetically:")
.emptyLine()
.addDiff(declaredModules, orderedModules, "Actual Order", "Required Order");
if (!this.ignoredModules.isEmpty()) {
report.emptyLine()
.addLine("You may place these modules anywhere in your <modules> section:")
| .addLine(toList(this.ignoredModules));
|
ferstl/pedantic-pom-enforcers | src/test/java/com/github/ferstl/maven/pomenforcers/PedanticPomSectionOrderEnforcerTest.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PomSection.java
// public enum PomSection {
// MODEL_VERSION("modelVersion"),
// PREREQUISITES("prerequisites"),
// PARENT("parent"),
// GROUP_ID("groupId"),
// ARTIFACT_ID("artifactId"),
// VERSION("version"),
// PACKAGING("packaging"),
// NAME("name"),
// DESCRIPTION("description"),
// URL("url"),
// LICENSES("licenses"),
// ORGANIZATION("organization"),
// INCEPTION_YEAR("inceptionYear"),
// CI_MANAGEMENT("ciManagement"),
// MAILING_LISTS("mailingLists"),
// ISSUE_MANAGEMENT("issueManagement"),
// DEVELOPERS("developers"),
// CONTRIBUTORS("contributors"),
// SCM("scm"),
// REPOSITORIES("repositories"),
// PLUGIN_REPOSITORIES("pluginRepositories"),
// DISTRIBUTION_MANAGEMENT("distributionManagement"),
// MODULES("modules"),
// PROPERTIES("properties"),
// DEPENDENCY_MANAGEMENT("dependencyManagement"),
// DEPENDENCIES("dependencies"),
// BUILD("build"),
// PROFILES("profiles"),
// REPORTING("reporting"),
// REPORTS("reports");
//
// private static final Map<String, PomSection> pomSectionMap;
//
// static {
// pomSectionMap = Maps.newHashMap();
// for (PomSection pomSection : values()) {
// pomSectionMap.put(pomSection.getSectionName(), pomSection);
// }
// }
//
// public static PomSection getBySectionName(String sectionName) {
// requireNonNull(sectionName, "Section name is null.");
//
// PomSection value = pomSectionMap.get(sectionName);
// if (value == null) {
// throw new IllegalArgumentException("POM section " + sectionName + " does not exist.");
// }
//
// return value;
// }
//
// private final String sectionName;
//
// PomSection(String sectionName) {
// this.sectionName = sectionName;
// }
//
// public String getSectionName() {
// return this.sectionName;
// }
// }
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.github.ferstl.maven.pomenforcers.model.PomSection;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; | /*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers;
/**
* JUnit tests for {@link PedanticPomSectionOrderEnforcer}.
*/
public class PedanticPomSectionOrderEnforcerTest extends AbstractPedanticEnforcerTest<PedanticPomSectionOrderEnforcer> {
@Override
PedanticPomSectionOrderEnforcer createRule() {
return new PedanticPomSectionOrderEnforcer();
}
@Override
@Test
public void getDescription() {
assertThat(this.testRule.getDescription(), equalTo(PedanticEnforcerRule.POM_SECTION_ORDER));
}
@Override
@Test
public void accept() {
PedanticEnforcerVisitor visitor = mock(PedanticEnforcerVisitor.class);
this.testRule.accept(visitor);
verify(visitor).visit(this.testRule);
}
@Test
public void defaultSettingsCorrect() { | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PomSection.java
// public enum PomSection {
// MODEL_VERSION("modelVersion"),
// PREREQUISITES("prerequisites"),
// PARENT("parent"),
// GROUP_ID("groupId"),
// ARTIFACT_ID("artifactId"),
// VERSION("version"),
// PACKAGING("packaging"),
// NAME("name"),
// DESCRIPTION("description"),
// URL("url"),
// LICENSES("licenses"),
// ORGANIZATION("organization"),
// INCEPTION_YEAR("inceptionYear"),
// CI_MANAGEMENT("ciManagement"),
// MAILING_LISTS("mailingLists"),
// ISSUE_MANAGEMENT("issueManagement"),
// DEVELOPERS("developers"),
// CONTRIBUTORS("contributors"),
// SCM("scm"),
// REPOSITORIES("repositories"),
// PLUGIN_REPOSITORIES("pluginRepositories"),
// DISTRIBUTION_MANAGEMENT("distributionManagement"),
// MODULES("modules"),
// PROPERTIES("properties"),
// DEPENDENCY_MANAGEMENT("dependencyManagement"),
// DEPENDENCIES("dependencies"),
// BUILD("build"),
// PROFILES("profiles"),
// REPORTING("reporting"),
// REPORTS("reports");
//
// private static final Map<String, PomSection> pomSectionMap;
//
// static {
// pomSectionMap = Maps.newHashMap();
// for (PomSection pomSection : values()) {
// pomSectionMap.put(pomSection.getSectionName(), pomSection);
// }
// }
//
// public static PomSection getBySectionName(String sectionName) {
// requireNonNull(sectionName, "Section name is null.");
//
// PomSection value = pomSectionMap.get(sectionName);
// if (value == null) {
// throw new IllegalArgumentException("POM section " + sectionName + " does not exist.");
// }
//
// return value;
// }
//
// private final String sectionName;
//
// PomSection(String sectionName) {
// this.sectionName = sectionName;
// }
//
// public String getSectionName() {
// return this.sectionName;
// }
// }
// Path: src/test/java/com/github/ferstl/maven/pomenforcers/PedanticPomSectionOrderEnforcerTest.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.github.ferstl.maven.pomenforcers.model.PomSection;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers;
/**
* JUnit tests for {@link PedanticPomSectionOrderEnforcer}.
*/
public class PedanticPomSectionOrderEnforcerTest extends AbstractPedanticEnforcerTest<PedanticPomSectionOrderEnforcer> {
@Override
PedanticPomSectionOrderEnforcer createRule() {
return new PedanticPomSectionOrderEnforcer();
}
@Override
@Test
public void getDescription() {
assertThat(this.testRule.getDescription(), equalTo(PedanticEnforcerRule.POM_SECTION_ORDER));
}
@Override
@Test
public void accept() {
PedanticEnforcerVisitor visitor = mock(PedanticEnforcerVisitor.class);
this.testRule.accept(visitor);
verify(visitor).visit(this.testRule);
}
@Test
public void defaultSettingsCorrect() { | configurePom(Arrays.asList(PomSection.values())); |
ferstl/pedantic-pom-enforcers | src/main/java/com/github/ferstl/maven/pomenforcers/model/DependencyElement.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/priority/PriorityOrdering.java
// public class PriorityOrdering<P extends Comparable<? super P>, T> extends Ordering<T> {
//
// /**
// * The priority collection.
// */
// private final Collection<P> priorityCollection;
//
// /**
// * Matches the values to be compared with the items in the priority collection.
// */
// private final Equivalence<? super P> priorityMatcher;
//
// /**
// * Transforms the type of the objects to be compared into the type of the priority collection. Use
// * {@link Function#identity()} if the type of the priority collection and the type of the objects to be
// * compared are the same.
// */
// private final Function<T, P> transformer;
//
//
// public PriorityOrdering(Collection<P> prioritizedItems, Function<T, P> transformer, Equivalence<? super P> priorityMatcher) {
// this.priorityCollection = prioritizedItems;
// this.priorityMatcher = priorityMatcher;
// this.transformer = transformer;
// }
//
// public PriorityOrdering(Collection<P> priorityCollection, Function<T, P> transformer) {
// this(priorityCollection, transformer, Equivalence.equals());
// }
//
// @Override
// public int compare(T object1, T object2) {
// P comparable1 = this.transformer.apply(object1);
// P comparable2 = this.transformer.apply(object2);
//
// int rank1 = this.rank(comparable1);
// int rank2 = this.rank(comparable2);
//
// if (rank1 == rank2) {
// return comparable1.compareTo(comparable2);
// }
//
// return rank1 - rank2;
//
// }
//
// /**
// * Determine the priority of the given item by matching it against the priority collection.
// * The lower the rank, the higher the priority.
// *
// * @param item The item to prioritize.
// * @return The priority of the given item or {@link Integer#MAX_VALUE} if the given item does not
// * match any element of the priority collection.
// */
// private int rank(P item) {
// int i = 0;
// for (P prioritizedItem : this.priorityCollection) {
// if (this.priorityMatcher.equivalent(item, prioritizedItem)) {
// return i;
// }
// i++;
// }
//
// return Integer.MAX_VALUE;
// }
//
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/priority/PriorityOrderingFactory.java
// public interface PriorityOrderingFactory<P extends Comparable<? super P>, T> {
// PriorityOrdering<P, T> createPriorityOrdering(Collection<P> priorityCollection);
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/functions/StringStartsWithEquivalence.java
// public static Equivalence<String> stringStartsWith() {
// return INSTANCE;
// }
| import java.util.Collection;
import java.util.Map;
import java.util.function.Function;
import com.github.ferstl.maven.pomenforcers.priority.PriorityOrdering;
import com.github.ferstl.maven.pomenforcers.priority.PriorityOrderingFactory;
import com.google.common.collect.Maps;
import static com.github.ferstl.maven.pomenforcers.model.functions.StringStartsWithEquivalence.stringStartsWith;
import static java.util.Objects.requireNonNull;
| /*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers.model;
public enum DependencyElement implements PriorityOrderingFactory<String, DependencyModel>, Function<DependencyModel, String> {
GROUP_ID("groupId") {
@Override
| // Path: src/main/java/com/github/ferstl/maven/pomenforcers/priority/PriorityOrdering.java
// public class PriorityOrdering<P extends Comparable<? super P>, T> extends Ordering<T> {
//
// /**
// * The priority collection.
// */
// private final Collection<P> priorityCollection;
//
// /**
// * Matches the values to be compared with the items in the priority collection.
// */
// private final Equivalence<? super P> priorityMatcher;
//
// /**
// * Transforms the type of the objects to be compared into the type of the priority collection. Use
// * {@link Function#identity()} if the type of the priority collection and the type of the objects to be
// * compared are the same.
// */
// private final Function<T, P> transformer;
//
//
// public PriorityOrdering(Collection<P> prioritizedItems, Function<T, P> transformer, Equivalence<? super P> priorityMatcher) {
// this.priorityCollection = prioritizedItems;
// this.priorityMatcher = priorityMatcher;
// this.transformer = transformer;
// }
//
// public PriorityOrdering(Collection<P> priorityCollection, Function<T, P> transformer) {
// this(priorityCollection, transformer, Equivalence.equals());
// }
//
// @Override
// public int compare(T object1, T object2) {
// P comparable1 = this.transformer.apply(object1);
// P comparable2 = this.transformer.apply(object2);
//
// int rank1 = this.rank(comparable1);
// int rank2 = this.rank(comparable2);
//
// if (rank1 == rank2) {
// return comparable1.compareTo(comparable2);
// }
//
// return rank1 - rank2;
//
// }
//
// /**
// * Determine the priority of the given item by matching it against the priority collection.
// * The lower the rank, the higher the priority.
// *
// * @param item The item to prioritize.
// * @return The priority of the given item or {@link Integer#MAX_VALUE} if the given item does not
// * match any element of the priority collection.
// */
// private int rank(P item) {
// int i = 0;
// for (P prioritizedItem : this.priorityCollection) {
// if (this.priorityMatcher.equivalent(item, prioritizedItem)) {
// return i;
// }
// i++;
// }
//
// return Integer.MAX_VALUE;
// }
//
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/priority/PriorityOrderingFactory.java
// public interface PriorityOrderingFactory<P extends Comparable<? super P>, T> {
// PriorityOrdering<P, T> createPriorityOrdering(Collection<P> priorityCollection);
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/functions/StringStartsWithEquivalence.java
// public static Equivalence<String> stringStartsWith() {
// return INSTANCE;
// }
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/DependencyElement.java
import java.util.Collection;
import java.util.Map;
import java.util.function.Function;
import com.github.ferstl.maven.pomenforcers.priority.PriorityOrdering;
import com.github.ferstl.maven.pomenforcers.priority.PriorityOrderingFactory;
import com.google.common.collect.Maps;
import static com.github.ferstl.maven.pomenforcers.model.functions.StringStartsWithEquivalence.stringStartsWith;
import static java.util.Objects.requireNonNull;
/*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers.model;
public enum DependencyElement implements PriorityOrderingFactory<String, DependencyModel>, Function<DependencyModel, String> {
GROUP_ID("groupId") {
@Override
| public PriorityOrdering<String, DependencyModel> createPriorityOrdering(Collection<String> priorityCollection) {
|
ferstl/pedantic-pom-enforcers | src/main/java/com/github/ferstl/maven/pomenforcers/model/DependencyElement.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/priority/PriorityOrdering.java
// public class PriorityOrdering<P extends Comparable<? super P>, T> extends Ordering<T> {
//
// /**
// * The priority collection.
// */
// private final Collection<P> priorityCollection;
//
// /**
// * Matches the values to be compared with the items in the priority collection.
// */
// private final Equivalence<? super P> priorityMatcher;
//
// /**
// * Transforms the type of the objects to be compared into the type of the priority collection. Use
// * {@link Function#identity()} if the type of the priority collection and the type of the objects to be
// * compared are the same.
// */
// private final Function<T, P> transformer;
//
//
// public PriorityOrdering(Collection<P> prioritizedItems, Function<T, P> transformer, Equivalence<? super P> priorityMatcher) {
// this.priorityCollection = prioritizedItems;
// this.priorityMatcher = priorityMatcher;
// this.transformer = transformer;
// }
//
// public PriorityOrdering(Collection<P> priorityCollection, Function<T, P> transformer) {
// this(priorityCollection, transformer, Equivalence.equals());
// }
//
// @Override
// public int compare(T object1, T object2) {
// P comparable1 = this.transformer.apply(object1);
// P comparable2 = this.transformer.apply(object2);
//
// int rank1 = this.rank(comparable1);
// int rank2 = this.rank(comparable2);
//
// if (rank1 == rank2) {
// return comparable1.compareTo(comparable2);
// }
//
// return rank1 - rank2;
//
// }
//
// /**
// * Determine the priority of the given item by matching it against the priority collection.
// * The lower the rank, the higher the priority.
// *
// * @param item The item to prioritize.
// * @return The priority of the given item or {@link Integer#MAX_VALUE} if the given item does not
// * match any element of the priority collection.
// */
// private int rank(P item) {
// int i = 0;
// for (P prioritizedItem : this.priorityCollection) {
// if (this.priorityMatcher.equivalent(item, prioritizedItem)) {
// return i;
// }
// i++;
// }
//
// return Integer.MAX_VALUE;
// }
//
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/priority/PriorityOrderingFactory.java
// public interface PriorityOrderingFactory<P extends Comparable<? super P>, T> {
// PriorityOrdering<P, T> createPriorityOrdering(Collection<P> priorityCollection);
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/functions/StringStartsWithEquivalence.java
// public static Equivalence<String> stringStartsWith() {
// return INSTANCE;
// }
| import java.util.Collection;
import java.util.Map;
import java.util.function.Function;
import com.github.ferstl.maven.pomenforcers.priority.PriorityOrdering;
import com.github.ferstl.maven.pomenforcers.priority.PriorityOrderingFactory;
import com.google.common.collect.Maps;
import static com.github.ferstl.maven.pomenforcers.model.functions.StringStartsWithEquivalence.stringStartsWith;
import static java.util.Objects.requireNonNull;
| /*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers.model;
public enum DependencyElement implements PriorityOrderingFactory<String, DependencyModel>, Function<DependencyModel, String> {
GROUP_ID("groupId") {
@Override
public PriorityOrdering<String, DependencyModel> createPriorityOrdering(Collection<String> priorityCollection) {
| // Path: src/main/java/com/github/ferstl/maven/pomenforcers/priority/PriorityOrdering.java
// public class PriorityOrdering<P extends Comparable<? super P>, T> extends Ordering<T> {
//
// /**
// * The priority collection.
// */
// private final Collection<P> priorityCollection;
//
// /**
// * Matches the values to be compared with the items in the priority collection.
// */
// private final Equivalence<? super P> priorityMatcher;
//
// /**
// * Transforms the type of the objects to be compared into the type of the priority collection. Use
// * {@link Function#identity()} if the type of the priority collection and the type of the objects to be
// * compared are the same.
// */
// private final Function<T, P> transformer;
//
//
// public PriorityOrdering(Collection<P> prioritizedItems, Function<T, P> transformer, Equivalence<? super P> priorityMatcher) {
// this.priorityCollection = prioritizedItems;
// this.priorityMatcher = priorityMatcher;
// this.transformer = transformer;
// }
//
// public PriorityOrdering(Collection<P> priorityCollection, Function<T, P> transformer) {
// this(priorityCollection, transformer, Equivalence.equals());
// }
//
// @Override
// public int compare(T object1, T object2) {
// P comparable1 = this.transformer.apply(object1);
// P comparable2 = this.transformer.apply(object2);
//
// int rank1 = this.rank(comparable1);
// int rank2 = this.rank(comparable2);
//
// if (rank1 == rank2) {
// return comparable1.compareTo(comparable2);
// }
//
// return rank1 - rank2;
//
// }
//
// /**
// * Determine the priority of the given item by matching it against the priority collection.
// * The lower the rank, the higher the priority.
// *
// * @param item The item to prioritize.
// * @return The priority of the given item or {@link Integer#MAX_VALUE} if the given item does not
// * match any element of the priority collection.
// */
// private int rank(P item) {
// int i = 0;
// for (P prioritizedItem : this.priorityCollection) {
// if (this.priorityMatcher.equivalent(item, prioritizedItem)) {
// return i;
// }
// i++;
// }
//
// return Integer.MAX_VALUE;
// }
//
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/priority/PriorityOrderingFactory.java
// public interface PriorityOrderingFactory<P extends Comparable<? super P>, T> {
// PriorityOrdering<P, T> createPriorityOrdering(Collection<P> priorityCollection);
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/functions/StringStartsWithEquivalence.java
// public static Equivalence<String> stringStartsWith() {
// return INSTANCE;
// }
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/DependencyElement.java
import java.util.Collection;
import java.util.Map;
import java.util.function.Function;
import com.github.ferstl.maven.pomenforcers.priority.PriorityOrdering;
import com.github.ferstl.maven.pomenforcers.priority.PriorityOrderingFactory;
import com.google.common.collect.Maps;
import static com.github.ferstl.maven.pomenforcers.model.functions.StringStartsWithEquivalence.stringStartsWith;
import static java.util.Objects.requireNonNull;
/*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers.model;
public enum DependencyElement implements PriorityOrderingFactory<String, DependencyModel>, Function<DependencyModel, String> {
GROUP_ID("groupId") {
@Override
public PriorityOrdering<String, DependencyModel> createPriorityOrdering(Collection<String> priorityCollection) {
| return new PriorityOrdering<>(priorityCollection, this, stringStartsWith());
|
ferstl/pedantic-pom-enforcers | src/main/java/com/github/ferstl/maven/pomenforcers/PedanticPluginConfigurationEnforcer.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PluginModel.java
// public class PluginModel extends ArtifactModel {
//
// @XmlElementWrapper(name = "configuration", namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlAnyElement
// private List<Element> configItems;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private DependenciesModel dependencies;
//
// PluginModel() {
// }
//
// public PluginModel(String groupId, String artifactId, String version) {
// super(groupId, artifactId, version);
// }
//
// public boolean isConfigured() {
// return this.configItems != null && !this.configItems.isEmpty();
// }
//
// public List<DependencyModel> getDependencies() {
// return this.dependencies != null ? this.dependencies.getDependencies() : Collections.emptyList();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (!(obj instanceof PluginModel)) {
// return false;
// }
//
// PluginModel other = (PluginModel) obj;
// return super.equals(other)
// // TODO: Element implementations may not implement equals()!!
// && Objects.equals(this.configItems, other.configItems)
// && Objects.equals(this.dependencies, other.dependencies);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.configItems, this.dependencies);
// }
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/ErrorReport.java
// public static <T> String toList(Collection<T> collection) {
// return toList(collection, Function.identity());
// }
| import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import com.github.ferstl.maven.pomenforcers.model.PluginModel;
import static com.github.ferstl.maven.pomenforcers.ErrorReport.toList; | public void setManageDependencies(boolean manageDependencies) {
this.manageDependencies = manageDependencies;
}
@Override
protected PedanticEnforcerRule getDescription() {
return PedanticEnforcerRule.PLUGIN_CONFIGURATION;
}
@Override
protected void accept(PedanticEnforcerVisitor visitor) {
visitor.visit(this);
}
@Override
protected void doEnforce(ErrorReport report) {
if (this.manageVersions) {
enforceManagedVersions(report);
}
if (this.manageConfigurations) {
enforceManagedConfiguration(report);
}
if (this.manageDependencies) {
enforceManagedDependencies(report);
}
}
private void enforceManagedVersions(ErrorReport report) { | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PluginModel.java
// public class PluginModel extends ArtifactModel {
//
// @XmlElementWrapper(name = "configuration", namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlAnyElement
// private List<Element> configItems;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private DependenciesModel dependencies;
//
// PluginModel() {
// }
//
// public PluginModel(String groupId, String artifactId, String version) {
// super(groupId, artifactId, version);
// }
//
// public boolean isConfigured() {
// return this.configItems != null && !this.configItems.isEmpty();
// }
//
// public List<DependencyModel> getDependencies() {
// return this.dependencies != null ? this.dependencies.getDependencies() : Collections.emptyList();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (!(obj instanceof PluginModel)) {
// return false;
// }
//
// PluginModel other = (PluginModel) obj;
// return super.equals(other)
// // TODO: Element implementations may not implement equals()!!
// && Objects.equals(this.configItems, other.configItems)
// && Objects.equals(this.dependencies, other.dependencies);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.configItems, this.dependencies);
// }
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/ErrorReport.java
// public static <T> String toList(Collection<T> collection) {
// return toList(collection, Function.identity());
// }
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/PedanticPluginConfigurationEnforcer.java
import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import com.github.ferstl.maven.pomenforcers.model.PluginModel;
import static com.github.ferstl.maven.pomenforcers.ErrorReport.toList;
public void setManageDependencies(boolean manageDependencies) {
this.manageDependencies = manageDependencies;
}
@Override
protected PedanticEnforcerRule getDescription() {
return PedanticEnforcerRule.PLUGIN_CONFIGURATION;
}
@Override
protected void accept(PedanticEnforcerVisitor visitor) {
visitor.visit(this);
}
@Override
protected void doEnforce(ErrorReport report) {
if (this.manageVersions) {
enforceManagedVersions(report);
}
if (this.manageConfigurations) {
enforceManagedConfiguration(report);
}
if (this.manageDependencies) {
enforceManagedDependencies(report);
}
}
private void enforceManagedVersions(ErrorReport report) { | Collection<PluginModel> versionedPlugins = searchForPlugins(PluginPredicate.WITH_VERSION); |
ferstl/pedantic-pom-enforcers | src/main/java/com/github/ferstl/maven/pomenforcers/PedanticPluginConfigurationEnforcer.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PluginModel.java
// public class PluginModel extends ArtifactModel {
//
// @XmlElementWrapper(name = "configuration", namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlAnyElement
// private List<Element> configItems;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private DependenciesModel dependencies;
//
// PluginModel() {
// }
//
// public PluginModel(String groupId, String artifactId, String version) {
// super(groupId, artifactId, version);
// }
//
// public boolean isConfigured() {
// return this.configItems != null && !this.configItems.isEmpty();
// }
//
// public List<DependencyModel> getDependencies() {
// return this.dependencies != null ? this.dependencies.getDependencies() : Collections.emptyList();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (!(obj instanceof PluginModel)) {
// return false;
// }
//
// PluginModel other = (PluginModel) obj;
// return super.equals(other)
// // TODO: Element implementations may not implement equals()!!
// && Objects.equals(this.configItems, other.configItems)
// && Objects.equals(this.dependencies, other.dependencies);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.configItems, this.dependencies);
// }
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/ErrorReport.java
// public static <T> String toList(Collection<T> collection) {
// return toList(collection, Function.identity());
// }
| import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import com.github.ferstl.maven.pomenforcers.model.PluginModel;
import static com.github.ferstl.maven.pomenforcers.ErrorReport.toList; | @Override
protected PedanticEnforcerRule getDescription() {
return PedanticEnforcerRule.PLUGIN_CONFIGURATION;
}
@Override
protected void accept(PedanticEnforcerVisitor visitor) {
visitor.visit(this);
}
@Override
protected void doEnforce(ErrorReport report) {
if (this.manageVersions) {
enforceManagedVersions(report);
}
if (this.manageConfigurations) {
enforceManagedConfiguration(report);
}
if (this.manageDependencies) {
enforceManagedDependencies(report);
}
}
private void enforceManagedVersions(ErrorReport report) {
Collection<PluginModel> versionedPlugins = searchForPlugins(PluginPredicate.WITH_VERSION);
if (!versionedPlugins.isEmpty()) {
report.addLine("Plugin versions have to be declared in <pluginManagement>:") | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PluginModel.java
// public class PluginModel extends ArtifactModel {
//
// @XmlElementWrapper(name = "configuration", namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlAnyElement
// private List<Element> configItems;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private DependenciesModel dependencies;
//
// PluginModel() {
// }
//
// public PluginModel(String groupId, String artifactId, String version) {
// super(groupId, artifactId, version);
// }
//
// public boolean isConfigured() {
// return this.configItems != null && !this.configItems.isEmpty();
// }
//
// public List<DependencyModel> getDependencies() {
// return this.dependencies != null ? this.dependencies.getDependencies() : Collections.emptyList();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (!(obj instanceof PluginModel)) {
// return false;
// }
//
// PluginModel other = (PluginModel) obj;
// return super.equals(other)
// // TODO: Element implementations may not implement equals()!!
// && Objects.equals(this.configItems, other.configItems)
// && Objects.equals(this.dependencies, other.dependencies);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.configItems, this.dependencies);
// }
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/ErrorReport.java
// public static <T> String toList(Collection<T> collection) {
// return toList(collection, Function.identity());
// }
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/PedanticPluginConfigurationEnforcer.java
import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import com.github.ferstl.maven.pomenforcers.model.PluginModel;
import static com.github.ferstl.maven.pomenforcers.ErrorReport.toList;
@Override
protected PedanticEnforcerRule getDescription() {
return PedanticEnforcerRule.PLUGIN_CONFIGURATION;
}
@Override
protected void accept(PedanticEnforcerVisitor visitor) {
visitor.visit(this);
}
@Override
protected void doEnforce(ErrorReport report) {
if (this.manageVersions) {
enforceManagedVersions(report);
}
if (this.manageConfigurations) {
enforceManagedConfiguration(report);
}
if (this.manageDependencies) {
enforceManagedDependencies(report);
}
}
private void enforceManagedVersions(ErrorReport report) {
Collection<PluginModel> versionedPlugins = searchForPlugins(PluginPredicate.WITH_VERSION);
if (!versionedPlugins.isEmpty()) {
report.addLine("Plugin versions have to be declared in <pluginManagement>:") | .addLine(toList(versionedPlugins)); |
ferstl/pedantic-pom-enforcers | src/main/java/com/github/ferstl/maven/pomenforcers/model/functions/PluginMatcher.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PluginModel.java
// public class PluginModel extends ArtifactModel {
//
// @XmlElementWrapper(name = "configuration", namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlAnyElement
// private List<Element> configItems;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private DependenciesModel dependencies;
//
// PluginModel() {
// }
//
// public PluginModel(String groupId, String artifactId, String version) {
// super(groupId, artifactId, version);
// }
//
// public boolean isConfigured() {
// return this.configItems != null && !this.configItems.isEmpty();
// }
//
// public List<DependencyModel> getDependencies() {
// return this.dependencies != null ? this.dependencies.getDependencies() : Collections.emptyList();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (!(obj instanceof PluginModel)) {
// return false;
// }
//
// PluginModel other = (PluginModel) obj;
// return super.equals(other)
// // TODO: Element implementations may not implement equals()!!
// && Objects.equals(this.configItems, other.configItems)
// && Objects.equals(this.dependencies, other.dependencies);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.configItems, this.dependencies);
// }
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/EnforcerRuleUtils.java
// public static String evaluateProperties(String input, EnforcerRuleHelper helper) {
// if (!Strings.isNullOrEmpty(input)) {
// Matcher matcher = PROPERTY_PATTERN.matcher(input);
// StringBuffer substituted = new StringBuffer();
// while (matcher.find()) {
// String property = matcher.group();
// matcher.appendReplacement(substituted, evaluateStringProperty(property, helper));
// }
// matcher.appendTail(substituted);
// return substituted.toString();
// }
// return input;
// }
| import java.util.Objects;
import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper;
import org.apache.maven.model.Plugin;
import com.github.ferstl.maven.pomenforcers.model.PluginModel;
import static com.github.ferstl.maven.pomenforcers.util.EnforcerRuleUtils.evaluateProperties;
import static com.google.common.base.Strings.isNullOrEmpty; | /*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers.model.functions;
/**
* Matches Maven {@link Plugin} objects with {@link PluginModel} objects.
*/
public class PluginMatcher extends AbstractOneToOneMatcher<Plugin, PluginModel> {
private static final String DEFAULT_GROUP_ID = "org.apache.maven.plugins";
public PluginMatcher(EnforcerRuleHelper helper) {
super(helper);
}
@Override
protected PluginModel transform(Plugin mavenPlugin) {
return new PluginModel(mavenPlugin.getGroupId(), mavenPlugin.getArtifactId(), mavenPlugin.getVersion());
}
@Override
protected boolean matches(PluginModel supersetItem, PluginModel subsetItem) {
String groupId = getGroupId(subsetItem); | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PluginModel.java
// public class PluginModel extends ArtifactModel {
//
// @XmlElementWrapper(name = "configuration", namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlAnyElement
// private List<Element> configItems;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private DependenciesModel dependencies;
//
// PluginModel() {
// }
//
// public PluginModel(String groupId, String artifactId, String version) {
// super(groupId, artifactId, version);
// }
//
// public boolean isConfigured() {
// return this.configItems != null && !this.configItems.isEmpty();
// }
//
// public List<DependencyModel> getDependencies() {
// return this.dependencies != null ? this.dependencies.getDependencies() : Collections.emptyList();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (!(obj instanceof PluginModel)) {
// return false;
// }
//
// PluginModel other = (PluginModel) obj;
// return super.equals(other)
// // TODO: Element implementations may not implement equals()!!
// && Objects.equals(this.configItems, other.configItems)
// && Objects.equals(this.dependencies, other.dependencies);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.configItems, this.dependencies);
// }
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/EnforcerRuleUtils.java
// public static String evaluateProperties(String input, EnforcerRuleHelper helper) {
// if (!Strings.isNullOrEmpty(input)) {
// Matcher matcher = PROPERTY_PATTERN.matcher(input);
// StringBuffer substituted = new StringBuffer();
// while (matcher.find()) {
// String property = matcher.group();
// matcher.appendReplacement(substituted, evaluateStringProperty(property, helper));
// }
// matcher.appendTail(substituted);
// return substituted.toString();
// }
// return input;
// }
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/functions/PluginMatcher.java
import java.util.Objects;
import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper;
import org.apache.maven.model.Plugin;
import com.github.ferstl.maven.pomenforcers.model.PluginModel;
import static com.github.ferstl.maven.pomenforcers.util.EnforcerRuleUtils.evaluateProperties;
import static com.google.common.base.Strings.isNullOrEmpty;
/*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers.model.functions;
/**
* Matches Maven {@link Plugin} objects with {@link PluginModel} objects.
*/
public class PluginMatcher extends AbstractOneToOneMatcher<Plugin, PluginModel> {
private static final String DEFAULT_GROUP_ID = "org.apache.maven.plugins";
public PluginMatcher(EnforcerRuleHelper helper) {
super(helper);
}
@Override
protected PluginModel transform(Plugin mavenPlugin) {
return new PluginModel(mavenPlugin.getGroupId(), mavenPlugin.getArtifactId(), mavenPlugin.getVersion());
}
@Override
protected boolean matches(PluginModel supersetItem, PluginModel subsetItem) {
String groupId = getGroupId(subsetItem); | String artifactId = evaluateProperties(subsetItem.getArtifactId(), getHelper()); |
ferstl/pedantic-pom-enforcers | src/test/java/com/github/ferstl/maven/pomenforcers/AbstractPedanticDependencyOrderEnforcerTest.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/DependencyScope.java
// public enum DependencyScope {
//
// IMPORT("import"),
// COMPILE("compile"),
// PROVIDED("provided"),
// RUNTIME("runtime"),
// SYSTEM("system"),
// TEST("test");
//
// private static final Map<String, DependencyScope> dependencyScopeMap;
//
// static {
// dependencyScopeMap = new LinkedHashMap<>();
// for (DependencyScope scope : values()) {
// dependencyScopeMap.put(scope.getScopeName(), scope);
// }
// }
//
// public static DependencyScope getByScopeName(String scopeName) {
// requireNonNull(scopeName, "Scope name is null.");
//
// DependencyScope scope = dependencyScopeMap.get(scopeName);
// if (scope == null) {
// throw new IllegalArgumentException("Dependency scope'" + scopeName + "' does not exist.");
// }
//
// return scope;
// }
//
// private final String scopeName;
//
// DependencyScope(String name) {
// this.scopeName = name;
// }
//
// public String getScopeName() {
// return this.scopeName;
// }
// }
| import org.junit.Before;
import org.junit.Test;
import com.github.ferstl.maven.pomenforcers.model.DependencyScope; | /*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers;
/**
* <p>
* Abstract test for {@link PedanticDependencyOrderEnforcer} and
* {@link PedanticDependencyManagementOrderEnforcer}. Both classes do the same thing but one works
* on the managed dependencies and one on the dependencies themselves.
* </p>
*/
public abstract class AbstractPedanticDependencyOrderEnforcerTest<T extends AbstractPedanticDependencyOrderEnforcer>
extends AbstractPedanticEnforcerTest<T> {
private DependencyAdder dependencyAdder;
@Before
public void setupDependencyAdder() {
this.dependencyAdder = createDependencyAdder();
}
protected abstract DependencyAdder createDependencyAdder();
@Test
public void defaultSettingsCorrect() { | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/DependencyScope.java
// public enum DependencyScope {
//
// IMPORT("import"),
// COMPILE("compile"),
// PROVIDED("provided"),
// RUNTIME("runtime"),
// SYSTEM("system"),
// TEST("test");
//
// private static final Map<String, DependencyScope> dependencyScopeMap;
//
// static {
// dependencyScopeMap = new LinkedHashMap<>();
// for (DependencyScope scope : values()) {
// dependencyScopeMap.put(scope.getScopeName(), scope);
// }
// }
//
// public static DependencyScope getByScopeName(String scopeName) {
// requireNonNull(scopeName, "Scope name is null.");
//
// DependencyScope scope = dependencyScopeMap.get(scopeName);
// if (scope == null) {
// throw new IllegalArgumentException("Dependency scope'" + scopeName + "' does not exist.");
// }
//
// return scope;
// }
//
// private final String scopeName;
//
// DependencyScope(String name) {
// this.scopeName = name;
// }
//
// public String getScopeName() {
// return this.scopeName;
// }
// }
// Path: src/test/java/com/github/ferstl/maven/pomenforcers/AbstractPedanticDependencyOrderEnforcerTest.java
import org.junit.Before;
import org.junit.Test;
import com.github.ferstl.maven.pomenforcers.model.DependencyScope;
/*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers;
/**
* <p>
* Abstract test for {@link PedanticDependencyOrderEnforcer} and
* {@link PedanticDependencyManagementOrderEnforcer}. Both classes do the same thing but one works
* on the managed dependencies and one on the dependencies themselves.
* </p>
*/
public abstract class AbstractPedanticDependencyOrderEnforcerTest<T extends AbstractPedanticDependencyOrderEnforcer>
extends AbstractPedanticEnforcerTest<T> {
private DependencyAdder dependencyAdder;
@Before
public void setupDependencyAdder() {
this.dependencyAdder = createDependencyAdder();
}
protected abstract DependencyAdder createDependencyAdder();
@Test
public void defaultSettingsCorrect() { | this.dependencyAdder.addDependency("d.e.f", "a", DependencyScope.IMPORT); |
ferstl/pedantic-pom-enforcers | src/main/java/com/github/ferstl/maven/pomenforcers/CompoundPedanticEnforcer.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/CommaSeparatorUtils.java
// public final class CommaSeparatorUtils {
//
// private static final Splitter COMMA_SPLITTER = Splitter.on(",").trimResults().omitEmptyStrings();
//
// public static void splitAndAddToCollection(String commaSeparatedItems, Collection<String> collection) {
// splitAndAddToCollection(commaSeparatedItems, collection, Function.identity());
// }
//
// public static <T> void splitAndAddToCollection(String commaSeparatedItems, Collection<T> collection, Function<String, T> transformer) {
// Iterable<String> items = COMMA_SPLITTER.split(commaSeparatedItems);
// // Don't touch the collection if there is nothing to add.
// if (items.iterator().hasNext()) {
// collection.clear();
// }
// StreamSupport.stream(items.spliterator(), false)
// .map(transformer)
// .collect(toCollection(() -> collection));
// }
//
// }
| import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.github.ferstl.maven.pomenforcers.util.CommaSeparatorUtils;
import com.google.common.base.Strings;
import com.google.common.collect.Sets; |
/**
* See {@link PedanticPluginElementEnforcer#checkPlugins}.
*
* @configParam
* @since 2.0.0
*/
private Boolean checkPluginElements;
/**
* See {@link PedanticPluginElementEnforcer#checkPluginManagement}.
*
* @configParam
* @since 2.0.0
*/
private Boolean checkPluginManagementElements;
/**
* Collection of enforcers to execute.
*/
private final Collection<PedanticEnforcerRule> enforcers;
private final PropertyInitializationVisitor propertyInitializer;
public CompoundPedanticEnforcer() {
this.enforcers = Sets.newLinkedHashSet();
this.propertyInitializer = new PropertyInitializationVisitor();
}
public void setEnforcers(String enforcers) { | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/CommaSeparatorUtils.java
// public final class CommaSeparatorUtils {
//
// private static final Splitter COMMA_SPLITTER = Splitter.on(",").trimResults().omitEmptyStrings();
//
// public static void splitAndAddToCollection(String commaSeparatedItems, Collection<String> collection) {
// splitAndAddToCollection(commaSeparatedItems, collection, Function.identity());
// }
//
// public static <T> void splitAndAddToCollection(String commaSeparatedItems, Collection<T> collection, Function<String, T> transformer) {
// Iterable<String> items = COMMA_SPLITTER.split(commaSeparatedItems);
// // Don't touch the collection if there is nothing to add.
// if (items.iterator().hasNext()) {
// collection.clear();
// }
// StreamSupport.stream(items.spliterator(), false)
// .map(transformer)
// .collect(toCollection(() -> collection));
// }
//
// }
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/CompoundPedanticEnforcer.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.github.ferstl.maven.pomenforcers.util.CommaSeparatorUtils;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
/**
* See {@link PedanticPluginElementEnforcer#checkPlugins}.
*
* @configParam
* @since 2.0.0
*/
private Boolean checkPluginElements;
/**
* See {@link PedanticPluginElementEnforcer#checkPluginManagement}.
*
* @configParam
* @since 2.0.0
*/
private Boolean checkPluginManagementElements;
/**
* Collection of enforcers to execute.
*/
private final Collection<PedanticEnforcerRule> enforcers;
private final PropertyInitializationVisitor propertyInitializer;
public CompoundPedanticEnforcer() {
this.enforcers = Sets.newLinkedHashSet();
this.propertyInitializer = new PropertyInitializationVisitor();
}
public void setEnforcers(String enforcers) { | CommaSeparatorUtils.splitAndAddToCollection(enforcers, this.enforcers, PedanticEnforcerRule::valueOf); |
ferstl/pedantic-pom-enforcers | src/test/java/com/github/ferstl/maven/pomenforcers/util/SideBySideDiffUtilTest.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PomSection.java
// public enum PomSection {
// MODEL_VERSION("modelVersion"),
// PREREQUISITES("prerequisites"),
// PARENT("parent"),
// GROUP_ID("groupId"),
// ARTIFACT_ID("artifactId"),
// VERSION("version"),
// PACKAGING("packaging"),
// NAME("name"),
// DESCRIPTION("description"),
// URL("url"),
// LICENSES("licenses"),
// ORGANIZATION("organization"),
// INCEPTION_YEAR("inceptionYear"),
// CI_MANAGEMENT("ciManagement"),
// MAILING_LISTS("mailingLists"),
// ISSUE_MANAGEMENT("issueManagement"),
// DEVELOPERS("developers"),
// CONTRIBUTORS("contributors"),
// SCM("scm"),
// REPOSITORIES("repositories"),
// PLUGIN_REPOSITORIES("pluginRepositories"),
// DISTRIBUTION_MANAGEMENT("distributionManagement"),
// MODULES("modules"),
// PROPERTIES("properties"),
// DEPENDENCY_MANAGEMENT("dependencyManagement"),
// DEPENDENCIES("dependencies"),
// BUILD("build"),
// PROFILES("profiles"),
// REPORTING("reporting"),
// REPORTS("reports");
//
// private static final Map<String, PomSection> pomSectionMap;
//
// static {
// pomSectionMap = Maps.newHashMap();
// for (PomSection pomSection : values()) {
// pomSectionMap.put(pomSection.getSectionName(), pomSection);
// }
// }
//
// public static PomSection getBySectionName(String sectionName) {
// requireNonNull(sectionName, "Section name is null.");
//
// PomSection value = pomSectionMap.get(sectionName);
// if (value == null) {
// throw new IllegalArgumentException("POM section " + sectionName + " does not exist.");
// }
//
// return value;
// }
//
// private final String sectionName;
//
// PomSection(String sectionName) {
// this.sectionName = sectionName;
// }
//
// public String getSectionName() {
// return this.sectionName;
// }
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/SideBySideDiffUtil.java
// public static String diff(Collection<String> actual, Collection<String> required, String leftTitle, String rightTitle) {
//
// SideBySideContext context = new SideBySideContext(actual, required, leftTitle, rightTitle);
// int offset = 0;
//
// for (Delta<String> delta : context.deltas) {
// Chunk<String> original = delta.getOriginal();
// Chunk<String> revised = delta.getRevised();
// int currentPosition = original.getPosition() + offset;
//
// switch (delta.getType()) {
// case INSERT:
// offset += context.expand(currentPosition, revised.size());
// context.setRightContent(currentPosition, revised.getLines());
// break;
//
// case CHANGE:
// int difference = revised.size() - original.size();
// if (difference > 0) {
// offset += context.expand(currentPosition + original.size(), difference);
// } else {
// context.clearRightContent(currentPosition + revised.size(), Math.abs(difference));
// }
//
// context.setLeftContent(currentPosition, original.getLines());
// context.setRightContent(currentPosition, revised.getLines());
// break;
//
// case DELETE:
// context.setLeftContent(currentPosition, original.getLines());
// context.clearRightContent(currentPosition, original.size());
// break;
//
// default:
// throw new IllegalStateException("Unsupported delta type: " + delta.getType());
//
// }
// }
//
// return context.toString();
// }
| import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeDiagnosingMatcher;
import org.junit.Test;
import com.github.ferstl.maven.pomenforcers.model.PomSection;
import com.google.common.collect.Ordering;
import static com.github.ferstl.maven.pomenforcers.util.SideBySideDiffUtil.diff;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.junit.Assert.assertEquals;
import static org.hamcrest.MatcherAssert.assertThat; | /*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers.util;
/**
* JUnit tests for {@link SideBySideDiffUtil}.
*/
public class SideBySideDiffUtilTest {
@Test
public void insertion() { | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PomSection.java
// public enum PomSection {
// MODEL_VERSION("modelVersion"),
// PREREQUISITES("prerequisites"),
// PARENT("parent"),
// GROUP_ID("groupId"),
// ARTIFACT_ID("artifactId"),
// VERSION("version"),
// PACKAGING("packaging"),
// NAME("name"),
// DESCRIPTION("description"),
// URL("url"),
// LICENSES("licenses"),
// ORGANIZATION("organization"),
// INCEPTION_YEAR("inceptionYear"),
// CI_MANAGEMENT("ciManagement"),
// MAILING_LISTS("mailingLists"),
// ISSUE_MANAGEMENT("issueManagement"),
// DEVELOPERS("developers"),
// CONTRIBUTORS("contributors"),
// SCM("scm"),
// REPOSITORIES("repositories"),
// PLUGIN_REPOSITORIES("pluginRepositories"),
// DISTRIBUTION_MANAGEMENT("distributionManagement"),
// MODULES("modules"),
// PROPERTIES("properties"),
// DEPENDENCY_MANAGEMENT("dependencyManagement"),
// DEPENDENCIES("dependencies"),
// BUILD("build"),
// PROFILES("profiles"),
// REPORTING("reporting"),
// REPORTS("reports");
//
// private static final Map<String, PomSection> pomSectionMap;
//
// static {
// pomSectionMap = Maps.newHashMap();
// for (PomSection pomSection : values()) {
// pomSectionMap.put(pomSection.getSectionName(), pomSection);
// }
// }
//
// public static PomSection getBySectionName(String sectionName) {
// requireNonNull(sectionName, "Section name is null.");
//
// PomSection value = pomSectionMap.get(sectionName);
// if (value == null) {
// throw new IllegalArgumentException("POM section " + sectionName + " does not exist.");
// }
//
// return value;
// }
//
// private final String sectionName;
//
// PomSection(String sectionName) {
// this.sectionName = sectionName;
// }
//
// public String getSectionName() {
// return this.sectionName;
// }
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/SideBySideDiffUtil.java
// public static String diff(Collection<String> actual, Collection<String> required, String leftTitle, String rightTitle) {
//
// SideBySideContext context = new SideBySideContext(actual, required, leftTitle, rightTitle);
// int offset = 0;
//
// for (Delta<String> delta : context.deltas) {
// Chunk<String> original = delta.getOriginal();
// Chunk<String> revised = delta.getRevised();
// int currentPosition = original.getPosition() + offset;
//
// switch (delta.getType()) {
// case INSERT:
// offset += context.expand(currentPosition, revised.size());
// context.setRightContent(currentPosition, revised.getLines());
// break;
//
// case CHANGE:
// int difference = revised.size() - original.size();
// if (difference > 0) {
// offset += context.expand(currentPosition + original.size(), difference);
// } else {
// context.clearRightContent(currentPosition + revised.size(), Math.abs(difference));
// }
//
// context.setLeftContent(currentPosition, original.getLines());
// context.setRightContent(currentPosition, revised.getLines());
// break;
//
// case DELETE:
// context.setLeftContent(currentPosition, original.getLines());
// context.clearRightContent(currentPosition, original.size());
// break;
//
// default:
// throw new IllegalStateException("Unsupported delta type: " + delta.getType());
//
// }
// }
//
// return context.toString();
// }
// Path: src/test/java/com/github/ferstl/maven/pomenforcers/util/SideBySideDiffUtilTest.java
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeDiagnosingMatcher;
import org.junit.Test;
import com.github.ferstl.maven.pomenforcers.model.PomSection;
import com.google.common.collect.Ordering;
import static com.github.ferstl.maven.pomenforcers.util.SideBySideDiffUtil.diff;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.junit.Assert.assertEquals;
import static org.hamcrest.MatcherAssert.assertThat;
/*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers.util;
/**
* JUnit tests for {@link SideBySideDiffUtil}.
*/
public class SideBySideDiffUtilTest {
@Test
public void insertion() { | String diff = diff( |
ferstl/pedantic-pom-enforcers | src/test/java/com/github/ferstl/maven/pomenforcers/util/SideBySideDiffUtilTest.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PomSection.java
// public enum PomSection {
// MODEL_VERSION("modelVersion"),
// PREREQUISITES("prerequisites"),
// PARENT("parent"),
// GROUP_ID("groupId"),
// ARTIFACT_ID("artifactId"),
// VERSION("version"),
// PACKAGING("packaging"),
// NAME("name"),
// DESCRIPTION("description"),
// URL("url"),
// LICENSES("licenses"),
// ORGANIZATION("organization"),
// INCEPTION_YEAR("inceptionYear"),
// CI_MANAGEMENT("ciManagement"),
// MAILING_LISTS("mailingLists"),
// ISSUE_MANAGEMENT("issueManagement"),
// DEVELOPERS("developers"),
// CONTRIBUTORS("contributors"),
// SCM("scm"),
// REPOSITORIES("repositories"),
// PLUGIN_REPOSITORIES("pluginRepositories"),
// DISTRIBUTION_MANAGEMENT("distributionManagement"),
// MODULES("modules"),
// PROPERTIES("properties"),
// DEPENDENCY_MANAGEMENT("dependencyManagement"),
// DEPENDENCIES("dependencies"),
// BUILD("build"),
// PROFILES("profiles"),
// REPORTING("reporting"),
// REPORTS("reports");
//
// private static final Map<String, PomSection> pomSectionMap;
//
// static {
// pomSectionMap = Maps.newHashMap();
// for (PomSection pomSection : values()) {
// pomSectionMap.put(pomSection.getSectionName(), pomSection);
// }
// }
//
// public static PomSection getBySectionName(String sectionName) {
// requireNonNull(sectionName, "Section name is null.");
//
// PomSection value = pomSectionMap.get(sectionName);
// if (value == null) {
// throw new IllegalArgumentException("POM section " + sectionName + " does not exist.");
// }
//
// return value;
// }
//
// private final String sectionName;
//
// PomSection(String sectionName) {
// this.sectionName = sectionName;
// }
//
// public String getSectionName() {
// return this.sectionName;
// }
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/SideBySideDiffUtil.java
// public static String diff(Collection<String> actual, Collection<String> required, String leftTitle, String rightTitle) {
//
// SideBySideContext context = new SideBySideContext(actual, required, leftTitle, rightTitle);
// int offset = 0;
//
// for (Delta<String> delta : context.deltas) {
// Chunk<String> original = delta.getOriginal();
// Chunk<String> revised = delta.getRevised();
// int currentPosition = original.getPosition() + offset;
//
// switch (delta.getType()) {
// case INSERT:
// offset += context.expand(currentPosition, revised.size());
// context.setRightContent(currentPosition, revised.getLines());
// break;
//
// case CHANGE:
// int difference = revised.size() - original.size();
// if (difference > 0) {
// offset += context.expand(currentPosition + original.size(), difference);
// } else {
// context.clearRightContent(currentPosition + revised.size(), Math.abs(difference));
// }
//
// context.setLeftContent(currentPosition, original.getLines());
// context.setRightContent(currentPosition, revised.getLines());
// break;
//
// case DELETE:
// context.setLeftContent(currentPosition, original.getLines());
// context.clearRightContent(currentPosition, original.size());
// break;
//
// default:
// throw new IllegalStateException("Unsupported delta type: " + delta.getType());
//
// }
// }
//
// return context.toString();
// }
| import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeDiagnosingMatcher;
import org.junit.Test;
import com.github.ferstl.maven.pomenforcers.model.PomSection;
import com.google.common.collect.Ordering;
import static com.github.ferstl.maven.pomenforcers.util.SideBySideDiffUtil.diff;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.junit.Assert.assertEquals;
import static org.hamcrest.MatcherAssert.assertThat; | @Test
public void differentLengthsShortOriginal() {
String diff = diff(singletonList("abc"), asList("def", "ghi", "jkl", "abc"), "", "");
assertThat(diff, hasContent(
" | + def",
" | + ghi",
" | + jkl",
" abc | abc"
));
}
@Test
public void differentLengthsShortRevised() {
String diff = diff(asList("def", "ghi", "jkl", "abc"), singletonList("abc"), "", "");
assertThat(diff, hasContent(
"- def |",
"- ghi |",
"- jkl |",
" abc | abc"
));
}
/**
* Tests the combination of all scenarios by comparing the required order of {@link PomSection}s
* to alphabetically sorted {@link PomSection}s.
*/
@Test
public void combinations() { | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PomSection.java
// public enum PomSection {
// MODEL_VERSION("modelVersion"),
// PREREQUISITES("prerequisites"),
// PARENT("parent"),
// GROUP_ID("groupId"),
// ARTIFACT_ID("artifactId"),
// VERSION("version"),
// PACKAGING("packaging"),
// NAME("name"),
// DESCRIPTION("description"),
// URL("url"),
// LICENSES("licenses"),
// ORGANIZATION("organization"),
// INCEPTION_YEAR("inceptionYear"),
// CI_MANAGEMENT("ciManagement"),
// MAILING_LISTS("mailingLists"),
// ISSUE_MANAGEMENT("issueManagement"),
// DEVELOPERS("developers"),
// CONTRIBUTORS("contributors"),
// SCM("scm"),
// REPOSITORIES("repositories"),
// PLUGIN_REPOSITORIES("pluginRepositories"),
// DISTRIBUTION_MANAGEMENT("distributionManagement"),
// MODULES("modules"),
// PROPERTIES("properties"),
// DEPENDENCY_MANAGEMENT("dependencyManagement"),
// DEPENDENCIES("dependencies"),
// BUILD("build"),
// PROFILES("profiles"),
// REPORTING("reporting"),
// REPORTS("reports");
//
// private static final Map<String, PomSection> pomSectionMap;
//
// static {
// pomSectionMap = Maps.newHashMap();
// for (PomSection pomSection : values()) {
// pomSectionMap.put(pomSection.getSectionName(), pomSection);
// }
// }
//
// public static PomSection getBySectionName(String sectionName) {
// requireNonNull(sectionName, "Section name is null.");
//
// PomSection value = pomSectionMap.get(sectionName);
// if (value == null) {
// throw new IllegalArgumentException("POM section " + sectionName + " does not exist.");
// }
//
// return value;
// }
//
// private final String sectionName;
//
// PomSection(String sectionName) {
// this.sectionName = sectionName;
// }
//
// public String getSectionName() {
// return this.sectionName;
// }
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/util/SideBySideDiffUtil.java
// public static String diff(Collection<String> actual, Collection<String> required, String leftTitle, String rightTitle) {
//
// SideBySideContext context = new SideBySideContext(actual, required, leftTitle, rightTitle);
// int offset = 0;
//
// for (Delta<String> delta : context.deltas) {
// Chunk<String> original = delta.getOriginal();
// Chunk<String> revised = delta.getRevised();
// int currentPosition = original.getPosition() + offset;
//
// switch (delta.getType()) {
// case INSERT:
// offset += context.expand(currentPosition, revised.size());
// context.setRightContent(currentPosition, revised.getLines());
// break;
//
// case CHANGE:
// int difference = revised.size() - original.size();
// if (difference > 0) {
// offset += context.expand(currentPosition + original.size(), difference);
// } else {
// context.clearRightContent(currentPosition + revised.size(), Math.abs(difference));
// }
//
// context.setLeftContent(currentPosition, original.getLines());
// context.setRightContent(currentPosition, revised.getLines());
// break;
//
// case DELETE:
// context.setLeftContent(currentPosition, original.getLines());
// context.clearRightContent(currentPosition, original.size());
// break;
//
// default:
// throw new IllegalStateException("Unsupported delta type: " + delta.getType());
//
// }
// }
//
// return context.toString();
// }
// Path: src/test/java/com/github/ferstl/maven/pomenforcers/util/SideBySideDiffUtilTest.java
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeDiagnosingMatcher;
import org.junit.Test;
import com.github.ferstl.maven.pomenforcers.model.PomSection;
import com.google.common.collect.Ordering;
import static com.github.ferstl.maven.pomenforcers.util.SideBySideDiffUtil.diff;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.junit.Assert.assertEquals;
import static org.hamcrest.MatcherAssert.assertThat;
@Test
public void differentLengthsShortOriginal() {
String diff = diff(singletonList("abc"), asList("def", "ghi", "jkl", "abc"), "", "");
assertThat(diff, hasContent(
" | + def",
" | + ghi",
" | + jkl",
" abc | abc"
));
}
@Test
public void differentLengthsShortRevised() {
String diff = diff(asList("def", "ghi", "jkl", "abc"), singletonList("abc"), "", "");
assertThat(diff, hasContent(
"- def |",
"- ghi |",
"- jkl |",
" abc | abc"
));
}
/**
* Tests the combination of all scenarios by comparing the required order of {@link PomSection}s
* to alphabetically sorted {@link PomSection}s.
*/
@Test
public void combinations() { | List<String> required = Arrays.stream(PomSection.values()).map(PomSection::getSectionName).collect(Collectors.toList()); |
ferstl/pedantic-pom-enforcers | src/main/java/com/github/ferstl/maven/pomenforcers/PedanticDependencyOrderEnforcer.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/DependencyModel.java
// @XmlRootElement(name = "dependency")
// public class DependencyModel extends ArtifactModel {
//
// private static final Joiner TO_STRING_JOINER = Joiner.on(":").skipNulls();
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlJavaTypeAdapter(value = DependencyScopeAdapter.class)
// private DependencyScope scope;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String classifier;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String type;
//
// @XmlElementWrapper(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlElement(name = "exclusion", namespace = "http://maven.apache.org/POM/4.0.0")
// private List<ArtifactModel> exclusions;
//
// // Constructor used by JAXB
// DependencyModel() {
// }
//
// public DependencyModel(
// String groupId, String artifactId, String version, String scope, String classifier, String type) {
//
// super(groupId, artifactId, version);
// this.scope = scope != null ? DependencyScope.getByScopeName(scope) : null;
// this.classifier = classifier;
// this.type = type;
// }
//
// public DependencyScope getScope() {
// return this.scope != null ? this.scope : DependencyScope.COMPILE;
// }
//
// public String getClassifier() {
// return this.classifier;
// }
//
// public String getType() {
// return this.type != null ? this.type : "jar";
// }
//
// public List<ArtifactModel> getExclusions() {
// return this.exclusions != null ? this.exclusions : Collections.emptyList();
// }
//
// @Override
// public String toString() {
// return TO_STRING_JOINER.join(
// super.toString(),
// getType(),
// getScope().getScopeName(),
// this.classifier);
// }
//
// // Note that this equals() implementation breaks the symmetry contract!
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (!(obj instanceof DependencyModel)) {
// return false;
// }
//
// DependencyModel other = (DependencyModel) obj;
// return super.equals(other)
// && equal(this.classifier, other.classifier)
// && equal(this.type, other.type)
// && equal(this.scope, other.scope)
// && equal(this.exclusions, other.exclusions);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.classifier, this.type, this.scope);
// }
//
// }
| import java.util.Collection;
import org.apache.maven.model.Dependency;
import org.apache.maven.project.MavenProject;
import com.github.ferstl.maven.pomenforcers.model.DependencyModel;
| /*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers;
/**
* This enforcer makes sure that all artifacts in your dependencies section are
* ordered. The ordering can be defined by any combination of <code>scope</code>, <code>groupId</code>
* and <code>artifactId</code>. Each of these attributes may be given a priority.
*
* <pre>
* ### Example
* <rules>
* <dependencyOrder implementation="com.github.ferstl.maven.pomenforcers.PedanticDependencyOrderEnforcer">
* <!-- order by scope, groupId and artifactId (default) -->
* <orderBy>scope,groupId,artifactId</orderBy>
* <!-- runtime scope should occur before provided scope -->
* <scopePriorities>compile,runtime,provided</scopePriorities>
* <!-- all group IDs starting with com.myproject and com.mylibs should occur first -->
* <groupIdPriorities>com.myproject,com.mylibs</groupIdPriorities>
* <!-- all artifact IDs starting with commons- and utils- should occur first -->
* <artifactIdPriorities>commons-,utils-</artifactIdPriorities>
* </dependencyOrder>
* </rules>
* </pre>
*
* @id {@link PedanticEnforcerRule#DEPENDENCY_ORDER}
* @since 1.0.0
*/
public class PedanticDependencyOrderEnforcer extends AbstractPedanticDependencyOrderEnforcer {
@Override
protected void accept(PedanticEnforcerVisitor visitor) {
visitor.visit(this);
}
@Override
protected PedanticEnforcerRule getDescription() {
return PedanticEnforcerRule.DEPENDENCY_ORDER;
}
@Override
| // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/DependencyModel.java
// @XmlRootElement(name = "dependency")
// public class DependencyModel extends ArtifactModel {
//
// private static final Joiner TO_STRING_JOINER = Joiner.on(":").skipNulls();
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlJavaTypeAdapter(value = DependencyScopeAdapter.class)
// private DependencyScope scope;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String classifier;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String type;
//
// @XmlElementWrapper(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlElement(name = "exclusion", namespace = "http://maven.apache.org/POM/4.0.0")
// private List<ArtifactModel> exclusions;
//
// // Constructor used by JAXB
// DependencyModel() {
// }
//
// public DependencyModel(
// String groupId, String artifactId, String version, String scope, String classifier, String type) {
//
// super(groupId, artifactId, version);
// this.scope = scope != null ? DependencyScope.getByScopeName(scope) : null;
// this.classifier = classifier;
// this.type = type;
// }
//
// public DependencyScope getScope() {
// return this.scope != null ? this.scope : DependencyScope.COMPILE;
// }
//
// public String getClassifier() {
// return this.classifier;
// }
//
// public String getType() {
// return this.type != null ? this.type : "jar";
// }
//
// public List<ArtifactModel> getExclusions() {
// return this.exclusions != null ? this.exclusions : Collections.emptyList();
// }
//
// @Override
// public String toString() {
// return TO_STRING_JOINER.join(
// super.toString(),
// getType(),
// getScope().getScopeName(),
// this.classifier);
// }
//
// // Note that this equals() implementation breaks the symmetry contract!
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (!(obj instanceof DependencyModel)) {
// return false;
// }
//
// DependencyModel other = (DependencyModel) obj;
// return super.equals(other)
// && equal(this.classifier, other.classifier)
// && equal(this.type, other.type)
// && equal(this.scope, other.scope)
// && equal(this.exclusions, other.exclusions);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.classifier, this.type, this.scope);
// }
//
// }
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/PedanticDependencyOrderEnforcer.java
import java.util.Collection;
import org.apache.maven.model.Dependency;
import org.apache.maven.project.MavenProject;
import com.github.ferstl.maven.pomenforcers.model.DependencyModel;
/*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers;
/**
* This enforcer makes sure that all artifacts in your dependencies section are
* ordered. The ordering can be defined by any combination of <code>scope</code>, <code>groupId</code>
* and <code>artifactId</code>. Each of these attributes may be given a priority.
*
* <pre>
* ### Example
* <rules>
* <dependencyOrder implementation="com.github.ferstl.maven.pomenforcers.PedanticDependencyOrderEnforcer">
* <!-- order by scope, groupId and artifactId (default) -->
* <orderBy>scope,groupId,artifactId</orderBy>
* <!-- runtime scope should occur before provided scope -->
* <scopePriorities>compile,runtime,provided</scopePriorities>
* <!-- all group IDs starting with com.myproject and com.mylibs should occur first -->
* <groupIdPriorities>com.myproject,com.mylibs</groupIdPriorities>
* <!-- all artifact IDs starting with commons- and utils- should occur first -->
* <artifactIdPriorities>commons-,utils-</artifactIdPriorities>
* </dependencyOrder>
* </rules>
* </pre>
*
* @id {@link PedanticEnforcerRule#DEPENDENCY_ORDER}
* @since 1.0.0
*/
public class PedanticDependencyOrderEnforcer extends AbstractPedanticDependencyOrderEnforcer {
@Override
protected void accept(PedanticEnforcerVisitor visitor) {
visitor.visit(this);
}
@Override
protected PedanticEnforcerRule getDescription() {
return PedanticEnforcerRule.DEPENDENCY_ORDER;
}
@Override
| protected Collection<DependencyModel> getDeclaredDependencies() {
|
ferstl/pedantic-pom-enforcers | src/test/java/com/github/ferstl/maven/pomenforcers/PedanticDependencyManagementLocationEnforcerTest.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/DependencyModel.java
// @XmlRootElement(name = "dependency")
// public class DependencyModel extends ArtifactModel {
//
// private static final Joiner TO_STRING_JOINER = Joiner.on(":").skipNulls();
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlJavaTypeAdapter(value = DependencyScopeAdapter.class)
// private DependencyScope scope;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String classifier;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String type;
//
// @XmlElementWrapper(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlElement(name = "exclusion", namespace = "http://maven.apache.org/POM/4.0.0")
// private List<ArtifactModel> exclusions;
//
// // Constructor used by JAXB
// DependencyModel() {
// }
//
// public DependencyModel(
// String groupId, String artifactId, String version, String scope, String classifier, String type) {
//
// super(groupId, artifactId, version);
// this.scope = scope != null ? DependencyScope.getByScopeName(scope) : null;
// this.classifier = classifier;
// this.type = type;
// }
//
// public DependencyScope getScope() {
// return this.scope != null ? this.scope : DependencyScope.COMPILE;
// }
//
// public String getClassifier() {
// return this.classifier;
// }
//
// public String getType() {
// return this.type != null ? this.type : "jar";
// }
//
// public List<ArtifactModel> getExclusions() {
// return this.exclusions != null ? this.exclusions : Collections.emptyList();
// }
//
// @Override
// public String toString() {
// return TO_STRING_JOINER.join(
// super.toString(),
// getType(),
// getScope().getScopeName(),
// this.classifier);
// }
//
// // Note that this equals() implementation breaks the symmetry contract!
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (!(obj instanceof DependencyModel)) {
// return false;
// }
//
// DependencyModel other = (DependencyModel) obj;
// return super.equals(other)
// && equal(this.classifier, other.classifier)
// && equal(this.type, other.type)
// && equal(this.scope, other.scope)
// && equal(this.exclusions, other.exclusions);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.classifier, this.type, this.scope);
// }
//
// }
| import org.junit.Before;
import org.junit.Test;
import com.github.ferstl.maven.pomenforcers.model.DependencyModel;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
| /*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers;
/**
* JUnit tests for {@link PedanticDependencyManagementLocationEnforcer}.
*/
public class PedanticDependencyManagementLocationEnforcerTest extends AbstractPedanticEnforcerTest<PedanticDependencyManagementLocationEnforcer> {
@Override
PedanticDependencyManagementLocationEnforcer createRule() {
return new PedanticDependencyManagementLocationEnforcer();
}
@Before
public void before() {
when(this.mockMavenProject.getGroupId()).thenReturn("a.b.c");
when(this.mockMavenProject.getArtifactId()).thenReturn("parent");
| // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/DependencyModel.java
// @XmlRootElement(name = "dependency")
// public class DependencyModel extends ArtifactModel {
//
// private static final Joiner TO_STRING_JOINER = Joiner.on(":").skipNulls();
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlJavaTypeAdapter(value = DependencyScopeAdapter.class)
// private DependencyScope scope;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String classifier;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String type;
//
// @XmlElementWrapper(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlElement(name = "exclusion", namespace = "http://maven.apache.org/POM/4.0.0")
// private List<ArtifactModel> exclusions;
//
// // Constructor used by JAXB
// DependencyModel() {
// }
//
// public DependencyModel(
// String groupId, String artifactId, String version, String scope, String classifier, String type) {
//
// super(groupId, artifactId, version);
// this.scope = scope != null ? DependencyScope.getByScopeName(scope) : null;
// this.classifier = classifier;
// this.type = type;
// }
//
// public DependencyScope getScope() {
// return this.scope != null ? this.scope : DependencyScope.COMPILE;
// }
//
// public String getClassifier() {
// return this.classifier;
// }
//
// public String getType() {
// return this.type != null ? this.type : "jar";
// }
//
// public List<ArtifactModel> getExclusions() {
// return this.exclusions != null ? this.exclusions : Collections.emptyList();
// }
//
// @Override
// public String toString() {
// return TO_STRING_JOINER.join(
// super.toString(),
// getType(),
// getScope().getScopeName(),
// this.classifier);
// }
//
// // Note that this equals() implementation breaks the symmetry contract!
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (!(obj instanceof DependencyModel)) {
// return false;
// }
//
// DependencyModel other = (DependencyModel) obj;
// return super.equals(other)
// && equal(this.classifier, other.classifier)
// && equal(this.type, other.type)
// && equal(this.scope, other.scope)
// && equal(this.exclusions, other.exclusions);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.classifier, this.type, this.scope);
// }
//
// }
// Path: src/test/java/com/github/ferstl/maven/pomenforcers/PedanticDependencyManagementLocationEnforcerTest.java
import org.junit.Before;
import org.junit.Test;
import com.github.ferstl.maven.pomenforcers.model.DependencyModel;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers;
/**
* JUnit tests for {@link PedanticDependencyManagementLocationEnforcer}.
*/
public class PedanticDependencyManagementLocationEnforcerTest extends AbstractPedanticEnforcerTest<PedanticDependencyManagementLocationEnforcer> {
@Override
PedanticDependencyManagementLocationEnforcer createRule() {
return new PedanticDependencyManagementLocationEnforcer();
}
@Before
public void before() {
when(this.mockMavenProject.getGroupId()).thenReturn("a.b.c");
when(this.mockMavenProject.getArtifactId()).thenReturn("parent");
| this.projectModel.getManagedDependencies().add(new DependencyModel("a.b.c", "a", "1.0", null, null, null));
|
ferstl/pedantic-pom-enforcers | src/test/java/com/github/ferstl/maven/pomenforcers/model/functions/PluginMatcherTest.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PluginModel.java
// public class PluginModel extends ArtifactModel {
//
// @XmlElementWrapper(name = "configuration", namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlAnyElement
// private List<Element> configItems;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private DependenciesModel dependencies;
//
// PluginModel() {
// }
//
// public PluginModel(String groupId, String artifactId, String version) {
// super(groupId, artifactId, version);
// }
//
// public boolean isConfigured() {
// return this.configItems != null && !this.configItems.isEmpty();
// }
//
// public List<DependencyModel> getDependencies() {
// return this.dependencies != null ? this.dependencies.getDependencies() : Collections.emptyList();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (!(obj instanceof PluginModel)) {
// return false;
// }
//
// PluginModel other = (PluginModel) obj;
// return super.equals(other)
// // TODO: Element implementations may not implement equals()!!
// && Objects.equals(this.configItems, other.configItems)
// && Objects.equals(this.dependencies, other.dependencies);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.configItems, this.dependencies);
// }
// }
| import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper;
import org.apache.maven.model.Plugin;
import org.junit.Before;
import org.junit.Test;
import com.github.ferstl.maven.pomenforcers.model.PluginModel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock; | /*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers.model.functions;
public class PluginMatcherTest {
private PluginMatcher pluginMatcher;
@Before
public void before() {
this.pluginMatcher = new PluginMatcher(mock(EnforcerRuleHelper.class));
}
@Test
public void transform() {
// arrange
Plugin plugin = new Plugin();
plugin.setGroupId("a");
plugin.setArtifactId("b");
plugin.setVersion("c");
// act | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PluginModel.java
// public class PluginModel extends ArtifactModel {
//
// @XmlElementWrapper(name = "configuration", namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlAnyElement
// private List<Element> configItems;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private DependenciesModel dependencies;
//
// PluginModel() {
// }
//
// public PluginModel(String groupId, String artifactId, String version) {
// super(groupId, artifactId, version);
// }
//
// public boolean isConfigured() {
// return this.configItems != null && !this.configItems.isEmpty();
// }
//
// public List<DependencyModel> getDependencies() {
// return this.dependencies != null ? this.dependencies.getDependencies() : Collections.emptyList();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (!(obj instanceof PluginModel)) {
// return false;
// }
//
// PluginModel other = (PluginModel) obj;
// return super.equals(other)
// // TODO: Element implementations may not implement equals()!!
// && Objects.equals(this.configItems, other.configItems)
// && Objects.equals(this.dependencies, other.dependencies);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.configItems, this.dependencies);
// }
// }
// Path: src/test/java/com/github/ferstl/maven/pomenforcers/model/functions/PluginMatcherTest.java
import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper;
import org.apache.maven.model.Plugin;
import org.junit.Before;
import org.junit.Test;
import com.github.ferstl.maven.pomenforcers.model.PluginModel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
/*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers.model.functions;
public class PluginMatcherTest {
private PluginMatcher pluginMatcher;
@Before
public void before() {
this.pluginMatcher = new PluginMatcher(mock(EnforcerRuleHelper.class));
}
@Test
public void transform() {
// arrange
Plugin plugin = new Plugin();
plugin.setGroupId("a");
plugin.setArtifactId("b");
plugin.setVersion("c");
// act | PluginModel pluginModel = this.pluginMatcher.transform(plugin); |
ferstl/pedantic-pom-enforcers | src/test/java/com/github/ferstl/maven/pomenforcers/PedanticPluginManagementLocationEnforcerTest.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PluginModel.java
// public class PluginModel extends ArtifactModel {
//
// @XmlElementWrapper(name = "configuration", namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlAnyElement
// private List<Element> configItems;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private DependenciesModel dependencies;
//
// PluginModel() {
// }
//
// public PluginModel(String groupId, String artifactId, String version) {
// super(groupId, artifactId, version);
// }
//
// public boolean isConfigured() {
// return this.configItems != null && !this.configItems.isEmpty();
// }
//
// public List<DependencyModel> getDependencies() {
// return this.dependencies != null ? this.dependencies.getDependencies() : Collections.emptyList();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (!(obj instanceof PluginModel)) {
// return false;
// }
//
// PluginModel other = (PluginModel) obj;
// return super.equals(other)
// // TODO: Element implementations may not implement equals()!!
// && Objects.equals(this.configItems, other.configItems)
// && Objects.equals(this.dependencies, other.dependencies);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.configItems, this.dependencies);
// }
// }
| import org.junit.Before;
import org.junit.Test;
import com.github.ferstl.maven.pomenforcers.model.PluginModel;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
| /*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers;
/**
* JUnit tests for {@link PedanticPluginManagementLocationEnforcer}.
*/
public class PedanticPluginManagementLocationEnforcerTest extends AbstractPedanticEnforcerTest<PedanticPluginManagementLocationEnforcer> {
@Override
PedanticPluginManagementLocationEnforcer createRule() {
return new PedanticPluginManagementLocationEnforcer();
}
@Before
public void before() {
when(this.mockMavenProject.getGroupId()).thenReturn("a.b.c");
when(this.mockMavenProject.getArtifactId()).thenReturn("parent");
| // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PluginModel.java
// public class PluginModel extends ArtifactModel {
//
// @XmlElementWrapper(name = "configuration", namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlAnyElement
// private List<Element> configItems;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private DependenciesModel dependencies;
//
// PluginModel() {
// }
//
// public PluginModel(String groupId, String artifactId, String version) {
// super(groupId, artifactId, version);
// }
//
// public boolean isConfigured() {
// return this.configItems != null && !this.configItems.isEmpty();
// }
//
// public List<DependencyModel> getDependencies() {
// return this.dependencies != null ? this.dependencies.getDependencies() : Collections.emptyList();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (!(obj instanceof PluginModel)) {
// return false;
// }
//
// PluginModel other = (PluginModel) obj;
// return super.equals(other)
// // TODO: Element implementations may not implement equals()!!
// && Objects.equals(this.configItems, other.configItems)
// && Objects.equals(this.dependencies, other.dependencies);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.configItems, this.dependencies);
// }
// }
// Path: src/test/java/com/github/ferstl/maven/pomenforcers/PedanticPluginManagementLocationEnforcerTest.java
import org.junit.Before;
import org.junit.Test;
import com.github.ferstl.maven.pomenforcers.model.PluginModel;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers;
/**
* JUnit tests for {@link PedanticPluginManagementLocationEnforcer}.
*/
public class PedanticPluginManagementLocationEnforcerTest extends AbstractPedanticEnforcerTest<PedanticPluginManagementLocationEnforcer> {
@Override
PedanticPluginManagementLocationEnforcer createRule() {
return new PedanticPluginManagementLocationEnforcer();
}
@Before
public void before() {
when(this.mockMavenProject.getGroupId()).thenReturn("a.b.c");
when(this.mockMavenProject.getArtifactId()).thenReturn("parent");
| this.projectModel.getManagedPlugins().add(new PluginModel("a.b.c", "a", "1.0"));
|
ferstl/pedantic-pom-enforcers | src/main/java/com/github/ferstl/maven/pomenforcers/PedanticDependencyManagementOrderEnforcer.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/DependencyModel.java
// @XmlRootElement(name = "dependency")
// public class DependencyModel extends ArtifactModel {
//
// private static final Joiner TO_STRING_JOINER = Joiner.on(":").skipNulls();
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlJavaTypeAdapter(value = DependencyScopeAdapter.class)
// private DependencyScope scope;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String classifier;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String type;
//
// @XmlElementWrapper(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlElement(name = "exclusion", namespace = "http://maven.apache.org/POM/4.0.0")
// private List<ArtifactModel> exclusions;
//
// // Constructor used by JAXB
// DependencyModel() {
// }
//
// public DependencyModel(
// String groupId, String artifactId, String version, String scope, String classifier, String type) {
//
// super(groupId, artifactId, version);
// this.scope = scope != null ? DependencyScope.getByScopeName(scope) : null;
// this.classifier = classifier;
// this.type = type;
// }
//
// public DependencyScope getScope() {
// return this.scope != null ? this.scope : DependencyScope.COMPILE;
// }
//
// public String getClassifier() {
// return this.classifier;
// }
//
// public String getType() {
// return this.type != null ? this.type : "jar";
// }
//
// public List<ArtifactModel> getExclusions() {
// return this.exclusions != null ? this.exclusions : Collections.emptyList();
// }
//
// @Override
// public String toString() {
// return TO_STRING_JOINER.join(
// super.toString(),
// getType(),
// getScope().getScopeName(),
// this.classifier);
// }
//
// // Note that this equals() implementation breaks the symmetry contract!
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (!(obj instanceof DependencyModel)) {
// return false;
// }
//
// DependencyModel other = (DependencyModel) obj;
// return super.equals(other)
// && equal(this.classifier, other.classifier)
// && equal(this.type, other.type)
// && equal(this.scope, other.scope)
// && equal(this.exclusions, other.exclusions);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.classifier, this.type, this.scope);
// }
//
// }
| import java.util.Collection;
import java.util.Collections;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.DependencyManagement;
import org.apache.maven.project.MavenProject;
import com.github.ferstl.maven.pomenforcers.model.DependencyModel; | /*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers;
/**
* This enforcer makes sure that all artifacts in your dependency management are
* ordered. The ordering can be defined by any combination of <code>scope</code>,
* <code>groupId</code> and <code>artifactId</code>. Each of these attributes
* may be given a priority.
*
* <pre>
* ### Example
* <rules>
* <dependencyManagementOrder implementation="com.github.ferstl.maven.pomenforcers.PedanticDependencyManagementOrderEnforcer">
* <!-- order by scope, groupId and artifactId (default) -->
* <orderBy>scope,groupId,artifactId</orderBy>
* <!-- runtime scope should occur before provided scope -->
* <scopePriorities>compile,runtime,provided</scopePriorities>
* <!-- all group IDs starting with com.myproject and com.mylibs should occur first -->
* <groupIdPriorities>com.myproject,com.mylibs</groupIdPriorities>
* <!-- all artifact IDs starting with commons- and utils- should occur first -->
* <artifactIdPriorities>commons-,utils-</artifactIdPriorities>
* </dependencyManagementOrder>
* </rules>
* </pre>
*
* @id {@link PedanticEnforcerRule#DEPENDENCY_MANAGEMENT_ORDER}
* @since 1.0.0
*/
public class PedanticDependencyManagementOrderEnforcer extends AbstractPedanticDependencyOrderEnforcer {
@Override
protected PedanticEnforcerRule getDescription() {
return PedanticEnforcerRule.DEPENDENCY_MANAGEMENT_ORDER;
}
@Override
protected void accept(PedanticEnforcerVisitor visitor) {
visitor.visit(this);
}
@Override | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/DependencyModel.java
// @XmlRootElement(name = "dependency")
// public class DependencyModel extends ArtifactModel {
//
// private static final Joiner TO_STRING_JOINER = Joiner.on(":").skipNulls();
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlJavaTypeAdapter(value = DependencyScopeAdapter.class)
// private DependencyScope scope;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String classifier;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String type;
//
// @XmlElementWrapper(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlElement(name = "exclusion", namespace = "http://maven.apache.org/POM/4.0.0")
// private List<ArtifactModel> exclusions;
//
// // Constructor used by JAXB
// DependencyModel() {
// }
//
// public DependencyModel(
// String groupId, String artifactId, String version, String scope, String classifier, String type) {
//
// super(groupId, artifactId, version);
// this.scope = scope != null ? DependencyScope.getByScopeName(scope) : null;
// this.classifier = classifier;
// this.type = type;
// }
//
// public DependencyScope getScope() {
// return this.scope != null ? this.scope : DependencyScope.COMPILE;
// }
//
// public String getClassifier() {
// return this.classifier;
// }
//
// public String getType() {
// return this.type != null ? this.type : "jar";
// }
//
// public List<ArtifactModel> getExclusions() {
// return this.exclusions != null ? this.exclusions : Collections.emptyList();
// }
//
// @Override
// public String toString() {
// return TO_STRING_JOINER.join(
// super.toString(),
// getType(),
// getScope().getScopeName(),
// this.classifier);
// }
//
// // Note that this equals() implementation breaks the symmetry contract!
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (!(obj instanceof DependencyModel)) {
// return false;
// }
//
// DependencyModel other = (DependencyModel) obj;
// return super.equals(other)
// && equal(this.classifier, other.classifier)
// && equal(this.type, other.type)
// && equal(this.scope, other.scope)
// && equal(this.exclusions, other.exclusions);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.classifier, this.type, this.scope);
// }
//
// }
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/PedanticDependencyManagementOrderEnforcer.java
import java.util.Collection;
import java.util.Collections;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.DependencyManagement;
import org.apache.maven.project.MavenProject;
import com.github.ferstl.maven.pomenforcers.model.DependencyModel;
/*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers;
/**
* This enforcer makes sure that all artifacts in your dependency management are
* ordered. The ordering can be defined by any combination of <code>scope</code>,
* <code>groupId</code> and <code>artifactId</code>. Each of these attributes
* may be given a priority.
*
* <pre>
* ### Example
* <rules>
* <dependencyManagementOrder implementation="com.github.ferstl.maven.pomenforcers.PedanticDependencyManagementOrderEnforcer">
* <!-- order by scope, groupId and artifactId (default) -->
* <orderBy>scope,groupId,artifactId</orderBy>
* <!-- runtime scope should occur before provided scope -->
* <scopePriorities>compile,runtime,provided</scopePriorities>
* <!-- all group IDs starting with com.myproject and com.mylibs should occur first -->
* <groupIdPriorities>com.myproject,com.mylibs</groupIdPriorities>
* <!-- all artifact IDs starting with commons- and utils- should occur first -->
* <artifactIdPriorities>commons-,utils-</artifactIdPriorities>
* </dependencyManagementOrder>
* </rules>
* </pre>
*
* @id {@link PedanticEnforcerRule#DEPENDENCY_MANAGEMENT_ORDER}
* @since 1.0.0
*/
public class PedanticDependencyManagementOrderEnforcer extends AbstractPedanticDependencyOrderEnforcer {
@Override
protected PedanticEnforcerRule getDescription() {
return PedanticEnforcerRule.DEPENDENCY_MANAGEMENT_ORDER;
}
@Override
protected void accept(PedanticEnforcerVisitor visitor) {
visitor.visit(this);
}
@Override | protected Collection<DependencyModel> getDeclaredDependencies() { |
ferstl/pedantic-pom-enforcers | src/main/java/com/github/ferstl/maven/pomenforcers/model/PluginElement.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/priority/PriorityOrdering.java
// public class PriorityOrdering<P extends Comparable<? super P>, T> extends Ordering<T> {
//
// /**
// * The priority collection.
// */
// private final Collection<P> priorityCollection;
//
// /**
// * Matches the values to be compared with the items in the priority collection.
// */
// private final Equivalence<? super P> priorityMatcher;
//
// /**
// * Transforms the type of the objects to be compared into the type of the priority collection. Use
// * {@link Function#identity()} if the type of the priority collection and the type of the objects to be
// * compared are the same.
// */
// private final Function<T, P> transformer;
//
//
// public PriorityOrdering(Collection<P> prioritizedItems, Function<T, P> transformer, Equivalence<? super P> priorityMatcher) {
// this.priorityCollection = prioritizedItems;
// this.priorityMatcher = priorityMatcher;
// this.transformer = transformer;
// }
//
// public PriorityOrdering(Collection<P> priorityCollection, Function<T, P> transformer) {
// this(priorityCollection, transformer, Equivalence.equals());
// }
//
// @Override
// public int compare(T object1, T object2) {
// P comparable1 = this.transformer.apply(object1);
// P comparable2 = this.transformer.apply(object2);
//
// int rank1 = this.rank(comparable1);
// int rank2 = this.rank(comparable2);
//
// if (rank1 == rank2) {
// return comparable1.compareTo(comparable2);
// }
//
// return rank1 - rank2;
//
// }
//
// /**
// * Determine the priority of the given item by matching it against the priority collection.
// * The lower the rank, the higher the priority.
// *
// * @param item The item to prioritize.
// * @return The priority of the given item or {@link Integer#MAX_VALUE} if the given item does not
// * match any element of the priority collection.
// */
// private int rank(P item) {
// int i = 0;
// for (P prioritizedItem : this.priorityCollection) {
// if (this.priorityMatcher.equivalent(item, prioritizedItem)) {
// return i;
// }
// i++;
// }
//
// return Integer.MAX_VALUE;
// }
//
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/priority/PriorityOrderingFactory.java
// public interface PriorityOrderingFactory<P extends Comparable<? super P>, T> {
// PriorityOrdering<P, T> createPriorityOrdering(Collection<P> priorityCollection);
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/functions/StringStartsWithEquivalence.java
// public static Equivalence<String> stringStartsWith() {
// return INSTANCE;
// }
| import java.util.Collection;
import java.util.Map;
import java.util.function.Function;
import com.github.ferstl.maven.pomenforcers.priority.PriorityOrdering;
import com.github.ferstl.maven.pomenforcers.priority.PriorityOrderingFactory;
import com.google.common.collect.Maps;
import static com.github.ferstl.maven.pomenforcers.model.functions.StringStartsWithEquivalence.stringStartsWith;
import static java.util.Objects.requireNonNull; | /*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers.model;
public enum PluginElement implements PriorityOrderingFactory<String, PluginModel>, Function<PluginModel, String> {
GROUP_ID("groupId") {
@Override | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/priority/PriorityOrdering.java
// public class PriorityOrdering<P extends Comparable<? super P>, T> extends Ordering<T> {
//
// /**
// * The priority collection.
// */
// private final Collection<P> priorityCollection;
//
// /**
// * Matches the values to be compared with the items in the priority collection.
// */
// private final Equivalence<? super P> priorityMatcher;
//
// /**
// * Transforms the type of the objects to be compared into the type of the priority collection. Use
// * {@link Function#identity()} if the type of the priority collection and the type of the objects to be
// * compared are the same.
// */
// private final Function<T, P> transformer;
//
//
// public PriorityOrdering(Collection<P> prioritizedItems, Function<T, P> transformer, Equivalence<? super P> priorityMatcher) {
// this.priorityCollection = prioritizedItems;
// this.priorityMatcher = priorityMatcher;
// this.transformer = transformer;
// }
//
// public PriorityOrdering(Collection<P> priorityCollection, Function<T, P> transformer) {
// this(priorityCollection, transformer, Equivalence.equals());
// }
//
// @Override
// public int compare(T object1, T object2) {
// P comparable1 = this.transformer.apply(object1);
// P comparable2 = this.transformer.apply(object2);
//
// int rank1 = this.rank(comparable1);
// int rank2 = this.rank(comparable2);
//
// if (rank1 == rank2) {
// return comparable1.compareTo(comparable2);
// }
//
// return rank1 - rank2;
//
// }
//
// /**
// * Determine the priority of the given item by matching it against the priority collection.
// * The lower the rank, the higher the priority.
// *
// * @param item The item to prioritize.
// * @return The priority of the given item or {@link Integer#MAX_VALUE} if the given item does not
// * match any element of the priority collection.
// */
// private int rank(P item) {
// int i = 0;
// for (P prioritizedItem : this.priorityCollection) {
// if (this.priorityMatcher.equivalent(item, prioritizedItem)) {
// return i;
// }
// i++;
// }
//
// return Integer.MAX_VALUE;
// }
//
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/priority/PriorityOrderingFactory.java
// public interface PriorityOrderingFactory<P extends Comparable<? super P>, T> {
// PriorityOrdering<P, T> createPriorityOrdering(Collection<P> priorityCollection);
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/functions/StringStartsWithEquivalence.java
// public static Equivalence<String> stringStartsWith() {
// return INSTANCE;
// }
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PluginElement.java
import java.util.Collection;
import java.util.Map;
import java.util.function.Function;
import com.github.ferstl.maven.pomenforcers.priority.PriorityOrdering;
import com.github.ferstl.maven.pomenforcers.priority.PriorityOrderingFactory;
import com.google.common.collect.Maps;
import static com.github.ferstl.maven.pomenforcers.model.functions.StringStartsWithEquivalence.stringStartsWith;
import static java.util.Objects.requireNonNull;
/*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers.model;
public enum PluginElement implements PriorityOrderingFactory<String, PluginModel>, Function<PluginModel, String> {
GROUP_ID("groupId") {
@Override | public PriorityOrdering<String, PluginModel> createPriorityOrdering(Collection<String> priorityCollection) { |
ferstl/pedantic-pom-enforcers | src/main/java/com/github/ferstl/maven/pomenforcers/model/PluginElement.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/priority/PriorityOrdering.java
// public class PriorityOrdering<P extends Comparable<? super P>, T> extends Ordering<T> {
//
// /**
// * The priority collection.
// */
// private final Collection<P> priorityCollection;
//
// /**
// * Matches the values to be compared with the items in the priority collection.
// */
// private final Equivalence<? super P> priorityMatcher;
//
// /**
// * Transforms the type of the objects to be compared into the type of the priority collection. Use
// * {@link Function#identity()} if the type of the priority collection and the type of the objects to be
// * compared are the same.
// */
// private final Function<T, P> transformer;
//
//
// public PriorityOrdering(Collection<P> prioritizedItems, Function<T, P> transformer, Equivalence<? super P> priorityMatcher) {
// this.priorityCollection = prioritizedItems;
// this.priorityMatcher = priorityMatcher;
// this.transformer = transformer;
// }
//
// public PriorityOrdering(Collection<P> priorityCollection, Function<T, P> transformer) {
// this(priorityCollection, transformer, Equivalence.equals());
// }
//
// @Override
// public int compare(T object1, T object2) {
// P comparable1 = this.transformer.apply(object1);
// P comparable2 = this.transformer.apply(object2);
//
// int rank1 = this.rank(comparable1);
// int rank2 = this.rank(comparable2);
//
// if (rank1 == rank2) {
// return comparable1.compareTo(comparable2);
// }
//
// return rank1 - rank2;
//
// }
//
// /**
// * Determine the priority of the given item by matching it against the priority collection.
// * The lower the rank, the higher the priority.
// *
// * @param item The item to prioritize.
// * @return The priority of the given item or {@link Integer#MAX_VALUE} if the given item does not
// * match any element of the priority collection.
// */
// private int rank(P item) {
// int i = 0;
// for (P prioritizedItem : this.priorityCollection) {
// if (this.priorityMatcher.equivalent(item, prioritizedItem)) {
// return i;
// }
// i++;
// }
//
// return Integer.MAX_VALUE;
// }
//
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/priority/PriorityOrderingFactory.java
// public interface PriorityOrderingFactory<P extends Comparable<? super P>, T> {
// PriorityOrdering<P, T> createPriorityOrdering(Collection<P> priorityCollection);
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/functions/StringStartsWithEquivalence.java
// public static Equivalence<String> stringStartsWith() {
// return INSTANCE;
// }
| import java.util.Collection;
import java.util.Map;
import java.util.function.Function;
import com.github.ferstl.maven.pomenforcers.priority.PriorityOrdering;
import com.github.ferstl.maven.pomenforcers.priority.PriorityOrderingFactory;
import com.google.common.collect.Maps;
import static com.github.ferstl.maven.pomenforcers.model.functions.StringStartsWithEquivalence.stringStartsWith;
import static java.util.Objects.requireNonNull; | /*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers.model;
public enum PluginElement implements PriorityOrderingFactory<String, PluginModel>, Function<PluginModel, String> {
GROUP_ID("groupId") {
@Override
public PriorityOrdering<String, PluginModel> createPriorityOrdering(Collection<String> priorityCollection) { | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/priority/PriorityOrdering.java
// public class PriorityOrdering<P extends Comparable<? super P>, T> extends Ordering<T> {
//
// /**
// * The priority collection.
// */
// private final Collection<P> priorityCollection;
//
// /**
// * Matches the values to be compared with the items in the priority collection.
// */
// private final Equivalence<? super P> priorityMatcher;
//
// /**
// * Transforms the type of the objects to be compared into the type of the priority collection. Use
// * {@link Function#identity()} if the type of the priority collection and the type of the objects to be
// * compared are the same.
// */
// private final Function<T, P> transformer;
//
//
// public PriorityOrdering(Collection<P> prioritizedItems, Function<T, P> transformer, Equivalence<? super P> priorityMatcher) {
// this.priorityCollection = prioritizedItems;
// this.priorityMatcher = priorityMatcher;
// this.transformer = transformer;
// }
//
// public PriorityOrdering(Collection<P> priorityCollection, Function<T, P> transformer) {
// this(priorityCollection, transformer, Equivalence.equals());
// }
//
// @Override
// public int compare(T object1, T object2) {
// P comparable1 = this.transformer.apply(object1);
// P comparable2 = this.transformer.apply(object2);
//
// int rank1 = this.rank(comparable1);
// int rank2 = this.rank(comparable2);
//
// if (rank1 == rank2) {
// return comparable1.compareTo(comparable2);
// }
//
// return rank1 - rank2;
//
// }
//
// /**
// * Determine the priority of the given item by matching it against the priority collection.
// * The lower the rank, the higher the priority.
// *
// * @param item The item to prioritize.
// * @return The priority of the given item or {@link Integer#MAX_VALUE} if the given item does not
// * match any element of the priority collection.
// */
// private int rank(P item) {
// int i = 0;
// for (P prioritizedItem : this.priorityCollection) {
// if (this.priorityMatcher.equivalent(item, prioritizedItem)) {
// return i;
// }
// i++;
// }
//
// return Integer.MAX_VALUE;
// }
//
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/priority/PriorityOrderingFactory.java
// public interface PriorityOrderingFactory<P extends Comparable<? super P>, T> {
// PriorityOrdering<P, T> createPriorityOrdering(Collection<P> priorityCollection);
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/functions/StringStartsWithEquivalence.java
// public static Equivalence<String> stringStartsWith() {
// return INSTANCE;
// }
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PluginElement.java
import java.util.Collection;
import java.util.Map;
import java.util.function.Function;
import com.github.ferstl.maven.pomenforcers.priority.PriorityOrdering;
import com.github.ferstl.maven.pomenforcers.priority.PriorityOrderingFactory;
import com.google.common.collect.Maps;
import static com.github.ferstl.maven.pomenforcers.model.functions.StringStartsWithEquivalence.stringStartsWith;
import static java.util.Objects.requireNonNull;
/*
* Copyright (c) 2012 - 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ferstl.maven.pomenforcers.model;
public enum PluginElement implements PriorityOrderingFactory<String, PluginModel>, Function<PluginModel, String> {
GROUP_ID("groupId") {
@Override
public PriorityOrdering<String, PluginModel> createPriorityOrdering(Collection<String> priorityCollection) { | return new PriorityOrdering<>(priorityCollection, this, stringStartsWith()); |
ferstl/pedantic-pom-enforcers | src/test/java/com/github/ferstl/maven/pomenforcers/PedanticPluginManagementOrderEnforcerTest.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PluginModel.java
// public class PluginModel extends ArtifactModel {
//
// @XmlElementWrapper(name = "configuration", namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlAnyElement
// private List<Element> configItems;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private DependenciesModel dependencies;
//
// PluginModel() {
// }
//
// public PluginModel(String groupId, String artifactId, String version) {
// super(groupId, artifactId, version);
// }
//
// public boolean isConfigured() {
// return this.configItems != null && !this.configItems.isEmpty();
// }
//
// public List<DependencyModel> getDependencies() {
// return this.dependencies != null ? this.dependencies.getDependencies() : Collections.emptyList();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (!(obj instanceof PluginModel)) {
// return false;
// }
//
// PluginModel other = (PluginModel) obj;
// return super.equals(other)
// // TODO: Element implementations may not implement equals()!!
// && Objects.equals(this.configItems, other.configItems)
// && Objects.equals(this.dependencies, other.dependencies);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.configItems, this.dependencies);
// }
// }
| import org.apache.maven.model.Plugin;
import org.junit.Test;
import com.github.ferstl.maven.pomenforcers.model.PluginModel;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; | addManagedPlugin("x.y.z", "a");
addManagedPlugin("u.v.w", "a");
addManagedPlugin("a.b.c", "a");
executeRuleAndCheckReport(false);
}
@Test
public void artifactIdPriorities() {
this.testRule.setArtifactIdPriorities("z,y");
addManagedPlugin("a.b.c", "z");
addManagedPlugin("a.b.c", "y");
addManagedPlugin("a.b.c", "a");
executeRuleAndCheckReport(false);
}
@Test
public void orderBy() {
this.testRule.setOrderBy("artifactId,groupId");
addManagedPlugin("x.y.z", "a");
addManagedPlugin("a.b.c", "b");
executeRuleAndCheckReport(false);
}
private void addManagedPlugin(String groupId, String artifactId) {
String defaultVersion = "1.0"; | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PluginModel.java
// public class PluginModel extends ArtifactModel {
//
// @XmlElementWrapper(name = "configuration", namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlAnyElement
// private List<Element> configItems;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private DependenciesModel dependencies;
//
// PluginModel() {
// }
//
// public PluginModel(String groupId, String artifactId, String version) {
// super(groupId, artifactId, version);
// }
//
// public boolean isConfigured() {
// return this.configItems != null && !this.configItems.isEmpty();
// }
//
// public List<DependencyModel> getDependencies() {
// return this.dependencies != null ? this.dependencies.getDependencies() : Collections.emptyList();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (!(obj instanceof PluginModel)) {
// return false;
// }
//
// PluginModel other = (PluginModel) obj;
// return super.equals(other)
// // TODO: Element implementations may not implement equals()!!
// && Objects.equals(this.configItems, other.configItems)
// && Objects.equals(this.dependencies, other.dependencies);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.configItems, this.dependencies);
// }
// }
// Path: src/test/java/com/github/ferstl/maven/pomenforcers/PedanticPluginManagementOrderEnforcerTest.java
import org.apache.maven.model.Plugin;
import org.junit.Test;
import com.github.ferstl.maven.pomenforcers.model.PluginModel;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
addManagedPlugin("x.y.z", "a");
addManagedPlugin("u.v.w", "a");
addManagedPlugin("a.b.c", "a");
executeRuleAndCheckReport(false);
}
@Test
public void artifactIdPriorities() {
this.testRule.setArtifactIdPriorities("z,y");
addManagedPlugin("a.b.c", "z");
addManagedPlugin("a.b.c", "y");
addManagedPlugin("a.b.c", "a");
executeRuleAndCheckReport(false);
}
@Test
public void orderBy() {
this.testRule.setOrderBy("artifactId,groupId");
addManagedPlugin("x.y.z", "a");
addManagedPlugin("a.b.c", "b");
executeRuleAndCheckReport(false);
}
private void addManagedPlugin(String groupId, String artifactId) {
String defaultVersion = "1.0"; | PluginModel pluginModel = new PluginModel(groupId, artifactId, defaultVersion); |
ferstl/pedantic-pom-enforcers | src/test/java/com/github/ferstl/maven/pomenforcers/PedanticPluginConfigurationEnforcerTest.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/DependencyModel.java
// @XmlRootElement(name = "dependency")
// public class DependencyModel extends ArtifactModel {
//
// private static final Joiner TO_STRING_JOINER = Joiner.on(":").skipNulls();
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlJavaTypeAdapter(value = DependencyScopeAdapter.class)
// private DependencyScope scope;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String classifier;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String type;
//
// @XmlElementWrapper(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlElement(name = "exclusion", namespace = "http://maven.apache.org/POM/4.0.0")
// private List<ArtifactModel> exclusions;
//
// // Constructor used by JAXB
// DependencyModel() {
// }
//
// public DependencyModel(
// String groupId, String artifactId, String version, String scope, String classifier, String type) {
//
// super(groupId, artifactId, version);
// this.scope = scope != null ? DependencyScope.getByScopeName(scope) : null;
// this.classifier = classifier;
// this.type = type;
// }
//
// public DependencyScope getScope() {
// return this.scope != null ? this.scope : DependencyScope.COMPILE;
// }
//
// public String getClassifier() {
// return this.classifier;
// }
//
// public String getType() {
// return this.type != null ? this.type : "jar";
// }
//
// public List<ArtifactModel> getExclusions() {
// return this.exclusions != null ? this.exclusions : Collections.emptyList();
// }
//
// @Override
// public String toString() {
// return TO_STRING_JOINER.join(
// super.toString(),
// getType(),
// getScope().getScopeName(),
// this.classifier);
// }
//
// // Note that this equals() implementation breaks the symmetry contract!
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (!(obj instanceof DependencyModel)) {
// return false;
// }
//
// DependencyModel other = (DependencyModel) obj;
// return super.equals(other)
// && equal(this.classifier, other.classifier)
// && equal(this.type, other.type)
// && equal(this.scope, other.scope)
// && equal(this.exclusions, other.exclusions);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.classifier, this.type, this.scope);
// }
//
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PluginModel.java
// public class PluginModel extends ArtifactModel {
//
// @XmlElementWrapper(name = "configuration", namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlAnyElement
// private List<Element> configItems;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private DependenciesModel dependencies;
//
// PluginModel() {
// }
//
// public PluginModel(String groupId, String artifactId, String version) {
// super(groupId, artifactId, version);
// }
//
// public boolean isConfigured() {
// return this.configItems != null && !this.configItems.isEmpty();
// }
//
// public List<DependencyModel> getDependencies() {
// return this.dependencies != null ? this.dependencies.getDependencies() : Collections.emptyList();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (!(obj instanceof PluginModel)) {
// return false;
// }
//
// PluginModel other = (PluginModel) obj;
// return super.equals(other)
// // TODO: Element implementations may not implement equals()!!
// && Objects.equals(this.configItems, other.configItems)
// && Objects.equals(this.dependencies, other.dependencies);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.configItems, this.dependencies);
// }
// }
| import java.util.Collections;
import org.junit.Test;
import com.github.ferstl.maven.pomenforcers.model.DependencyModel;
import com.github.ferstl.maven.pomenforcers.model.PluginModel;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
| addPlugin(false, false, true);
executeRuleAndCheckReport(false);
}
@Test
public void forbiddenUnmanagedDependencies() {
this.testRule.setManageDependencies(true);
addPlugin(false, false, true);
executeRuleAndCheckReport(true);
}
@Test
public void allowedManagedVersion() {
this.testRule.setManageVersions(false);
addPlugin(true, false, false);
executeRuleAndCheckReport(false);
}
@Test
public void forbiddenManagedVersion() {
this.testRule.setManageVersions(true);
addPlugin(true, false, false);
executeRuleAndCheckReport(true);
}
private void addPlugin(boolean withVersion, boolean withConfiguration, boolean withDependencies) {
| // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/DependencyModel.java
// @XmlRootElement(name = "dependency")
// public class DependencyModel extends ArtifactModel {
//
// private static final Joiner TO_STRING_JOINER = Joiner.on(":").skipNulls();
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlJavaTypeAdapter(value = DependencyScopeAdapter.class)
// private DependencyScope scope;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String classifier;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String type;
//
// @XmlElementWrapper(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlElement(name = "exclusion", namespace = "http://maven.apache.org/POM/4.0.0")
// private List<ArtifactModel> exclusions;
//
// // Constructor used by JAXB
// DependencyModel() {
// }
//
// public DependencyModel(
// String groupId, String artifactId, String version, String scope, String classifier, String type) {
//
// super(groupId, artifactId, version);
// this.scope = scope != null ? DependencyScope.getByScopeName(scope) : null;
// this.classifier = classifier;
// this.type = type;
// }
//
// public DependencyScope getScope() {
// return this.scope != null ? this.scope : DependencyScope.COMPILE;
// }
//
// public String getClassifier() {
// return this.classifier;
// }
//
// public String getType() {
// return this.type != null ? this.type : "jar";
// }
//
// public List<ArtifactModel> getExclusions() {
// return this.exclusions != null ? this.exclusions : Collections.emptyList();
// }
//
// @Override
// public String toString() {
// return TO_STRING_JOINER.join(
// super.toString(),
// getType(),
// getScope().getScopeName(),
// this.classifier);
// }
//
// // Note that this equals() implementation breaks the symmetry contract!
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (!(obj instanceof DependencyModel)) {
// return false;
// }
//
// DependencyModel other = (DependencyModel) obj;
// return super.equals(other)
// && equal(this.classifier, other.classifier)
// && equal(this.type, other.type)
// && equal(this.scope, other.scope)
// && equal(this.exclusions, other.exclusions);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.classifier, this.type, this.scope);
// }
//
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PluginModel.java
// public class PluginModel extends ArtifactModel {
//
// @XmlElementWrapper(name = "configuration", namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlAnyElement
// private List<Element> configItems;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private DependenciesModel dependencies;
//
// PluginModel() {
// }
//
// public PluginModel(String groupId, String artifactId, String version) {
// super(groupId, artifactId, version);
// }
//
// public boolean isConfigured() {
// return this.configItems != null && !this.configItems.isEmpty();
// }
//
// public List<DependencyModel> getDependencies() {
// return this.dependencies != null ? this.dependencies.getDependencies() : Collections.emptyList();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (!(obj instanceof PluginModel)) {
// return false;
// }
//
// PluginModel other = (PluginModel) obj;
// return super.equals(other)
// // TODO: Element implementations may not implement equals()!!
// && Objects.equals(this.configItems, other.configItems)
// && Objects.equals(this.dependencies, other.dependencies);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.configItems, this.dependencies);
// }
// }
// Path: src/test/java/com/github/ferstl/maven/pomenforcers/PedanticPluginConfigurationEnforcerTest.java
import java.util.Collections;
import org.junit.Test;
import com.github.ferstl.maven.pomenforcers.model.DependencyModel;
import com.github.ferstl.maven.pomenforcers.model.PluginModel;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
addPlugin(false, false, true);
executeRuleAndCheckReport(false);
}
@Test
public void forbiddenUnmanagedDependencies() {
this.testRule.setManageDependencies(true);
addPlugin(false, false, true);
executeRuleAndCheckReport(true);
}
@Test
public void allowedManagedVersion() {
this.testRule.setManageVersions(false);
addPlugin(true, false, false);
executeRuleAndCheckReport(false);
}
@Test
public void forbiddenManagedVersion() {
this.testRule.setManageVersions(true);
addPlugin(true, false, false);
executeRuleAndCheckReport(true);
}
private void addPlugin(boolean withVersion, boolean withConfiguration, boolean withDependencies) {
| PluginModel plugin = mock(PluginModel.class);
|
ferstl/pedantic-pom-enforcers | src/test/java/com/github/ferstl/maven/pomenforcers/PedanticPluginConfigurationEnforcerTest.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/DependencyModel.java
// @XmlRootElement(name = "dependency")
// public class DependencyModel extends ArtifactModel {
//
// private static final Joiner TO_STRING_JOINER = Joiner.on(":").skipNulls();
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlJavaTypeAdapter(value = DependencyScopeAdapter.class)
// private DependencyScope scope;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String classifier;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String type;
//
// @XmlElementWrapper(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlElement(name = "exclusion", namespace = "http://maven.apache.org/POM/4.0.0")
// private List<ArtifactModel> exclusions;
//
// // Constructor used by JAXB
// DependencyModel() {
// }
//
// public DependencyModel(
// String groupId, String artifactId, String version, String scope, String classifier, String type) {
//
// super(groupId, artifactId, version);
// this.scope = scope != null ? DependencyScope.getByScopeName(scope) : null;
// this.classifier = classifier;
// this.type = type;
// }
//
// public DependencyScope getScope() {
// return this.scope != null ? this.scope : DependencyScope.COMPILE;
// }
//
// public String getClassifier() {
// return this.classifier;
// }
//
// public String getType() {
// return this.type != null ? this.type : "jar";
// }
//
// public List<ArtifactModel> getExclusions() {
// return this.exclusions != null ? this.exclusions : Collections.emptyList();
// }
//
// @Override
// public String toString() {
// return TO_STRING_JOINER.join(
// super.toString(),
// getType(),
// getScope().getScopeName(),
// this.classifier);
// }
//
// // Note that this equals() implementation breaks the symmetry contract!
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (!(obj instanceof DependencyModel)) {
// return false;
// }
//
// DependencyModel other = (DependencyModel) obj;
// return super.equals(other)
// && equal(this.classifier, other.classifier)
// && equal(this.type, other.type)
// && equal(this.scope, other.scope)
// && equal(this.exclusions, other.exclusions);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.classifier, this.type, this.scope);
// }
//
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PluginModel.java
// public class PluginModel extends ArtifactModel {
//
// @XmlElementWrapper(name = "configuration", namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlAnyElement
// private List<Element> configItems;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private DependenciesModel dependencies;
//
// PluginModel() {
// }
//
// public PluginModel(String groupId, String artifactId, String version) {
// super(groupId, artifactId, version);
// }
//
// public boolean isConfigured() {
// return this.configItems != null && !this.configItems.isEmpty();
// }
//
// public List<DependencyModel> getDependencies() {
// return this.dependencies != null ? this.dependencies.getDependencies() : Collections.emptyList();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (!(obj instanceof PluginModel)) {
// return false;
// }
//
// PluginModel other = (PluginModel) obj;
// return super.equals(other)
// // TODO: Element implementations may not implement equals()!!
// && Objects.equals(this.configItems, other.configItems)
// && Objects.equals(this.dependencies, other.dependencies);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.configItems, this.dependencies);
// }
// }
| import java.util.Collections;
import org.junit.Test;
import com.github.ferstl.maven.pomenforcers.model.DependencyModel;
import com.github.ferstl.maven.pomenforcers.model.PluginModel;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
| this.testRule.setManageVersions(false);
addPlugin(true, false, false);
executeRuleAndCheckReport(false);
}
@Test
public void forbiddenManagedVersion() {
this.testRule.setManageVersions(true);
addPlugin(true, false, false);
executeRuleAndCheckReport(true);
}
private void addPlugin(boolean withVersion, boolean withConfiguration, boolean withDependencies) {
PluginModel plugin = mock(PluginModel.class);
when(plugin.getGroupId()).thenReturn("a.b.c");
when(plugin.getArtifactId()).thenReturn("a");
if (withVersion) {
when(plugin.getVersion()).thenReturn("1.0");
}
if (withConfiguration) {
when(plugin.isConfigured()).thenReturn(true);
}
if (withDependencies) {
when(plugin.getDependencies()).thenReturn(
| // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/DependencyModel.java
// @XmlRootElement(name = "dependency")
// public class DependencyModel extends ArtifactModel {
//
// private static final Joiner TO_STRING_JOINER = Joiner.on(":").skipNulls();
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlJavaTypeAdapter(value = DependencyScopeAdapter.class)
// private DependencyScope scope;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String classifier;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String type;
//
// @XmlElementWrapper(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlElement(name = "exclusion", namespace = "http://maven.apache.org/POM/4.0.0")
// private List<ArtifactModel> exclusions;
//
// // Constructor used by JAXB
// DependencyModel() {
// }
//
// public DependencyModel(
// String groupId, String artifactId, String version, String scope, String classifier, String type) {
//
// super(groupId, artifactId, version);
// this.scope = scope != null ? DependencyScope.getByScopeName(scope) : null;
// this.classifier = classifier;
// this.type = type;
// }
//
// public DependencyScope getScope() {
// return this.scope != null ? this.scope : DependencyScope.COMPILE;
// }
//
// public String getClassifier() {
// return this.classifier;
// }
//
// public String getType() {
// return this.type != null ? this.type : "jar";
// }
//
// public List<ArtifactModel> getExclusions() {
// return this.exclusions != null ? this.exclusions : Collections.emptyList();
// }
//
// @Override
// public String toString() {
// return TO_STRING_JOINER.join(
// super.toString(),
// getType(),
// getScope().getScopeName(),
// this.classifier);
// }
//
// // Note that this equals() implementation breaks the symmetry contract!
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (!(obj instanceof DependencyModel)) {
// return false;
// }
//
// DependencyModel other = (DependencyModel) obj;
// return super.equals(other)
// && equal(this.classifier, other.classifier)
// && equal(this.type, other.type)
// && equal(this.scope, other.scope)
// && equal(this.exclusions, other.exclusions);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.classifier, this.type, this.scope);
// }
//
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/PluginModel.java
// public class PluginModel extends ArtifactModel {
//
// @XmlElementWrapper(name = "configuration", namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlAnyElement
// private List<Element> configItems;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private DependenciesModel dependencies;
//
// PluginModel() {
// }
//
// public PluginModel(String groupId, String artifactId, String version) {
// super(groupId, artifactId, version);
// }
//
// public boolean isConfigured() {
// return this.configItems != null && !this.configItems.isEmpty();
// }
//
// public List<DependencyModel> getDependencies() {
// return this.dependencies != null ? this.dependencies.getDependencies() : Collections.emptyList();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (!(obj instanceof PluginModel)) {
// return false;
// }
//
// PluginModel other = (PluginModel) obj;
// return super.equals(other)
// // TODO: Element implementations may not implement equals()!!
// && Objects.equals(this.configItems, other.configItems)
// && Objects.equals(this.dependencies, other.dependencies);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.configItems, this.dependencies);
// }
// }
// Path: src/test/java/com/github/ferstl/maven/pomenforcers/PedanticPluginConfigurationEnforcerTest.java
import java.util.Collections;
import org.junit.Test;
import com.github.ferstl.maven.pomenforcers.model.DependencyModel;
import com.github.ferstl.maven.pomenforcers.model.PluginModel;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
this.testRule.setManageVersions(false);
addPlugin(true, false, false);
executeRuleAndCheckReport(false);
}
@Test
public void forbiddenManagedVersion() {
this.testRule.setManageVersions(true);
addPlugin(true, false, false);
executeRuleAndCheckReport(true);
}
private void addPlugin(boolean withVersion, boolean withConfiguration, boolean withDependencies) {
PluginModel plugin = mock(PluginModel.class);
when(plugin.getGroupId()).thenReturn("a.b.c");
when(plugin.getArtifactId()).thenReturn("a");
if (withVersion) {
when(plugin.getVersion()).thenReturn("1.0");
}
if (withConfiguration) {
when(plugin.isConfigured()).thenReturn(true);
}
if (withDependencies) {
when(plugin.getDependencies()).thenReturn(
| Collections.singletonList(new DependencyModel("x.y.z", "z", "1.0", null, null, null)));
|
ferstl/pedantic-pom-enforcers | src/main/java/com/github/ferstl/maven/pomenforcers/PedanticDependencyConfigurationEnforcer.java | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/DependencyModel.java
// @XmlRootElement(name = "dependency")
// public class DependencyModel extends ArtifactModel {
//
// private static final Joiner TO_STRING_JOINER = Joiner.on(":").skipNulls();
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlJavaTypeAdapter(value = DependencyScopeAdapter.class)
// private DependencyScope scope;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String classifier;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String type;
//
// @XmlElementWrapper(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlElement(name = "exclusion", namespace = "http://maven.apache.org/POM/4.0.0")
// private List<ArtifactModel> exclusions;
//
// // Constructor used by JAXB
// DependencyModel() {
// }
//
// public DependencyModel(
// String groupId, String artifactId, String version, String scope, String classifier, String type) {
//
// super(groupId, artifactId, version);
// this.scope = scope != null ? DependencyScope.getByScopeName(scope) : null;
// this.classifier = classifier;
// this.type = type;
// }
//
// public DependencyScope getScope() {
// return this.scope != null ? this.scope : DependencyScope.COMPILE;
// }
//
// public String getClassifier() {
// return this.classifier;
// }
//
// public String getType() {
// return this.type != null ? this.type : "jar";
// }
//
// public List<ArtifactModel> getExclusions() {
// return this.exclusions != null ? this.exclusions : Collections.emptyList();
// }
//
// @Override
// public String toString() {
// return TO_STRING_JOINER.join(
// super.toString(),
// getType(),
// getScope().getScopeName(),
// this.classifier);
// }
//
// // Note that this equals() implementation breaks the symmetry contract!
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (!(obj instanceof DependencyModel)) {
// return false;
// }
//
// DependencyModel other = (DependencyModel) obj;
// return super.equals(other)
// && equal(this.classifier, other.classifier)
// && equal(this.type, other.type)
// && equal(this.scope, other.scope)
// && equal(this.exclusions, other.exclusions);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.classifier, this.type, this.scope);
// }
//
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/ErrorReport.java
// public static <T> String toList(Collection<T> collection) {
// return toList(collection, Function.identity());
// }
| import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import com.github.ferstl.maven.pomenforcers.model.DependencyModel;
import static com.github.ferstl.maven.pomenforcers.ErrorReport.toList; | * @param manageExclusions Manage exclusion in dependency management.
* @configParam
* @default <code>true</code>
* @since 1.0.0
*/
public void setManageExclusions(boolean manageExclusions) {
this.manageExclusions = manageExclusions;
}
@Override
protected PedanticEnforcerRule getDescription() {
return PedanticEnforcerRule.DEPENDENCY_CONFIGURATION;
}
@Override
protected void accept(PedanticEnforcerVisitor visitor) {
visitor.visit(this);
}
@Override
protected void doEnforce(ErrorReport report) {
if (this.manageVersions) {
enforceManagedVersions(report);
}
if (this.manageExclusions) {
enforceManagedExclusion(report);
}
}
private void enforceManagedVersions(ErrorReport report) { | // Path: src/main/java/com/github/ferstl/maven/pomenforcers/model/DependencyModel.java
// @XmlRootElement(name = "dependency")
// public class DependencyModel extends ArtifactModel {
//
// private static final Joiner TO_STRING_JOINER = Joiner.on(":").skipNulls();
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlJavaTypeAdapter(value = DependencyScopeAdapter.class)
// private DependencyScope scope;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String classifier;
//
// @XmlElement(namespace = "http://maven.apache.org/POM/4.0.0")
// private String type;
//
// @XmlElementWrapper(namespace = "http://maven.apache.org/POM/4.0.0")
// @XmlElement(name = "exclusion", namespace = "http://maven.apache.org/POM/4.0.0")
// private List<ArtifactModel> exclusions;
//
// // Constructor used by JAXB
// DependencyModel() {
// }
//
// public DependencyModel(
// String groupId, String artifactId, String version, String scope, String classifier, String type) {
//
// super(groupId, artifactId, version);
// this.scope = scope != null ? DependencyScope.getByScopeName(scope) : null;
// this.classifier = classifier;
// this.type = type;
// }
//
// public DependencyScope getScope() {
// return this.scope != null ? this.scope : DependencyScope.COMPILE;
// }
//
// public String getClassifier() {
// return this.classifier;
// }
//
// public String getType() {
// return this.type != null ? this.type : "jar";
// }
//
// public List<ArtifactModel> getExclusions() {
// return this.exclusions != null ? this.exclusions : Collections.emptyList();
// }
//
// @Override
// public String toString() {
// return TO_STRING_JOINER.join(
// super.toString(),
// getType(),
// getScope().getScopeName(),
// this.classifier);
// }
//
// // Note that this equals() implementation breaks the symmetry contract!
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (!(obj instanceof DependencyModel)) {
// return false;
// }
//
// DependencyModel other = (DependencyModel) obj;
// return super.equals(other)
// && equal(this.classifier, other.classifier)
// && equal(this.type, other.type)
// && equal(this.scope, other.scope)
// && equal(this.exclusions, other.exclusions);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(super.hashCode(), this.classifier, this.type, this.scope);
// }
//
// }
//
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/ErrorReport.java
// public static <T> String toList(Collection<T> collection) {
// return toList(collection, Function.identity());
// }
// Path: src/main/java/com/github/ferstl/maven/pomenforcers/PedanticDependencyConfigurationEnforcer.java
import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import com.github.ferstl.maven.pomenforcers.model.DependencyModel;
import static com.github.ferstl.maven.pomenforcers.ErrorReport.toList;
* @param manageExclusions Manage exclusion in dependency management.
* @configParam
* @default <code>true</code>
* @since 1.0.0
*/
public void setManageExclusions(boolean manageExclusions) {
this.manageExclusions = manageExclusions;
}
@Override
protected PedanticEnforcerRule getDescription() {
return PedanticEnforcerRule.DEPENDENCY_CONFIGURATION;
}
@Override
protected void accept(PedanticEnforcerVisitor visitor) {
visitor.visit(this);
}
@Override
protected void doEnforce(ErrorReport report) {
if (this.manageVersions) {
enforceManagedVersions(report);
}
if (this.manageExclusions) {
enforceManagedExclusion(report);
}
}
private void enforceManagedVersions(ErrorReport report) { | Collection<DependencyModel> versionedDependencies = searchForDependencies(DependencyPredicate.WITH_VERSION); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.