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 |
|---|---|---|---|---|---|---|
gustavkarlsson/rocketchat-jira-trigger | src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/jira/AuthHandlerProvider.java | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/JiraConfiguration.java
// @Singleton
// public class JiraConfiguration {
// private static final String KEY_PREFIX = "jira.";
// static final String URI_KEY = KEY_PREFIX + "uri";
// static final String USER_KEY = KEY_PREFIX + "username";
// static final String PASSWORD_KEY = KEY_PREFIX + "password";
//
// private final URI uri;
// private final String username;
// private final String password;
//
// @Inject
// JiraConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// uri = URI.create(notNull(configMap.getString(URI_KEY), String.format("%s must be provided", URI_KEY)));
// username = configMap.getString(USER_KEY);
// password = configMap.getString(PASSWORD_KEY);
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// public URI getUri() {
// return uri;
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getPassword() {
// return password;
// }
// }
| import com.atlassian.jira.rest.client.api.AuthenticationHandler;
import com.atlassian.jira.rest.client.auth.AnonymousAuthenticationHandler;
import com.atlassian.jira.rest.client.auth.BasicHttpAuthenticationHandler;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import org.slf4j.Logger;
import se.gustavkarlsson.rocketchat.jira_trigger.configuration.JiraConfiguration;
import javax.annotation.Nullable;
import java.io.Console;
import static org.slf4j.LoggerFactory.getLogger; | package se.gustavkarlsson.rocketchat.jira_trigger.jira;
@Singleton
class AuthHandlerProvider implements Provider<AuthenticationHandler> {
private static final Logger log = getLogger(AuthHandlerProvider.class);
private final String username;
private final String password;
private final Console console;
@Inject | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/JiraConfiguration.java
// @Singleton
// public class JiraConfiguration {
// private static final String KEY_PREFIX = "jira.";
// static final String URI_KEY = KEY_PREFIX + "uri";
// static final String USER_KEY = KEY_PREFIX + "username";
// static final String PASSWORD_KEY = KEY_PREFIX + "password";
//
// private final URI uri;
// private final String username;
// private final String password;
//
// @Inject
// JiraConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// uri = URI.create(notNull(configMap.getString(URI_KEY), String.format("%s must be provided", URI_KEY)));
// username = configMap.getString(USER_KEY);
// password = configMap.getString(PASSWORD_KEY);
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// public URI getUri() {
// return uri;
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getPassword() {
// return password;
// }
// }
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/jira/AuthHandlerProvider.java
import com.atlassian.jira.rest.client.api.AuthenticationHandler;
import com.atlassian.jira.rest.client.auth.AnonymousAuthenticationHandler;
import com.atlassian.jira.rest.client.auth.BasicHttpAuthenticationHandler;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import org.slf4j.Logger;
import se.gustavkarlsson.rocketchat.jira_trigger.configuration.JiraConfiguration;
import javax.annotation.Nullable;
import java.io.Console;
import static org.slf4j.LoggerFactory.getLogger;
package se.gustavkarlsson.rocketchat.jira_trigger.jira;
@Singleton
class AuthHandlerProvider implements Provider<AuthenticationHandler> {
private static final Logger log = getLogger(AuthHandlerProvider.class);
private final String username;
private final String password;
private final Console console;
@Inject | AuthHandlerProvider(JiraConfiguration jiraConfig, @Nullable Console console) { |
gustavkarlsson/rocketchat-jira-trigger | src/test/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/MessageConfigurationTest.java | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/MessageConfiguration.java
// @Singleton
// public class MessageConfiguration {
// private static final String KEY_PREFIX = "message.";
// static final String USERNAME_KEY = KEY_PREFIX + "username";
// static final String USE_REAL_NAMES_KEY = KEY_PREFIX + "use_real_names";
// static final String ICON_URL_KEY = KEY_PREFIX + "icon_url";
// static final String DATE_PATTERN_KEY = KEY_PREFIX + "date_pattern";
// static final String DATE_LOCALE_KEY = KEY_PREFIX + "date_locale";
// static final String PRIORITY_COLORS_KEY = KEY_PREFIX + "priority_colors";
// static final String DEFAULT_COLOR_KEY = KEY_PREFIX + "default_color";
// static final String FIELDS_KEY = KEY_PREFIX + "fields";
// static final String WHITELISTED_KEY_PREFIXES_KEY = KEY_PREFIX + "whitelisted_jira_key_prefixes";
// static final String WHITELISTED_KEY_SUFFIXES_KEY = KEY_PREFIX + "whitelisted_jira_key_suffixes";
// static final String MAX_TEXT_LENGTH_KEY = KEY_PREFIX + "max_text_length";
//
// private final String username;
// private final boolean useRealNames;
// private final String iconUrl;
// private final DateTimeFormatter dateFormatter;
// private final boolean priorityColors;
// private final String defaultColor;
// private final List<String> fields;
// private final Set<Character> whitelistedJiraKeyPrefixes;
// private final Set<Character> whitelistedJiraKeySuffixes;
// private final int maxTextLength;
//
// @Inject
// MessageConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// username = configMap.getString(USERNAME_KEY);
// useRealNames = notNull(configMap.getBoolean(USE_REAL_NAMES_KEY), String.format("%s must be provided", USE_REAL_NAMES_KEY));
// iconUrl = configMap.getString(ICON_URL_KEY);
// dateFormatter = DateTimeFormat
// .forPattern(notNull(configMap.getString(DATE_PATTERN_KEY), String.format("%s must be provided", DATE_PATTERN_KEY)))
// .withLocale(Locale.forLanguageTag(notNull(configMap.getString(DATE_LOCALE_KEY), String.format("%s must be provided", DATE_LOCALE_KEY))));
// priorityColors = notNull(configMap.getBoolean(PRIORITY_COLORS_KEY), String.format("%s must be provided", PRIORITY_COLORS_KEY));
// defaultColor = notNull(configMap.getString(DEFAULT_COLOR_KEY), String.format("%s must be provided", DEFAULT_COLOR_KEY));
// fields = Optional.ofNullable(configMap.getStringList(FIELDS_KEY)).orElse(emptyList());
// whitelistedJiraKeyPrefixes = toCharacterSet(Optional.ofNullable(configMap.getString(WHITELISTED_KEY_PREFIXES_KEY)).orElse(""));
// whitelistedJiraKeySuffixes = toCharacterSet(Optional.ofNullable(configMap.getString(WHITELISTED_KEY_SUFFIXES_KEY)).orElse(""));
// maxTextLength = notNull(configMap.getLong(MAX_TEXT_LENGTH_KEY), String.format("%s must be provided", MAX_TEXT_LENGTH_KEY)).intValue();
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// private static Set<Character> toCharacterSet(String string) {
// return string.chars()
// .mapToObj(c -> (char) c)
// .collect(toSet());
// }
//
// public String getUsername() {
// return username;
// }
//
// public boolean isUseRealNames() {
// return useRealNames;
// }
//
// public String getIconUrl() {
// return iconUrl;
// }
//
// public DateTimeFormatter getDateFormatter() {
// return dateFormatter;
// }
//
// public boolean isPriorityColors() {
// return priorityColors;
// }
//
// public String getDefaultColor() {
// return defaultColor;
// }
//
// public List<String> getFields() {
// return fields;
// }
//
// public Set<Character> getWhitelistedJiraKeyPrefixes() {
// return whitelistedJiraKeyPrefixes;
// }
//
// public Set<Character> getWhitelistedJiraKeySuffixes() {
// return whitelistedJiraKeySuffixes;
// }
//
// public int getMaxTextLength() {
// return maxTextLength;
// }
// }
| import org.joda.time.Instant;
import org.joda.time.ReadableInstant;
import org.joda.time.format.DateTimeFormatter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static se.gustavkarlsson.rocketchat.jira_trigger.configuration.MessageConfiguration.*; | package se.gustavkarlsson.rocketchat.jira_trigger.configuration;
@RunWith(MockitoJUnitRunner.class)
public class MessageConfigurationTest {
private static final ReadableInstant EPOCH = new Instant(0);
@Mock
private ConfigMap mockConfigMap;
@Before
public void setUp() throws Exception {
when(mockConfigMap.getString(DATE_PATTERN_KEY)).thenReturn("EEE, d MMM, yyyy");
when(mockConfigMap.getString(DATE_LOCALE_KEY)).thenReturn("en-US");
when(mockConfigMap.getString(WHITELISTED_KEY_PREFIXES_KEY)).thenReturn("A");
when(mockConfigMap.getString(WHITELISTED_KEY_SUFFIXES_KEY)).thenReturn("B");
}
@Test(expected = NullPointerException.class)
public void createWithNullConfigMapThrowsNPE() throws Exception { | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/MessageConfiguration.java
// @Singleton
// public class MessageConfiguration {
// private static final String KEY_PREFIX = "message.";
// static final String USERNAME_KEY = KEY_PREFIX + "username";
// static final String USE_REAL_NAMES_KEY = KEY_PREFIX + "use_real_names";
// static final String ICON_URL_KEY = KEY_PREFIX + "icon_url";
// static final String DATE_PATTERN_KEY = KEY_PREFIX + "date_pattern";
// static final String DATE_LOCALE_KEY = KEY_PREFIX + "date_locale";
// static final String PRIORITY_COLORS_KEY = KEY_PREFIX + "priority_colors";
// static final String DEFAULT_COLOR_KEY = KEY_PREFIX + "default_color";
// static final String FIELDS_KEY = KEY_PREFIX + "fields";
// static final String WHITELISTED_KEY_PREFIXES_KEY = KEY_PREFIX + "whitelisted_jira_key_prefixes";
// static final String WHITELISTED_KEY_SUFFIXES_KEY = KEY_PREFIX + "whitelisted_jira_key_suffixes";
// static final String MAX_TEXT_LENGTH_KEY = KEY_PREFIX + "max_text_length";
//
// private final String username;
// private final boolean useRealNames;
// private final String iconUrl;
// private final DateTimeFormatter dateFormatter;
// private final boolean priorityColors;
// private final String defaultColor;
// private final List<String> fields;
// private final Set<Character> whitelistedJiraKeyPrefixes;
// private final Set<Character> whitelistedJiraKeySuffixes;
// private final int maxTextLength;
//
// @Inject
// MessageConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// username = configMap.getString(USERNAME_KEY);
// useRealNames = notNull(configMap.getBoolean(USE_REAL_NAMES_KEY), String.format("%s must be provided", USE_REAL_NAMES_KEY));
// iconUrl = configMap.getString(ICON_URL_KEY);
// dateFormatter = DateTimeFormat
// .forPattern(notNull(configMap.getString(DATE_PATTERN_KEY), String.format("%s must be provided", DATE_PATTERN_KEY)))
// .withLocale(Locale.forLanguageTag(notNull(configMap.getString(DATE_LOCALE_KEY), String.format("%s must be provided", DATE_LOCALE_KEY))));
// priorityColors = notNull(configMap.getBoolean(PRIORITY_COLORS_KEY), String.format("%s must be provided", PRIORITY_COLORS_KEY));
// defaultColor = notNull(configMap.getString(DEFAULT_COLOR_KEY), String.format("%s must be provided", DEFAULT_COLOR_KEY));
// fields = Optional.ofNullable(configMap.getStringList(FIELDS_KEY)).orElse(emptyList());
// whitelistedJiraKeyPrefixes = toCharacterSet(Optional.ofNullable(configMap.getString(WHITELISTED_KEY_PREFIXES_KEY)).orElse(""));
// whitelistedJiraKeySuffixes = toCharacterSet(Optional.ofNullable(configMap.getString(WHITELISTED_KEY_SUFFIXES_KEY)).orElse(""));
// maxTextLength = notNull(configMap.getLong(MAX_TEXT_LENGTH_KEY), String.format("%s must be provided", MAX_TEXT_LENGTH_KEY)).intValue();
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// private static Set<Character> toCharacterSet(String string) {
// return string.chars()
// .mapToObj(c -> (char) c)
// .collect(toSet());
// }
//
// public String getUsername() {
// return username;
// }
//
// public boolean isUseRealNames() {
// return useRealNames;
// }
//
// public String getIconUrl() {
// return iconUrl;
// }
//
// public DateTimeFormatter getDateFormatter() {
// return dateFormatter;
// }
//
// public boolean isPriorityColors() {
// return priorityColors;
// }
//
// public String getDefaultColor() {
// return defaultColor;
// }
//
// public List<String> getFields() {
// return fields;
// }
//
// public Set<Character> getWhitelistedJiraKeyPrefixes() {
// return whitelistedJiraKeyPrefixes;
// }
//
// public Set<Character> getWhitelistedJiraKeySuffixes() {
// return whitelistedJiraKeySuffixes;
// }
//
// public int getMaxTextLength() {
// return maxTextLength;
// }
// }
// Path: src/test/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/MessageConfigurationTest.java
import org.joda.time.Instant;
import org.joda.time.ReadableInstant;
import org.joda.time.format.DateTimeFormatter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static se.gustavkarlsson.rocketchat.jira_trigger.configuration.MessageConfiguration.*;
package se.gustavkarlsson.rocketchat.jira_trigger.configuration;
@RunWith(MockitoJUnitRunner.class)
public class MessageConfigurationTest {
private static final ReadableInstant EPOCH = new Instant(0);
@Mock
private ConfigMap mockConfigMap;
@Before
public void setUp() throws Exception {
when(mockConfigMap.getString(DATE_PATTERN_KEY)).thenReturn("EEE, d MMM, yyyy");
when(mockConfigMap.getString(DATE_LOCALE_KEY)).thenReturn("en-US");
when(mockConfigMap.getString(WHITELISTED_KEY_PREFIXES_KEY)).thenReturn("A");
when(mockConfigMap.getString(WHITELISTED_KEY_SUFFIXES_KEY)).thenReturn("B");
}
@Test(expected = NullPointerException.class)
public void createWithNullConfigMapThrowsNPE() throws Exception { | new MessageConfiguration(null); |
gustavkarlsson/rocketchat-jira-trigger | src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/routes/RouteModule.java | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/MessageConfiguration.java
// @Singleton
// public class MessageConfiguration {
// private static final String KEY_PREFIX = "message.";
// static final String USERNAME_KEY = KEY_PREFIX + "username";
// static final String USE_REAL_NAMES_KEY = KEY_PREFIX + "use_real_names";
// static final String ICON_URL_KEY = KEY_PREFIX + "icon_url";
// static final String DATE_PATTERN_KEY = KEY_PREFIX + "date_pattern";
// static final String DATE_LOCALE_KEY = KEY_PREFIX + "date_locale";
// static final String PRIORITY_COLORS_KEY = KEY_PREFIX + "priority_colors";
// static final String DEFAULT_COLOR_KEY = KEY_PREFIX + "default_color";
// static final String FIELDS_KEY = KEY_PREFIX + "fields";
// static final String WHITELISTED_KEY_PREFIXES_KEY = KEY_PREFIX + "whitelisted_jira_key_prefixes";
// static final String WHITELISTED_KEY_SUFFIXES_KEY = KEY_PREFIX + "whitelisted_jira_key_suffixes";
// static final String MAX_TEXT_LENGTH_KEY = KEY_PREFIX + "max_text_length";
//
// private final String username;
// private final boolean useRealNames;
// private final String iconUrl;
// private final DateTimeFormatter dateFormatter;
// private final boolean priorityColors;
// private final String defaultColor;
// private final List<String> fields;
// private final Set<Character> whitelistedJiraKeyPrefixes;
// private final Set<Character> whitelistedJiraKeySuffixes;
// private final int maxTextLength;
//
// @Inject
// MessageConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// username = configMap.getString(USERNAME_KEY);
// useRealNames = notNull(configMap.getBoolean(USE_REAL_NAMES_KEY), String.format("%s must be provided", USE_REAL_NAMES_KEY));
// iconUrl = configMap.getString(ICON_URL_KEY);
// dateFormatter = DateTimeFormat
// .forPattern(notNull(configMap.getString(DATE_PATTERN_KEY), String.format("%s must be provided", DATE_PATTERN_KEY)))
// .withLocale(Locale.forLanguageTag(notNull(configMap.getString(DATE_LOCALE_KEY), String.format("%s must be provided", DATE_LOCALE_KEY))));
// priorityColors = notNull(configMap.getBoolean(PRIORITY_COLORS_KEY), String.format("%s must be provided", PRIORITY_COLORS_KEY));
// defaultColor = notNull(configMap.getString(DEFAULT_COLOR_KEY), String.format("%s must be provided", DEFAULT_COLOR_KEY));
// fields = Optional.ofNullable(configMap.getStringList(FIELDS_KEY)).orElse(emptyList());
// whitelistedJiraKeyPrefixes = toCharacterSet(Optional.ofNullable(configMap.getString(WHITELISTED_KEY_PREFIXES_KEY)).orElse(""));
// whitelistedJiraKeySuffixes = toCharacterSet(Optional.ofNullable(configMap.getString(WHITELISTED_KEY_SUFFIXES_KEY)).orElse(""));
// maxTextLength = notNull(configMap.getLong(MAX_TEXT_LENGTH_KEY), String.format("%s must be provided", MAX_TEXT_LENGTH_KEY)).intValue();
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// private static Set<Character> toCharacterSet(String string) {
// return string.chars()
// .mapToObj(c -> (char) c)
// .collect(toSet());
// }
//
// public String getUsername() {
// return username;
// }
//
// public boolean isUseRealNames() {
// return useRealNames;
// }
//
// public String getIconUrl() {
// return iconUrl;
// }
//
// public DateTimeFormatter getDateFormatter() {
// return dateFormatter;
// }
//
// public boolean isPriorityColors() {
// return priorityColors;
// }
//
// public String getDefaultColor() {
// return defaultColor;
// }
//
// public List<String> getFields() {
// return fields;
// }
//
// public Set<Character> getWhitelistedJiraKeyPrefixes() {
// return whitelistedJiraKeyPrefixes;
// }
//
// public Set<Character> getWhitelistedJiraKeySuffixes() {
// return whitelistedJiraKeySuffixes;
// }
//
// public int getMaxTextLength() {
// return maxTextLength;
// }
// }
| import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import se.gustavkarlsson.rocketchat.jira_trigger.configuration.MessageConfiguration; | package se.gustavkarlsson.rocketchat.jira_trigger.routes;
public class RouteModule extends AbstractModule {
@Override
protected void configure() {
}
@Provides
@Singleton | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/MessageConfiguration.java
// @Singleton
// public class MessageConfiguration {
// private static final String KEY_PREFIX = "message.";
// static final String USERNAME_KEY = KEY_PREFIX + "username";
// static final String USE_REAL_NAMES_KEY = KEY_PREFIX + "use_real_names";
// static final String ICON_URL_KEY = KEY_PREFIX + "icon_url";
// static final String DATE_PATTERN_KEY = KEY_PREFIX + "date_pattern";
// static final String DATE_LOCALE_KEY = KEY_PREFIX + "date_locale";
// static final String PRIORITY_COLORS_KEY = KEY_PREFIX + "priority_colors";
// static final String DEFAULT_COLOR_KEY = KEY_PREFIX + "default_color";
// static final String FIELDS_KEY = KEY_PREFIX + "fields";
// static final String WHITELISTED_KEY_PREFIXES_KEY = KEY_PREFIX + "whitelisted_jira_key_prefixes";
// static final String WHITELISTED_KEY_SUFFIXES_KEY = KEY_PREFIX + "whitelisted_jira_key_suffixes";
// static final String MAX_TEXT_LENGTH_KEY = KEY_PREFIX + "max_text_length";
//
// private final String username;
// private final boolean useRealNames;
// private final String iconUrl;
// private final DateTimeFormatter dateFormatter;
// private final boolean priorityColors;
// private final String defaultColor;
// private final List<String> fields;
// private final Set<Character> whitelistedJiraKeyPrefixes;
// private final Set<Character> whitelistedJiraKeySuffixes;
// private final int maxTextLength;
//
// @Inject
// MessageConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// username = configMap.getString(USERNAME_KEY);
// useRealNames = notNull(configMap.getBoolean(USE_REAL_NAMES_KEY), String.format("%s must be provided", USE_REAL_NAMES_KEY));
// iconUrl = configMap.getString(ICON_URL_KEY);
// dateFormatter = DateTimeFormat
// .forPattern(notNull(configMap.getString(DATE_PATTERN_KEY), String.format("%s must be provided", DATE_PATTERN_KEY)))
// .withLocale(Locale.forLanguageTag(notNull(configMap.getString(DATE_LOCALE_KEY), String.format("%s must be provided", DATE_LOCALE_KEY))));
// priorityColors = notNull(configMap.getBoolean(PRIORITY_COLORS_KEY), String.format("%s must be provided", PRIORITY_COLORS_KEY));
// defaultColor = notNull(configMap.getString(DEFAULT_COLOR_KEY), String.format("%s must be provided", DEFAULT_COLOR_KEY));
// fields = Optional.ofNullable(configMap.getStringList(FIELDS_KEY)).orElse(emptyList());
// whitelistedJiraKeyPrefixes = toCharacterSet(Optional.ofNullable(configMap.getString(WHITELISTED_KEY_PREFIXES_KEY)).orElse(""));
// whitelistedJiraKeySuffixes = toCharacterSet(Optional.ofNullable(configMap.getString(WHITELISTED_KEY_SUFFIXES_KEY)).orElse(""));
// maxTextLength = notNull(configMap.getLong(MAX_TEXT_LENGTH_KEY), String.format("%s must be provided", MAX_TEXT_LENGTH_KEY)).intValue();
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// private static Set<Character> toCharacterSet(String string) {
// return string.chars()
// .mapToObj(c -> (char) c)
// .collect(toSet());
// }
//
// public String getUsername() {
// return username;
// }
//
// public boolean isUseRealNames() {
// return useRealNames;
// }
//
// public String getIconUrl() {
// return iconUrl;
// }
//
// public DateTimeFormatter getDateFormatter() {
// return dateFormatter;
// }
//
// public boolean isPriorityColors() {
// return priorityColors;
// }
//
// public String getDefaultColor() {
// return defaultColor;
// }
//
// public List<String> getFields() {
// return fields;
// }
//
// public Set<Character> getWhitelistedJiraKeyPrefixes() {
// return whitelistedJiraKeyPrefixes;
// }
//
// public Set<Character> getWhitelistedJiraKeySuffixes() {
// return whitelistedJiraKeySuffixes;
// }
//
// public int getMaxTextLength() {
// return maxTextLength;
// }
// }
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/routes/RouteModule.java
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import se.gustavkarlsson.rocketchat.jira_trigger.configuration.MessageConfiguration;
package se.gustavkarlsson.rocketchat.jira_trigger.routes;
public class RouteModule extends AbstractModule {
@Override
protected void configure() {
}
@Provides
@Singleton | JiraKeyParser provideJiraKeyParser(MessageConfiguration messageConfig) { |
gustavkarlsson/rocketchat-jira-trigger | src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/FieldCreatorsProvider.java | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/MessageConfiguration.java
// @Singleton
// public class MessageConfiguration {
// private static final String KEY_PREFIX = "message.";
// static final String USERNAME_KEY = KEY_PREFIX + "username";
// static final String USE_REAL_NAMES_KEY = KEY_PREFIX + "use_real_names";
// static final String ICON_URL_KEY = KEY_PREFIX + "icon_url";
// static final String DATE_PATTERN_KEY = KEY_PREFIX + "date_pattern";
// static final String DATE_LOCALE_KEY = KEY_PREFIX + "date_locale";
// static final String PRIORITY_COLORS_KEY = KEY_PREFIX + "priority_colors";
// static final String DEFAULT_COLOR_KEY = KEY_PREFIX + "default_color";
// static final String FIELDS_KEY = KEY_PREFIX + "fields";
// static final String WHITELISTED_KEY_PREFIXES_KEY = KEY_PREFIX + "whitelisted_jira_key_prefixes";
// static final String WHITELISTED_KEY_SUFFIXES_KEY = KEY_PREFIX + "whitelisted_jira_key_suffixes";
// static final String MAX_TEXT_LENGTH_KEY = KEY_PREFIX + "max_text_length";
//
// private final String username;
// private final boolean useRealNames;
// private final String iconUrl;
// private final DateTimeFormatter dateFormatter;
// private final boolean priorityColors;
// private final String defaultColor;
// private final List<String> fields;
// private final Set<Character> whitelistedJiraKeyPrefixes;
// private final Set<Character> whitelistedJiraKeySuffixes;
// private final int maxTextLength;
//
// @Inject
// MessageConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// username = configMap.getString(USERNAME_KEY);
// useRealNames = notNull(configMap.getBoolean(USE_REAL_NAMES_KEY), String.format("%s must be provided", USE_REAL_NAMES_KEY));
// iconUrl = configMap.getString(ICON_URL_KEY);
// dateFormatter = DateTimeFormat
// .forPattern(notNull(configMap.getString(DATE_PATTERN_KEY), String.format("%s must be provided", DATE_PATTERN_KEY)))
// .withLocale(Locale.forLanguageTag(notNull(configMap.getString(DATE_LOCALE_KEY), String.format("%s must be provided", DATE_LOCALE_KEY))));
// priorityColors = notNull(configMap.getBoolean(PRIORITY_COLORS_KEY), String.format("%s must be provided", PRIORITY_COLORS_KEY));
// defaultColor = notNull(configMap.getString(DEFAULT_COLOR_KEY), String.format("%s must be provided", DEFAULT_COLOR_KEY));
// fields = Optional.ofNullable(configMap.getStringList(FIELDS_KEY)).orElse(emptyList());
// whitelistedJiraKeyPrefixes = toCharacterSet(Optional.ofNullable(configMap.getString(WHITELISTED_KEY_PREFIXES_KEY)).orElse(""));
// whitelistedJiraKeySuffixes = toCharacterSet(Optional.ofNullable(configMap.getString(WHITELISTED_KEY_SUFFIXES_KEY)).orElse(""));
// maxTextLength = notNull(configMap.getLong(MAX_TEXT_LENGTH_KEY), String.format("%s must be provided", MAX_TEXT_LENGTH_KEY)).intValue();
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// private static Set<Character> toCharacterSet(String string) {
// return string.chars()
// .mapToObj(c -> (char) c)
// .collect(toSet());
// }
//
// public String getUsername() {
// return username;
// }
//
// public boolean isUseRealNames() {
// return useRealNames;
// }
//
// public String getIconUrl() {
// return iconUrl;
// }
//
// public DateTimeFormatter getDateFormatter() {
// return dateFormatter;
// }
//
// public boolean isPriorityColors() {
// return priorityColors;
// }
//
// public String getDefaultColor() {
// return defaultColor;
// }
//
// public List<String> getFields() {
// return fields;
// }
//
// public Set<Character> getWhitelistedJiraKeyPrefixes() {
// return whitelistedJiraKeyPrefixes;
// }
//
// public Set<Character> getWhitelistedJiraKeySuffixes() {
// return whitelistedJiraKeySuffixes;
// }
//
// public int getMaxTextLength() {
// return maxTextLength;
// }
// }
//
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/field_creators/FieldCreator.java
// public interface FieldCreator {
// Field create(Issue issue);
// }
| import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import se.gustavkarlsson.rocketchat.jira_trigger.configuration.MessageConfiguration;
import se.gustavkarlsson.rocketchat.jira_trigger.messages.field_creators.FieldCreator;
import java.util.List;
import static org.apache.commons.lang3.Validate.notNull; | package se.gustavkarlsson.rocketchat.jira_trigger.messages;
@Singleton
class FieldCreatorsProvider implements Provider<List<FieldCreator>> {
private final FieldCreatorMapper fieldCreatorMapper; | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/MessageConfiguration.java
// @Singleton
// public class MessageConfiguration {
// private static final String KEY_PREFIX = "message.";
// static final String USERNAME_KEY = KEY_PREFIX + "username";
// static final String USE_REAL_NAMES_KEY = KEY_PREFIX + "use_real_names";
// static final String ICON_URL_KEY = KEY_PREFIX + "icon_url";
// static final String DATE_PATTERN_KEY = KEY_PREFIX + "date_pattern";
// static final String DATE_LOCALE_KEY = KEY_PREFIX + "date_locale";
// static final String PRIORITY_COLORS_KEY = KEY_PREFIX + "priority_colors";
// static final String DEFAULT_COLOR_KEY = KEY_PREFIX + "default_color";
// static final String FIELDS_KEY = KEY_PREFIX + "fields";
// static final String WHITELISTED_KEY_PREFIXES_KEY = KEY_PREFIX + "whitelisted_jira_key_prefixes";
// static final String WHITELISTED_KEY_SUFFIXES_KEY = KEY_PREFIX + "whitelisted_jira_key_suffixes";
// static final String MAX_TEXT_LENGTH_KEY = KEY_PREFIX + "max_text_length";
//
// private final String username;
// private final boolean useRealNames;
// private final String iconUrl;
// private final DateTimeFormatter dateFormatter;
// private final boolean priorityColors;
// private final String defaultColor;
// private final List<String> fields;
// private final Set<Character> whitelistedJiraKeyPrefixes;
// private final Set<Character> whitelistedJiraKeySuffixes;
// private final int maxTextLength;
//
// @Inject
// MessageConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// username = configMap.getString(USERNAME_KEY);
// useRealNames = notNull(configMap.getBoolean(USE_REAL_NAMES_KEY), String.format("%s must be provided", USE_REAL_NAMES_KEY));
// iconUrl = configMap.getString(ICON_URL_KEY);
// dateFormatter = DateTimeFormat
// .forPattern(notNull(configMap.getString(DATE_PATTERN_KEY), String.format("%s must be provided", DATE_PATTERN_KEY)))
// .withLocale(Locale.forLanguageTag(notNull(configMap.getString(DATE_LOCALE_KEY), String.format("%s must be provided", DATE_LOCALE_KEY))));
// priorityColors = notNull(configMap.getBoolean(PRIORITY_COLORS_KEY), String.format("%s must be provided", PRIORITY_COLORS_KEY));
// defaultColor = notNull(configMap.getString(DEFAULT_COLOR_KEY), String.format("%s must be provided", DEFAULT_COLOR_KEY));
// fields = Optional.ofNullable(configMap.getStringList(FIELDS_KEY)).orElse(emptyList());
// whitelistedJiraKeyPrefixes = toCharacterSet(Optional.ofNullable(configMap.getString(WHITELISTED_KEY_PREFIXES_KEY)).orElse(""));
// whitelistedJiraKeySuffixes = toCharacterSet(Optional.ofNullable(configMap.getString(WHITELISTED_KEY_SUFFIXES_KEY)).orElse(""));
// maxTextLength = notNull(configMap.getLong(MAX_TEXT_LENGTH_KEY), String.format("%s must be provided", MAX_TEXT_LENGTH_KEY)).intValue();
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// private static Set<Character> toCharacterSet(String string) {
// return string.chars()
// .mapToObj(c -> (char) c)
// .collect(toSet());
// }
//
// public String getUsername() {
// return username;
// }
//
// public boolean isUseRealNames() {
// return useRealNames;
// }
//
// public String getIconUrl() {
// return iconUrl;
// }
//
// public DateTimeFormatter getDateFormatter() {
// return dateFormatter;
// }
//
// public boolean isPriorityColors() {
// return priorityColors;
// }
//
// public String getDefaultColor() {
// return defaultColor;
// }
//
// public List<String> getFields() {
// return fields;
// }
//
// public Set<Character> getWhitelistedJiraKeyPrefixes() {
// return whitelistedJiraKeyPrefixes;
// }
//
// public Set<Character> getWhitelistedJiraKeySuffixes() {
// return whitelistedJiraKeySuffixes;
// }
//
// public int getMaxTextLength() {
// return maxTextLength;
// }
// }
//
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/field_creators/FieldCreator.java
// public interface FieldCreator {
// Field create(Issue issue);
// }
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/messages/FieldCreatorsProvider.java
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import se.gustavkarlsson.rocketchat.jira_trigger.configuration.MessageConfiguration;
import se.gustavkarlsson.rocketchat.jira_trigger.messages.field_creators.FieldCreator;
import java.util.List;
import static org.apache.commons.lang3.Validate.notNull;
package se.gustavkarlsson.rocketchat.jira_trigger.messages;
@Singleton
class FieldCreatorsProvider implements Provider<List<FieldCreator>> {
private final FieldCreatorMapper fieldCreatorMapper; | private final MessageConfiguration messageConfig; |
gustavkarlsson/rocketchat-jira-trigger | src/test/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/RocketChatConfigurationTest.java | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/RocketChatConfiguration.java
// static final String TOKENS_KEY = KEY_PREFIX + "tokens";
| import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.mockito.Mockito.when;
import static se.gustavkarlsson.rocketchat.jira_trigger.configuration.RocketChatConfiguration.TOKENS_KEY; | package se.gustavkarlsson.rocketchat.jira_trigger.configuration;
@RunWith(MockitoJUnitRunner.class)
public class RocketChatConfigurationTest {
@Mock
private ConfigMap mockConfigMap;
@Test(expected = NullPointerException.class)
public void createWithNullConfigMapThrowsNPE() throws Exception {
new RocketChatConfiguration(null);
}
@Test(expected = ValidationException.class)
public void createWithNullTokensConfigMapThrowsValidationException() throws Exception { | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/RocketChatConfiguration.java
// static final String TOKENS_KEY = KEY_PREFIX + "tokens";
// Path: src/test/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/RocketChatConfigurationTest.java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.mockito.Mockito.when;
import static se.gustavkarlsson.rocketchat.jira_trigger.configuration.RocketChatConfiguration.TOKENS_KEY;
package se.gustavkarlsson.rocketchat.jira_trigger.configuration;
@RunWith(MockitoJUnitRunner.class)
public class RocketChatConfigurationTest {
@Mock
private ConfigMap mockConfigMap;
@Test(expected = NullPointerException.class)
public void createWithNullConfigMapThrowsNPE() throws Exception {
new RocketChatConfiguration(null);
}
@Test(expected = ValidationException.class)
public void createWithNullTokensConfigMapThrowsValidationException() throws Exception { | when(mockConfigMap.getStringList(TOKENS_KEY)).thenReturn(null); |
gustavkarlsson/rocketchat-jira-trigger | src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/validation/ValidationModule.java | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/RocketChatConfiguration.java
// @Singleton
// public class RocketChatConfiguration {
// private static final String KEY_PREFIX = "rocketchat.";
// static final String TOKENS_KEY = KEY_PREFIX + "tokens";
// static final String WHITELISTED_USERS = KEY_PREFIX + "whitelisted_users";
// static final String BLACKLISTED_USERS = KEY_PREFIX + "blacklisted_users";
// static final String WHITELISTED_CHANNELS = KEY_PREFIX + "whitelisted_channels";
// static final String BLACKLISTED_CHANNELS = KEY_PREFIX + "blacklisted_channels";
// static final String IGNORE_BOTS = KEY_PREFIX + "ignore_bots";
//
// private final Set<String> tokens;
// private final Set<String> whitelistedUsers;
// private final Set<String> blacklistedUsers;
// private final Set<String> whitelistedChannels;
// private final Set<String> blacklistedChannels;
// private final boolean ignoreBots;
//
// @Inject
// RocketChatConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// tokens = new HashSet<>(Optional.of(configMap.getStringList(TOKENS_KEY)).orElse(Collections.emptyList()));
// whitelistedUsers = new HashSet<>(Optional.of(configMap.getStringList(WHITELISTED_USERS)).orElse(Collections.emptyList()));
// blacklistedUsers = new HashSet<>(Optional.of(configMap.getStringList(BLACKLISTED_USERS)).orElse(Collections.emptyList()));
// whitelistedChannels = new HashSet<>(Optional.of(configMap.getStringList(WHITELISTED_CHANNELS)).orElse(Collections.emptyList()));
// blacklistedChannels = new HashSet<>(Optional.of(configMap.getStringList(BLACKLISTED_CHANNELS)).orElse(Collections.emptyList()));
// ignoreBots = notNull(configMap.getBoolean(IGNORE_BOTS), String.format("%s must be provided", IGNORE_BOTS));
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// public Set<String> getTokens() {
// return tokens;
// }
//
// public Set<String> getWhitelistedUsers() {
// return whitelistedUsers;
// }
//
// public Set<String> getBlacklistedUsers() {
// return blacklistedUsers;
// }
//
// public Set<String> getWhitelistedChannels() {
// return whitelistedChannels;
// }
//
// public Set<String> getBlacklistedChannels() {
// return blacklistedChannels;
// }
//
// public boolean isIgnoreBots() {
// return ignoreBots;
// }
// }
| import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import se.gustavkarlsson.rocketchat.jira_trigger.configuration.RocketChatConfiguration;
import java.util.Arrays;
import java.util.List; | package se.gustavkarlsson.rocketchat.jira_trigger.validation;
public class ValidationModule extends AbstractModule {
@Override
protected void configure() {
}
@Provides
@Singleton | // Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/configuration/RocketChatConfiguration.java
// @Singleton
// public class RocketChatConfiguration {
// private static final String KEY_PREFIX = "rocketchat.";
// static final String TOKENS_KEY = KEY_PREFIX + "tokens";
// static final String WHITELISTED_USERS = KEY_PREFIX + "whitelisted_users";
// static final String BLACKLISTED_USERS = KEY_PREFIX + "blacklisted_users";
// static final String WHITELISTED_CHANNELS = KEY_PREFIX + "whitelisted_channels";
// static final String BLACKLISTED_CHANNELS = KEY_PREFIX + "blacklisted_channels";
// static final String IGNORE_BOTS = KEY_PREFIX + "ignore_bots";
//
// private final Set<String> tokens;
// private final Set<String> whitelistedUsers;
// private final Set<String> blacklistedUsers;
// private final Set<String> whitelistedChannels;
// private final Set<String> blacklistedChannels;
// private final boolean ignoreBots;
//
// @Inject
// RocketChatConfiguration(ConfigMap configMap) throws ValidationException {
// notNull(configMap);
// try {
// tokens = new HashSet<>(Optional.of(configMap.getStringList(TOKENS_KEY)).orElse(Collections.emptyList()));
// whitelistedUsers = new HashSet<>(Optional.of(configMap.getStringList(WHITELISTED_USERS)).orElse(Collections.emptyList()));
// blacklistedUsers = new HashSet<>(Optional.of(configMap.getStringList(BLACKLISTED_USERS)).orElse(Collections.emptyList()));
// whitelistedChannels = new HashSet<>(Optional.of(configMap.getStringList(WHITELISTED_CHANNELS)).orElse(Collections.emptyList()));
// blacklistedChannels = new HashSet<>(Optional.of(configMap.getStringList(BLACKLISTED_CHANNELS)).orElse(Collections.emptyList()));
// ignoreBots = notNull(configMap.getBoolean(IGNORE_BOTS), String.format("%s must be provided", IGNORE_BOTS));
// } catch (Exception e) {
// throw new ValidationException(e);
// }
// }
//
// public Set<String> getTokens() {
// return tokens;
// }
//
// public Set<String> getWhitelistedUsers() {
// return whitelistedUsers;
// }
//
// public Set<String> getBlacklistedUsers() {
// return blacklistedUsers;
// }
//
// public Set<String> getWhitelistedChannels() {
// return whitelistedChannels;
// }
//
// public Set<String> getBlacklistedChannels() {
// return blacklistedChannels;
// }
//
// public boolean isIgnoreBots() {
// return ignoreBots;
// }
// }
// Path: src/main/java/se/gustavkarlsson/rocketchat/jira_trigger/validation/ValidationModule.java
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import se.gustavkarlsson.rocketchat.jira_trigger.configuration.RocketChatConfiguration;
import java.util.Arrays;
import java.util.List;
package se.gustavkarlsson.rocketchat.jira_trigger.validation;
public class ValidationModule extends AbstractModule {
@Override
protected void configure() {
}
@Provides
@Singleton | TokenValidator provideTokenValidator(RocketChatConfiguration rocketChatConfig) { |
sensorstorm/StormCV | stormcv/src/main/java/nl/tno/stormcv/model/serializer/VideoChunkSerializer.java | // Path: stormcv/src/main/java/nl/tno/stormcv/model/CVParticle.java
// public abstract class CVParticle implements Comparable<CVParticle>{
//
// private Tuple tuple;
// private long requestId = -1;
// private String streamId;
// private long sequenceNr;
// private HashMap<String, Object> metadata = new HashMap<String, Object>();
//
// /**
// * Constructs a generic type based on the provided tuple. The tuple must contain streamID and sequenceNR
// * values.
// * @param tuple
// */
// @SuppressWarnings("unchecked")
// public CVParticle(Tuple tuple){
// this(tuple.getStringByField(CVParticleSerializer.STREAMID),
// tuple.getLongByField(CVParticleSerializer.SEQUENCENR));
// this.tuple = tuple;
// this.setRequestId(tuple.getLongByField(CVParticleSerializer.REQUESTID));
// this.setMetadata((HashMap<String, Object>)tuple.getValueByField(CVParticleSerializer.METADATA));
// }
//
// /**
// * Constructs a GenericType object for some piece of information regarding a stream
// * @param streamId the id of the stream
// * @param sequenceNr the sequence number of the the information (used for ordering)
// */
// public CVParticle(String streamId, long sequenceNr){
// this.streamId = streamId;
// this.sequenceNr = sequenceNr;
// }
//
// public String getStreamId(){
// return streamId;
// }
//
// public long getSequenceNr(){
// return sequenceNr;
// }
//
// public Tuple getTuple() {
// return tuple;
// }
//
// public HashMap<String, Object> getMetadata() {
// return metadata;
// }
//
// public void setMetadata(HashMap<String, Object> metadata) {
// if(metadata != null){
// this.metadata = metadata;
// }
// }
//
// public void setRequestId(long id){
// this.requestId = id;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// /**
// * Compares one generictype to another based on their sequence number.
// * @return -1 if this.sequenceNr < other.sequenceNr, 0 if this.sequenceNr == other.sequenceNr else 1
// */
// @Override
// public int compareTo(CVParticle other){
// return (int)(getSequenceNr() - other.getSequenceNr());
// }
//
//
// }
//
// Path: stormcv/src/main/java/nl/tno/stormcv/model/VideoChunk.java
// public class VideoChunk extends CVParticle {
//
// private long numberOfFrames;
// private byte[] video;
// private String container;
//
// public VideoChunk(String streamId, long sequenceNr, long nrOfFrames, byte[] videoBytes, String container) {
// super(streamId, sequenceNr);
// this.numberOfFrames = nrOfFrames;
// this.video = videoBytes;
// this.container = container;
// }
//
// public VideoChunk(Tuple tuple, long duration, byte[] videoBlob, String container){
// super(tuple);
// this.numberOfFrames = duration;
// this.video = videoBlob;
// this.container = container;
// }
//
// public long getDuration() {
// return numberOfFrames;
// }
//
// public byte[] getVideo() {
// return video;
// }
//
// public String getContainer() {
// return container;
// }
//
// }
| import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Values;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import nl.tno.stormcv.model.CVParticle;
import nl.tno.stormcv.model.VideoChunk; | package nl.tno.stormcv.model.serializer;
public class VideoChunkSerializer extends CVParticleSerializer<VideoChunk> implements Serializable{
private static final long serialVersionUID = 7864791957493203664L;
public static final String VIDEO = "video";
public static final String TIMESTAMP = "timeStamp";
public static final String CONTAINER = "container";
@Override
protected List<String> getTypeFields() {
List<String> fields = new ArrayList<String>();
fields.add(TIMESTAMP);
fields.add(VIDEO);
fields.add(CONTAINER);
return fields;
}
@Override | // Path: stormcv/src/main/java/nl/tno/stormcv/model/CVParticle.java
// public abstract class CVParticle implements Comparable<CVParticle>{
//
// private Tuple tuple;
// private long requestId = -1;
// private String streamId;
// private long sequenceNr;
// private HashMap<String, Object> metadata = new HashMap<String, Object>();
//
// /**
// * Constructs a generic type based on the provided tuple. The tuple must contain streamID and sequenceNR
// * values.
// * @param tuple
// */
// @SuppressWarnings("unchecked")
// public CVParticle(Tuple tuple){
// this(tuple.getStringByField(CVParticleSerializer.STREAMID),
// tuple.getLongByField(CVParticleSerializer.SEQUENCENR));
// this.tuple = tuple;
// this.setRequestId(tuple.getLongByField(CVParticleSerializer.REQUESTID));
// this.setMetadata((HashMap<String, Object>)tuple.getValueByField(CVParticleSerializer.METADATA));
// }
//
// /**
// * Constructs a GenericType object for some piece of information regarding a stream
// * @param streamId the id of the stream
// * @param sequenceNr the sequence number of the the information (used for ordering)
// */
// public CVParticle(String streamId, long sequenceNr){
// this.streamId = streamId;
// this.sequenceNr = sequenceNr;
// }
//
// public String getStreamId(){
// return streamId;
// }
//
// public long getSequenceNr(){
// return sequenceNr;
// }
//
// public Tuple getTuple() {
// return tuple;
// }
//
// public HashMap<String, Object> getMetadata() {
// return metadata;
// }
//
// public void setMetadata(HashMap<String, Object> metadata) {
// if(metadata != null){
// this.metadata = metadata;
// }
// }
//
// public void setRequestId(long id){
// this.requestId = id;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// /**
// * Compares one generictype to another based on their sequence number.
// * @return -1 if this.sequenceNr < other.sequenceNr, 0 if this.sequenceNr == other.sequenceNr else 1
// */
// @Override
// public int compareTo(CVParticle other){
// return (int)(getSequenceNr() - other.getSequenceNr());
// }
//
//
// }
//
// Path: stormcv/src/main/java/nl/tno/stormcv/model/VideoChunk.java
// public class VideoChunk extends CVParticle {
//
// private long numberOfFrames;
// private byte[] video;
// private String container;
//
// public VideoChunk(String streamId, long sequenceNr, long nrOfFrames, byte[] videoBytes, String container) {
// super(streamId, sequenceNr);
// this.numberOfFrames = nrOfFrames;
// this.video = videoBytes;
// this.container = container;
// }
//
// public VideoChunk(Tuple tuple, long duration, byte[] videoBlob, String container){
// super(tuple);
// this.numberOfFrames = duration;
// this.video = videoBlob;
// this.container = container;
// }
//
// public long getDuration() {
// return numberOfFrames;
// }
//
// public byte[] getVideo() {
// return video;
// }
//
// public String getContainer() {
// return container;
// }
//
// }
// Path: stormcv/src/main/java/nl/tno/stormcv/model/serializer/VideoChunkSerializer.java
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Values;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import nl.tno.stormcv.model.CVParticle;
import nl.tno.stormcv.model.VideoChunk;
package nl.tno.stormcv.model.serializer;
public class VideoChunkSerializer extends CVParticleSerializer<VideoChunk> implements Serializable{
private static final long serialVersionUID = 7864791957493203664L;
public static final String VIDEO = "video";
public static final String TIMESTAMP = "timeStamp";
public static final String CONTAINER = "container";
@Override
protected List<String> getTypeFields() {
List<String> fields = new ArrayList<String>();
fields.add(TIMESTAMP);
fields.add(VIDEO);
fields.add(CONTAINER);
return fields;
}
@Override | protected Values getValues(CVParticle object) throws IOException { |
sensorstorm/StormCV | stormcv/src/main/java/nl/tno/stormcv/drpc/IResultOp.java | // Path: stormcv/src/main/java/nl/tno/stormcv/model/CVParticle.java
// public abstract class CVParticle implements Comparable<CVParticle>{
//
// private Tuple tuple;
// private long requestId = -1;
// private String streamId;
// private long sequenceNr;
// private HashMap<String, Object> metadata = new HashMap<String, Object>();
//
// /**
// * Constructs a generic type based on the provided tuple. The tuple must contain streamID and sequenceNR
// * values.
// * @param tuple
// */
// @SuppressWarnings("unchecked")
// public CVParticle(Tuple tuple){
// this(tuple.getStringByField(CVParticleSerializer.STREAMID),
// tuple.getLongByField(CVParticleSerializer.SEQUENCENR));
// this.tuple = tuple;
// this.setRequestId(tuple.getLongByField(CVParticleSerializer.REQUESTID));
// this.setMetadata((HashMap<String, Object>)tuple.getValueByField(CVParticleSerializer.METADATA));
// }
//
// /**
// * Constructs a GenericType object for some piece of information regarding a stream
// * @param streamId the id of the stream
// * @param sequenceNr the sequence number of the the information (used for ordering)
// */
// public CVParticle(String streamId, long sequenceNr){
// this.streamId = streamId;
// this.sequenceNr = sequenceNr;
// }
//
// public String getStreamId(){
// return streamId;
// }
//
// public long getSequenceNr(){
// return sequenceNr;
// }
//
// public Tuple getTuple() {
// return tuple;
// }
//
// public HashMap<String, Object> getMetadata() {
// return metadata;
// }
//
// public void setMetadata(HashMap<String, Object> metadata) {
// if(metadata != null){
// this.metadata = metadata;
// }
// }
//
// public void setRequestId(long id){
// this.requestId = id;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// /**
// * Compares one generictype to another based on their sequence number.
// * @return -1 if this.sequenceNr < other.sequenceNr, 0 if this.sequenceNr == other.sequenceNr else 1
// */
// @Override
// public int compareTo(CVParticle other){
// return (int)(getSequenceNr() - other.getSequenceNr());
// }
//
//
// }
| import java.io.Serializable;
import java.util.Map;
import backtype.storm.task.TopologyContext;
import nl.tno.stormcv.model.CVParticle; | package nl.tno.stormcv.drpc;
public interface IResultOp extends Serializable{
/**
* Called each time a new request has to be answered
* @param stormConf
* @param context
* @throws Exception
*/
@SuppressWarnings("rawtypes")
public void initBatch(Map stormConf, TopologyContext context) throws Exception;
/**
* Called every time there is data to be added to the current result
* @param particle
* @throws Exception
*/ | // Path: stormcv/src/main/java/nl/tno/stormcv/model/CVParticle.java
// public abstract class CVParticle implements Comparable<CVParticle>{
//
// private Tuple tuple;
// private long requestId = -1;
// private String streamId;
// private long sequenceNr;
// private HashMap<String, Object> metadata = new HashMap<String, Object>();
//
// /**
// * Constructs a generic type based on the provided tuple. The tuple must contain streamID and sequenceNR
// * values.
// * @param tuple
// */
// @SuppressWarnings("unchecked")
// public CVParticle(Tuple tuple){
// this(tuple.getStringByField(CVParticleSerializer.STREAMID),
// tuple.getLongByField(CVParticleSerializer.SEQUENCENR));
// this.tuple = tuple;
// this.setRequestId(tuple.getLongByField(CVParticleSerializer.REQUESTID));
// this.setMetadata((HashMap<String, Object>)tuple.getValueByField(CVParticleSerializer.METADATA));
// }
//
// /**
// * Constructs a GenericType object for some piece of information regarding a stream
// * @param streamId the id of the stream
// * @param sequenceNr the sequence number of the the information (used for ordering)
// */
// public CVParticle(String streamId, long sequenceNr){
// this.streamId = streamId;
// this.sequenceNr = sequenceNr;
// }
//
// public String getStreamId(){
// return streamId;
// }
//
// public long getSequenceNr(){
// return sequenceNr;
// }
//
// public Tuple getTuple() {
// return tuple;
// }
//
// public HashMap<String, Object> getMetadata() {
// return metadata;
// }
//
// public void setMetadata(HashMap<String, Object> metadata) {
// if(metadata != null){
// this.metadata = metadata;
// }
// }
//
// public void setRequestId(long id){
// this.requestId = id;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// /**
// * Compares one generictype to another based on their sequence number.
// * @return -1 if this.sequenceNr < other.sequenceNr, 0 if this.sequenceNr == other.sequenceNr else 1
// */
// @Override
// public int compareTo(CVParticle other){
// return (int)(getSequenceNr() - other.getSequenceNr());
// }
//
//
// }
// Path: stormcv/src/main/java/nl/tno/stormcv/drpc/IResultOp.java
import java.io.Serializable;
import java.util.Map;
import backtype.storm.task.TopologyContext;
import nl.tno.stormcv.model.CVParticle;
package nl.tno.stormcv.drpc;
public interface IResultOp extends Serializable{
/**
* Called each time a new request has to be answered
* @param stormConf
* @param context
* @throws Exception
*/
@SuppressWarnings("rawtypes")
public void initBatch(Map stormConf, TopologyContext context) throws Exception;
/**
* Called every time there is data to be added to the current result
* @param particle
* @throws Exception
*/ | public void processData(CVParticle particle) throws Exception; |
sensorstorm/StormCV | stormcv/src/main/java/nl/tno/stormcv/bolt/SingleInputBolt.java | // Path: stormcv/src/main/java/nl/tno/stormcv/model/CVParticle.java
// public abstract class CVParticle implements Comparable<CVParticle>{
//
// private Tuple tuple;
// private long requestId = -1;
// private String streamId;
// private long sequenceNr;
// private HashMap<String, Object> metadata = new HashMap<String, Object>();
//
// /**
// * Constructs a generic type based on the provided tuple. The tuple must contain streamID and sequenceNR
// * values.
// * @param tuple
// */
// @SuppressWarnings("unchecked")
// public CVParticle(Tuple tuple){
// this(tuple.getStringByField(CVParticleSerializer.STREAMID),
// tuple.getLongByField(CVParticleSerializer.SEQUENCENR));
// this.tuple = tuple;
// this.setRequestId(tuple.getLongByField(CVParticleSerializer.REQUESTID));
// this.setMetadata((HashMap<String, Object>)tuple.getValueByField(CVParticleSerializer.METADATA));
// }
//
// /**
// * Constructs a GenericType object for some piece of information regarding a stream
// * @param streamId the id of the stream
// * @param sequenceNr the sequence number of the the information (used for ordering)
// */
// public CVParticle(String streamId, long sequenceNr){
// this.streamId = streamId;
// this.sequenceNr = sequenceNr;
// }
//
// public String getStreamId(){
// return streamId;
// }
//
// public long getSequenceNr(){
// return sequenceNr;
// }
//
// public Tuple getTuple() {
// return tuple;
// }
//
// public HashMap<String, Object> getMetadata() {
// return metadata;
// }
//
// public void setMetadata(HashMap<String, Object> metadata) {
// if(metadata != null){
// this.metadata = metadata;
// }
// }
//
// public void setRequestId(long id){
// this.requestId = id;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// /**
// * Compares one generictype to another based on their sequence number.
// * @return -1 if this.sequenceNr < other.sequenceNr, 0 if this.sequenceNr == other.sequenceNr else 1
// */
// @Override
// public int compareTo(CVParticle other){
// return (int)(getSequenceNr() - other.getSequenceNr());
// }
//
//
// }
//
// Path: stormcv/src/main/java/nl/tno/stormcv/operation/ISingleInputOperation.java
// public interface ISingleInputOperation <Output extends CVParticle> extends IOperation<Output>{
//
// public List<Output> execute(CVParticle particle) throws Exception;
//
// }
| import java.util.List;
import java.util.Map;
import nl.tno.stormcv.model.CVParticle;
import nl.tno.stormcv.operation.ISingleInputOperation;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer; | package nl.tno.stormcv.bolt;
/**
* A basic {@link CVParticleBolt} implementation that works with single items received (hence maintains no
* history of items received). The bolt will ask the provided {@link ISingleInputOperation} implementation to
* work on the input it received and produce zero or more results which will be emitted by the bolt.
* If an operation throws an exception the input will be failed in all other situations the input will be acked.
*
* @author Corne Versloot
*
*/
public class SingleInputBolt extends CVParticleBolt {
private static final long serialVersionUID = 8954087163234223475L;
| // Path: stormcv/src/main/java/nl/tno/stormcv/model/CVParticle.java
// public abstract class CVParticle implements Comparable<CVParticle>{
//
// private Tuple tuple;
// private long requestId = -1;
// private String streamId;
// private long sequenceNr;
// private HashMap<String, Object> metadata = new HashMap<String, Object>();
//
// /**
// * Constructs a generic type based on the provided tuple. The tuple must contain streamID and sequenceNR
// * values.
// * @param tuple
// */
// @SuppressWarnings("unchecked")
// public CVParticle(Tuple tuple){
// this(tuple.getStringByField(CVParticleSerializer.STREAMID),
// tuple.getLongByField(CVParticleSerializer.SEQUENCENR));
// this.tuple = tuple;
// this.setRequestId(tuple.getLongByField(CVParticleSerializer.REQUESTID));
// this.setMetadata((HashMap<String, Object>)tuple.getValueByField(CVParticleSerializer.METADATA));
// }
//
// /**
// * Constructs a GenericType object for some piece of information regarding a stream
// * @param streamId the id of the stream
// * @param sequenceNr the sequence number of the the information (used for ordering)
// */
// public CVParticle(String streamId, long sequenceNr){
// this.streamId = streamId;
// this.sequenceNr = sequenceNr;
// }
//
// public String getStreamId(){
// return streamId;
// }
//
// public long getSequenceNr(){
// return sequenceNr;
// }
//
// public Tuple getTuple() {
// return tuple;
// }
//
// public HashMap<String, Object> getMetadata() {
// return metadata;
// }
//
// public void setMetadata(HashMap<String, Object> metadata) {
// if(metadata != null){
// this.metadata = metadata;
// }
// }
//
// public void setRequestId(long id){
// this.requestId = id;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// /**
// * Compares one generictype to another based on their sequence number.
// * @return -1 if this.sequenceNr < other.sequenceNr, 0 if this.sequenceNr == other.sequenceNr else 1
// */
// @Override
// public int compareTo(CVParticle other){
// return (int)(getSequenceNr() - other.getSequenceNr());
// }
//
//
// }
//
// Path: stormcv/src/main/java/nl/tno/stormcv/operation/ISingleInputOperation.java
// public interface ISingleInputOperation <Output extends CVParticle> extends IOperation<Output>{
//
// public List<Output> execute(CVParticle particle) throws Exception;
//
// }
// Path: stormcv/src/main/java/nl/tno/stormcv/bolt/SingleInputBolt.java
import java.util.List;
import java.util.Map;
import nl.tno.stormcv.model.CVParticle;
import nl.tno.stormcv.operation.ISingleInputOperation;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
package nl.tno.stormcv.bolt;
/**
* A basic {@link CVParticleBolt} implementation that works with single items received (hence maintains no
* history of items received). The bolt will ask the provided {@link ISingleInputOperation} implementation to
* work on the input it received and produce zero or more results which will be emitted by the bolt.
* If an operation throws an exception the input will be failed in all other situations the input will be acked.
*
* @author Corne Versloot
*
*/
public class SingleInputBolt extends CVParticleBolt {
private static final long serialVersionUID = 8954087163234223475L;
| private ISingleInputOperation<? extends CVParticle> operation; |
sensorstorm/StormCV | stormcv/src/main/java/nl/tno/stormcv/bolt/SingleInputBolt.java | // Path: stormcv/src/main/java/nl/tno/stormcv/model/CVParticle.java
// public abstract class CVParticle implements Comparable<CVParticle>{
//
// private Tuple tuple;
// private long requestId = -1;
// private String streamId;
// private long sequenceNr;
// private HashMap<String, Object> metadata = new HashMap<String, Object>();
//
// /**
// * Constructs a generic type based on the provided tuple. The tuple must contain streamID and sequenceNR
// * values.
// * @param tuple
// */
// @SuppressWarnings("unchecked")
// public CVParticle(Tuple tuple){
// this(tuple.getStringByField(CVParticleSerializer.STREAMID),
// tuple.getLongByField(CVParticleSerializer.SEQUENCENR));
// this.tuple = tuple;
// this.setRequestId(tuple.getLongByField(CVParticleSerializer.REQUESTID));
// this.setMetadata((HashMap<String, Object>)tuple.getValueByField(CVParticleSerializer.METADATA));
// }
//
// /**
// * Constructs a GenericType object for some piece of information regarding a stream
// * @param streamId the id of the stream
// * @param sequenceNr the sequence number of the the information (used for ordering)
// */
// public CVParticle(String streamId, long sequenceNr){
// this.streamId = streamId;
// this.sequenceNr = sequenceNr;
// }
//
// public String getStreamId(){
// return streamId;
// }
//
// public long getSequenceNr(){
// return sequenceNr;
// }
//
// public Tuple getTuple() {
// return tuple;
// }
//
// public HashMap<String, Object> getMetadata() {
// return metadata;
// }
//
// public void setMetadata(HashMap<String, Object> metadata) {
// if(metadata != null){
// this.metadata = metadata;
// }
// }
//
// public void setRequestId(long id){
// this.requestId = id;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// /**
// * Compares one generictype to another based on their sequence number.
// * @return -1 if this.sequenceNr < other.sequenceNr, 0 if this.sequenceNr == other.sequenceNr else 1
// */
// @Override
// public int compareTo(CVParticle other){
// return (int)(getSequenceNr() - other.getSequenceNr());
// }
//
//
// }
//
// Path: stormcv/src/main/java/nl/tno/stormcv/operation/ISingleInputOperation.java
// public interface ISingleInputOperation <Output extends CVParticle> extends IOperation<Output>{
//
// public List<Output> execute(CVParticle particle) throws Exception;
//
// }
| import java.util.List;
import java.util.Map;
import nl.tno.stormcv.model.CVParticle;
import nl.tno.stormcv.operation.ISingleInputOperation;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer; | package nl.tno.stormcv.bolt;
/**
* A basic {@link CVParticleBolt} implementation that works with single items received (hence maintains no
* history of items received). The bolt will ask the provided {@link ISingleInputOperation} implementation to
* work on the input it received and produce zero or more results which will be emitted by the bolt.
* If an operation throws an exception the input will be failed in all other situations the input will be acked.
*
* @author Corne Versloot
*
*/
public class SingleInputBolt extends CVParticleBolt {
private static final long serialVersionUID = 8954087163234223475L;
| // Path: stormcv/src/main/java/nl/tno/stormcv/model/CVParticle.java
// public abstract class CVParticle implements Comparable<CVParticle>{
//
// private Tuple tuple;
// private long requestId = -1;
// private String streamId;
// private long sequenceNr;
// private HashMap<String, Object> metadata = new HashMap<String, Object>();
//
// /**
// * Constructs a generic type based on the provided tuple. The tuple must contain streamID and sequenceNR
// * values.
// * @param tuple
// */
// @SuppressWarnings("unchecked")
// public CVParticle(Tuple tuple){
// this(tuple.getStringByField(CVParticleSerializer.STREAMID),
// tuple.getLongByField(CVParticleSerializer.SEQUENCENR));
// this.tuple = tuple;
// this.setRequestId(tuple.getLongByField(CVParticleSerializer.REQUESTID));
// this.setMetadata((HashMap<String, Object>)tuple.getValueByField(CVParticleSerializer.METADATA));
// }
//
// /**
// * Constructs a GenericType object for some piece of information regarding a stream
// * @param streamId the id of the stream
// * @param sequenceNr the sequence number of the the information (used for ordering)
// */
// public CVParticle(String streamId, long sequenceNr){
// this.streamId = streamId;
// this.sequenceNr = sequenceNr;
// }
//
// public String getStreamId(){
// return streamId;
// }
//
// public long getSequenceNr(){
// return sequenceNr;
// }
//
// public Tuple getTuple() {
// return tuple;
// }
//
// public HashMap<String, Object> getMetadata() {
// return metadata;
// }
//
// public void setMetadata(HashMap<String, Object> metadata) {
// if(metadata != null){
// this.metadata = metadata;
// }
// }
//
// public void setRequestId(long id){
// this.requestId = id;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// /**
// * Compares one generictype to another based on their sequence number.
// * @return -1 if this.sequenceNr < other.sequenceNr, 0 if this.sequenceNr == other.sequenceNr else 1
// */
// @Override
// public int compareTo(CVParticle other){
// return (int)(getSequenceNr() - other.getSequenceNr());
// }
//
//
// }
//
// Path: stormcv/src/main/java/nl/tno/stormcv/operation/ISingleInputOperation.java
// public interface ISingleInputOperation <Output extends CVParticle> extends IOperation<Output>{
//
// public List<Output> execute(CVParticle particle) throws Exception;
//
// }
// Path: stormcv/src/main/java/nl/tno/stormcv/bolt/SingleInputBolt.java
import java.util.List;
import java.util.Map;
import nl.tno.stormcv.model.CVParticle;
import nl.tno.stormcv.operation.ISingleInputOperation;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
package nl.tno.stormcv.bolt;
/**
* A basic {@link CVParticleBolt} implementation that works with single items received (hence maintains no
* history of items received). The bolt will ask the provided {@link ISingleInputOperation} implementation to
* work on the input it received and produce zero or more results which will be emitted by the bolt.
* If an operation throws an exception the input will be failed in all other situations the input will be acked.
*
* @author Corne Versloot
*
*/
public class SingleInputBolt extends CVParticleBolt {
private static final long serialVersionUID = 8954087163234223475L;
| private ISingleInputOperation<? extends CVParticle> operation; |
sensorstorm/StormCV | stormcv/src/main/java/nl/tno/stormcv/drpc/BatchBolt.java | // Path: stormcv/src/main/java/nl/tno/stormcv/model/CVParticle.java
// public abstract class CVParticle implements Comparable<CVParticle>{
//
// private Tuple tuple;
// private long requestId = -1;
// private String streamId;
// private long sequenceNr;
// private HashMap<String, Object> metadata = new HashMap<String, Object>();
//
// /**
// * Constructs a generic type based on the provided tuple. The tuple must contain streamID and sequenceNR
// * values.
// * @param tuple
// */
// @SuppressWarnings("unchecked")
// public CVParticle(Tuple tuple){
// this(tuple.getStringByField(CVParticleSerializer.STREAMID),
// tuple.getLongByField(CVParticleSerializer.SEQUENCENR));
// this.tuple = tuple;
// this.setRequestId(tuple.getLongByField(CVParticleSerializer.REQUESTID));
// this.setMetadata((HashMap<String, Object>)tuple.getValueByField(CVParticleSerializer.METADATA));
// }
//
// /**
// * Constructs a GenericType object for some piece of information regarding a stream
// * @param streamId the id of the stream
// * @param sequenceNr the sequence number of the the information (used for ordering)
// */
// public CVParticle(String streamId, long sequenceNr){
// this.streamId = streamId;
// this.sequenceNr = sequenceNr;
// }
//
// public String getStreamId(){
// return streamId;
// }
//
// public long getSequenceNr(){
// return sequenceNr;
// }
//
// public Tuple getTuple() {
// return tuple;
// }
//
// public HashMap<String, Object> getMetadata() {
// return metadata;
// }
//
// public void setMetadata(HashMap<String, Object> metadata) {
// if(metadata != null){
// this.metadata = metadata;
// }
// }
//
// public void setRequestId(long id){
// this.requestId = id;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// /**
// * Compares one generictype to another based on their sequence number.
// * @return -1 if this.sequenceNr < other.sequenceNr, 0 if this.sequenceNr == other.sequenceNr else 1
// */
// @Override
// public int compareTo(CVParticle other){
// return (int)(getSequenceNr() - other.getSequenceNr());
// }
//
//
// }
| import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import clojure.lang.PersistentArrayMap;
import nl.tno.stormcv.model.CVParticle;
import nl.tno.stormcv.model.serializer.CVParticleSerializer;
import backtype.storm.Config;
import backtype.storm.coordination.BatchOutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseBatchBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Values; | package nl.tno.stormcv.drpc;
public class BatchBolt extends BaseBatchBolt<Long>{
private static final long serialVersionUID = 1280873294403747903L;
private Logger logger = LoggerFactory.getLogger(getClass()); | // Path: stormcv/src/main/java/nl/tno/stormcv/model/CVParticle.java
// public abstract class CVParticle implements Comparable<CVParticle>{
//
// private Tuple tuple;
// private long requestId = -1;
// private String streamId;
// private long sequenceNr;
// private HashMap<String, Object> metadata = new HashMap<String, Object>();
//
// /**
// * Constructs a generic type based on the provided tuple. The tuple must contain streamID and sequenceNR
// * values.
// * @param tuple
// */
// @SuppressWarnings("unchecked")
// public CVParticle(Tuple tuple){
// this(tuple.getStringByField(CVParticleSerializer.STREAMID),
// tuple.getLongByField(CVParticleSerializer.SEQUENCENR));
// this.tuple = tuple;
// this.setRequestId(tuple.getLongByField(CVParticleSerializer.REQUESTID));
// this.setMetadata((HashMap<String, Object>)tuple.getValueByField(CVParticleSerializer.METADATA));
// }
//
// /**
// * Constructs a GenericType object for some piece of information regarding a stream
// * @param streamId the id of the stream
// * @param sequenceNr the sequence number of the the information (used for ordering)
// */
// public CVParticle(String streamId, long sequenceNr){
// this.streamId = streamId;
// this.sequenceNr = sequenceNr;
// }
//
// public String getStreamId(){
// return streamId;
// }
//
// public long getSequenceNr(){
// return sequenceNr;
// }
//
// public Tuple getTuple() {
// return tuple;
// }
//
// public HashMap<String, Object> getMetadata() {
// return metadata;
// }
//
// public void setMetadata(HashMap<String, Object> metadata) {
// if(metadata != null){
// this.metadata = metadata;
// }
// }
//
// public void setRequestId(long id){
// this.requestId = id;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// /**
// * Compares one generictype to another based on their sequence number.
// * @return -1 if this.sequenceNr < other.sequenceNr, 0 if this.sequenceNr == other.sequenceNr else 1
// */
// @Override
// public int compareTo(CVParticle other){
// return (int)(getSequenceNr() - other.getSequenceNr());
// }
//
//
// }
// Path: stormcv/src/main/java/nl/tno/stormcv/drpc/BatchBolt.java
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import clojure.lang.PersistentArrayMap;
import nl.tno.stormcv.model.CVParticle;
import nl.tno.stormcv.model.serializer.CVParticleSerializer;
import backtype.storm.Config;
import backtype.storm.coordination.BatchOutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseBatchBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Values;
package nl.tno.stormcv.drpc;
public class BatchBolt extends BaseBatchBolt<Long>{
private static final long serialVersionUID = 1280873294403747903L;
private Logger logger = LoggerFactory.getLogger(getClass()); | private IBatchOp<? extends CVParticle> batchOp; |
sensorstorm/StormCV | stormcv/src/main/java/nl/tno/stormcv/bolt/CVParticleBolt.java | // Path: stormcv/src/main/java/nl/tno/stormcv/model/CVParticle.java
// public abstract class CVParticle implements Comparable<CVParticle>{
//
// private Tuple tuple;
// private long requestId = -1;
// private String streamId;
// private long sequenceNr;
// private HashMap<String, Object> metadata = new HashMap<String, Object>();
//
// /**
// * Constructs a generic type based on the provided tuple. The tuple must contain streamID and sequenceNR
// * values.
// * @param tuple
// */
// @SuppressWarnings("unchecked")
// public CVParticle(Tuple tuple){
// this(tuple.getStringByField(CVParticleSerializer.STREAMID),
// tuple.getLongByField(CVParticleSerializer.SEQUENCENR));
// this.tuple = tuple;
// this.setRequestId(tuple.getLongByField(CVParticleSerializer.REQUESTID));
// this.setMetadata((HashMap<String, Object>)tuple.getValueByField(CVParticleSerializer.METADATA));
// }
//
// /**
// * Constructs a GenericType object for some piece of information regarding a stream
// * @param streamId the id of the stream
// * @param sequenceNr the sequence number of the the information (used for ordering)
// */
// public CVParticle(String streamId, long sequenceNr){
// this.streamId = streamId;
// this.sequenceNr = sequenceNr;
// }
//
// public String getStreamId(){
// return streamId;
// }
//
// public long getSequenceNr(){
// return sequenceNr;
// }
//
// public Tuple getTuple() {
// return tuple;
// }
//
// public HashMap<String, Object> getMetadata() {
// return metadata;
// }
//
// public void setMetadata(HashMap<String, Object> metadata) {
// if(metadata != null){
// this.metadata = metadata;
// }
// }
//
// public void setRequestId(long id){
// this.requestId = id;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// /**
// * Compares one generictype to another based on their sequence number.
// * @return -1 if this.sequenceNr < other.sequenceNr, 0 if this.sequenceNr == other.sequenceNr else 1
// */
// @Override
// public int compareTo(CVParticle other){
// return (int)(getSequenceNr() - other.getSequenceNr());
// }
//
//
// }
| import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import nl.tno.stormcv.model.CVParticle;
import nl.tno.stormcv.model.serializer.CVParticleSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import clojure.lang.PersistentArrayMap;
import backtype.storm.Config;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Tuple; | package nl.tno.stormcv.bolt;
/**
* StormCV's basic BaseRichBolt implementation that supports the use of {@link CVParticle} objects.
* This bolt supports fault tolerance if it is configured to do so and supports the serialization of model objects.
*
* @author Corne Versloot
*
*/
public abstract class CVParticleBolt extends BaseRichBolt{
private static final long serialVersionUID = -5421951488628303992L;
protected Logger logger = LoggerFactory.getLogger(CVParticleBolt.class); | // Path: stormcv/src/main/java/nl/tno/stormcv/model/CVParticle.java
// public abstract class CVParticle implements Comparable<CVParticle>{
//
// private Tuple tuple;
// private long requestId = -1;
// private String streamId;
// private long sequenceNr;
// private HashMap<String, Object> metadata = new HashMap<String, Object>();
//
// /**
// * Constructs a generic type based on the provided tuple. The tuple must contain streamID and sequenceNR
// * values.
// * @param tuple
// */
// @SuppressWarnings("unchecked")
// public CVParticle(Tuple tuple){
// this(tuple.getStringByField(CVParticleSerializer.STREAMID),
// tuple.getLongByField(CVParticleSerializer.SEQUENCENR));
// this.tuple = tuple;
// this.setRequestId(tuple.getLongByField(CVParticleSerializer.REQUESTID));
// this.setMetadata((HashMap<String, Object>)tuple.getValueByField(CVParticleSerializer.METADATA));
// }
//
// /**
// * Constructs a GenericType object for some piece of information regarding a stream
// * @param streamId the id of the stream
// * @param sequenceNr the sequence number of the the information (used for ordering)
// */
// public CVParticle(String streamId, long sequenceNr){
// this.streamId = streamId;
// this.sequenceNr = sequenceNr;
// }
//
// public String getStreamId(){
// return streamId;
// }
//
// public long getSequenceNr(){
// return sequenceNr;
// }
//
// public Tuple getTuple() {
// return tuple;
// }
//
// public HashMap<String, Object> getMetadata() {
// return metadata;
// }
//
// public void setMetadata(HashMap<String, Object> metadata) {
// if(metadata != null){
// this.metadata = metadata;
// }
// }
//
// public void setRequestId(long id){
// this.requestId = id;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// /**
// * Compares one generictype to another based on their sequence number.
// * @return -1 if this.sequenceNr < other.sequenceNr, 0 if this.sequenceNr == other.sequenceNr else 1
// */
// @Override
// public int compareTo(CVParticle other){
// return (int)(getSequenceNr() - other.getSequenceNr());
// }
//
//
// }
// Path: stormcv/src/main/java/nl/tno/stormcv/bolt/CVParticleBolt.java
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import nl.tno.stormcv.model.CVParticle;
import nl.tno.stormcv.model.serializer.CVParticleSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import clojure.lang.PersistentArrayMap;
import backtype.storm.Config;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Tuple;
package nl.tno.stormcv.bolt;
/**
* StormCV's basic BaseRichBolt implementation that supports the use of {@link CVParticle} objects.
* This bolt supports fault tolerance if it is configured to do so and supports the serialization of model objects.
*
* @author Corne Versloot
*
*/
public abstract class CVParticleBolt extends BaseRichBolt{
private static final long serialVersionUID = -5421951488628303992L;
protected Logger logger = LoggerFactory.getLogger(CVParticleBolt.class); | protected HashMap<String, CVParticleSerializer<? extends CVParticle>> serializers = new HashMap<String, CVParticleSerializer<? extends CVParticle>>(); |
sensorstorm/StormCV | stormcv/src/main/java/nl/tno/stormcv/model/Frame.java | // Path: stormcv/src/main/java/nl/tno/stormcv/util/ImageUtils.java
// public class ImageUtils {
//
// /**
// * Converts an image to byte buffer representing PNG (bytes as they would exist on disk)
// * @param image
// * @param encoding the encoding to be used, one of: png, jpeg, bmp, wbmp, gif
// * @return byte[] representing the image
// * @throws IOException if the bytes[] could not be written
// */
// public static byte[] imageToBytes(BufferedImage image, String encoding) throws IOException{
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// ImageIO.write(image, encoding, baos);
// return baos.toByteArray();
// }
//
// /**
// * Converts the provided byte buffer into an BufferedImage
// * @param buf byte[] of an image as it would exist on disk
// * @return
// * @throws IOException
// */
// public static BufferedImage bytesToImage(byte[] buf) throws IOException{
// ByteArrayInputStream bais = new ByteArrayInputStream(buf);
// return ImageIO.read(bais);
// }
//
// /**
// * Converts a given image into grayscalse
// * @param src
// * @return
// */
// public static BufferedImage convertToGray(BufferedImage src){
// ColorConvertOp grayOp = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
// return grayOp.filter(src,null);
// }
//
// /**
// * Creates a Mat object for the image in the provided frame
// * @param frame
// * @return Mat object representing the image of type Highgui.CV_LOAD_IMAGE_COLOR
// * @throws IOException if the image cannot be read or converted into binary format
// */
// public static Mat Frame2Mat(Frame frame) throws IOException{
// if(frame.getImage() == null) throw new IOException("Frame does not contain an image");
// return bytes2Mat(frame.getImageBytes());
// }
//
// /**
// * Creates a Mat object for the image in the provided frame
// * @param image the image to be converted to mat
// * @param imageType the encoding to use, see {@link Frame}
// * @return Mat object representing the image of type Highgui.CV_LOAD_IMAGE_COLOR
// * @throws IOException if the image cannot be read or converted into binary format
// */
// public static Mat Image2Mat(BufferedImage image, String imageType) throws IOException{
// MatOfByte mob = new MatOfByte( ImageUtils.imageToBytes(image, imageType) );
// return Highgui.imdecode(mob, Highgui.CV_LOAD_IMAGE_COLOR);
// }
//
// /**
// * creates a Mat object directly from a set of bytes
// * @param bytes binary representation of an image
// * @return Mat object of type Highgui.CV_LOAD_IMAGE_COLOR
// */
// public static Mat bytes2Mat(byte[] bytes){
// MatOfByte mob = new MatOfByte( bytes );
// return Highgui.imdecode(mob, Highgui.CV_LOAD_IMAGE_COLOR);
// }
//
// /**
// * Creates a byte representation of the provided mat object encoded using the imageType
// * @param mat
// * @param imageType
// * @return
// */
// public static byte[] Mat2ImageBytes(Mat mat, String imageType){
// MatOfByte buffer = new MatOfByte();
// Highgui.imencode("."+imageType, mat, buffer);
// return buffer.toArray();
// }
// }
| import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import nl.tno.stormcv.util.ImageUtils;
import backtype.storm.tuple.Tuple; | if(features != null) this.features = features;
}
public Frame(String streamId, long sequenceNr, String imageType, byte[] image, long timeStamp, Rectangle boundingBox ) {
super(streamId, sequenceNr);
this.imageType = imageType;
this.imageBytes = image;
this.timeStamp = timeStamp;
this.boundingBox = boundingBox;
}
public Frame(Tuple tuple, String imageType, byte[] image, long timeStamp, Rectangle box) {
super(tuple);
this.imageType = imageType;
this.imageBytes = image;
this.timeStamp = timeStamp;
this.boundingBox = box;
}
public Rectangle getBoundingBox() {
return boundingBox;
}
public BufferedImage getImage() throws IOException {
if(imageBytes == null) {
imageType = NO_IMAGE;
return null;
}
if(image == null){ | // Path: stormcv/src/main/java/nl/tno/stormcv/util/ImageUtils.java
// public class ImageUtils {
//
// /**
// * Converts an image to byte buffer representing PNG (bytes as they would exist on disk)
// * @param image
// * @param encoding the encoding to be used, one of: png, jpeg, bmp, wbmp, gif
// * @return byte[] representing the image
// * @throws IOException if the bytes[] could not be written
// */
// public static byte[] imageToBytes(BufferedImage image, String encoding) throws IOException{
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// ImageIO.write(image, encoding, baos);
// return baos.toByteArray();
// }
//
// /**
// * Converts the provided byte buffer into an BufferedImage
// * @param buf byte[] of an image as it would exist on disk
// * @return
// * @throws IOException
// */
// public static BufferedImage bytesToImage(byte[] buf) throws IOException{
// ByteArrayInputStream bais = new ByteArrayInputStream(buf);
// return ImageIO.read(bais);
// }
//
// /**
// * Converts a given image into grayscalse
// * @param src
// * @return
// */
// public static BufferedImage convertToGray(BufferedImage src){
// ColorConvertOp grayOp = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
// return grayOp.filter(src,null);
// }
//
// /**
// * Creates a Mat object for the image in the provided frame
// * @param frame
// * @return Mat object representing the image of type Highgui.CV_LOAD_IMAGE_COLOR
// * @throws IOException if the image cannot be read or converted into binary format
// */
// public static Mat Frame2Mat(Frame frame) throws IOException{
// if(frame.getImage() == null) throw new IOException("Frame does not contain an image");
// return bytes2Mat(frame.getImageBytes());
// }
//
// /**
// * Creates a Mat object for the image in the provided frame
// * @param image the image to be converted to mat
// * @param imageType the encoding to use, see {@link Frame}
// * @return Mat object representing the image of type Highgui.CV_LOAD_IMAGE_COLOR
// * @throws IOException if the image cannot be read or converted into binary format
// */
// public static Mat Image2Mat(BufferedImage image, String imageType) throws IOException{
// MatOfByte mob = new MatOfByte( ImageUtils.imageToBytes(image, imageType) );
// return Highgui.imdecode(mob, Highgui.CV_LOAD_IMAGE_COLOR);
// }
//
// /**
// * creates a Mat object directly from a set of bytes
// * @param bytes binary representation of an image
// * @return Mat object of type Highgui.CV_LOAD_IMAGE_COLOR
// */
// public static Mat bytes2Mat(byte[] bytes){
// MatOfByte mob = new MatOfByte( bytes );
// return Highgui.imdecode(mob, Highgui.CV_LOAD_IMAGE_COLOR);
// }
//
// /**
// * Creates a byte representation of the provided mat object encoded using the imageType
// * @param mat
// * @param imageType
// * @return
// */
// public static byte[] Mat2ImageBytes(Mat mat, String imageType){
// MatOfByte buffer = new MatOfByte();
// Highgui.imencode("."+imageType, mat, buffer);
// return buffer.toArray();
// }
// }
// Path: stormcv/src/main/java/nl/tno/stormcv/model/Frame.java
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import nl.tno.stormcv.util.ImageUtils;
import backtype.storm.tuple.Tuple;
if(features != null) this.features = features;
}
public Frame(String streamId, long sequenceNr, String imageType, byte[] image, long timeStamp, Rectangle boundingBox ) {
super(streamId, sequenceNr);
this.imageType = imageType;
this.imageBytes = image;
this.timeStamp = timeStamp;
this.boundingBox = boundingBox;
}
public Frame(Tuple tuple, String imageType, byte[] image, long timeStamp, Rectangle box) {
super(tuple);
this.imageType = imageType;
this.imageBytes = image;
this.timeStamp = timeStamp;
this.boundingBox = box;
}
public Rectangle getBoundingBox() {
return boundingBox;
}
public BufferedImage getImage() throws IOException {
if(imageBytes == null) {
imageType = NO_IMAGE;
return null;
}
if(image == null){ | image = ImageUtils.bytesToImage(imageBytes); |
sensorstorm/StormCV | stormcv/src/main/java/nl/tno/stormcv/fetcher/FetchAndOperateFetcher.java | // Path: stormcv/src/main/java/nl/tno/stormcv/model/CVParticle.java
// public abstract class CVParticle implements Comparable<CVParticle>{
//
// private Tuple tuple;
// private long requestId = -1;
// private String streamId;
// private long sequenceNr;
// private HashMap<String, Object> metadata = new HashMap<String, Object>();
//
// /**
// * Constructs a generic type based on the provided tuple. The tuple must contain streamID and sequenceNR
// * values.
// * @param tuple
// */
// @SuppressWarnings("unchecked")
// public CVParticle(Tuple tuple){
// this(tuple.getStringByField(CVParticleSerializer.STREAMID),
// tuple.getLongByField(CVParticleSerializer.SEQUENCENR));
// this.tuple = tuple;
// this.setRequestId(tuple.getLongByField(CVParticleSerializer.REQUESTID));
// this.setMetadata((HashMap<String, Object>)tuple.getValueByField(CVParticleSerializer.METADATA));
// }
//
// /**
// * Constructs a GenericType object for some piece of information regarding a stream
// * @param streamId the id of the stream
// * @param sequenceNr the sequence number of the the information (used for ordering)
// */
// public CVParticle(String streamId, long sequenceNr){
// this.streamId = streamId;
// this.sequenceNr = sequenceNr;
// }
//
// public String getStreamId(){
// return streamId;
// }
//
// public long getSequenceNr(){
// return sequenceNr;
// }
//
// public Tuple getTuple() {
// return tuple;
// }
//
// public HashMap<String, Object> getMetadata() {
// return metadata;
// }
//
// public void setMetadata(HashMap<String, Object> metadata) {
// if(metadata != null){
// this.metadata = metadata;
// }
// }
//
// public void setRequestId(long id){
// this.requestId = id;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// /**
// * Compares one generictype to another based on their sequence number.
// * @return -1 if this.sequenceNr < other.sequenceNr, 0 if this.sequenceNr == other.sequenceNr else 1
// */
// @Override
// public int compareTo(CVParticle other){
// return (int)(getSequenceNr() - other.getSequenceNr());
// }
//
//
// }
//
// Path: stormcv/src/main/java/nl/tno/stormcv/model/GroupOfFrames.java
// public class GroupOfFrames extends CVParticle{
//
// private List<Frame> frames;
//
// public GroupOfFrames(String streamId, long sequenceNr, List<Frame> frames) {
// super(streamId, sequenceNr);
// this.frames = frames;
// }
//
// public GroupOfFrames(Tuple tuple, List<Frame> list) {
// super(tuple);
// this.frames = list;
// }
//
// public List<Frame> getFrames(){
// return frames;
// }
//
// public int nrOfFrames(){
// return frames.size();
// }
//
// }
//
// Path: stormcv/src/main/java/nl/tno/stormcv/operation/IOperation.java
// public interface IOperation <Output extends CVParticle> extends Serializable{
//
// /**
// * Called when the topology is activated and can be used to configure itself and load
// * resources required
// * @param stormConf
// * @param context
// * @throws Exception
// */
// @SuppressWarnings("rawtypes")
// public void prepare(Map stormConf, TopologyContext context) throws Exception;
//
// /**
// * Called when the topology is halted and can be used to clean up resources used
// */
// public void deactivate();
//
// /**
// * Provides the {@link CVParticleSerializer} implementation to be used to serialize the output of the {@link IOperation}
// * @return
// */
// public CVParticleSerializer<Output> getSerializer();
//
// }
//
// Path: stormcv/src/main/java/nl/tno/stormcv/operation/ISingleInputOperation.java
// public interface ISingleInputOperation <Output extends CVParticle> extends IOperation<Output>{
//
// public List<Output> execute(CVParticle particle) throws Exception;
//
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import backtype.storm.task.TopologyContext;
import nl.tno.stormcv.model.CVParticle;
import nl.tno.stormcv.model.GroupOfFrames;
import nl.tno.stormcv.model.serializer.CVParticleSerializer;
import nl.tno.stormcv.operation.IBatchOperation;
import nl.tno.stormcv.operation.IOperation;
import nl.tno.stormcv.operation.SequentialFrameOp;
import nl.tno.stormcv.operation.ISingleInputOperation; | package nl.tno.stormcv.fetcher;
/**
* A meta {@link IFetcher} that enables the use of an Operation directly within the spout. Data fetched is directly executed by the
* configured operation. This avoids data transfer from Spout to Bolt but is only useful when the operation can keep up with the
* load provided by the fetcher. A typical setup will be some Fetcher emitting Frame objects and a {@link ISingleInputOperation}
* that processes the Frame. Hence it is also possible to use a {@link SequentialFrameOp}.
*
* It is possible to provide a {@link IBatchOperation} if the output of the Fetcher is set to emit {@link GroupOfFrames} using the
* groupOfFramesOutput(...) function some Fetchers have.
*
* @author Corne Versloot
*
*/
@SuppressWarnings("rawtypes")
public class FetchAndOperateFetcher implements IFetcher<CVParticle> {
private static final long serialVersionUID = -1900017732079975170L;
private Logger logger = LoggerFactory.getLogger(this.getClass());
private IFetcher fetcher;
private boolean sio = false; | // Path: stormcv/src/main/java/nl/tno/stormcv/model/CVParticle.java
// public abstract class CVParticle implements Comparable<CVParticle>{
//
// private Tuple tuple;
// private long requestId = -1;
// private String streamId;
// private long sequenceNr;
// private HashMap<String, Object> metadata = new HashMap<String, Object>();
//
// /**
// * Constructs a generic type based on the provided tuple. The tuple must contain streamID and sequenceNR
// * values.
// * @param tuple
// */
// @SuppressWarnings("unchecked")
// public CVParticle(Tuple tuple){
// this(tuple.getStringByField(CVParticleSerializer.STREAMID),
// tuple.getLongByField(CVParticleSerializer.SEQUENCENR));
// this.tuple = tuple;
// this.setRequestId(tuple.getLongByField(CVParticleSerializer.REQUESTID));
// this.setMetadata((HashMap<String, Object>)tuple.getValueByField(CVParticleSerializer.METADATA));
// }
//
// /**
// * Constructs a GenericType object for some piece of information regarding a stream
// * @param streamId the id of the stream
// * @param sequenceNr the sequence number of the the information (used for ordering)
// */
// public CVParticle(String streamId, long sequenceNr){
// this.streamId = streamId;
// this.sequenceNr = sequenceNr;
// }
//
// public String getStreamId(){
// return streamId;
// }
//
// public long getSequenceNr(){
// return sequenceNr;
// }
//
// public Tuple getTuple() {
// return tuple;
// }
//
// public HashMap<String, Object> getMetadata() {
// return metadata;
// }
//
// public void setMetadata(HashMap<String, Object> metadata) {
// if(metadata != null){
// this.metadata = metadata;
// }
// }
//
// public void setRequestId(long id){
// this.requestId = id;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// /**
// * Compares one generictype to another based on their sequence number.
// * @return -1 if this.sequenceNr < other.sequenceNr, 0 if this.sequenceNr == other.sequenceNr else 1
// */
// @Override
// public int compareTo(CVParticle other){
// return (int)(getSequenceNr() - other.getSequenceNr());
// }
//
//
// }
//
// Path: stormcv/src/main/java/nl/tno/stormcv/model/GroupOfFrames.java
// public class GroupOfFrames extends CVParticle{
//
// private List<Frame> frames;
//
// public GroupOfFrames(String streamId, long sequenceNr, List<Frame> frames) {
// super(streamId, sequenceNr);
// this.frames = frames;
// }
//
// public GroupOfFrames(Tuple tuple, List<Frame> list) {
// super(tuple);
// this.frames = list;
// }
//
// public List<Frame> getFrames(){
// return frames;
// }
//
// public int nrOfFrames(){
// return frames.size();
// }
//
// }
//
// Path: stormcv/src/main/java/nl/tno/stormcv/operation/IOperation.java
// public interface IOperation <Output extends CVParticle> extends Serializable{
//
// /**
// * Called when the topology is activated and can be used to configure itself and load
// * resources required
// * @param stormConf
// * @param context
// * @throws Exception
// */
// @SuppressWarnings("rawtypes")
// public void prepare(Map stormConf, TopologyContext context) throws Exception;
//
// /**
// * Called when the topology is halted and can be used to clean up resources used
// */
// public void deactivate();
//
// /**
// * Provides the {@link CVParticleSerializer} implementation to be used to serialize the output of the {@link IOperation}
// * @return
// */
// public CVParticleSerializer<Output> getSerializer();
//
// }
//
// Path: stormcv/src/main/java/nl/tno/stormcv/operation/ISingleInputOperation.java
// public interface ISingleInputOperation <Output extends CVParticle> extends IOperation<Output>{
//
// public List<Output> execute(CVParticle particle) throws Exception;
//
// }
// Path: stormcv/src/main/java/nl/tno/stormcv/fetcher/FetchAndOperateFetcher.java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import backtype.storm.task.TopologyContext;
import nl.tno.stormcv.model.CVParticle;
import nl.tno.stormcv.model.GroupOfFrames;
import nl.tno.stormcv.model.serializer.CVParticleSerializer;
import nl.tno.stormcv.operation.IBatchOperation;
import nl.tno.stormcv.operation.IOperation;
import nl.tno.stormcv.operation.SequentialFrameOp;
import nl.tno.stormcv.operation.ISingleInputOperation;
package nl.tno.stormcv.fetcher;
/**
* A meta {@link IFetcher} that enables the use of an Operation directly within the spout. Data fetched is directly executed by the
* configured operation. This avoids data transfer from Spout to Bolt but is only useful when the operation can keep up with the
* load provided by the fetcher. A typical setup will be some Fetcher emitting Frame objects and a {@link ISingleInputOperation}
* that processes the Frame. Hence it is also possible to use a {@link SequentialFrameOp}.
*
* It is possible to provide a {@link IBatchOperation} if the output of the Fetcher is set to emit {@link GroupOfFrames} using the
* groupOfFramesOutput(...) function some Fetchers have.
*
* @author Corne Versloot
*
*/
@SuppressWarnings("rawtypes")
public class FetchAndOperateFetcher implements IFetcher<CVParticle> {
private static final long serialVersionUID = -1900017732079975170L;
private Logger logger = LoggerFactory.getLogger(this.getClass());
private IFetcher fetcher;
private boolean sio = false; | private ISingleInputOperation singleInOp; |
sensorstorm/StormCV | stormcv/src/main/java/nl/tno/stormcv/fetcher/FetchAndOperateFetcher.java | // Path: stormcv/src/main/java/nl/tno/stormcv/model/CVParticle.java
// public abstract class CVParticle implements Comparable<CVParticle>{
//
// private Tuple tuple;
// private long requestId = -1;
// private String streamId;
// private long sequenceNr;
// private HashMap<String, Object> metadata = new HashMap<String, Object>();
//
// /**
// * Constructs a generic type based on the provided tuple. The tuple must contain streamID and sequenceNR
// * values.
// * @param tuple
// */
// @SuppressWarnings("unchecked")
// public CVParticle(Tuple tuple){
// this(tuple.getStringByField(CVParticleSerializer.STREAMID),
// tuple.getLongByField(CVParticleSerializer.SEQUENCENR));
// this.tuple = tuple;
// this.setRequestId(tuple.getLongByField(CVParticleSerializer.REQUESTID));
// this.setMetadata((HashMap<String, Object>)tuple.getValueByField(CVParticleSerializer.METADATA));
// }
//
// /**
// * Constructs a GenericType object for some piece of information regarding a stream
// * @param streamId the id of the stream
// * @param sequenceNr the sequence number of the the information (used for ordering)
// */
// public CVParticle(String streamId, long sequenceNr){
// this.streamId = streamId;
// this.sequenceNr = sequenceNr;
// }
//
// public String getStreamId(){
// return streamId;
// }
//
// public long getSequenceNr(){
// return sequenceNr;
// }
//
// public Tuple getTuple() {
// return tuple;
// }
//
// public HashMap<String, Object> getMetadata() {
// return metadata;
// }
//
// public void setMetadata(HashMap<String, Object> metadata) {
// if(metadata != null){
// this.metadata = metadata;
// }
// }
//
// public void setRequestId(long id){
// this.requestId = id;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// /**
// * Compares one generictype to another based on their sequence number.
// * @return -1 if this.sequenceNr < other.sequenceNr, 0 if this.sequenceNr == other.sequenceNr else 1
// */
// @Override
// public int compareTo(CVParticle other){
// return (int)(getSequenceNr() - other.getSequenceNr());
// }
//
//
// }
//
// Path: stormcv/src/main/java/nl/tno/stormcv/model/GroupOfFrames.java
// public class GroupOfFrames extends CVParticle{
//
// private List<Frame> frames;
//
// public GroupOfFrames(String streamId, long sequenceNr, List<Frame> frames) {
// super(streamId, sequenceNr);
// this.frames = frames;
// }
//
// public GroupOfFrames(Tuple tuple, List<Frame> list) {
// super(tuple);
// this.frames = list;
// }
//
// public List<Frame> getFrames(){
// return frames;
// }
//
// public int nrOfFrames(){
// return frames.size();
// }
//
// }
//
// Path: stormcv/src/main/java/nl/tno/stormcv/operation/IOperation.java
// public interface IOperation <Output extends CVParticle> extends Serializable{
//
// /**
// * Called when the topology is activated and can be used to configure itself and load
// * resources required
// * @param stormConf
// * @param context
// * @throws Exception
// */
// @SuppressWarnings("rawtypes")
// public void prepare(Map stormConf, TopologyContext context) throws Exception;
//
// /**
// * Called when the topology is halted and can be used to clean up resources used
// */
// public void deactivate();
//
// /**
// * Provides the {@link CVParticleSerializer} implementation to be used to serialize the output of the {@link IOperation}
// * @return
// */
// public CVParticleSerializer<Output> getSerializer();
//
// }
//
// Path: stormcv/src/main/java/nl/tno/stormcv/operation/ISingleInputOperation.java
// public interface ISingleInputOperation <Output extends CVParticle> extends IOperation<Output>{
//
// public List<Output> execute(CVParticle particle) throws Exception;
//
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import backtype.storm.task.TopologyContext;
import nl.tno.stormcv.model.CVParticle;
import nl.tno.stormcv.model.GroupOfFrames;
import nl.tno.stormcv.model.serializer.CVParticleSerializer;
import nl.tno.stormcv.operation.IBatchOperation;
import nl.tno.stormcv.operation.IOperation;
import nl.tno.stormcv.operation.SequentialFrameOp;
import nl.tno.stormcv.operation.ISingleInputOperation; | }
@SuppressWarnings("unchecked")
@Override
public CVParticleSerializer<CVParticle> getSerializer() {
if(sio) return singleInOp.getSerializer();
return batchOp.getSerializer();
}
@Override
public void activate() {
fetcher.activate();
}
@Override
public void deactivate() {
fetcher.deactivate();
}
@Override
@SuppressWarnings("unchecked")
public CVParticle fetchData() {
// first empty the current list with particles before fetching new data
if(results.size() > 0) return results.remove(0);
// fetch data from particle
CVParticle particle = fetcher.fetchData();
if(particle == null) return null;
try{
if(sio) results = singleInOp.execute(particle); | // Path: stormcv/src/main/java/nl/tno/stormcv/model/CVParticle.java
// public abstract class CVParticle implements Comparable<CVParticle>{
//
// private Tuple tuple;
// private long requestId = -1;
// private String streamId;
// private long sequenceNr;
// private HashMap<String, Object> metadata = new HashMap<String, Object>();
//
// /**
// * Constructs a generic type based on the provided tuple. The tuple must contain streamID and sequenceNR
// * values.
// * @param tuple
// */
// @SuppressWarnings("unchecked")
// public CVParticle(Tuple tuple){
// this(tuple.getStringByField(CVParticleSerializer.STREAMID),
// tuple.getLongByField(CVParticleSerializer.SEQUENCENR));
// this.tuple = tuple;
// this.setRequestId(tuple.getLongByField(CVParticleSerializer.REQUESTID));
// this.setMetadata((HashMap<String, Object>)tuple.getValueByField(CVParticleSerializer.METADATA));
// }
//
// /**
// * Constructs a GenericType object for some piece of information regarding a stream
// * @param streamId the id of the stream
// * @param sequenceNr the sequence number of the the information (used for ordering)
// */
// public CVParticle(String streamId, long sequenceNr){
// this.streamId = streamId;
// this.sequenceNr = sequenceNr;
// }
//
// public String getStreamId(){
// return streamId;
// }
//
// public long getSequenceNr(){
// return sequenceNr;
// }
//
// public Tuple getTuple() {
// return tuple;
// }
//
// public HashMap<String, Object> getMetadata() {
// return metadata;
// }
//
// public void setMetadata(HashMap<String, Object> metadata) {
// if(metadata != null){
// this.metadata = metadata;
// }
// }
//
// public void setRequestId(long id){
// this.requestId = id;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// /**
// * Compares one generictype to another based on their sequence number.
// * @return -1 if this.sequenceNr < other.sequenceNr, 0 if this.sequenceNr == other.sequenceNr else 1
// */
// @Override
// public int compareTo(CVParticle other){
// return (int)(getSequenceNr() - other.getSequenceNr());
// }
//
//
// }
//
// Path: stormcv/src/main/java/nl/tno/stormcv/model/GroupOfFrames.java
// public class GroupOfFrames extends CVParticle{
//
// private List<Frame> frames;
//
// public GroupOfFrames(String streamId, long sequenceNr, List<Frame> frames) {
// super(streamId, sequenceNr);
// this.frames = frames;
// }
//
// public GroupOfFrames(Tuple tuple, List<Frame> list) {
// super(tuple);
// this.frames = list;
// }
//
// public List<Frame> getFrames(){
// return frames;
// }
//
// public int nrOfFrames(){
// return frames.size();
// }
//
// }
//
// Path: stormcv/src/main/java/nl/tno/stormcv/operation/IOperation.java
// public interface IOperation <Output extends CVParticle> extends Serializable{
//
// /**
// * Called when the topology is activated and can be used to configure itself and load
// * resources required
// * @param stormConf
// * @param context
// * @throws Exception
// */
// @SuppressWarnings("rawtypes")
// public void prepare(Map stormConf, TopologyContext context) throws Exception;
//
// /**
// * Called when the topology is halted and can be used to clean up resources used
// */
// public void deactivate();
//
// /**
// * Provides the {@link CVParticleSerializer} implementation to be used to serialize the output of the {@link IOperation}
// * @return
// */
// public CVParticleSerializer<Output> getSerializer();
//
// }
//
// Path: stormcv/src/main/java/nl/tno/stormcv/operation/ISingleInputOperation.java
// public interface ISingleInputOperation <Output extends CVParticle> extends IOperation<Output>{
//
// public List<Output> execute(CVParticle particle) throws Exception;
//
// }
// Path: stormcv/src/main/java/nl/tno/stormcv/fetcher/FetchAndOperateFetcher.java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import backtype.storm.task.TopologyContext;
import nl.tno.stormcv.model.CVParticle;
import nl.tno.stormcv.model.GroupOfFrames;
import nl.tno.stormcv.model.serializer.CVParticleSerializer;
import nl.tno.stormcv.operation.IBatchOperation;
import nl.tno.stormcv.operation.IOperation;
import nl.tno.stormcv.operation.SequentialFrameOp;
import nl.tno.stormcv.operation.ISingleInputOperation;
}
@SuppressWarnings("unchecked")
@Override
public CVParticleSerializer<CVParticle> getSerializer() {
if(sio) return singleInOp.getSerializer();
return batchOp.getSerializer();
}
@Override
public void activate() {
fetcher.activate();
}
@Override
public void deactivate() {
fetcher.deactivate();
}
@Override
@SuppressWarnings("unchecked")
public CVParticle fetchData() {
// first empty the current list with particles before fetching new data
if(results.size() > 0) return results.remove(0);
// fetch data from particle
CVParticle particle = fetcher.fetchData();
if(particle == null) return null;
try{
if(sio) results = singleInOp.execute(particle); | else if (!sio && particle instanceof GroupOfFrames){ |
sensorstorm/StormCV | stormcv/src/main/java/nl/tno/stormcv/operation/DrawFeaturesOp.java | // Path: stormcv/src/main/java/nl/tno/stormcv/util/connector/ConnectorHolder.java
// public class ConnectorHolder {
//
// private HashMap<String, FileConnector> connectors;
// Logger logger = LoggerFactory.getLogger(ConnectorHolder.class);
//
// /**
// * Uses the provided stormConf to instantiate and configure registered {@link FileConnector}'s
// * using {@link StormCVConfig}.STORMCV_CONNECTORS
// * @param stormConf
// */
// @SuppressWarnings({ "rawtypes", "unchecked" })
// public ConnectorHolder(Map stormConf){
// connectors = new HashMap<String, FileConnector>();
// List<String> registered = (List<String>)stormConf.get(StormCVConfig.STORMCV_CONNECTORS);
// for(String name : registered) try{
// FileConnector connector = (FileConnector)Class.forName(name).newInstance();
// connector.prepare(stormConf);
// connectors.put(connector.getProtocol(), connector);
// }catch(Exception e){
// logger.warn("Unable to instantiate FileConnector: "+name+" due to: "+e.getMessage());
// }
// }
//
// public FileConnector getConnector(String location){
// try {
// return connectors.get(new URI(location).getScheme());
// } catch (URISyntaxException e) {
// logger.warn(location+" does hot have valid URI syntax: "+e.getMessage());
// }
// return null;
// }
//
// }
//
// Path: stormcv/src/main/java/nl/tno/stormcv/util/connector/FileConnector.java
// public interface FileConnector extends Serializable{
//
// @SuppressWarnings("rawtypes")
// /**
// * Prepare can be called to get storm configuration in FileConector (typically performed by
// * {@link Operation}s/{@link Fetcher}s that receive StormConf and require FileConnector;
// * @param stormConf
// */
// public void prepare(Map stormConf) throws DatatypeConfigurationException;
//
// /**
// * Specify the valid extensions to use by this FileLocation (used by list).
// * If no extensions are set all files will match
// * @param extensions
// * @return itself
// */
// public FileConnector setExtensions(String[] extensions);
//
// /**
// * Moves the remote location to the specified point
// * @param location
// * @return
// */
// public void moveTo(String location) throws IOException;
//
// /**
// * Copies the specified local file to the currently set (remote) location.
// * If the remote location is a 'directory' it will copy the file into the directory.
// * If the remote location points to a file the remote file will likely be overwritten
// * (or an exception is thrown).
// * @param localFile
// * @param delete indicates if the localFile must be deleted after a successful copy
// * @throws IOException
// */
// public void copyFile(File localFile, boolean delete) throws IOException;
//
// /**
// * List all 'files' within the current location which match the provided extensions.
// * If the extensions is null than all files will be returned.
// * @return
// */
// public List<String> list();
//
// /**
// * Returns the FileLocation's prefix (ftp, s3, file, ...)
// * @return
// */
// public String getProtocol();
//
// /**
// * Gets the current location as a file. If the location is remote this will trigger a download
// * @return
// */
// public File getAsFile() throws IOException;
//
// /**
// * Makes a deep copy of this object
// * @return
// */
// public FileConnector deepCopy();
//
// }
| import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import backtype.storm.task.TopologyContext;
import nl.tno.stormcv.model.*;
import nl.tno.stormcv.model.serializer.*;
import nl.tno.stormcv.util.connector.ConnectorHolder;
import nl.tno.stormcv.util.connector.FileConnector;
import nl.tno.stormcv.util.connector.LocalFileConnector; | package nl.tno.stormcv.operation;
/**
* Draws the features contained within a {@link Frame} on the image itself and is primarily used for testing purposes.
* The bounding boxes are drawn to indicate the location of a {@link Descriptor}. If a <code>writeLocation</code> is provided the image will be written
* to that location as PNG image with filename: streamID_sequenceNR_randomNR.png.
*
* @author Corne Versloot
*/
public class DrawFeaturesOp implements ISingleInputOperation<Frame> {
private static final long serialVersionUID = 5628467120758880353L;
private FrameSerializer serializer = new FrameSerializer();
private static Color[] colors = new Color[]{Color.RED, Color.BLUE, Color.GREEN, Color.PINK, Color.YELLOW, Color.CYAN, Color.MAGENTA};
private String writeLocation; | // Path: stormcv/src/main/java/nl/tno/stormcv/util/connector/ConnectorHolder.java
// public class ConnectorHolder {
//
// private HashMap<String, FileConnector> connectors;
// Logger logger = LoggerFactory.getLogger(ConnectorHolder.class);
//
// /**
// * Uses the provided stormConf to instantiate and configure registered {@link FileConnector}'s
// * using {@link StormCVConfig}.STORMCV_CONNECTORS
// * @param stormConf
// */
// @SuppressWarnings({ "rawtypes", "unchecked" })
// public ConnectorHolder(Map stormConf){
// connectors = new HashMap<String, FileConnector>();
// List<String> registered = (List<String>)stormConf.get(StormCVConfig.STORMCV_CONNECTORS);
// for(String name : registered) try{
// FileConnector connector = (FileConnector)Class.forName(name).newInstance();
// connector.prepare(stormConf);
// connectors.put(connector.getProtocol(), connector);
// }catch(Exception e){
// logger.warn("Unable to instantiate FileConnector: "+name+" due to: "+e.getMessage());
// }
// }
//
// public FileConnector getConnector(String location){
// try {
// return connectors.get(new URI(location).getScheme());
// } catch (URISyntaxException e) {
// logger.warn(location+" does hot have valid URI syntax: "+e.getMessage());
// }
// return null;
// }
//
// }
//
// Path: stormcv/src/main/java/nl/tno/stormcv/util/connector/FileConnector.java
// public interface FileConnector extends Serializable{
//
// @SuppressWarnings("rawtypes")
// /**
// * Prepare can be called to get storm configuration in FileConector (typically performed by
// * {@link Operation}s/{@link Fetcher}s that receive StormConf and require FileConnector;
// * @param stormConf
// */
// public void prepare(Map stormConf) throws DatatypeConfigurationException;
//
// /**
// * Specify the valid extensions to use by this FileLocation (used by list).
// * If no extensions are set all files will match
// * @param extensions
// * @return itself
// */
// public FileConnector setExtensions(String[] extensions);
//
// /**
// * Moves the remote location to the specified point
// * @param location
// * @return
// */
// public void moveTo(String location) throws IOException;
//
// /**
// * Copies the specified local file to the currently set (remote) location.
// * If the remote location is a 'directory' it will copy the file into the directory.
// * If the remote location points to a file the remote file will likely be overwritten
// * (or an exception is thrown).
// * @param localFile
// * @param delete indicates if the localFile must be deleted after a successful copy
// * @throws IOException
// */
// public void copyFile(File localFile, boolean delete) throws IOException;
//
// /**
// * List all 'files' within the current location which match the provided extensions.
// * If the extensions is null than all files will be returned.
// * @return
// */
// public List<String> list();
//
// /**
// * Returns the FileLocation's prefix (ftp, s3, file, ...)
// * @return
// */
// public String getProtocol();
//
// /**
// * Gets the current location as a file. If the location is remote this will trigger a download
// * @return
// */
// public File getAsFile() throws IOException;
//
// /**
// * Makes a deep copy of this object
// * @return
// */
// public FileConnector deepCopy();
//
// }
// Path: stormcv/src/main/java/nl/tno/stormcv/operation/DrawFeaturesOp.java
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import backtype.storm.task.TopologyContext;
import nl.tno.stormcv.model.*;
import nl.tno.stormcv.model.serializer.*;
import nl.tno.stormcv.util.connector.ConnectorHolder;
import nl.tno.stormcv.util.connector.FileConnector;
import nl.tno.stormcv.util.connector.LocalFileConnector;
package nl.tno.stormcv.operation;
/**
* Draws the features contained within a {@link Frame} on the image itself and is primarily used for testing purposes.
* The bounding boxes are drawn to indicate the location of a {@link Descriptor}. If a <code>writeLocation</code> is provided the image will be written
* to that location as PNG image with filename: streamID_sequenceNR_randomNR.png.
*
* @author Corne Versloot
*/
public class DrawFeaturesOp implements ISingleInputOperation<Frame> {
private static final long serialVersionUID = 5628467120758880353L;
private FrameSerializer serializer = new FrameSerializer();
private static Color[] colors = new Color[]{Color.RED, Color.BLUE, Color.GREEN, Color.PINK, Color.YELLOW, Color.CYAN, Color.MAGENTA};
private String writeLocation; | private ConnectorHolder connectorHolder; |
sensorstorm/StormCV | stormcv/src/main/java/nl/tno/stormcv/operation/DrawFeaturesOp.java | // Path: stormcv/src/main/java/nl/tno/stormcv/util/connector/ConnectorHolder.java
// public class ConnectorHolder {
//
// private HashMap<String, FileConnector> connectors;
// Logger logger = LoggerFactory.getLogger(ConnectorHolder.class);
//
// /**
// * Uses the provided stormConf to instantiate and configure registered {@link FileConnector}'s
// * using {@link StormCVConfig}.STORMCV_CONNECTORS
// * @param stormConf
// */
// @SuppressWarnings({ "rawtypes", "unchecked" })
// public ConnectorHolder(Map stormConf){
// connectors = new HashMap<String, FileConnector>();
// List<String> registered = (List<String>)stormConf.get(StormCVConfig.STORMCV_CONNECTORS);
// for(String name : registered) try{
// FileConnector connector = (FileConnector)Class.forName(name).newInstance();
// connector.prepare(stormConf);
// connectors.put(connector.getProtocol(), connector);
// }catch(Exception e){
// logger.warn("Unable to instantiate FileConnector: "+name+" due to: "+e.getMessage());
// }
// }
//
// public FileConnector getConnector(String location){
// try {
// return connectors.get(new URI(location).getScheme());
// } catch (URISyntaxException e) {
// logger.warn(location+" does hot have valid URI syntax: "+e.getMessage());
// }
// return null;
// }
//
// }
//
// Path: stormcv/src/main/java/nl/tno/stormcv/util/connector/FileConnector.java
// public interface FileConnector extends Serializable{
//
// @SuppressWarnings("rawtypes")
// /**
// * Prepare can be called to get storm configuration in FileConector (typically performed by
// * {@link Operation}s/{@link Fetcher}s that receive StormConf and require FileConnector;
// * @param stormConf
// */
// public void prepare(Map stormConf) throws DatatypeConfigurationException;
//
// /**
// * Specify the valid extensions to use by this FileLocation (used by list).
// * If no extensions are set all files will match
// * @param extensions
// * @return itself
// */
// public FileConnector setExtensions(String[] extensions);
//
// /**
// * Moves the remote location to the specified point
// * @param location
// * @return
// */
// public void moveTo(String location) throws IOException;
//
// /**
// * Copies the specified local file to the currently set (remote) location.
// * If the remote location is a 'directory' it will copy the file into the directory.
// * If the remote location points to a file the remote file will likely be overwritten
// * (or an exception is thrown).
// * @param localFile
// * @param delete indicates if the localFile must be deleted after a successful copy
// * @throws IOException
// */
// public void copyFile(File localFile, boolean delete) throws IOException;
//
// /**
// * List all 'files' within the current location which match the provided extensions.
// * If the extensions is null than all files will be returned.
// * @return
// */
// public List<String> list();
//
// /**
// * Returns the FileLocation's prefix (ftp, s3, file, ...)
// * @return
// */
// public String getProtocol();
//
// /**
// * Gets the current location as a file. If the location is remote this will trigger a download
// * @return
// */
// public File getAsFile() throws IOException;
//
// /**
// * Makes a deep copy of this object
// * @return
// */
// public FileConnector deepCopy();
//
// }
| import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import backtype.storm.task.TopologyContext;
import nl.tno.stormcv.model.*;
import nl.tno.stormcv.model.serializer.*;
import nl.tno.stormcv.util.connector.ConnectorHolder;
import nl.tno.stormcv.util.connector.FileConnector;
import nl.tno.stormcv.util.connector.LocalFileConnector; | int colorIndex = 0;
for(Feature feature : sf.getFeatures()){
graphics.setColor(colors[colorIndex % colors.length]);
for(Descriptor descr : feature.getSparseDescriptors()){
Rectangle box = descr.getBoundingBox().getBounds();
if(box.width == 0 ) box.width = 1;
if(box.height == 0) box.height = 1;
graphics.draw(box);
}
colorIndex++;
}
int y = 10;
// draw feature legenda on top of everything else
for(colorIndex = 0; colorIndex < sf.getFeatures().size(); colorIndex++){
graphics.setColor(colors[colorIndex % colors.length]);
graphics.drawString(sf.getFeatures().get(colorIndex).getName(), 5, y);
y += 12;
}
if(drawMetadata) for(String key : sf.getMetadata().keySet()){
colorIndex++;
graphics.setColor(colors[colorIndex % colors.length]);
graphics.drawString(key+" = "+sf.getMetadata().get(key), 5, y);
y += 12;
}
sf.setImage(image);
if(writeLocation != null){
String destination = writeLocation + (writeLocation.endsWith("/") ? "" : "/") + sf.getStreamId()+"_"+sf.getSequenceNr()+"_"+Math.random()+".png"; | // Path: stormcv/src/main/java/nl/tno/stormcv/util/connector/ConnectorHolder.java
// public class ConnectorHolder {
//
// private HashMap<String, FileConnector> connectors;
// Logger logger = LoggerFactory.getLogger(ConnectorHolder.class);
//
// /**
// * Uses the provided stormConf to instantiate and configure registered {@link FileConnector}'s
// * using {@link StormCVConfig}.STORMCV_CONNECTORS
// * @param stormConf
// */
// @SuppressWarnings({ "rawtypes", "unchecked" })
// public ConnectorHolder(Map stormConf){
// connectors = new HashMap<String, FileConnector>();
// List<String> registered = (List<String>)stormConf.get(StormCVConfig.STORMCV_CONNECTORS);
// for(String name : registered) try{
// FileConnector connector = (FileConnector)Class.forName(name).newInstance();
// connector.prepare(stormConf);
// connectors.put(connector.getProtocol(), connector);
// }catch(Exception e){
// logger.warn("Unable to instantiate FileConnector: "+name+" due to: "+e.getMessage());
// }
// }
//
// public FileConnector getConnector(String location){
// try {
// return connectors.get(new URI(location).getScheme());
// } catch (URISyntaxException e) {
// logger.warn(location+" does hot have valid URI syntax: "+e.getMessage());
// }
// return null;
// }
//
// }
//
// Path: stormcv/src/main/java/nl/tno/stormcv/util/connector/FileConnector.java
// public interface FileConnector extends Serializable{
//
// @SuppressWarnings("rawtypes")
// /**
// * Prepare can be called to get storm configuration in FileConector (typically performed by
// * {@link Operation}s/{@link Fetcher}s that receive StormConf and require FileConnector;
// * @param stormConf
// */
// public void prepare(Map stormConf) throws DatatypeConfigurationException;
//
// /**
// * Specify the valid extensions to use by this FileLocation (used by list).
// * If no extensions are set all files will match
// * @param extensions
// * @return itself
// */
// public FileConnector setExtensions(String[] extensions);
//
// /**
// * Moves the remote location to the specified point
// * @param location
// * @return
// */
// public void moveTo(String location) throws IOException;
//
// /**
// * Copies the specified local file to the currently set (remote) location.
// * If the remote location is a 'directory' it will copy the file into the directory.
// * If the remote location points to a file the remote file will likely be overwritten
// * (or an exception is thrown).
// * @param localFile
// * @param delete indicates if the localFile must be deleted after a successful copy
// * @throws IOException
// */
// public void copyFile(File localFile, boolean delete) throws IOException;
//
// /**
// * List all 'files' within the current location which match the provided extensions.
// * If the extensions is null than all files will be returned.
// * @return
// */
// public List<String> list();
//
// /**
// * Returns the FileLocation's prefix (ftp, s3, file, ...)
// * @return
// */
// public String getProtocol();
//
// /**
// * Gets the current location as a file. If the location is remote this will trigger a download
// * @return
// */
// public File getAsFile() throws IOException;
//
// /**
// * Makes a deep copy of this object
// * @return
// */
// public FileConnector deepCopy();
//
// }
// Path: stormcv/src/main/java/nl/tno/stormcv/operation/DrawFeaturesOp.java
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import backtype.storm.task.TopologyContext;
import nl.tno.stormcv.model.*;
import nl.tno.stormcv.model.serializer.*;
import nl.tno.stormcv.util.connector.ConnectorHolder;
import nl.tno.stormcv.util.connector.FileConnector;
import nl.tno.stormcv.util.connector.LocalFileConnector;
int colorIndex = 0;
for(Feature feature : sf.getFeatures()){
graphics.setColor(colors[colorIndex % colors.length]);
for(Descriptor descr : feature.getSparseDescriptors()){
Rectangle box = descr.getBoundingBox().getBounds();
if(box.width == 0 ) box.width = 1;
if(box.height == 0) box.height = 1;
graphics.draw(box);
}
colorIndex++;
}
int y = 10;
// draw feature legenda on top of everything else
for(colorIndex = 0; colorIndex < sf.getFeatures().size(); colorIndex++){
graphics.setColor(colors[colorIndex % colors.length]);
graphics.drawString(sf.getFeatures().get(colorIndex).getName(), 5, y);
y += 12;
}
if(drawMetadata) for(String key : sf.getMetadata().keySet()){
colorIndex++;
graphics.setColor(colors[colorIndex % colors.length]);
graphics.drawString(key+" = "+sf.getMetadata().get(key), 5, y);
y += 12;
}
sf.setImage(image);
if(writeLocation != null){
String destination = writeLocation + (writeLocation.endsWith("/") ? "" : "/") + sf.getStreamId()+"_"+sf.getSequenceNr()+"_"+Math.random()+".png"; | FileConnector fl = connectorHolder.getConnector(destination); |
sensorstorm/StormCV | stormcv/src/main/java/nl/tno/stormcv/util/connector/ConnectorHolder.java | // Path: stormcv/src/main/java/nl/tno/stormcv/StormCVConfig.java
// public class StormCVConfig extends Config{
//
// private static final long serialVersionUID = 6290659199719921212L;
//
// /**
// * <b>Boolean (default = false)</b> configuration parameter indicating if the spout must cache emitted tuples so they can be replayed
// */
// public static final String STORMCV_SPOUT_FAULTTOLERANT = "stormcv.spout.faulttolerant";
//
// /**
// * <b>String (default = "jpg" (Frame.JPG))</b> configuration parameter setting the image encoding for frames in the topology. It is up to Operation implementations
// * to read this configuration parameter and use it properly.
// */
// public static final String STORMCV_FRAME_ENCODING = "stormcv.frame.encoding";
//
// /**
// * <b>Integer (default = 30)</b> configuration parameter setting the maximum time to live for items being cached within the topology (both spouts and bolts use this configuration)
// */
// public static final String STORMCV_CACHES_TIMEOUT_SEC = "stormcv.caches.timeout";
//
// /**
// * <b>Integer (default = 500)</b> configuration parameter setting the maximum number of elements being cached by spouts and bolts (used to avoid memory overload)
// */
// public static final String STORMCV_CACHES_MAX_SIZE = "stormcv.caches.maxsize";
//
// /**
// * <b>List<Class) (default = NONE) </b> configuration parameter the available {@link FileConnector} in the topology
// */
// public static final String STORMCV_CONNECTORS = "stormcv.connectors";
//
// /**
// * <b>Integer (default = 30)</b> configuration parameter setting the maximum idle time in seconds after which the {@link StreamWriterOperation} will close the file
// */
// public static final String STORMCV_MAXIDLE_SEC = "stormcv.streamwriter.maxidlesecs";
//
// /**
// * <b>String</b> configuration parameter setting the library name of the OpenCV lib to be used
// */
// public static final String STORMCV_OPENCV_LIB = "stormcv.opencv.lib";
//
//
// /**
// * Creates a specific Configuration for StormCV.
// * <ul>
// * <li>Sets buffer sizes to 2 to optimize for few large size {@link Tuple}s instead of loads of small sized Tuples</li>
// * <li>Registers known Kryo serializers for the Model. Other serializers can be added using the registerSerialization function.</li>
// * <li>Registers known {@link FileConnector} implementations. New file connectors can be added through registerConnector</li>
// * </ul>
// */
// public StormCVConfig(){
// super();
// // ------- Create StormCV specific config -------
// put(Config.TOPOLOGY_RECEIVER_BUFFER_SIZE, 2); // sets the maximum number of messages to batch before sending them to executers
// put(Config.TOPOLOGY_TRANSFER_BUFFER_SIZE, 2); // sets the size of the output queue for each worker.
// put(STORMCV_FRAME_ENCODING, Frame.JPG_IMAGE); // sets the encoding of frames which determines both serialization speed and tuple size
//
// // register the basic set Kryo serializers
// registerSerialization(VideoChunk.class, VideoChunkSerializer.class);
// registerSerialization(GroupOfFrames.class, GroupOfFramesSerializer.class);
// registerSerialization(Frame.class, FrameSerializer.class);
// registerSerialization(Descriptor.class, DescriptorSerializer.class);
// registerSerialization(Feature.class, FeatureSerializer.class);
//
// // register FileConnectors
// ArrayList<String> connectorList = new ArrayList<String>();
// connectorList.add(LocalFileConnector.class.getName());
// connectorList.add(S3Connector.class.getName());
// connectorList.add(FtpConnector.class.getName());
// connectorList.add(ClasspathConnector.class.getName());
// put(StormCVConfig.STORMCV_CONNECTORS, connectorList);
// }
//
// /**
// * Registers an {@link FileConnector} class which can be used throughout the topology
// * @param connectorClass
// * @return
// */
// @SuppressWarnings("unchecked")
// public StormCVConfig registerConnector(Class<? extends FileConnector> connectorClass){
// ((ArrayList<String>)get(StormCVConfig.STORMCV_CONNECTORS)).add(connectorClass.getName());
// return this;
// }
//
// }
| import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import nl.tno.stormcv.StormCVConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package nl.tno.stormcv.util.connector;
/**
* Utility class used to maintain a set of {@link FileConnector} implementations registered in the {@link StormCVConfig}.
* An instantiated ConnectorHolder can be fetched from the Storm configuration after which it can be used to request
* connectors for urls. getConnector("s3://bucket/path/bideo.mp4") will return the configured {@link S3Connector} object.
*
* @author Corne Versloot
*
*/
public class ConnectorHolder {
private HashMap<String, FileConnector> connectors;
Logger logger = LoggerFactory.getLogger(ConnectorHolder.class);
/**
* Uses the provided stormConf to instantiate and configure registered {@link FileConnector}'s
* using {@link StormCVConfig}.STORMCV_CONNECTORS
* @param stormConf
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public ConnectorHolder(Map stormConf){
connectors = new HashMap<String, FileConnector>(); | // Path: stormcv/src/main/java/nl/tno/stormcv/StormCVConfig.java
// public class StormCVConfig extends Config{
//
// private static final long serialVersionUID = 6290659199719921212L;
//
// /**
// * <b>Boolean (default = false)</b> configuration parameter indicating if the spout must cache emitted tuples so they can be replayed
// */
// public static final String STORMCV_SPOUT_FAULTTOLERANT = "stormcv.spout.faulttolerant";
//
// /**
// * <b>String (default = "jpg" (Frame.JPG))</b> configuration parameter setting the image encoding for frames in the topology. It is up to Operation implementations
// * to read this configuration parameter and use it properly.
// */
// public static final String STORMCV_FRAME_ENCODING = "stormcv.frame.encoding";
//
// /**
// * <b>Integer (default = 30)</b> configuration parameter setting the maximum time to live for items being cached within the topology (both spouts and bolts use this configuration)
// */
// public static final String STORMCV_CACHES_TIMEOUT_SEC = "stormcv.caches.timeout";
//
// /**
// * <b>Integer (default = 500)</b> configuration parameter setting the maximum number of elements being cached by spouts and bolts (used to avoid memory overload)
// */
// public static final String STORMCV_CACHES_MAX_SIZE = "stormcv.caches.maxsize";
//
// /**
// * <b>List<Class) (default = NONE) </b> configuration parameter the available {@link FileConnector} in the topology
// */
// public static final String STORMCV_CONNECTORS = "stormcv.connectors";
//
// /**
// * <b>Integer (default = 30)</b> configuration parameter setting the maximum idle time in seconds after which the {@link StreamWriterOperation} will close the file
// */
// public static final String STORMCV_MAXIDLE_SEC = "stormcv.streamwriter.maxidlesecs";
//
// /**
// * <b>String</b> configuration parameter setting the library name of the OpenCV lib to be used
// */
// public static final String STORMCV_OPENCV_LIB = "stormcv.opencv.lib";
//
//
// /**
// * Creates a specific Configuration for StormCV.
// * <ul>
// * <li>Sets buffer sizes to 2 to optimize for few large size {@link Tuple}s instead of loads of small sized Tuples</li>
// * <li>Registers known Kryo serializers for the Model. Other serializers can be added using the registerSerialization function.</li>
// * <li>Registers known {@link FileConnector} implementations. New file connectors can be added through registerConnector</li>
// * </ul>
// */
// public StormCVConfig(){
// super();
// // ------- Create StormCV specific config -------
// put(Config.TOPOLOGY_RECEIVER_BUFFER_SIZE, 2); // sets the maximum number of messages to batch before sending them to executers
// put(Config.TOPOLOGY_TRANSFER_BUFFER_SIZE, 2); // sets the size of the output queue for each worker.
// put(STORMCV_FRAME_ENCODING, Frame.JPG_IMAGE); // sets the encoding of frames which determines both serialization speed and tuple size
//
// // register the basic set Kryo serializers
// registerSerialization(VideoChunk.class, VideoChunkSerializer.class);
// registerSerialization(GroupOfFrames.class, GroupOfFramesSerializer.class);
// registerSerialization(Frame.class, FrameSerializer.class);
// registerSerialization(Descriptor.class, DescriptorSerializer.class);
// registerSerialization(Feature.class, FeatureSerializer.class);
//
// // register FileConnectors
// ArrayList<String> connectorList = new ArrayList<String>();
// connectorList.add(LocalFileConnector.class.getName());
// connectorList.add(S3Connector.class.getName());
// connectorList.add(FtpConnector.class.getName());
// connectorList.add(ClasspathConnector.class.getName());
// put(StormCVConfig.STORMCV_CONNECTORS, connectorList);
// }
//
// /**
// * Registers an {@link FileConnector} class which can be used throughout the topology
// * @param connectorClass
// * @return
// */
// @SuppressWarnings("unchecked")
// public StormCVConfig registerConnector(Class<? extends FileConnector> connectorClass){
// ((ArrayList<String>)get(StormCVConfig.STORMCV_CONNECTORS)).add(connectorClass.getName());
// return this;
// }
//
// }
// Path: stormcv/src/main/java/nl/tno/stormcv/util/connector/ConnectorHolder.java
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import nl.tno.stormcv.StormCVConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package nl.tno.stormcv.util.connector;
/**
* Utility class used to maintain a set of {@link FileConnector} implementations registered in the {@link StormCVConfig}.
* An instantiated ConnectorHolder can be fetched from the Storm configuration after which it can be used to request
* connectors for urls. getConnector("s3://bucket/path/bideo.mp4") will return the configured {@link S3Connector} object.
*
* @author Corne Versloot
*
*/
public class ConnectorHolder {
private HashMap<String, FileConnector> connectors;
Logger logger = LoggerFactory.getLogger(ConnectorHolder.class);
/**
* Uses the provided stormConf to instantiate and configure registered {@link FileConnector}'s
* using {@link StormCVConfig}.STORMCV_CONNECTORS
* @param stormConf
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public ConnectorHolder(Map stormConf){
connectors = new HashMap<String, FileConnector>(); | List<String> registered = (List<String>)stormConf.get(StormCVConfig.STORMCV_CONNECTORS); |
juliuskrah/spring-profiles | src/main/java/com/jipasoft/config/H2Config.java | // Path: src/main/java/com/jipasoft/repository/h2/BaseRepositoryImpl.java
// public interface BaseRepositoryImpl {
//
// }
//
// Path: src/main/java/com/jipasoft/util/Profiles.java
// public class Profiles {
// public static final String H2 = "h2";
// public static final String POSTGRES = "postgres";
// public static final String MYSQL = "mysql";
// public static final String MONGO = "mongo";
// public static final String EMAIL = "email";
// public static final String HEROKU = "heroku";
// public static final String ASPECT = "aspect";
// }
| import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.jipasoft.repository.h2.BaseRepositoryImpl;
import com.jipasoft.util.Profiles; | /*
* Copyright 2016, Julius Krah
* by the @authors tag. See the LICENCE in the distribution for a
* full listing of individual contributors.
*
* 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.jipasoft.config;
/**
* Configuration specific for {@code h2} profile. This configuration uses Spring
* Data JPA. The underlying datastore is H2 embedded database for it's JPA
* access
*
* @author Julius Krah
*
*/
@Configuration
@Profile({ Profiles.H2, Profiles.HEROKU }) | // Path: src/main/java/com/jipasoft/repository/h2/BaseRepositoryImpl.java
// public interface BaseRepositoryImpl {
//
// }
//
// Path: src/main/java/com/jipasoft/util/Profiles.java
// public class Profiles {
// public static final String H2 = "h2";
// public static final String POSTGRES = "postgres";
// public static final String MYSQL = "mysql";
// public static final String MONGO = "mongo";
// public static final String EMAIL = "email";
// public static final String HEROKU = "heroku";
// public static final String ASPECT = "aspect";
// }
// Path: src/main/java/com/jipasoft/config/H2Config.java
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.jipasoft.repository.h2.BaseRepositoryImpl;
import com.jipasoft.util.Profiles;
/*
* Copyright 2016, Julius Krah
* by the @authors tag. See the LICENCE in the distribution for a
* full listing of individual contributors.
*
* 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.jipasoft.config;
/**
* Configuration specific for {@code h2} profile. This configuration uses Spring
* Data JPA. The underlying datastore is H2 embedded database for it's JPA
* access
*
* @author Julius Krah
*
*/
@Configuration
@Profile({ Profiles.H2, Profiles.HEROKU }) | @EnableJpaRepositories(basePackageClasses = BaseRepositoryImpl.class) |
juliuskrah/spring-profiles | src/main/java/com/jipasoft/config/AspectConfig.java | // Path: src/main/java/com/jipasoft/task/AsyncMailSender.java
// public class AsyncMailSender extends JavaMailSenderImpl {
//
// @Async
// @Override
// public void send(SimpleMailMessage simpleMessage) throws MailException {
// super.send(simpleMessage);
// }
//
// @Async
// @Override
// public void send(SimpleMailMessage... simpleMessages) throws MailException {
// super.send(simpleMessages);
// }
// }
//
// Path: src/main/java/com/jipasoft/task/ExceptionAspect.java
// @Slf4j
// @Aspect
// @Component
// public class ExceptionAspect {
//
// @Inject
// private MailSender mailSender;
// @Value("${spring.user.email}")
// private String[] to;
//
// @Pointcut("within(com.jipasoft.web..*)")
// public void mailingPointcut() {
// }
//
// @AfterThrowing(pointcut = "mailingPointcut()", throwing = "e")
// public void mailAfterThrowing(JoinPoint joinPoint, Throwable e) {
// // @formatter:off
// // Building stack trace string
// StringWriter stackTrace = new StringWriter();
// e.printStackTrace(new PrintWriter(stackTrace));
// // Building e-mail
// SimpleMailMessage email = new SimpleMailMessage();
// email.setTo(to);
// email.setSubject("[Spring Profiles Aspect] Exception in '" + joinPoint.getSignature().getName() + "' method");
// email.setText(
// "Exception in: " + joinPoint.getSignature().getName() + "\n\n" +
// "Class: " + joinPoint.getSignature().getDeclaringTypeName() + "\n\n" +
// "Time: " + ZonedDateTime.now() + "\n\n" +
// "Message: " + e.getMessage() + "\n\n" +
// "StackTrace:\n" + stackTrace.getBuffer().toString()
// );
// // Sending e-mail
// try {
// this.mailSender.send(email);
// } catch (MailException mailException) {
// log.error(mailException.getMessage());
// }
// }
// }
//
// Path: src/main/java/com/jipasoft/task/ExceptionInterceptor.java
// @Slf4j
// public class ExceptionInterceptor implements MethodInterceptor {
// @Inject
// private MailSender mailSender;
// @Value("${spring.user.email}")
// private String[] to;
//
// @Override
// public Object invoke(MethodInvocation method) throws Throwable {
// Object result = null;
// try {
// result = method.proceed();
// } catch (Exception e) {
// // @formatter:off
// // Building stack trace string
// StringWriter stackTrace = new StringWriter();
// e.printStackTrace(new PrintWriter(stackTrace));
// // Building e-mail
// SimpleMailMessage email = new SimpleMailMessage();
// email.setTo(to);
// email.setSubject("[Spring Profiles] Exception in '" + method.getMethod().getName() + "' method");
// email.setText(
// "Exception in: " + method.getMethod().getName() + "\n\n" +
// "Class: " + method.getMethod().getDeclaringClass().getName() + "\n\n" +
// "Time: " + ZonedDateTime.now() + "\n\n" +
// "Message: " + e.getMessage() + "\n\n" +
// "StackTrace:\n" + stackTrace.getBuffer().toString()
// );
// // Sending e-mail
// try {
// this.mailSender.send(email);
// } catch (MailException mailException) {
// log.error(mailException.getMessage());
// }
// throw e;
// // @formatter:on
//
// }
// return result;
// }
// }
//
// Path: src/main/java/com/jipasoft/util/Profiles.java
// public class Profiles {
// public static final String H2 = "h2";
// public static final String POSTGRES = "postgres";
// public static final String MYSQL = "mysql";
// public static final String MONGO = "mongo";
// public static final String EMAIL = "email";
// public static final String HEROKU = "heroku";
// public static final String ASPECT = "aspect";
// }
| import com.jipasoft.task.AsyncMailSender;
import com.jipasoft.task.ExceptionAspect;
import com.jipasoft.task.ExceptionInterceptor;
import com.jipasoft.util.Profiles;
import java.util.Map;
import java.util.Properties;
import javax.inject.Inject;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; | /*
* Copyright 2016, Julius Krah
* by the @authors tag. See the LICENCE in the distribution for a
* full listing of individual contributors.
*
* 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.jipasoft.config;
/**
* Configures asynchronous mailing When an exception is encountered in the
* application, it will send an email to the developer.<br />
* It may also send the <i>Stacktrace</i> of the error depending on the
* configured property of the application.<br />
* <p>
*
* The application's email feature can be enabled when the {@code aspect}
* profile is active.
* </p>
*
* @author Julius Krah
*
*/
@EnableAsync
@Profile(Profiles.ASPECT)
@Configuration | // Path: src/main/java/com/jipasoft/task/AsyncMailSender.java
// public class AsyncMailSender extends JavaMailSenderImpl {
//
// @Async
// @Override
// public void send(SimpleMailMessage simpleMessage) throws MailException {
// super.send(simpleMessage);
// }
//
// @Async
// @Override
// public void send(SimpleMailMessage... simpleMessages) throws MailException {
// super.send(simpleMessages);
// }
// }
//
// Path: src/main/java/com/jipasoft/task/ExceptionAspect.java
// @Slf4j
// @Aspect
// @Component
// public class ExceptionAspect {
//
// @Inject
// private MailSender mailSender;
// @Value("${spring.user.email}")
// private String[] to;
//
// @Pointcut("within(com.jipasoft.web..*)")
// public void mailingPointcut() {
// }
//
// @AfterThrowing(pointcut = "mailingPointcut()", throwing = "e")
// public void mailAfterThrowing(JoinPoint joinPoint, Throwable e) {
// // @formatter:off
// // Building stack trace string
// StringWriter stackTrace = new StringWriter();
// e.printStackTrace(new PrintWriter(stackTrace));
// // Building e-mail
// SimpleMailMessage email = new SimpleMailMessage();
// email.setTo(to);
// email.setSubject("[Spring Profiles Aspect] Exception in '" + joinPoint.getSignature().getName() + "' method");
// email.setText(
// "Exception in: " + joinPoint.getSignature().getName() + "\n\n" +
// "Class: " + joinPoint.getSignature().getDeclaringTypeName() + "\n\n" +
// "Time: " + ZonedDateTime.now() + "\n\n" +
// "Message: " + e.getMessage() + "\n\n" +
// "StackTrace:\n" + stackTrace.getBuffer().toString()
// );
// // Sending e-mail
// try {
// this.mailSender.send(email);
// } catch (MailException mailException) {
// log.error(mailException.getMessage());
// }
// }
// }
//
// Path: src/main/java/com/jipasoft/task/ExceptionInterceptor.java
// @Slf4j
// public class ExceptionInterceptor implements MethodInterceptor {
// @Inject
// private MailSender mailSender;
// @Value("${spring.user.email}")
// private String[] to;
//
// @Override
// public Object invoke(MethodInvocation method) throws Throwable {
// Object result = null;
// try {
// result = method.proceed();
// } catch (Exception e) {
// // @formatter:off
// // Building stack trace string
// StringWriter stackTrace = new StringWriter();
// e.printStackTrace(new PrintWriter(stackTrace));
// // Building e-mail
// SimpleMailMessage email = new SimpleMailMessage();
// email.setTo(to);
// email.setSubject("[Spring Profiles] Exception in '" + method.getMethod().getName() + "' method");
// email.setText(
// "Exception in: " + method.getMethod().getName() + "\n\n" +
// "Class: " + method.getMethod().getDeclaringClass().getName() + "\n\n" +
// "Time: " + ZonedDateTime.now() + "\n\n" +
// "Message: " + e.getMessage() + "\n\n" +
// "StackTrace:\n" + stackTrace.getBuffer().toString()
// );
// // Sending e-mail
// try {
// this.mailSender.send(email);
// } catch (MailException mailException) {
// log.error(mailException.getMessage());
// }
// throw e;
// // @formatter:on
//
// }
// return result;
// }
// }
//
// Path: src/main/java/com/jipasoft/util/Profiles.java
// public class Profiles {
// public static final String H2 = "h2";
// public static final String POSTGRES = "postgres";
// public static final String MYSQL = "mysql";
// public static final String MONGO = "mongo";
// public static final String EMAIL = "email";
// public static final String HEROKU = "heroku";
// public static final String ASPECT = "aspect";
// }
// Path: src/main/java/com/jipasoft/config/AspectConfig.java
import com.jipasoft.task.AsyncMailSender;
import com.jipasoft.task.ExceptionAspect;
import com.jipasoft.task.ExceptionInterceptor;
import com.jipasoft.util.Profiles;
import java.util.Map;
import java.util.Properties;
import javax.inject.Inject;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/*
* Copyright 2016, Julius Krah
* by the @authors tag. See the LICENCE in the distribution for a
* full listing of individual contributors.
*
* 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.jipasoft.config;
/**
* Configures asynchronous mailing When an exception is encountered in the
* application, it will send an email to the developer.<br />
* It may also send the <i>Stacktrace</i> of the error depending on the
* configured property of the application.<br />
* <p>
*
* The application's email feature can be enabled when the {@code aspect}
* profile is active.
* </p>
*
* @author Julius Krah
*
*/
@EnableAsync
@Profile(Profiles.ASPECT)
@Configuration | @ComponentScan(basePackageClasses = ExceptionAspect.class) |
juliuskrah/spring-profiles | src/main/java/com/jipasoft/config/AspectConfig.java | // Path: src/main/java/com/jipasoft/task/AsyncMailSender.java
// public class AsyncMailSender extends JavaMailSenderImpl {
//
// @Async
// @Override
// public void send(SimpleMailMessage simpleMessage) throws MailException {
// super.send(simpleMessage);
// }
//
// @Async
// @Override
// public void send(SimpleMailMessage... simpleMessages) throws MailException {
// super.send(simpleMessages);
// }
// }
//
// Path: src/main/java/com/jipasoft/task/ExceptionAspect.java
// @Slf4j
// @Aspect
// @Component
// public class ExceptionAspect {
//
// @Inject
// private MailSender mailSender;
// @Value("${spring.user.email}")
// private String[] to;
//
// @Pointcut("within(com.jipasoft.web..*)")
// public void mailingPointcut() {
// }
//
// @AfterThrowing(pointcut = "mailingPointcut()", throwing = "e")
// public void mailAfterThrowing(JoinPoint joinPoint, Throwable e) {
// // @formatter:off
// // Building stack trace string
// StringWriter stackTrace = new StringWriter();
// e.printStackTrace(new PrintWriter(stackTrace));
// // Building e-mail
// SimpleMailMessage email = new SimpleMailMessage();
// email.setTo(to);
// email.setSubject("[Spring Profiles Aspect] Exception in '" + joinPoint.getSignature().getName() + "' method");
// email.setText(
// "Exception in: " + joinPoint.getSignature().getName() + "\n\n" +
// "Class: " + joinPoint.getSignature().getDeclaringTypeName() + "\n\n" +
// "Time: " + ZonedDateTime.now() + "\n\n" +
// "Message: " + e.getMessage() + "\n\n" +
// "StackTrace:\n" + stackTrace.getBuffer().toString()
// );
// // Sending e-mail
// try {
// this.mailSender.send(email);
// } catch (MailException mailException) {
// log.error(mailException.getMessage());
// }
// }
// }
//
// Path: src/main/java/com/jipasoft/task/ExceptionInterceptor.java
// @Slf4j
// public class ExceptionInterceptor implements MethodInterceptor {
// @Inject
// private MailSender mailSender;
// @Value("${spring.user.email}")
// private String[] to;
//
// @Override
// public Object invoke(MethodInvocation method) throws Throwable {
// Object result = null;
// try {
// result = method.proceed();
// } catch (Exception e) {
// // @formatter:off
// // Building stack trace string
// StringWriter stackTrace = new StringWriter();
// e.printStackTrace(new PrintWriter(stackTrace));
// // Building e-mail
// SimpleMailMessage email = new SimpleMailMessage();
// email.setTo(to);
// email.setSubject("[Spring Profiles] Exception in '" + method.getMethod().getName() + "' method");
// email.setText(
// "Exception in: " + method.getMethod().getName() + "\n\n" +
// "Class: " + method.getMethod().getDeclaringClass().getName() + "\n\n" +
// "Time: " + ZonedDateTime.now() + "\n\n" +
// "Message: " + e.getMessage() + "\n\n" +
// "StackTrace:\n" + stackTrace.getBuffer().toString()
// );
// // Sending e-mail
// try {
// this.mailSender.send(email);
// } catch (MailException mailException) {
// log.error(mailException.getMessage());
// }
// throw e;
// // @formatter:on
//
// }
// return result;
// }
// }
//
// Path: src/main/java/com/jipasoft/util/Profiles.java
// public class Profiles {
// public static final String H2 = "h2";
// public static final String POSTGRES = "postgres";
// public static final String MYSQL = "mysql";
// public static final String MONGO = "mongo";
// public static final String EMAIL = "email";
// public static final String HEROKU = "heroku";
// public static final String ASPECT = "aspect";
// }
| import com.jipasoft.task.AsyncMailSender;
import com.jipasoft.task.ExceptionAspect;
import com.jipasoft.task.ExceptionInterceptor;
import com.jipasoft.util.Profiles;
import java.util.Map;
import java.util.Properties;
import javax.inject.Inject;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; | sender.setProtocol(this.mailProperties.getProtocol());
if (this.mailProperties.getDefaultEncoding() != null) {
sender.setDefaultEncoding(this.mailProperties.getDefaultEncoding().name());
}
if (!this.mailProperties.getProperties().isEmpty()) {
sender.setJavaMailProperties(asProperties(this.mailProperties.getProperties()));
}
}
private Properties asProperties(Map<String, String> source) {
Properties properties = new Properties();
properties.putAll(source);
return properties;
}
@Bean
public JavaMailSender mailSender() {
JavaMailSenderImpl sender = new AsyncMailSender();
applyProperties(sender);
return sender;
}
/**
* Bean to intercept all application exceptions and queue them for asynchronous mail sending
*
* @return ExceptionInterceptor
*/
// @Bean uncomment to enable | // Path: src/main/java/com/jipasoft/task/AsyncMailSender.java
// public class AsyncMailSender extends JavaMailSenderImpl {
//
// @Async
// @Override
// public void send(SimpleMailMessage simpleMessage) throws MailException {
// super.send(simpleMessage);
// }
//
// @Async
// @Override
// public void send(SimpleMailMessage... simpleMessages) throws MailException {
// super.send(simpleMessages);
// }
// }
//
// Path: src/main/java/com/jipasoft/task/ExceptionAspect.java
// @Slf4j
// @Aspect
// @Component
// public class ExceptionAspect {
//
// @Inject
// private MailSender mailSender;
// @Value("${spring.user.email}")
// private String[] to;
//
// @Pointcut("within(com.jipasoft.web..*)")
// public void mailingPointcut() {
// }
//
// @AfterThrowing(pointcut = "mailingPointcut()", throwing = "e")
// public void mailAfterThrowing(JoinPoint joinPoint, Throwable e) {
// // @formatter:off
// // Building stack trace string
// StringWriter stackTrace = new StringWriter();
// e.printStackTrace(new PrintWriter(stackTrace));
// // Building e-mail
// SimpleMailMessage email = new SimpleMailMessage();
// email.setTo(to);
// email.setSubject("[Spring Profiles Aspect] Exception in '" + joinPoint.getSignature().getName() + "' method");
// email.setText(
// "Exception in: " + joinPoint.getSignature().getName() + "\n\n" +
// "Class: " + joinPoint.getSignature().getDeclaringTypeName() + "\n\n" +
// "Time: " + ZonedDateTime.now() + "\n\n" +
// "Message: " + e.getMessage() + "\n\n" +
// "StackTrace:\n" + stackTrace.getBuffer().toString()
// );
// // Sending e-mail
// try {
// this.mailSender.send(email);
// } catch (MailException mailException) {
// log.error(mailException.getMessage());
// }
// }
// }
//
// Path: src/main/java/com/jipasoft/task/ExceptionInterceptor.java
// @Slf4j
// public class ExceptionInterceptor implements MethodInterceptor {
// @Inject
// private MailSender mailSender;
// @Value("${spring.user.email}")
// private String[] to;
//
// @Override
// public Object invoke(MethodInvocation method) throws Throwable {
// Object result = null;
// try {
// result = method.proceed();
// } catch (Exception e) {
// // @formatter:off
// // Building stack trace string
// StringWriter stackTrace = new StringWriter();
// e.printStackTrace(new PrintWriter(stackTrace));
// // Building e-mail
// SimpleMailMessage email = new SimpleMailMessage();
// email.setTo(to);
// email.setSubject("[Spring Profiles] Exception in '" + method.getMethod().getName() + "' method");
// email.setText(
// "Exception in: " + method.getMethod().getName() + "\n\n" +
// "Class: " + method.getMethod().getDeclaringClass().getName() + "\n\n" +
// "Time: " + ZonedDateTime.now() + "\n\n" +
// "Message: " + e.getMessage() + "\n\n" +
// "StackTrace:\n" + stackTrace.getBuffer().toString()
// );
// // Sending e-mail
// try {
// this.mailSender.send(email);
// } catch (MailException mailException) {
// log.error(mailException.getMessage());
// }
// throw e;
// // @formatter:on
//
// }
// return result;
// }
// }
//
// Path: src/main/java/com/jipasoft/util/Profiles.java
// public class Profiles {
// public static final String H2 = "h2";
// public static final String POSTGRES = "postgres";
// public static final String MYSQL = "mysql";
// public static final String MONGO = "mongo";
// public static final String EMAIL = "email";
// public static final String HEROKU = "heroku";
// public static final String ASPECT = "aspect";
// }
// Path: src/main/java/com/jipasoft/config/AspectConfig.java
import com.jipasoft.task.AsyncMailSender;
import com.jipasoft.task.ExceptionAspect;
import com.jipasoft.task.ExceptionInterceptor;
import com.jipasoft.util.Profiles;
import java.util.Map;
import java.util.Properties;
import javax.inject.Inject;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
sender.setProtocol(this.mailProperties.getProtocol());
if (this.mailProperties.getDefaultEncoding() != null) {
sender.setDefaultEncoding(this.mailProperties.getDefaultEncoding().name());
}
if (!this.mailProperties.getProperties().isEmpty()) {
sender.setJavaMailProperties(asProperties(this.mailProperties.getProperties()));
}
}
private Properties asProperties(Map<String, String> source) {
Properties properties = new Properties();
properties.putAll(source);
return properties;
}
@Bean
public JavaMailSender mailSender() {
JavaMailSenderImpl sender = new AsyncMailSender();
applyProperties(sender);
return sender;
}
/**
* Bean to intercept all application exceptions and queue them for asynchronous mail sending
*
* @return ExceptionInterceptor
*/
// @Bean uncomment to enable | public ExceptionInterceptor exceptionInterceptor() { |
juliuskrah/spring-profiles | src/main/java/com/jipasoft/config/PostgresConfig.java | // Path: src/main/java/com/jipasoft/repository/postgres/BaseRepositoryImpl.java
// @Slf4j
// public class BaseRepositoryImpl<T, ID extends Serializable> implements BaseRepository<T, ID> {
// private Class<T> persistentClass;
//
// @PersistenceContext
// protected EntityManager em;
//
// //@formatter:off
// public BaseRepositoryImpl() {}
// //@formatter:on
//
// public BaseRepositoryImpl(Class<T> persistentClass) {
// this.persistentClass = persistentClass;
// }
//
// @Override
// public void save(T entity) {
// if (this.em.contains(entity))
// this.em.merge(entity);
// else
// this.em.persist(entity);
// }
//
// @Override
// public void delete(T entity) {
// this.em.remove(this.em.contains(entity) ? entity : em.merge(entity));
// }
//
// @Override
// public void deleteAll() {
// Query query = this.em.createQuery(String.format("DELETE FROM %s e", persistentClass.getSimpleName()));
// log.debug("Query executed: {}", String.format("DELETE FROM %s e", persistentClass.getSimpleName()));
// query.executeUpdate();
// }
//
// @Override
// public Optional<T> findOneById(ID id) {
// return Optional.ofNullable(this.em.find(persistentClass, id));
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public List<T> findAll() {
// Query query = this.em.createQuery(String.format("SELECT e FROM %s e", persistentClass.getSimpleName()));
// log.debug("Query executed: {}", String.format("SELECT e FROM %s e", persistentClass.getSimpleName()));
// return query.getResultList();
// }
//
// }
//
// Path: src/main/java/com/jipasoft/util/Profiles.java
// public class Profiles {
// public static final String H2 = "h2";
// public static final String POSTGRES = "postgres";
// public static final String MYSQL = "mysql";
// public static final String MONGO = "mongo";
// public static final String EMAIL = "email";
// public static final String HEROKU = "heroku";
// public static final String ASPECT = "aspect";
// }
| import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import com.jipasoft.repository.postgres.BaseRepositoryImpl;
import com.jipasoft.util.Profiles; | /*
* Copyright 2016, Julius Krah
* by the @authors tag. See the LICENCE in the distribution for a
* full listing of individual contributors.
*
* 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.jipasoft.config;
/**
* Configuration specific to the {@code postgres} and {@code mysql} profiles. The implementation of
* JPA here is standard specification JPA. The underlying datastore is
* PostgreSQL and/or MySQL
*
* @author Julius Krah
*
*/
@Configuration
@Profile({ Profiles.POSTGRES, Profiles.MYSQL }) | // Path: src/main/java/com/jipasoft/repository/postgres/BaseRepositoryImpl.java
// @Slf4j
// public class BaseRepositoryImpl<T, ID extends Serializable> implements BaseRepository<T, ID> {
// private Class<T> persistentClass;
//
// @PersistenceContext
// protected EntityManager em;
//
// //@formatter:off
// public BaseRepositoryImpl() {}
// //@formatter:on
//
// public BaseRepositoryImpl(Class<T> persistentClass) {
// this.persistentClass = persistentClass;
// }
//
// @Override
// public void save(T entity) {
// if (this.em.contains(entity))
// this.em.merge(entity);
// else
// this.em.persist(entity);
// }
//
// @Override
// public void delete(T entity) {
// this.em.remove(this.em.contains(entity) ? entity : em.merge(entity));
// }
//
// @Override
// public void deleteAll() {
// Query query = this.em.createQuery(String.format("DELETE FROM %s e", persistentClass.getSimpleName()));
// log.debug("Query executed: {}", String.format("DELETE FROM %s e", persistentClass.getSimpleName()));
// query.executeUpdate();
// }
//
// @Override
// public Optional<T> findOneById(ID id) {
// return Optional.ofNullable(this.em.find(persistentClass, id));
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public List<T> findAll() {
// Query query = this.em.createQuery(String.format("SELECT e FROM %s e", persistentClass.getSimpleName()));
// log.debug("Query executed: {}", String.format("SELECT e FROM %s e", persistentClass.getSimpleName()));
// return query.getResultList();
// }
//
// }
//
// Path: src/main/java/com/jipasoft/util/Profiles.java
// public class Profiles {
// public static final String H2 = "h2";
// public static final String POSTGRES = "postgres";
// public static final String MYSQL = "mysql";
// public static final String MONGO = "mongo";
// public static final String EMAIL = "email";
// public static final String HEROKU = "heroku";
// public static final String ASPECT = "aspect";
// }
// Path: src/main/java/com/jipasoft/config/PostgresConfig.java
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import com.jipasoft.repository.postgres.BaseRepositoryImpl;
import com.jipasoft.util.Profiles;
/*
* Copyright 2016, Julius Krah
* by the @authors tag. See the LICENCE in the distribution for a
* full listing of individual contributors.
*
* 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.jipasoft.config;
/**
* Configuration specific to the {@code postgres} and {@code mysql} profiles. The implementation of
* JPA here is standard specification JPA. The underlying datastore is
* PostgreSQL and/or MySQL
*
* @author Julius Krah
*
*/
@Configuration
@Profile({ Profiles.POSTGRES, Profiles.MYSQL }) | @ComponentScan(basePackageClasses = BaseRepositoryImpl.class) |
juliuskrah/spring-profiles | src/main/java/com/jipasoft/domain/dto/UserDTO.java | // Path: src/main/java/com/jipasoft/domain/Authority.java
// @Data
// @Entity
// @Document(collection = "role")
// @NoArgsConstructor
// @AllArgsConstructor
// @Table(name = "role")
// public class Authority implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @NotNull
// @org.springframework.data.annotation.Id
// @Size(min = 1, max = 50)
// private String name;
//
// }
//
// Path: src/main/java/com/jipasoft/domain/User.java
// @Data
// @Entity
// @Document(collection = "account")
// @Table(name = "account")
// @ToString(exclude = { "password", "authorities" })
// @EqualsAndHashCode(callSuper = true)
// public class User extends AbstractAuditEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @org.springframework.data.annotation.Id
// @GeneratedValue(generator = "uuid2")
// @GenericGenerator(name = "uuid2", strategy = "uuid2")
// private String id;
//
// @NotNull
// @Pattern(regexp = "^[a-z0-9]*$|(anonymousUser)")
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String login;
//
// @NotNull
// @Size(min = 60, max = 60)
// @Column(name = "password_hash")
// @JsonIgnore
// private String password;
//
// @Size(max = 50)
// @Field("first_name")
// private String firstName;
//
// @Size(max = 50)
// @Field("last_name")
// private String lastName;
//
// @NotNull
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String email;
//
// @NotNull
// private boolean activated = false;
//
// @Size(max = 20)
// @Field("activation_key")
// @JsonIgnore
// private String activationKey;
//
// @Size(max = 20)
// @Field("reset_key")
// @JsonIgnore
// private String resetKey;
//
// @Field("reset_date")
// private ZonedDateTime resetDate = null;
//
// @ManyToMany
// //@formatter:off
// @JoinTable(name = "user_role", inverseJoinColumns = {
// @JoinColumn(name = "role_name")
// }, joinColumns = {
// @JoinColumn(name = "account_id")
// }
// )
// //@formatter:on
// private Set<Authority> authorities;
// }
| import java.time.ZonedDateTime;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.jipasoft.domain.Authority;
import com.jipasoft.domain.User;
import lombok.Data; | /*
* Copyright 2016, Julius Krah
* by the @authors tag. See the LICENCE in the distribution for a
* full listing of individual contributors.
*
* 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.jipasoft.domain.dto;
/**
* Data Transfer Object for User. It is bound to the UI for validation
*
* @author Julius Krah
*
*/
@Data
public class UserDTO {
private String id;
@NotNull
@Pattern(regexp = "^[a-z0-9]*$|(anonymousUser)")
@Size(min = 1, max = 100)
private String login;
@NotNull
@Size(min = 1, max = 60)
private String password;
@NotNull
@Size(min = 1, max = 50)
private String firstName;
@NotNull
@Size(min = 1, max = 50)
private String lastName;
@Email
@NotNull
@Size(min = 1, max = 100)
private String email;
@NotNull
private boolean activated = false;
@NotNull
private String createdBy = "system";
@NotNull
private ZonedDateTime createdDate = ZonedDateTime.now();
| // Path: src/main/java/com/jipasoft/domain/Authority.java
// @Data
// @Entity
// @Document(collection = "role")
// @NoArgsConstructor
// @AllArgsConstructor
// @Table(name = "role")
// public class Authority implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @NotNull
// @org.springframework.data.annotation.Id
// @Size(min = 1, max = 50)
// private String name;
//
// }
//
// Path: src/main/java/com/jipasoft/domain/User.java
// @Data
// @Entity
// @Document(collection = "account")
// @Table(name = "account")
// @ToString(exclude = { "password", "authorities" })
// @EqualsAndHashCode(callSuper = true)
// public class User extends AbstractAuditEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @org.springframework.data.annotation.Id
// @GeneratedValue(generator = "uuid2")
// @GenericGenerator(name = "uuid2", strategy = "uuid2")
// private String id;
//
// @NotNull
// @Pattern(regexp = "^[a-z0-9]*$|(anonymousUser)")
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String login;
//
// @NotNull
// @Size(min = 60, max = 60)
// @Column(name = "password_hash")
// @JsonIgnore
// private String password;
//
// @Size(max = 50)
// @Field("first_name")
// private String firstName;
//
// @Size(max = 50)
// @Field("last_name")
// private String lastName;
//
// @NotNull
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String email;
//
// @NotNull
// private boolean activated = false;
//
// @Size(max = 20)
// @Field("activation_key")
// @JsonIgnore
// private String activationKey;
//
// @Size(max = 20)
// @Field("reset_key")
// @JsonIgnore
// private String resetKey;
//
// @Field("reset_date")
// private ZonedDateTime resetDate = null;
//
// @ManyToMany
// //@formatter:off
// @JoinTable(name = "user_role", inverseJoinColumns = {
// @JoinColumn(name = "role_name")
// }, joinColumns = {
// @JoinColumn(name = "account_id")
// }
// )
// //@formatter:on
// private Set<Authority> authorities;
// }
// Path: src/main/java/com/jipasoft/domain/dto/UserDTO.java
import java.time.ZonedDateTime;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.jipasoft.domain.Authority;
import com.jipasoft.domain.User;
import lombok.Data;
/*
* Copyright 2016, Julius Krah
* by the @authors tag. See the LICENCE in the distribution for a
* full listing of individual contributors.
*
* 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.jipasoft.domain.dto;
/**
* Data Transfer Object for User. It is bound to the UI for validation
*
* @author Julius Krah
*
*/
@Data
public class UserDTO {
private String id;
@NotNull
@Pattern(regexp = "^[a-z0-9]*$|(anonymousUser)")
@Size(min = 1, max = 100)
private String login;
@NotNull
@Size(min = 1, max = 60)
private String password;
@NotNull
@Size(min = 1, max = 50)
private String firstName;
@NotNull
@Size(min = 1, max = 50)
private String lastName;
@Email
@NotNull
@Size(min = 1, max = 100)
private String email;
@NotNull
private boolean activated = false;
@NotNull
private String createdBy = "system";
@NotNull
private ZonedDateTime createdDate = ZonedDateTime.now();
| public User createUser(PasswordEncoder encoder) { |
juliuskrah/spring-profiles | src/main/java/com/jipasoft/domain/dto/UserDTO.java | // Path: src/main/java/com/jipasoft/domain/Authority.java
// @Data
// @Entity
// @Document(collection = "role")
// @NoArgsConstructor
// @AllArgsConstructor
// @Table(name = "role")
// public class Authority implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @NotNull
// @org.springframework.data.annotation.Id
// @Size(min = 1, max = 50)
// private String name;
//
// }
//
// Path: src/main/java/com/jipasoft/domain/User.java
// @Data
// @Entity
// @Document(collection = "account")
// @Table(name = "account")
// @ToString(exclude = { "password", "authorities" })
// @EqualsAndHashCode(callSuper = true)
// public class User extends AbstractAuditEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @org.springframework.data.annotation.Id
// @GeneratedValue(generator = "uuid2")
// @GenericGenerator(name = "uuid2", strategy = "uuid2")
// private String id;
//
// @NotNull
// @Pattern(regexp = "^[a-z0-9]*$|(anonymousUser)")
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String login;
//
// @NotNull
// @Size(min = 60, max = 60)
// @Column(name = "password_hash")
// @JsonIgnore
// private String password;
//
// @Size(max = 50)
// @Field("first_name")
// private String firstName;
//
// @Size(max = 50)
// @Field("last_name")
// private String lastName;
//
// @NotNull
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String email;
//
// @NotNull
// private boolean activated = false;
//
// @Size(max = 20)
// @Field("activation_key")
// @JsonIgnore
// private String activationKey;
//
// @Size(max = 20)
// @Field("reset_key")
// @JsonIgnore
// private String resetKey;
//
// @Field("reset_date")
// private ZonedDateTime resetDate = null;
//
// @ManyToMany
// //@formatter:off
// @JoinTable(name = "user_role", inverseJoinColumns = {
// @JoinColumn(name = "role_name")
// }, joinColumns = {
// @JoinColumn(name = "account_id")
// }
// )
// //@formatter:on
// private Set<Authority> authorities;
// }
| import java.time.ZonedDateTime;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.jipasoft.domain.Authority;
import com.jipasoft.domain.User;
import lombok.Data; | private String firstName;
@NotNull
@Size(min = 1, max = 50)
private String lastName;
@Email
@NotNull
@Size(min = 1, max = 100)
private String email;
@NotNull
private boolean activated = false;
@NotNull
private String createdBy = "system";
@NotNull
private ZonedDateTime createdDate = ZonedDateTime.now();
public User createUser(PasswordEncoder encoder) {
User user = new User();
user.setLogin(login);
user.setPassword(encoder.encode(password));
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmail(email);
user.setActivated(activated);
user.setCreatedBy(createdBy);
user.setCreatedDate(createdDate); | // Path: src/main/java/com/jipasoft/domain/Authority.java
// @Data
// @Entity
// @Document(collection = "role")
// @NoArgsConstructor
// @AllArgsConstructor
// @Table(name = "role")
// public class Authority implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @NotNull
// @org.springframework.data.annotation.Id
// @Size(min = 1, max = 50)
// private String name;
//
// }
//
// Path: src/main/java/com/jipasoft/domain/User.java
// @Data
// @Entity
// @Document(collection = "account")
// @Table(name = "account")
// @ToString(exclude = { "password", "authorities" })
// @EqualsAndHashCode(callSuper = true)
// public class User extends AbstractAuditEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @org.springframework.data.annotation.Id
// @GeneratedValue(generator = "uuid2")
// @GenericGenerator(name = "uuid2", strategy = "uuid2")
// private String id;
//
// @NotNull
// @Pattern(regexp = "^[a-z0-9]*$|(anonymousUser)")
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String login;
//
// @NotNull
// @Size(min = 60, max = 60)
// @Column(name = "password_hash")
// @JsonIgnore
// private String password;
//
// @Size(max = 50)
// @Field("first_name")
// private String firstName;
//
// @Size(max = 50)
// @Field("last_name")
// private String lastName;
//
// @NotNull
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String email;
//
// @NotNull
// private boolean activated = false;
//
// @Size(max = 20)
// @Field("activation_key")
// @JsonIgnore
// private String activationKey;
//
// @Size(max = 20)
// @Field("reset_key")
// @JsonIgnore
// private String resetKey;
//
// @Field("reset_date")
// private ZonedDateTime resetDate = null;
//
// @ManyToMany
// //@formatter:off
// @JoinTable(name = "user_role", inverseJoinColumns = {
// @JoinColumn(name = "role_name")
// }, joinColumns = {
// @JoinColumn(name = "account_id")
// }
// )
// //@formatter:on
// private Set<Authority> authorities;
// }
// Path: src/main/java/com/jipasoft/domain/dto/UserDTO.java
import java.time.ZonedDateTime;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.jipasoft.domain.Authority;
import com.jipasoft.domain.User;
import lombok.Data;
private String firstName;
@NotNull
@Size(min = 1, max = 50)
private String lastName;
@Email
@NotNull
@Size(min = 1, max = 100)
private String email;
@NotNull
private boolean activated = false;
@NotNull
private String createdBy = "system";
@NotNull
private ZonedDateTime createdDate = ZonedDateTime.now();
public User createUser(PasswordEncoder encoder) {
User user = new User();
user.setLogin(login);
user.setPassword(encoder.encode(password));
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmail(email);
user.setActivated(activated);
user.setCreatedBy(createdBy);
user.setCreatedDate(createdDate); | user.setAuthorities(Stream.of(new Authority("ROLE_USER")).collect(Collectors.toSet())); |
juliuskrah/spring-profiles | src/main/java/com/jipasoft/config/Application.java | // Path: src/main/java/com/jipasoft/domain/AbstractAuditEntity.java
// @Data
// @MappedSuperclass
// public abstract class AbstractAuditEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @NotNull
// @Field("created_by")
// @Size(min = 1, max = 50)
// @Column(updatable = false)
// @CreatedBy
// private String createdBy;
//
// @Field("created_date")
// @Column(nullable = false)
// @CreatedDate
// private ZonedDateTime createdDate = ZonedDateTime.now();
//
// @Field("last_modified_by")
// @Size(max = 50)
// @LastModifiedBy
// private String lastModifiedBy;
//
// @Field("last_modified_date")
// @LastModifiedDate
// private ZonedDateTime lastModifiedDate;
// }
//
// Path: src/main/java/com/jipasoft/service/Services.java
// public interface Services {
//
// }
//
// Path: src/main/java/com/jipasoft/util/Profiles.java
// public class Profiles {
// public static final String H2 = "h2";
// public static final String POSTGRES = "postgres";
// public static final String MYSQL = "mysql";
// public static final String MONGO = "mongo";
// public static final String EMAIL = "email";
// public static final String HEROKU = "heroku";
// public static final String ASPECT = "aspect";
// }
//
// Path: src/main/java/com/jipasoft/web/Controllers.java
// public interface Controllers {
//
// }
| import java.util.Locale;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import com.github.mongobee.Mongobee;
import com.jipasoft.domain.AbstractAuditEntity;
import com.jipasoft.service.Services;
import com.jipasoft.util.Profiles;
import com.jipasoft.web.Controllers;
import com.mongodb.Mongo;
import liquibase.integration.spring.SpringLiquibase;
import lombok.extern.slf4j.Slf4j;
| /*
* Copyright 2016, Julius Krah
* by the @authors tag. See the LICENCE in the distribution for a
* full listing of individual contributors.
*
* 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.jipasoft.config;
/**
* Application root configuration. The
* {@link SpringBootApplication @SpringBootApplication} <br />
* is a convenience annotation for {@link ComponentScan @ComponentScan},
* {@link Configuration @Configuration}, and <br />
* {@link EnableAutoConfiguration @EnableAutoConfiguration}. The
* {@code scanBasePackageClasses} in this context is type safe.
* <p>
* The application can run on multiple profiles to support different types of
* databases, relational and non-relational.<br />
* In the current state, the application runs on:
* <ol>
* <li>{@link H2Config H2 Database}</li>
* <li>{@link PostgresConfig PostgreSQL Database}</li>
* <li>{@link MySQLConfig MySQL Database}</li>
* <li>{@link MongoConfig MongoDB}</li>
* </ol>
* </p>
*
* @see H2Config
* @see PostgresConfig
* @see MongoConfig
*
* @author Julius Krah
*
*/
@Slf4j
@SpringBootApplication(scanBasePackageClasses = { Controllers.class, Services.class })
@EnableConfigurationProperties({ LiquibaseProperties.class, MailProperties.class })
@EnableAspectJAutoProxy
| // Path: src/main/java/com/jipasoft/domain/AbstractAuditEntity.java
// @Data
// @MappedSuperclass
// public abstract class AbstractAuditEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @NotNull
// @Field("created_by")
// @Size(min = 1, max = 50)
// @Column(updatable = false)
// @CreatedBy
// private String createdBy;
//
// @Field("created_date")
// @Column(nullable = false)
// @CreatedDate
// private ZonedDateTime createdDate = ZonedDateTime.now();
//
// @Field("last_modified_by")
// @Size(max = 50)
// @LastModifiedBy
// private String lastModifiedBy;
//
// @Field("last_modified_date")
// @LastModifiedDate
// private ZonedDateTime lastModifiedDate;
// }
//
// Path: src/main/java/com/jipasoft/service/Services.java
// public interface Services {
//
// }
//
// Path: src/main/java/com/jipasoft/util/Profiles.java
// public class Profiles {
// public static final String H2 = "h2";
// public static final String POSTGRES = "postgres";
// public static final String MYSQL = "mysql";
// public static final String MONGO = "mongo";
// public static final String EMAIL = "email";
// public static final String HEROKU = "heroku";
// public static final String ASPECT = "aspect";
// }
//
// Path: src/main/java/com/jipasoft/web/Controllers.java
// public interface Controllers {
//
// }
// Path: src/main/java/com/jipasoft/config/Application.java
import java.util.Locale;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import com.github.mongobee.Mongobee;
import com.jipasoft.domain.AbstractAuditEntity;
import com.jipasoft.service.Services;
import com.jipasoft.util.Profiles;
import com.jipasoft.web.Controllers;
import com.mongodb.Mongo;
import liquibase.integration.spring.SpringLiquibase;
import lombok.extern.slf4j.Slf4j;
/*
* Copyright 2016, Julius Krah
* by the @authors tag. See the LICENCE in the distribution for a
* full listing of individual contributors.
*
* 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.jipasoft.config;
/**
* Application root configuration. The
* {@link SpringBootApplication @SpringBootApplication} <br />
* is a convenience annotation for {@link ComponentScan @ComponentScan},
* {@link Configuration @Configuration}, and <br />
* {@link EnableAutoConfiguration @EnableAutoConfiguration}. The
* {@code scanBasePackageClasses} in this context is type safe.
* <p>
* The application can run on multiple profiles to support different types of
* databases, relational and non-relational.<br />
* In the current state, the application runs on:
* <ol>
* <li>{@link H2Config H2 Database}</li>
* <li>{@link PostgresConfig PostgreSQL Database}</li>
* <li>{@link MySQLConfig MySQL Database}</li>
* <li>{@link MongoConfig MongoDB}</li>
* </ol>
* </p>
*
* @see H2Config
* @see PostgresConfig
* @see MongoConfig
*
* @author Julius Krah
*
*/
@Slf4j
@SpringBootApplication(scanBasePackageClasses = { Controllers.class, Services.class })
@EnableConfigurationProperties({ LiquibaseProperties.class, MailProperties.class })
@EnableAspectJAutoProxy
| @EntityScan(basePackageClasses = AbstractAuditEntity.class)
|
juliuskrah/spring-profiles | src/main/java/com/jipasoft/config/Application.java | // Path: src/main/java/com/jipasoft/domain/AbstractAuditEntity.java
// @Data
// @MappedSuperclass
// public abstract class AbstractAuditEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @NotNull
// @Field("created_by")
// @Size(min = 1, max = 50)
// @Column(updatable = false)
// @CreatedBy
// private String createdBy;
//
// @Field("created_date")
// @Column(nullable = false)
// @CreatedDate
// private ZonedDateTime createdDate = ZonedDateTime.now();
//
// @Field("last_modified_by")
// @Size(max = 50)
// @LastModifiedBy
// private String lastModifiedBy;
//
// @Field("last_modified_date")
// @LastModifiedDate
// private ZonedDateTime lastModifiedDate;
// }
//
// Path: src/main/java/com/jipasoft/service/Services.java
// public interface Services {
//
// }
//
// Path: src/main/java/com/jipasoft/util/Profiles.java
// public class Profiles {
// public static final String H2 = "h2";
// public static final String POSTGRES = "postgres";
// public static final String MYSQL = "mysql";
// public static final String MONGO = "mongo";
// public static final String EMAIL = "email";
// public static final String HEROKU = "heroku";
// public static final String ASPECT = "aspect";
// }
//
// Path: src/main/java/com/jipasoft/web/Controllers.java
// public interface Controllers {
//
// }
| import java.util.Locale;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import com.github.mongobee.Mongobee;
import com.jipasoft.domain.AbstractAuditEntity;
import com.jipasoft.service.Services;
import com.jipasoft.util.Profiles;
import com.jipasoft.web.Controllers;
import com.mongodb.Mongo;
import liquibase.integration.spring.SpringLiquibase;
import lombok.extern.slf4j.Slf4j;
| /**
* i18n bean support for switching locale through a request param. <br />
* Users who are authenticated can change their default locale to another
* when they pass in a<br />
* url (http://example.com/<contextpath>/<em>lang=<locale></em>)
*
* @return
*/
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
lci.setParamName("lang");
return lci;
}
/**
* SQL database migration. Liquibase keeps track of database changes
*
* @param dataSource
* @return
*/
@Bean
public SpringLiquibase liquibase(DataSource dataSource) {
SpringLiquibase liquibase = new SpringLiquibase();
liquibase.setDataSource(dataSource);
liquibase.setChangeLog(liquibaseProperties.getChangeLog());
liquibase.setContexts(liquibaseProperties.getContexts());
liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema());
liquibase.setDropFirst(liquibaseProperties.isDropFirst());
// When the mongo profile is active, the migration is not required
| // Path: src/main/java/com/jipasoft/domain/AbstractAuditEntity.java
// @Data
// @MappedSuperclass
// public abstract class AbstractAuditEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @NotNull
// @Field("created_by")
// @Size(min = 1, max = 50)
// @Column(updatable = false)
// @CreatedBy
// private String createdBy;
//
// @Field("created_date")
// @Column(nullable = false)
// @CreatedDate
// private ZonedDateTime createdDate = ZonedDateTime.now();
//
// @Field("last_modified_by")
// @Size(max = 50)
// @LastModifiedBy
// private String lastModifiedBy;
//
// @Field("last_modified_date")
// @LastModifiedDate
// private ZonedDateTime lastModifiedDate;
// }
//
// Path: src/main/java/com/jipasoft/service/Services.java
// public interface Services {
//
// }
//
// Path: src/main/java/com/jipasoft/util/Profiles.java
// public class Profiles {
// public static final String H2 = "h2";
// public static final String POSTGRES = "postgres";
// public static final String MYSQL = "mysql";
// public static final String MONGO = "mongo";
// public static final String EMAIL = "email";
// public static final String HEROKU = "heroku";
// public static final String ASPECT = "aspect";
// }
//
// Path: src/main/java/com/jipasoft/web/Controllers.java
// public interface Controllers {
//
// }
// Path: src/main/java/com/jipasoft/config/Application.java
import java.util.Locale;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import com.github.mongobee.Mongobee;
import com.jipasoft.domain.AbstractAuditEntity;
import com.jipasoft.service.Services;
import com.jipasoft.util.Profiles;
import com.jipasoft.web.Controllers;
import com.mongodb.Mongo;
import liquibase.integration.spring.SpringLiquibase;
import lombok.extern.slf4j.Slf4j;
/**
* i18n bean support for switching locale through a request param. <br />
* Users who are authenticated can change their default locale to another
* when they pass in a<br />
* url (http://example.com/<contextpath>/<em>lang=<locale></em>)
*
* @return
*/
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
lci.setParamName("lang");
return lci;
}
/**
* SQL database migration. Liquibase keeps track of database changes
*
* @param dataSource
* @return
*/
@Bean
public SpringLiquibase liquibase(DataSource dataSource) {
SpringLiquibase liquibase = new SpringLiquibase();
liquibase.setDataSource(dataSource);
liquibase.setChangeLog(liquibaseProperties.getChangeLog());
liquibase.setContexts(liquibaseProperties.getContexts());
liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema());
liquibase.setDropFirst(liquibaseProperties.isDropFirst());
// When the mongo profile is active, the migration is not required
| if (env.acceptsProfiles(Profiles.MONGO))
|
juliuskrah/spring-profiles | src/main/java/com/jipasoft/service/AccountService.java | // Path: src/main/java/com/jipasoft/domain/User.java
// @Data
// @Entity
// @Document(collection = "account")
// @Table(name = "account")
// @ToString(exclude = { "password", "authorities" })
// @EqualsAndHashCode(callSuper = true)
// public class User extends AbstractAuditEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @org.springframework.data.annotation.Id
// @GeneratedValue(generator = "uuid2")
// @GenericGenerator(name = "uuid2", strategy = "uuid2")
// private String id;
//
// @NotNull
// @Pattern(regexp = "^[a-z0-9]*$|(anonymousUser)")
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String login;
//
// @NotNull
// @Size(min = 60, max = 60)
// @Column(name = "password_hash")
// @JsonIgnore
// private String password;
//
// @Size(max = 50)
// @Field("first_name")
// private String firstName;
//
// @Size(max = 50)
// @Field("last_name")
// private String lastName;
//
// @NotNull
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String email;
//
// @NotNull
// private boolean activated = false;
//
// @Size(max = 20)
// @Field("activation_key")
// @JsonIgnore
// private String activationKey;
//
// @Size(max = 20)
// @Field("reset_key")
// @JsonIgnore
// private String resetKey;
//
// @Field("reset_date")
// private ZonedDateTime resetDate = null;
//
// @ManyToMany
// //@formatter:off
// @JoinTable(name = "user_role", inverseJoinColumns = {
// @JoinColumn(name = "role_name")
// }, joinColumns = {
// @JoinColumn(name = "account_id")
// }
// )
// //@formatter:on
// private Set<Authority> authorities;
// }
| import java.util.List;
import java.util.Optional;
import com.jipasoft.domain.User; | /*
* Copyright 2016, Julius Krah
* by the @authors tag. See the LICENCE in the distribution for a
* full listing of individual contributors.
*
* 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.jipasoft.service;
/**
* Contains service methods for the management of User accounts
*
* @author Julius Krah
*
*/
public interface AccountService {
/**
* This is a utility method to drop all accounts in the database
*/
public void deleteAllAccounts();
/**
* Detaches a User entity from the current persistence context
*
* @param user
* the User entity to detach
*/ | // Path: src/main/java/com/jipasoft/domain/User.java
// @Data
// @Entity
// @Document(collection = "account")
// @Table(name = "account")
// @ToString(exclude = { "password", "authorities" })
// @EqualsAndHashCode(callSuper = true)
// public class User extends AbstractAuditEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @org.springframework.data.annotation.Id
// @GeneratedValue(generator = "uuid2")
// @GenericGenerator(name = "uuid2", strategy = "uuid2")
// private String id;
//
// @NotNull
// @Pattern(regexp = "^[a-z0-9]*$|(anonymousUser)")
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String login;
//
// @NotNull
// @Size(min = 60, max = 60)
// @Column(name = "password_hash")
// @JsonIgnore
// private String password;
//
// @Size(max = 50)
// @Field("first_name")
// private String firstName;
//
// @Size(max = 50)
// @Field("last_name")
// private String lastName;
//
// @NotNull
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String email;
//
// @NotNull
// private boolean activated = false;
//
// @Size(max = 20)
// @Field("activation_key")
// @JsonIgnore
// private String activationKey;
//
// @Size(max = 20)
// @Field("reset_key")
// @JsonIgnore
// private String resetKey;
//
// @Field("reset_date")
// private ZonedDateTime resetDate = null;
//
// @ManyToMany
// //@formatter:off
// @JoinTable(name = "user_role", inverseJoinColumns = {
// @JoinColumn(name = "role_name")
// }, joinColumns = {
// @JoinColumn(name = "account_id")
// }
// )
// //@formatter:on
// private Set<Authority> authorities;
// }
// Path: src/main/java/com/jipasoft/service/AccountService.java
import java.util.List;
import java.util.Optional;
import com.jipasoft.domain.User;
/*
* Copyright 2016, Julius Krah
* by the @authors tag. See the LICENCE in the distribution for a
* full listing of individual contributors.
*
* 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.jipasoft.service;
/**
* Contains service methods for the management of User accounts
*
* @author Julius Krah
*
*/
public interface AccountService {
/**
* This is a utility method to drop all accounts in the database
*/
public void deleteAllAccounts();
/**
* Detaches a User entity from the current persistence context
*
* @param user
* the User entity to detach
*/ | public void deleteAccount(User user); |
juliuskrah/spring-profiles | src/test/java/com/jipasoft/repository/UserRepositoryTests.java | // Path: src/test/java/com/jipasoft/config/ApplicationTests.java
// @RunWith(SpringRunner.class)
// @SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.NONE)
// public class ApplicationTests {
//
// @Test
// public void contextsLoad() {
//
// }
// }
//
// Path: src/main/java/com/jipasoft/domain/Authority.java
// @Data
// @Entity
// @Document(collection = "role")
// @NoArgsConstructor
// @AllArgsConstructor
// @Table(name = "role")
// public class Authority implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @NotNull
// @org.springframework.data.annotation.Id
// @Size(min = 1, max = 50)
// private String name;
//
// }
//
// Path: src/main/java/com/jipasoft/domain/User.java
// @Data
// @Entity
// @Document(collection = "account")
// @Table(name = "account")
// @ToString(exclude = { "password", "authorities" })
// @EqualsAndHashCode(callSuper = true)
// public class User extends AbstractAuditEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @org.springframework.data.annotation.Id
// @GeneratedValue(generator = "uuid2")
// @GenericGenerator(name = "uuid2", strategy = "uuid2")
// private String id;
//
// @NotNull
// @Pattern(regexp = "^[a-z0-9]*$|(anonymousUser)")
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String login;
//
// @NotNull
// @Size(min = 60, max = 60)
// @Column(name = "password_hash")
// @JsonIgnore
// private String password;
//
// @Size(max = 50)
// @Field("first_name")
// private String firstName;
//
// @Size(max = 50)
// @Field("last_name")
// private String lastName;
//
// @NotNull
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String email;
//
// @NotNull
// private boolean activated = false;
//
// @Size(max = 20)
// @Field("activation_key")
// @JsonIgnore
// private String activationKey;
//
// @Size(max = 20)
// @Field("reset_key")
// @JsonIgnore
// private String resetKey;
//
// @Field("reset_date")
// private ZonedDateTime resetDate = null;
//
// @ManyToMany
// //@formatter:off
// @JoinTable(name = "user_role", inverseJoinColumns = {
// @JoinColumn(name = "role_name")
// }, joinColumns = {
// @JoinColumn(name = "account_id")
// }
// )
// //@formatter:on
// private Set<Authority> authorities;
// }
//
// Path: src/main/java/com/jipasoft/util/Profiles.java
// public class Profiles {
// public static final String H2 = "h2";
// public static final String POSTGRES = "postgres";
// public static final String MYSQL = "mysql";
// public static final String MONGO = "mongo";
// public static final String EMAIL = "email";
// public static final String HEROKU = "heroku";
// public static final String ASPECT = "aspect";
// }
| import com.jipasoft.domain.Authority;
import com.jipasoft.domain.User;
import com.jipasoft.util.Profiles;
import lombok.extern.slf4j.Slf4j;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import java.time.ZonedDateTime;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.transaction.annotation.Transactional;
import com.jipasoft.config.ApplicationTests; | /*
* Copyright 2016, Julius Krah
* by the @authors tag. See the LICENCE in the distribution for a
* full listing of individual contributors.
*
* 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.jipasoft.repository;
@Slf4j
@ActiveProfiles(Profiles.H2)
@Transactional | // Path: src/test/java/com/jipasoft/config/ApplicationTests.java
// @RunWith(SpringRunner.class)
// @SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.NONE)
// public class ApplicationTests {
//
// @Test
// public void contextsLoad() {
//
// }
// }
//
// Path: src/main/java/com/jipasoft/domain/Authority.java
// @Data
// @Entity
// @Document(collection = "role")
// @NoArgsConstructor
// @AllArgsConstructor
// @Table(name = "role")
// public class Authority implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @NotNull
// @org.springframework.data.annotation.Id
// @Size(min = 1, max = 50)
// private String name;
//
// }
//
// Path: src/main/java/com/jipasoft/domain/User.java
// @Data
// @Entity
// @Document(collection = "account")
// @Table(name = "account")
// @ToString(exclude = { "password", "authorities" })
// @EqualsAndHashCode(callSuper = true)
// public class User extends AbstractAuditEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @org.springframework.data.annotation.Id
// @GeneratedValue(generator = "uuid2")
// @GenericGenerator(name = "uuid2", strategy = "uuid2")
// private String id;
//
// @NotNull
// @Pattern(regexp = "^[a-z0-9]*$|(anonymousUser)")
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String login;
//
// @NotNull
// @Size(min = 60, max = 60)
// @Column(name = "password_hash")
// @JsonIgnore
// private String password;
//
// @Size(max = 50)
// @Field("first_name")
// private String firstName;
//
// @Size(max = 50)
// @Field("last_name")
// private String lastName;
//
// @NotNull
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String email;
//
// @NotNull
// private boolean activated = false;
//
// @Size(max = 20)
// @Field("activation_key")
// @JsonIgnore
// private String activationKey;
//
// @Size(max = 20)
// @Field("reset_key")
// @JsonIgnore
// private String resetKey;
//
// @Field("reset_date")
// private ZonedDateTime resetDate = null;
//
// @ManyToMany
// //@formatter:off
// @JoinTable(name = "user_role", inverseJoinColumns = {
// @JoinColumn(name = "role_name")
// }, joinColumns = {
// @JoinColumn(name = "account_id")
// }
// )
// //@formatter:on
// private Set<Authority> authorities;
// }
//
// Path: src/main/java/com/jipasoft/util/Profiles.java
// public class Profiles {
// public static final String H2 = "h2";
// public static final String POSTGRES = "postgres";
// public static final String MYSQL = "mysql";
// public static final String MONGO = "mongo";
// public static final String EMAIL = "email";
// public static final String HEROKU = "heroku";
// public static final String ASPECT = "aspect";
// }
// Path: src/test/java/com/jipasoft/repository/UserRepositoryTests.java
import com.jipasoft.domain.Authority;
import com.jipasoft.domain.User;
import com.jipasoft.util.Profiles;
import lombok.extern.slf4j.Slf4j;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import java.time.ZonedDateTime;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.transaction.annotation.Transactional;
import com.jipasoft.config.ApplicationTests;
/*
* Copyright 2016, Julius Krah
* by the @authors tag. See the LICENCE in the distribution for a
* full listing of individual contributors.
*
* 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.jipasoft.repository;
@Slf4j
@ActiveProfiles(Profiles.H2)
@Transactional | public class UserRepositoryTests extends ApplicationTests { |
juliuskrah/spring-profiles | src/test/java/com/jipasoft/repository/UserRepositoryTests.java | // Path: src/test/java/com/jipasoft/config/ApplicationTests.java
// @RunWith(SpringRunner.class)
// @SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.NONE)
// public class ApplicationTests {
//
// @Test
// public void contextsLoad() {
//
// }
// }
//
// Path: src/main/java/com/jipasoft/domain/Authority.java
// @Data
// @Entity
// @Document(collection = "role")
// @NoArgsConstructor
// @AllArgsConstructor
// @Table(name = "role")
// public class Authority implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @NotNull
// @org.springframework.data.annotation.Id
// @Size(min = 1, max = 50)
// private String name;
//
// }
//
// Path: src/main/java/com/jipasoft/domain/User.java
// @Data
// @Entity
// @Document(collection = "account")
// @Table(name = "account")
// @ToString(exclude = { "password", "authorities" })
// @EqualsAndHashCode(callSuper = true)
// public class User extends AbstractAuditEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @org.springframework.data.annotation.Id
// @GeneratedValue(generator = "uuid2")
// @GenericGenerator(name = "uuid2", strategy = "uuid2")
// private String id;
//
// @NotNull
// @Pattern(regexp = "^[a-z0-9]*$|(anonymousUser)")
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String login;
//
// @NotNull
// @Size(min = 60, max = 60)
// @Column(name = "password_hash")
// @JsonIgnore
// private String password;
//
// @Size(max = 50)
// @Field("first_name")
// private String firstName;
//
// @Size(max = 50)
// @Field("last_name")
// private String lastName;
//
// @NotNull
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String email;
//
// @NotNull
// private boolean activated = false;
//
// @Size(max = 20)
// @Field("activation_key")
// @JsonIgnore
// private String activationKey;
//
// @Size(max = 20)
// @Field("reset_key")
// @JsonIgnore
// private String resetKey;
//
// @Field("reset_date")
// private ZonedDateTime resetDate = null;
//
// @ManyToMany
// //@formatter:off
// @JoinTable(name = "user_role", inverseJoinColumns = {
// @JoinColumn(name = "role_name")
// }, joinColumns = {
// @JoinColumn(name = "account_id")
// }
// )
// //@formatter:on
// private Set<Authority> authorities;
// }
//
// Path: src/main/java/com/jipasoft/util/Profiles.java
// public class Profiles {
// public static final String H2 = "h2";
// public static final String POSTGRES = "postgres";
// public static final String MYSQL = "mysql";
// public static final String MONGO = "mongo";
// public static final String EMAIL = "email";
// public static final String HEROKU = "heroku";
// public static final String ASPECT = "aspect";
// }
| import com.jipasoft.domain.Authority;
import com.jipasoft.domain.User;
import com.jipasoft.util.Profiles;
import lombok.extern.slf4j.Slf4j;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import java.time.ZonedDateTime;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.transaction.annotation.Transactional;
import com.jipasoft.config.ApplicationTests; | /*
* Copyright 2016, Julius Krah
* by the @authors tag. See the LICENCE in the distribution for a
* full listing of individual contributors.
*
* 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.jipasoft.repository;
@Slf4j
@ActiveProfiles(Profiles.H2)
@Transactional
public class UserRepositoryTests extends ApplicationTests {
@Autowired
private UserRepository userRepository;
@Before
public void setUp() {
userRepository.deleteAll();
| // Path: src/test/java/com/jipasoft/config/ApplicationTests.java
// @RunWith(SpringRunner.class)
// @SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.NONE)
// public class ApplicationTests {
//
// @Test
// public void contextsLoad() {
//
// }
// }
//
// Path: src/main/java/com/jipasoft/domain/Authority.java
// @Data
// @Entity
// @Document(collection = "role")
// @NoArgsConstructor
// @AllArgsConstructor
// @Table(name = "role")
// public class Authority implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @NotNull
// @org.springframework.data.annotation.Id
// @Size(min = 1, max = 50)
// private String name;
//
// }
//
// Path: src/main/java/com/jipasoft/domain/User.java
// @Data
// @Entity
// @Document(collection = "account")
// @Table(name = "account")
// @ToString(exclude = { "password", "authorities" })
// @EqualsAndHashCode(callSuper = true)
// public class User extends AbstractAuditEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @org.springframework.data.annotation.Id
// @GeneratedValue(generator = "uuid2")
// @GenericGenerator(name = "uuid2", strategy = "uuid2")
// private String id;
//
// @NotNull
// @Pattern(regexp = "^[a-z0-9]*$|(anonymousUser)")
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String login;
//
// @NotNull
// @Size(min = 60, max = 60)
// @Column(name = "password_hash")
// @JsonIgnore
// private String password;
//
// @Size(max = 50)
// @Field("first_name")
// private String firstName;
//
// @Size(max = 50)
// @Field("last_name")
// private String lastName;
//
// @NotNull
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String email;
//
// @NotNull
// private boolean activated = false;
//
// @Size(max = 20)
// @Field("activation_key")
// @JsonIgnore
// private String activationKey;
//
// @Size(max = 20)
// @Field("reset_key")
// @JsonIgnore
// private String resetKey;
//
// @Field("reset_date")
// private ZonedDateTime resetDate = null;
//
// @ManyToMany
// //@formatter:off
// @JoinTable(name = "user_role", inverseJoinColumns = {
// @JoinColumn(name = "role_name")
// }, joinColumns = {
// @JoinColumn(name = "account_id")
// }
// )
// //@formatter:on
// private Set<Authority> authorities;
// }
//
// Path: src/main/java/com/jipasoft/util/Profiles.java
// public class Profiles {
// public static final String H2 = "h2";
// public static final String POSTGRES = "postgres";
// public static final String MYSQL = "mysql";
// public static final String MONGO = "mongo";
// public static final String EMAIL = "email";
// public static final String HEROKU = "heroku";
// public static final String ASPECT = "aspect";
// }
// Path: src/test/java/com/jipasoft/repository/UserRepositoryTests.java
import com.jipasoft.domain.Authority;
import com.jipasoft.domain.User;
import com.jipasoft.util.Profiles;
import lombok.extern.slf4j.Slf4j;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import java.time.ZonedDateTime;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.transaction.annotation.Transactional;
import com.jipasoft.config.ApplicationTests;
/*
* Copyright 2016, Julius Krah
* by the @authors tag. See the LICENCE in the distribution for a
* full listing of individual contributors.
*
* 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.jipasoft.repository;
@Slf4j
@ActiveProfiles(Profiles.H2)
@Transactional
public class UserRepositoryTests extends ApplicationTests {
@Autowired
private UserRepository userRepository;
@Before
public void setUp() {
userRepository.deleteAll();
| User user = new User(); |
juliuskrah/spring-profiles | src/test/java/com/jipasoft/repository/UserRepositoryTests.java | // Path: src/test/java/com/jipasoft/config/ApplicationTests.java
// @RunWith(SpringRunner.class)
// @SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.NONE)
// public class ApplicationTests {
//
// @Test
// public void contextsLoad() {
//
// }
// }
//
// Path: src/main/java/com/jipasoft/domain/Authority.java
// @Data
// @Entity
// @Document(collection = "role")
// @NoArgsConstructor
// @AllArgsConstructor
// @Table(name = "role")
// public class Authority implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @NotNull
// @org.springframework.data.annotation.Id
// @Size(min = 1, max = 50)
// private String name;
//
// }
//
// Path: src/main/java/com/jipasoft/domain/User.java
// @Data
// @Entity
// @Document(collection = "account")
// @Table(name = "account")
// @ToString(exclude = { "password", "authorities" })
// @EqualsAndHashCode(callSuper = true)
// public class User extends AbstractAuditEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @org.springframework.data.annotation.Id
// @GeneratedValue(generator = "uuid2")
// @GenericGenerator(name = "uuid2", strategy = "uuid2")
// private String id;
//
// @NotNull
// @Pattern(regexp = "^[a-z0-9]*$|(anonymousUser)")
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String login;
//
// @NotNull
// @Size(min = 60, max = 60)
// @Column(name = "password_hash")
// @JsonIgnore
// private String password;
//
// @Size(max = 50)
// @Field("first_name")
// private String firstName;
//
// @Size(max = 50)
// @Field("last_name")
// private String lastName;
//
// @NotNull
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String email;
//
// @NotNull
// private boolean activated = false;
//
// @Size(max = 20)
// @Field("activation_key")
// @JsonIgnore
// private String activationKey;
//
// @Size(max = 20)
// @Field("reset_key")
// @JsonIgnore
// private String resetKey;
//
// @Field("reset_date")
// private ZonedDateTime resetDate = null;
//
// @ManyToMany
// //@formatter:off
// @JoinTable(name = "user_role", inverseJoinColumns = {
// @JoinColumn(name = "role_name")
// }, joinColumns = {
// @JoinColumn(name = "account_id")
// }
// )
// //@formatter:on
// private Set<Authority> authorities;
// }
//
// Path: src/main/java/com/jipasoft/util/Profiles.java
// public class Profiles {
// public static final String H2 = "h2";
// public static final String POSTGRES = "postgres";
// public static final String MYSQL = "mysql";
// public static final String MONGO = "mongo";
// public static final String EMAIL = "email";
// public static final String HEROKU = "heroku";
// public static final String ASPECT = "aspect";
// }
| import com.jipasoft.domain.Authority;
import com.jipasoft.domain.User;
import com.jipasoft.util.Profiles;
import lombok.extern.slf4j.Slf4j;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import java.time.ZonedDateTime;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.transaction.annotation.Transactional;
import com.jipasoft.config.ApplicationTests; | /*
* Copyright 2016, Julius Krah
* by the @authors tag. See the LICENCE in the distribution for a
* full listing of individual contributors.
*
* 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.jipasoft.repository;
@Slf4j
@ActiveProfiles(Profiles.H2)
@Transactional
public class UserRepositoryTests extends ApplicationTests {
@Autowired
private UserRepository userRepository;
@Before
public void setUp() {
userRepository.deleteAll();
User user = new User();
user.setEmail("juliuskrah@gmail.com");
user.setLogin("julius");
user.setResetKey("aw55asa7d5Sdcs8dAsa8");
user.setCreatedBy("system");
user.setPassword("$2a$10$mE.qmcV0mFU5NcKh73TZx.z4ueI/.bDWbj0T1BYyqP481kGGarKLG"); | // Path: src/test/java/com/jipasoft/config/ApplicationTests.java
// @RunWith(SpringRunner.class)
// @SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.NONE)
// public class ApplicationTests {
//
// @Test
// public void contextsLoad() {
//
// }
// }
//
// Path: src/main/java/com/jipasoft/domain/Authority.java
// @Data
// @Entity
// @Document(collection = "role")
// @NoArgsConstructor
// @AllArgsConstructor
// @Table(name = "role")
// public class Authority implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @NotNull
// @org.springframework.data.annotation.Id
// @Size(min = 1, max = 50)
// private String name;
//
// }
//
// Path: src/main/java/com/jipasoft/domain/User.java
// @Data
// @Entity
// @Document(collection = "account")
// @Table(name = "account")
// @ToString(exclude = { "password", "authorities" })
// @EqualsAndHashCode(callSuper = true)
// public class User extends AbstractAuditEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @org.springframework.data.annotation.Id
// @GeneratedValue(generator = "uuid2")
// @GenericGenerator(name = "uuid2", strategy = "uuid2")
// private String id;
//
// @NotNull
// @Pattern(regexp = "^[a-z0-9]*$|(anonymousUser)")
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String login;
//
// @NotNull
// @Size(min = 60, max = 60)
// @Column(name = "password_hash")
// @JsonIgnore
// private String password;
//
// @Size(max = 50)
// @Field("first_name")
// private String firstName;
//
// @Size(max = 50)
// @Field("last_name")
// private String lastName;
//
// @NotNull
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String email;
//
// @NotNull
// private boolean activated = false;
//
// @Size(max = 20)
// @Field("activation_key")
// @JsonIgnore
// private String activationKey;
//
// @Size(max = 20)
// @Field("reset_key")
// @JsonIgnore
// private String resetKey;
//
// @Field("reset_date")
// private ZonedDateTime resetDate = null;
//
// @ManyToMany
// //@formatter:off
// @JoinTable(name = "user_role", inverseJoinColumns = {
// @JoinColumn(name = "role_name")
// }, joinColumns = {
// @JoinColumn(name = "account_id")
// }
// )
// //@formatter:on
// private Set<Authority> authorities;
// }
//
// Path: src/main/java/com/jipasoft/util/Profiles.java
// public class Profiles {
// public static final String H2 = "h2";
// public static final String POSTGRES = "postgres";
// public static final String MYSQL = "mysql";
// public static final String MONGO = "mongo";
// public static final String EMAIL = "email";
// public static final String HEROKU = "heroku";
// public static final String ASPECT = "aspect";
// }
// Path: src/test/java/com/jipasoft/repository/UserRepositoryTests.java
import com.jipasoft.domain.Authority;
import com.jipasoft.domain.User;
import com.jipasoft.util.Profiles;
import lombok.extern.slf4j.Slf4j;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import java.time.ZonedDateTime;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.transaction.annotation.Transactional;
import com.jipasoft.config.ApplicationTests;
/*
* Copyright 2016, Julius Krah
* by the @authors tag. See the LICENCE in the distribution for a
* full listing of individual contributors.
*
* 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.jipasoft.repository;
@Slf4j
@ActiveProfiles(Profiles.H2)
@Transactional
public class UserRepositoryTests extends ApplicationTests {
@Autowired
private UserRepository userRepository;
@Before
public void setUp() {
userRepository.deleteAll();
User user = new User();
user.setEmail("juliuskrah@gmail.com");
user.setLogin("julius");
user.setResetKey("aw55asa7d5Sdcs8dAsa8");
user.setCreatedBy("system");
user.setPassword("$2a$10$mE.qmcV0mFU5NcKh73TZx.z4ueI/.bDWbj0T1BYyqP481kGGarKLG"); | user.setAuthorities(Stream.of(new Authority("ROLE_ADMIN"), new Authority("ROLE_USER")).collect(Collectors.toSet())); |
juliuskrah/spring-profiles | src/main/java/com/jipasoft/service/Impl/UserDetailsServiceImpl.java | // Path: src/main/java/com/jipasoft/domain/User.java
// @Data
// @Entity
// @Document(collection = "account")
// @Table(name = "account")
// @ToString(exclude = { "password", "authorities" })
// @EqualsAndHashCode(callSuper = true)
// public class User extends AbstractAuditEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @org.springframework.data.annotation.Id
// @GeneratedValue(generator = "uuid2")
// @GenericGenerator(name = "uuid2", strategy = "uuid2")
// private String id;
//
// @NotNull
// @Pattern(regexp = "^[a-z0-9]*$|(anonymousUser)")
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String login;
//
// @NotNull
// @Size(min = 60, max = 60)
// @Column(name = "password_hash")
// @JsonIgnore
// private String password;
//
// @Size(max = 50)
// @Field("first_name")
// private String firstName;
//
// @Size(max = 50)
// @Field("last_name")
// private String lastName;
//
// @NotNull
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String email;
//
// @NotNull
// private boolean activated = false;
//
// @Size(max = 20)
// @Field("activation_key")
// @JsonIgnore
// private String activationKey;
//
// @Size(max = 20)
// @Field("reset_key")
// @JsonIgnore
// private String resetKey;
//
// @Field("reset_date")
// private ZonedDateTime resetDate = null;
//
// @ManyToMany
// //@formatter:off
// @JoinTable(name = "user_role", inverseJoinColumns = {
// @JoinColumn(name = "role_name")
// }, joinColumns = {
// @JoinColumn(name = "account_id")
// }
// )
// //@formatter:on
// private Set<Authority> authorities;
// }
//
// Path: src/main/java/com/jipasoft/exception/AccountNotActivatedException.java
// public class AccountNotActivatedException extends AuthenticationException {
//
// private static final long serialVersionUID = 8415982426813000504L;
//
// public AccountNotActivatedException(String message) {
// super(message);
// }
//
// public AccountNotActivatedException(String message, Throwable t) {
// super(message, t);
// }
// }
//
// Path: src/main/java/com/jipasoft/repository/UserRepository.java
// @NoRepositoryBean
// public interface UserRepository extends BaseRepository<User, String> {
//
// /**
// * Retrieves a {@link User} entity from the underlying datastore by its
// * ResetKey
// *
// * @param resetKey
// * the resetKey
// * @return a User entity
// * @see User#getResetKey()
// */
// public Optional<User> findOneByResetKey(String resetKey);
//
// /**
// * Retrieves a {@link User} entity from the underlying datastore by its
// * Email
// *
// * @param email
// * the User's email
// * @return a User entity
// * @see User#getEmail()
// */
// public Optional<User> findOneByEmail(String email);
//
// /**
// * Retrieves a {@link User} entity from the underlying datastore by its
// * login
// *
// * @param login
// * the username
// * @return a User entity
// * @see User#getLogin()
// */
// public Optional<User> findOneByLogin(String login);
//
// }
| import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Provider;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.jipasoft.domain.User;
import com.jipasoft.exception.AccountNotActivatedException;
import com.jipasoft.repository.UserRepository;
import lombok.extern.slf4j.Slf4j; | package com.jipasoft.service.Impl;
@Slf4j
@Service
@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService {
@Inject | // Path: src/main/java/com/jipasoft/domain/User.java
// @Data
// @Entity
// @Document(collection = "account")
// @Table(name = "account")
// @ToString(exclude = { "password", "authorities" })
// @EqualsAndHashCode(callSuper = true)
// public class User extends AbstractAuditEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @org.springframework.data.annotation.Id
// @GeneratedValue(generator = "uuid2")
// @GenericGenerator(name = "uuid2", strategy = "uuid2")
// private String id;
//
// @NotNull
// @Pattern(regexp = "^[a-z0-9]*$|(anonymousUser)")
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String login;
//
// @NotNull
// @Size(min = 60, max = 60)
// @Column(name = "password_hash")
// @JsonIgnore
// private String password;
//
// @Size(max = 50)
// @Field("first_name")
// private String firstName;
//
// @Size(max = 50)
// @Field("last_name")
// private String lastName;
//
// @NotNull
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String email;
//
// @NotNull
// private boolean activated = false;
//
// @Size(max = 20)
// @Field("activation_key")
// @JsonIgnore
// private String activationKey;
//
// @Size(max = 20)
// @Field("reset_key")
// @JsonIgnore
// private String resetKey;
//
// @Field("reset_date")
// private ZonedDateTime resetDate = null;
//
// @ManyToMany
// //@formatter:off
// @JoinTable(name = "user_role", inverseJoinColumns = {
// @JoinColumn(name = "role_name")
// }, joinColumns = {
// @JoinColumn(name = "account_id")
// }
// )
// //@formatter:on
// private Set<Authority> authorities;
// }
//
// Path: src/main/java/com/jipasoft/exception/AccountNotActivatedException.java
// public class AccountNotActivatedException extends AuthenticationException {
//
// private static final long serialVersionUID = 8415982426813000504L;
//
// public AccountNotActivatedException(String message) {
// super(message);
// }
//
// public AccountNotActivatedException(String message, Throwable t) {
// super(message, t);
// }
// }
//
// Path: src/main/java/com/jipasoft/repository/UserRepository.java
// @NoRepositoryBean
// public interface UserRepository extends BaseRepository<User, String> {
//
// /**
// * Retrieves a {@link User} entity from the underlying datastore by its
// * ResetKey
// *
// * @param resetKey
// * the resetKey
// * @return a User entity
// * @see User#getResetKey()
// */
// public Optional<User> findOneByResetKey(String resetKey);
//
// /**
// * Retrieves a {@link User} entity from the underlying datastore by its
// * Email
// *
// * @param email
// * the User's email
// * @return a User entity
// * @see User#getEmail()
// */
// public Optional<User> findOneByEmail(String email);
//
// /**
// * Retrieves a {@link User} entity from the underlying datastore by its
// * login
// *
// * @param login
// * the username
// * @return a User entity
// * @see User#getLogin()
// */
// public Optional<User> findOneByLogin(String login);
//
// }
// Path: src/main/java/com/jipasoft/service/Impl/UserDetailsServiceImpl.java
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Provider;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.jipasoft.domain.User;
import com.jipasoft.exception.AccountNotActivatedException;
import com.jipasoft.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
package com.jipasoft.service.Impl;
@Slf4j
@Service
@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService {
@Inject | private Provider<UserRepository> userRepositoryProvider; |
juliuskrah/spring-profiles | src/main/java/com/jipasoft/service/Impl/UserDetailsServiceImpl.java | // Path: src/main/java/com/jipasoft/domain/User.java
// @Data
// @Entity
// @Document(collection = "account")
// @Table(name = "account")
// @ToString(exclude = { "password", "authorities" })
// @EqualsAndHashCode(callSuper = true)
// public class User extends AbstractAuditEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @org.springframework.data.annotation.Id
// @GeneratedValue(generator = "uuid2")
// @GenericGenerator(name = "uuid2", strategy = "uuid2")
// private String id;
//
// @NotNull
// @Pattern(regexp = "^[a-z0-9]*$|(anonymousUser)")
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String login;
//
// @NotNull
// @Size(min = 60, max = 60)
// @Column(name = "password_hash")
// @JsonIgnore
// private String password;
//
// @Size(max = 50)
// @Field("first_name")
// private String firstName;
//
// @Size(max = 50)
// @Field("last_name")
// private String lastName;
//
// @NotNull
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String email;
//
// @NotNull
// private boolean activated = false;
//
// @Size(max = 20)
// @Field("activation_key")
// @JsonIgnore
// private String activationKey;
//
// @Size(max = 20)
// @Field("reset_key")
// @JsonIgnore
// private String resetKey;
//
// @Field("reset_date")
// private ZonedDateTime resetDate = null;
//
// @ManyToMany
// //@formatter:off
// @JoinTable(name = "user_role", inverseJoinColumns = {
// @JoinColumn(name = "role_name")
// }, joinColumns = {
// @JoinColumn(name = "account_id")
// }
// )
// //@formatter:on
// private Set<Authority> authorities;
// }
//
// Path: src/main/java/com/jipasoft/exception/AccountNotActivatedException.java
// public class AccountNotActivatedException extends AuthenticationException {
//
// private static final long serialVersionUID = 8415982426813000504L;
//
// public AccountNotActivatedException(String message) {
// super(message);
// }
//
// public AccountNotActivatedException(String message, Throwable t) {
// super(message, t);
// }
// }
//
// Path: src/main/java/com/jipasoft/repository/UserRepository.java
// @NoRepositoryBean
// public interface UserRepository extends BaseRepository<User, String> {
//
// /**
// * Retrieves a {@link User} entity from the underlying datastore by its
// * ResetKey
// *
// * @param resetKey
// * the resetKey
// * @return a User entity
// * @see User#getResetKey()
// */
// public Optional<User> findOneByResetKey(String resetKey);
//
// /**
// * Retrieves a {@link User} entity from the underlying datastore by its
// * Email
// *
// * @param email
// * the User's email
// * @return a User entity
// * @see User#getEmail()
// */
// public Optional<User> findOneByEmail(String email);
//
// /**
// * Retrieves a {@link User} entity from the underlying datastore by its
// * login
// *
// * @param login
// * the username
// * @return a User entity
// * @see User#getLogin()
// */
// public Optional<User> findOneByLogin(String login);
//
// }
| import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Provider;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.jipasoft.domain.User;
import com.jipasoft.exception.AccountNotActivatedException;
import com.jipasoft.repository.UserRepository;
import lombok.extern.slf4j.Slf4j; | package com.jipasoft.service.Impl;
@Slf4j
@Service
@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService {
@Inject
private Provider<UserRepository> userRepositoryProvider;
@Override | // Path: src/main/java/com/jipasoft/domain/User.java
// @Data
// @Entity
// @Document(collection = "account")
// @Table(name = "account")
// @ToString(exclude = { "password", "authorities" })
// @EqualsAndHashCode(callSuper = true)
// public class User extends AbstractAuditEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @org.springframework.data.annotation.Id
// @GeneratedValue(generator = "uuid2")
// @GenericGenerator(name = "uuid2", strategy = "uuid2")
// private String id;
//
// @NotNull
// @Pattern(regexp = "^[a-z0-9]*$|(anonymousUser)")
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String login;
//
// @NotNull
// @Size(min = 60, max = 60)
// @Column(name = "password_hash")
// @JsonIgnore
// private String password;
//
// @Size(max = 50)
// @Field("first_name")
// private String firstName;
//
// @Size(max = 50)
// @Field("last_name")
// private String lastName;
//
// @NotNull
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String email;
//
// @NotNull
// private boolean activated = false;
//
// @Size(max = 20)
// @Field("activation_key")
// @JsonIgnore
// private String activationKey;
//
// @Size(max = 20)
// @Field("reset_key")
// @JsonIgnore
// private String resetKey;
//
// @Field("reset_date")
// private ZonedDateTime resetDate = null;
//
// @ManyToMany
// //@formatter:off
// @JoinTable(name = "user_role", inverseJoinColumns = {
// @JoinColumn(name = "role_name")
// }, joinColumns = {
// @JoinColumn(name = "account_id")
// }
// )
// //@formatter:on
// private Set<Authority> authorities;
// }
//
// Path: src/main/java/com/jipasoft/exception/AccountNotActivatedException.java
// public class AccountNotActivatedException extends AuthenticationException {
//
// private static final long serialVersionUID = 8415982426813000504L;
//
// public AccountNotActivatedException(String message) {
// super(message);
// }
//
// public AccountNotActivatedException(String message, Throwable t) {
// super(message, t);
// }
// }
//
// Path: src/main/java/com/jipasoft/repository/UserRepository.java
// @NoRepositoryBean
// public interface UserRepository extends BaseRepository<User, String> {
//
// /**
// * Retrieves a {@link User} entity from the underlying datastore by its
// * ResetKey
// *
// * @param resetKey
// * the resetKey
// * @return a User entity
// * @see User#getResetKey()
// */
// public Optional<User> findOneByResetKey(String resetKey);
//
// /**
// * Retrieves a {@link User} entity from the underlying datastore by its
// * Email
// *
// * @param email
// * the User's email
// * @return a User entity
// * @see User#getEmail()
// */
// public Optional<User> findOneByEmail(String email);
//
// /**
// * Retrieves a {@link User} entity from the underlying datastore by its
// * login
// *
// * @param login
// * the username
// * @return a User entity
// * @see User#getLogin()
// */
// public Optional<User> findOneByLogin(String login);
//
// }
// Path: src/main/java/com/jipasoft/service/Impl/UserDetailsServiceImpl.java
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Provider;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.jipasoft.domain.User;
import com.jipasoft.exception.AccountNotActivatedException;
import com.jipasoft.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
package com.jipasoft.service.Impl;
@Slf4j
@Service
@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService {
@Inject
private Provider<UserRepository> userRepositoryProvider;
@Override | public UserDetails loadUserByUsername(final String login) throws UsernameNotFoundException, AccountNotActivatedException { |
juliuskrah/spring-profiles | src/main/java/com/jipasoft/service/Impl/UserDetailsServiceImpl.java | // Path: src/main/java/com/jipasoft/domain/User.java
// @Data
// @Entity
// @Document(collection = "account")
// @Table(name = "account")
// @ToString(exclude = { "password", "authorities" })
// @EqualsAndHashCode(callSuper = true)
// public class User extends AbstractAuditEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @org.springframework.data.annotation.Id
// @GeneratedValue(generator = "uuid2")
// @GenericGenerator(name = "uuid2", strategy = "uuid2")
// private String id;
//
// @NotNull
// @Pattern(regexp = "^[a-z0-9]*$|(anonymousUser)")
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String login;
//
// @NotNull
// @Size(min = 60, max = 60)
// @Column(name = "password_hash")
// @JsonIgnore
// private String password;
//
// @Size(max = 50)
// @Field("first_name")
// private String firstName;
//
// @Size(max = 50)
// @Field("last_name")
// private String lastName;
//
// @NotNull
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String email;
//
// @NotNull
// private boolean activated = false;
//
// @Size(max = 20)
// @Field("activation_key")
// @JsonIgnore
// private String activationKey;
//
// @Size(max = 20)
// @Field("reset_key")
// @JsonIgnore
// private String resetKey;
//
// @Field("reset_date")
// private ZonedDateTime resetDate = null;
//
// @ManyToMany
// //@formatter:off
// @JoinTable(name = "user_role", inverseJoinColumns = {
// @JoinColumn(name = "role_name")
// }, joinColumns = {
// @JoinColumn(name = "account_id")
// }
// )
// //@formatter:on
// private Set<Authority> authorities;
// }
//
// Path: src/main/java/com/jipasoft/exception/AccountNotActivatedException.java
// public class AccountNotActivatedException extends AuthenticationException {
//
// private static final long serialVersionUID = 8415982426813000504L;
//
// public AccountNotActivatedException(String message) {
// super(message);
// }
//
// public AccountNotActivatedException(String message, Throwable t) {
// super(message, t);
// }
// }
//
// Path: src/main/java/com/jipasoft/repository/UserRepository.java
// @NoRepositoryBean
// public interface UserRepository extends BaseRepository<User, String> {
//
// /**
// * Retrieves a {@link User} entity from the underlying datastore by its
// * ResetKey
// *
// * @param resetKey
// * the resetKey
// * @return a User entity
// * @see User#getResetKey()
// */
// public Optional<User> findOneByResetKey(String resetKey);
//
// /**
// * Retrieves a {@link User} entity from the underlying datastore by its
// * Email
// *
// * @param email
// * the User's email
// * @return a User entity
// * @see User#getEmail()
// */
// public Optional<User> findOneByEmail(String email);
//
// /**
// * Retrieves a {@link User} entity from the underlying datastore by its
// * login
// *
// * @param login
// * the username
// * @return a User entity
// * @see User#getLogin()
// */
// public Optional<User> findOneByLogin(String login);
//
// }
| import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Provider;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.jipasoft.domain.User;
import com.jipasoft.exception.AccountNotActivatedException;
import com.jipasoft.repository.UserRepository;
import lombok.extern.slf4j.Slf4j; | package com.jipasoft.service.Impl;
@Slf4j
@Service
@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService {
@Inject
private Provider<UserRepository> userRepositoryProvider;
@Override
public UserDetails loadUserByUsername(final String login) throws UsernameNotFoundException, AccountNotActivatedException {
log.debug("Authenticating {}", login);
String lowercaseLogin = login.toLowerCase(); | // Path: src/main/java/com/jipasoft/domain/User.java
// @Data
// @Entity
// @Document(collection = "account")
// @Table(name = "account")
// @ToString(exclude = { "password", "authorities" })
// @EqualsAndHashCode(callSuper = true)
// public class User extends AbstractAuditEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @org.springframework.data.annotation.Id
// @GeneratedValue(generator = "uuid2")
// @GenericGenerator(name = "uuid2", strategy = "uuid2")
// private String id;
//
// @NotNull
// @Pattern(regexp = "^[a-z0-9]*$|(anonymousUser)")
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String login;
//
// @NotNull
// @Size(min = 60, max = 60)
// @Column(name = "password_hash")
// @JsonIgnore
// private String password;
//
// @Size(max = 50)
// @Field("first_name")
// private String firstName;
//
// @Size(max = 50)
// @Field("last_name")
// private String lastName;
//
// @NotNull
// @Size(min = 1, max = 100)
// @Column(unique = true)
// private String email;
//
// @NotNull
// private boolean activated = false;
//
// @Size(max = 20)
// @Field("activation_key")
// @JsonIgnore
// private String activationKey;
//
// @Size(max = 20)
// @Field("reset_key")
// @JsonIgnore
// private String resetKey;
//
// @Field("reset_date")
// private ZonedDateTime resetDate = null;
//
// @ManyToMany
// //@formatter:off
// @JoinTable(name = "user_role", inverseJoinColumns = {
// @JoinColumn(name = "role_name")
// }, joinColumns = {
// @JoinColumn(name = "account_id")
// }
// )
// //@formatter:on
// private Set<Authority> authorities;
// }
//
// Path: src/main/java/com/jipasoft/exception/AccountNotActivatedException.java
// public class AccountNotActivatedException extends AuthenticationException {
//
// private static final long serialVersionUID = 8415982426813000504L;
//
// public AccountNotActivatedException(String message) {
// super(message);
// }
//
// public AccountNotActivatedException(String message, Throwable t) {
// super(message, t);
// }
// }
//
// Path: src/main/java/com/jipasoft/repository/UserRepository.java
// @NoRepositoryBean
// public interface UserRepository extends BaseRepository<User, String> {
//
// /**
// * Retrieves a {@link User} entity from the underlying datastore by its
// * ResetKey
// *
// * @param resetKey
// * the resetKey
// * @return a User entity
// * @see User#getResetKey()
// */
// public Optional<User> findOneByResetKey(String resetKey);
//
// /**
// * Retrieves a {@link User} entity from the underlying datastore by its
// * Email
// *
// * @param email
// * the User's email
// * @return a User entity
// * @see User#getEmail()
// */
// public Optional<User> findOneByEmail(String email);
//
// /**
// * Retrieves a {@link User} entity from the underlying datastore by its
// * login
// *
// * @param login
// * the username
// * @return a User entity
// * @see User#getLogin()
// */
// public Optional<User> findOneByLogin(String login);
//
// }
// Path: src/main/java/com/jipasoft/service/Impl/UserDetailsServiceImpl.java
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Provider;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.jipasoft.domain.User;
import com.jipasoft.exception.AccountNotActivatedException;
import com.jipasoft.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
package com.jipasoft.service.Impl;
@Slf4j
@Service
@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService {
@Inject
private Provider<UserRepository> userRepositoryProvider;
@Override
public UserDetails loadUserByUsername(final String login) throws UsernameNotFoundException, AccountNotActivatedException {
log.debug("Authenticating {}", login);
String lowercaseLogin = login.toLowerCase(); | Optional<User> userFromDatabase = userRepositoryProvider.get().findOneByLogin(lowercaseLogin); |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/parser/lang/LanguageSupport.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
// public final class ImportStatement {
//
// private static final String IMPORT_PREFIX = "import ";
// private static final String STATIC_PREFIX = "static ";
// private final String importName;
// private final int line;
// private final boolean staticImport;
//
// public ImportStatement(String importName, int line, boolean staticImport) {
// Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty");
// Preconditions.checkArgument(!importName.startsWith(IMPORT_PREFIX),
// "importName should be the raw package name without 'import ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(!importName.startsWith(STATIC_PREFIX),
// "importName should be the raw package name without 'static ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(importName.trim().equals(importName),
// "importName has leading or trailing spaces: '%s'", importName);
// Preconditions.checkArgument(line > 0, "line numbers should be 1-based and not start at 0");
//
// this.importName = importName;
// this.line = line;
// this.staticImport = staticImport;
// }
//
// /**
// * The physical line within the source file in which the import has occurred. Number
// * is always 1-based!
// *
// * @return The line number of the matched imports.
// */
// public int getLine() {
// return line;
// }
//
// /**
// * Returns the import name including the 'static ' prefix if this represents a static
// * import.
// *
// * @return The full import name.
// */
// public String getImportName() {
// if (staticImport) {
// return STATIC_PREFIX + importName;
// }
// return importName;
// }
//
// public String getFqcn() {
// return importName;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("import", importName)
// .add("line", line)
// .add("static", staticImport)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(importName, line, staticImport);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ImportStatement
// && Objects.equals(this.line, ((ImportStatement) obj).line)
// && Objects.equals(this.staticImport, ((ImportStatement) obj).staticImport)
// && Objects.equals(this.importName, ((ImportStatement) obj).importName);
// }
// }
| import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.ServiceLoader;
import java.util.Set;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatement; | package de.skuzzle.enforcer.restrictimports.parser.lang;
/**
* SPI for plugging in import statement recognition for different languages.
* Implementations will be looked up using java's {@link ServiceLoader}.
*
* @author Simon Taddiken
*/
public interface LanguageSupport {
/**
* Returns the {@link LanguageSupport} implementation for the given file.
*
* @param path The path to a file.
* @return The {@link LanguageSupport} implementation or an empty optional if none was
* found.
*/
static LanguageSupport getLanguageSupport(Path path) {
final String extension = FileExtension.fromPath(path);
return SupportedLanguageHolder.getLanguageSupport(extension)
.orElseThrow(() -> new IllegalArgumentException(String.format(
"Could not find a LanguageSupport implementation for normalized file extension: '%s' (%s)",
extension, path)));
}
/**
* Determines whether there exists a {@link LanguageSupport} implementation for the
* given path.
*
* @param path The path to a file.
* @return Whether such implementation exists.
* @since 1.1.0
*/
static boolean isLanguageSupported(Path path) {
final Path filename = path.getFileName();
return !Files.isDirectory(path)
&& SupportedLanguageHolder.isLanguageSupported(FileExtension.fromPath(filename));
}
/**
* The set of supported file extensions. Extensions returned here are case insensitive
* and may or may not start with a '.' (dot).
*
* @return The set of file extensions.
*/
Set<String> getSupportedFileExtensions();
/**
* Parses the given line and returns the declared package
*
* @param line Line in the source file
* @return The package declared
*/
Optional<String> parsePackage(String line);
/**
* Extract the package names that this import statement represents. As some languages
* allow to specify multiple imports in a single line, this method returns a list.
* <p>
* e.g. import java.util.List; The above should return java.util.List in a Java source
* file.
*
* @param importLine Line in the source file
* @param lineNumber The line number of the import.
* @return Fully qualified package name that this import represents
*/ | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
// public final class ImportStatement {
//
// private static final String IMPORT_PREFIX = "import ";
// private static final String STATIC_PREFIX = "static ";
// private final String importName;
// private final int line;
// private final boolean staticImport;
//
// public ImportStatement(String importName, int line, boolean staticImport) {
// Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty");
// Preconditions.checkArgument(!importName.startsWith(IMPORT_PREFIX),
// "importName should be the raw package name without 'import ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(!importName.startsWith(STATIC_PREFIX),
// "importName should be the raw package name without 'static ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(importName.trim().equals(importName),
// "importName has leading or trailing spaces: '%s'", importName);
// Preconditions.checkArgument(line > 0, "line numbers should be 1-based and not start at 0");
//
// this.importName = importName;
// this.line = line;
// this.staticImport = staticImport;
// }
//
// /**
// * The physical line within the source file in which the import has occurred. Number
// * is always 1-based!
// *
// * @return The line number of the matched imports.
// */
// public int getLine() {
// return line;
// }
//
// /**
// * Returns the import name including the 'static ' prefix if this represents a static
// * import.
// *
// * @return The full import name.
// */
// public String getImportName() {
// if (staticImport) {
// return STATIC_PREFIX + importName;
// }
// return importName;
// }
//
// public String getFqcn() {
// return importName;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("import", importName)
// .add("line", line)
// .add("static", staticImport)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(importName, line, staticImport);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ImportStatement
// && Objects.equals(this.line, ((ImportStatement) obj).line)
// && Objects.equals(this.staticImport, ((ImportStatement) obj).staticImport)
// && Objects.equals(this.importName, ((ImportStatement) obj).importName);
// }
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/lang/LanguageSupport.java
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.ServiceLoader;
import java.util.Set;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatement;
package de.skuzzle.enforcer.restrictimports.parser.lang;
/**
* SPI for plugging in import statement recognition for different languages.
* Implementations will be looked up using java's {@link ServiceLoader}.
*
* @author Simon Taddiken
*/
public interface LanguageSupport {
/**
* Returns the {@link LanguageSupport} implementation for the given file.
*
* @param path The path to a file.
* @return The {@link LanguageSupport} implementation or an empty optional if none was
* found.
*/
static LanguageSupport getLanguageSupport(Path path) {
final String extension = FileExtension.fromPath(path);
return SupportedLanguageHolder.getLanguageSupport(extension)
.orElseThrow(() -> new IllegalArgumentException(String.format(
"Could not find a LanguageSupport implementation for normalized file extension: '%s' (%s)",
extension, path)));
}
/**
* Determines whether there exists a {@link LanguageSupport} implementation for the
* given path.
*
* @param path The path to a file.
* @return Whether such implementation exists.
* @since 1.1.0
*/
static boolean isLanguageSupported(Path path) {
final Path filename = path.getFileName();
return !Files.isDirectory(path)
&& SupportedLanguageHolder.isLanguageSupported(FileExtension.fromPath(filename));
}
/**
* The set of supported file extensions. Extensions returned here are case insensitive
* and may or may not start with a '.' (dot).
*
* @return The set of file extensions.
*/
Set<String> getSupportedFileExtensions();
/**
* Parses the given line and returns the declared package
*
* @param line Line in the source file
* @return The package declared
*/
Optional<String> parsePackage(String line);
/**
* Extract the package names that this import statement represents. As some languages
* allow to specify multiple imports in a single line, this method returns a list.
* <p>
* e.g. import java.util.List; The above should return java.util.List in a Java source
* file.
*
* @param importLine Line in the source file
* @param lineNumber The line number of the import.
* @return Fully qualified package name that this import represents
*/ | List<ImportStatement> parseImport(String importLine, int lineNumber); |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/analyze/MatchedFile.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/StringRepresentation.java
// public final class StringRepresentation {
//
// private final String name;
// private final List<Attribute> attributes = new ArrayList<>();
//
// private StringRepresentation(String name) {
// this.name = name;
// }
//
// public static StringRepresentation ofType(Class<?> type) {
// return new StringRepresentation(type.getSimpleName());
// }
//
// public static StringRepresentation ofInstance(Object instance) {
// return ofType(instance.getClass());
// }
//
// public StringRepresentation add(String attribute, Object value) {
// attributes.add(new Attribute(attribute, value));
// return this;
// }
//
// @Override
// public String toString() {
// return new StringBuilder(name)
// .append("{")
// .append(attributes.stream().map(Attribute::toString).collect(Collectors.joining(", ")))
// .append("}")
// .toString();
// }
//
// private static final class Attribute {
// private final String name;
// private final Object value;
//
// private Attribute(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public String toString() {
// return name + "=" + value;
// }
// }
// }
| import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import de.skuzzle.enforcer.restrictimports.util.Preconditions;
import de.skuzzle.enforcer.restrictimports.util.StringRepresentation; | */
public List<MatchedImport> getMatchedImports() {
return this.matchedImports;
}
/**
* Returns the group that contains the banned import that caused the match in this
* file.
*
* @return The group.
*/
public BannedImportGroup getMatchedBy() {
return this.matchedBy;
}
@Override
public int hashCode() {
return Objects.hash(sourceFile, matchedImports, matchedBy);
}
@Override
public boolean equals(Object obj) {
return obj == this || obj instanceof MatchedFile
&& Objects.equals(sourceFile, ((MatchedFile) obj).sourceFile)
&& Objects.equals(matchedImports, ((MatchedFile) obj).matchedImports)
&& Objects.equals(matchedBy, ((MatchedFile) obj).matchedBy);
}
@Override
public String toString() { | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/StringRepresentation.java
// public final class StringRepresentation {
//
// private final String name;
// private final List<Attribute> attributes = new ArrayList<>();
//
// private StringRepresentation(String name) {
// this.name = name;
// }
//
// public static StringRepresentation ofType(Class<?> type) {
// return new StringRepresentation(type.getSimpleName());
// }
//
// public static StringRepresentation ofInstance(Object instance) {
// return ofType(instance.getClass());
// }
//
// public StringRepresentation add(String attribute, Object value) {
// attributes.add(new Attribute(attribute, value));
// return this;
// }
//
// @Override
// public String toString() {
// return new StringBuilder(name)
// .append("{")
// .append(attributes.stream().map(Attribute::toString).collect(Collectors.joining(", ")))
// .append("}")
// .toString();
// }
//
// private static final class Attribute {
// private final String name;
// private final Object value;
//
// private Attribute(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public String toString() {
// return name + "=" + value;
// }
// }
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/analyze/MatchedFile.java
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import de.skuzzle.enforcer.restrictimports.util.Preconditions;
import de.skuzzle.enforcer.restrictimports.util.StringRepresentation;
*/
public List<MatchedImport> getMatchedImports() {
return this.matchedImports;
}
/**
* Returns the group that contains the banned import that caused the match in this
* file.
*
* @return The group.
*/
public BannedImportGroup getMatchedBy() {
return this.matchedBy;
}
@Override
public int hashCode() {
return Objects.hash(sourceFile, matchedImports, matchedBy);
}
@Override
public boolean equals(Object obj) {
return obj == this || obj instanceof MatchedFile
&& Objects.equals(sourceFile, ((MatchedFile) obj).sourceFile)
&& Objects.equals(matchedImports, ((MatchedFile) obj).matchedImports)
&& Objects.equals(matchedBy, ((MatchedFile) obj).matchedBy);
}
@Override
public String toString() { | return StringRepresentation.ofInstance(this) |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/analyze/MatchedFile.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/StringRepresentation.java
// public final class StringRepresentation {
//
// private final String name;
// private final List<Attribute> attributes = new ArrayList<>();
//
// private StringRepresentation(String name) {
// this.name = name;
// }
//
// public static StringRepresentation ofType(Class<?> type) {
// return new StringRepresentation(type.getSimpleName());
// }
//
// public static StringRepresentation ofInstance(Object instance) {
// return ofType(instance.getClass());
// }
//
// public StringRepresentation add(String attribute, Object value) {
// attributes.add(new Attribute(attribute, value));
// return this;
// }
//
// @Override
// public String toString() {
// return new StringBuilder(name)
// .append("{")
// .append(attributes.stream().map(Attribute::toString).collect(Collectors.joining(", ")))
// .append("}")
// .toString();
// }
//
// private static final class Attribute {
// private final String name;
// private final Object value;
//
// private Attribute(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public String toString() {
// return name + "=" + value;
// }
// }
// }
| import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import de.skuzzle.enforcer.restrictimports.util.Preconditions;
import de.skuzzle.enforcer.restrictimports.util.StringRepresentation; | }
@Override
public int hashCode() {
return Objects.hash(sourceFile, matchedImports, matchedBy);
}
@Override
public boolean equals(Object obj) {
return obj == this || obj instanceof MatchedFile
&& Objects.equals(sourceFile, ((MatchedFile) obj).sourceFile)
&& Objects.equals(matchedImports, ((MatchedFile) obj).matchedImports)
&& Objects.equals(matchedBy, ((MatchedFile) obj).matchedBy);
}
@Override
public String toString() {
return StringRepresentation.ofInstance(this)
.add("sourceFile", this.sourceFile)
.add("matchedImports", matchedImports)
.add("matchedBy", matchedBy)
.toString();
}
public static class Builder {
private final Path sourceFile;
private final List<MatchedImport> matchedImports = new ArrayList<>();
private BannedImportGroup matchedBy;
private Builder(Path sourceFile) { | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/StringRepresentation.java
// public final class StringRepresentation {
//
// private final String name;
// private final List<Attribute> attributes = new ArrayList<>();
//
// private StringRepresentation(String name) {
// this.name = name;
// }
//
// public static StringRepresentation ofType(Class<?> type) {
// return new StringRepresentation(type.getSimpleName());
// }
//
// public static StringRepresentation ofInstance(Object instance) {
// return ofType(instance.getClass());
// }
//
// public StringRepresentation add(String attribute, Object value) {
// attributes.add(new Attribute(attribute, value));
// return this;
// }
//
// @Override
// public String toString() {
// return new StringBuilder(name)
// .append("{")
// .append(attributes.stream().map(Attribute::toString).collect(Collectors.joining(", ")))
// .append("}")
// .toString();
// }
//
// private static final class Attribute {
// private final String name;
// private final Object value;
//
// private Attribute(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public String toString() {
// return name + "=" + value;
// }
// }
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/analyze/MatchedFile.java
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import de.skuzzle.enforcer.restrictimports.util.Preconditions;
import de.skuzzle.enforcer.restrictimports.util.StringRepresentation;
}
@Override
public int hashCode() {
return Objects.hash(sourceFile, matchedImports, matchedBy);
}
@Override
public boolean equals(Object obj) {
return obj == this || obj instanceof MatchedFile
&& Objects.equals(sourceFile, ((MatchedFile) obj).sourceFile)
&& Objects.equals(matchedImports, ((MatchedFile) obj).matchedImports)
&& Objects.equals(matchedBy, ((MatchedFile) obj).matchedBy);
}
@Override
public String toString() {
return StringRepresentation.ofInstance(this)
.add("sourceFile", this.sourceFile)
.add("matchedImports", matchedImports)
.add("matchedBy", matchedBy)
.toString();
}
public static class Builder {
private final Path sourceFile;
private final List<MatchedImport> matchedImports = new ArrayList<>();
private BannedImportGroup matchedBy;
private Builder(Path sourceFile) { | Preconditions.checkArgument(sourceFile != null, "sourceFile must not be null"); |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/parser/ParsedFile.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/StringRepresentation.java
// public final class StringRepresentation {
//
// private final String name;
// private final List<Attribute> attributes = new ArrayList<>();
//
// private StringRepresentation(String name) {
// this.name = name;
// }
//
// public static StringRepresentation ofType(Class<?> type) {
// return new StringRepresentation(type.getSimpleName());
// }
//
// public static StringRepresentation ofInstance(Object instance) {
// return ofType(instance.getClass());
// }
//
// public StringRepresentation add(String attribute, Object value) {
// attributes.add(new Attribute(attribute, value));
// return this;
// }
//
// @Override
// public String toString() {
// return new StringBuilder(name)
// .append("{")
// .append(attributes.stream().map(Attribute::toString).collect(Collectors.joining(", ")))
// .append("}")
// .toString();
// }
//
// private static final class Attribute {
// private final String name;
// private final Object value;
//
// private Attribute(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public String toString() {
// return name + "=" + value;
// }
// }
// }
| import java.nio.file.Path;
import java.util.Collection;
import java.util.Objects;
import de.skuzzle.enforcer.restrictimports.util.StringRepresentation; | package de.skuzzle.enforcer.restrictimports.parser;
/**
* Represents a source file that has been parsed for import statements.
*/
public final class ParsedFile {
private final Path path;
private final String declaredPackage;
private final String fqcn;
private final Collection<ImportStatement> imports;
public ParsedFile(Path path, String declaredPackage, String fqcn, Collection<ImportStatement> imports) {
this.path = path;
this.declaredPackage = declaredPackage;
this.fqcn = fqcn;
this.imports = imports;
}
public Path getPath() {
return path;
}
public Collection<ImportStatement> getImports() {
return imports;
}
public String getFqcn() {
return fqcn;
}
@Override
public String toString() { | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/StringRepresentation.java
// public final class StringRepresentation {
//
// private final String name;
// private final List<Attribute> attributes = new ArrayList<>();
//
// private StringRepresentation(String name) {
// this.name = name;
// }
//
// public static StringRepresentation ofType(Class<?> type) {
// return new StringRepresentation(type.getSimpleName());
// }
//
// public static StringRepresentation ofInstance(Object instance) {
// return ofType(instance.getClass());
// }
//
// public StringRepresentation add(String attribute, Object value) {
// attributes.add(new Attribute(attribute, value));
// return this;
// }
//
// @Override
// public String toString() {
// return new StringBuilder(name)
// .append("{")
// .append(attributes.stream().map(Attribute::toString).collect(Collectors.joining(", ")))
// .append("}")
// .toString();
// }
//
// private static final class Attribute {
// private final String name;
// private final Object value;
//
// private Attribute(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public String toString() {
// return name + "=" + value;
// }
// }
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ParsedFile.java
import java.nio.file.Path;
import java.util.Collection;
import java.util.Objects;
import de.skuzzle.enforcer.restrictimports.util.StringRepresentation;
package de.skuzzle.enforcer.restrictimports.parser;
/**
* Represents a source file that has been parsed for import statements.
*/
public final class ParsedFile {
private final Path path;
private final String declaredPackage;
private final String fqcn;
private final Collection<ImportStatement> imports;
public ParsedFile(Path path, String declaredPackage, String fqcn, Collection<ImportStatement> imports) {
this.path = path;
this.declaredPackage = declaredPackage;
this.fqcn = fqcn;
this.imports = imports;
}
public Path getPath() {
return path;
}
public Collection<ImportStatement> getImports() {
return imports;
}
public String getFqcn() {
return fqcn;
}
@Override
public String toString() { | return StringRepresentation.ofInstance(this) |
skuzzle/restrict-imports-enforcer-rule | src/test/java/de/skuzzle/enforcer/restrictimports/parser/lang/JavaLanguageSupportTest.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
// public final class ImportStatement {
//
// private static final String IMPORT_PREFIX = "import ";
// private static final String STATIC_PREFIX = "static ";
// private final String importName;
// private final int line;
// private final boolean staticImport;
//
// public ImportStatement(String importName, int line, boolean staticImport) {
// Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty");
// Preconditions.checkArgument(!importName.startsWith(IMPORT_PREFIX),
// "importName should be the raw package name without 'import ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(!importName.startsWith(STATIC_PREFIX),
// "importName should be the raw package name without 'static ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(importName.trim().equals(importName),
// "importName has leading or trailing spaces: '%s'", importName);
// Preconditions.checkArgument(line > 0, "line numbers should be 1-based and not start at 0");
//
// this.importName = importName;
// this.line = line;
// this.staticImport = staticImport;
// }
//
// /**
// * The physical line within the source file in which the import has occurred. Number
// * is always 1-based!
// *
// * @return The line number of the matched imports.
// */
// public int getLine() {
// return line;
// }
//
// /**
// * Returns the import name including the 'static ' prefix if this represents a static
// * import.
// *
// * @return The full import name.
// */
// public String getImportName() {
// if (staticImport) {
// return STATIC_PREFIX + importName;
// }
// return importName;
// }
//
// public String getFqcn() {
// return importName;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("import", importName)
// .add("line", line)
// .add("static", staticImport)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(importName, line, staticImport);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ImportStatement
// && Objects.equals(this.line, ((ImportStatement) obj).line)
// && Objects.equals(this.staticImport, ((ImportStatement) obj).staticImport)
// && Objects.equals(this.importName, ((ImportStatement) obj).importName);
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatement; | package de.skuzzle.enforcer.restrictimports.parser.lang;
public class JavaLanguageSupportTest {
private final JavaLanguageSupport subject = new JavaLanguageSupport();
@Test
public void testValidImport() {
assertThat(subject.parseImport("import java.util.List;", 1)).first() | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
// public final class ImportStatement {
//
// private static final String IMPORT_PREFIX = "import ";
// private static final String STATIC_PREFIX = "static ";
// private final String importName;
// private final int line;
// private final boolean staticImport;
//
// public ImportStatement(String importName, int line, boolean staticImport) {
// Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty");
// Preconditions.checkArgument(!importName.startsWith(IMPORT_PREFIX),
// "importName should be the raw package name without 'import ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(!importName.startsWith(STATIC_PREFIX),
// "importName should be the raw package name without 'static ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(importName.trim().equals(importName),
// "importName has leading or trailing spaces: '%s'", importName);
// Preconditions.checkArgument(line > 0, "line numbers should be 1-based and not start at 0");
//
// this.importName = importName;
// this.line = line;
// this.staticImport = staticImport;
// }
//
// /**
// * The physical line within the source file in which the import has occurred. Number
// * is always 1-based!
// *
// * @return The line number of the matched imports.
// */
// public int getLine() {
// return line;
// }
//
// /**
// * Returns the import name including the 'static ' prefix if this represents a static
// * import.
// *
// * @return The full import name.
// */
// public String getImportName() {
// if (staticImport) {
// return STATIC_PREFIX + importName;
// }
// return importName;
// }
//
// public String getFqcn() {
// return importName;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("import", importName)
// .add("line", line)
// .add("static", staticImport)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(importName, line, staticImport);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ImportStatement
// && Objects.equals(this.line, ((ImportStatement) obj).line)
// && Objects.equals(this.staticImport, ((ImportStatement) obj).staticImport)
// && Objects.equals(this.importName, ((ImportStatement) obj).importName);
// }
// }
// Path: src/test/java/de/skuzzle/enforcer/restrictimports/parser/lang/JavaLanguageSupportTest.java
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatement;
package de.skuzzle.enforcer.restrictimports.parser.lang;
public class JavaLanguageSupportTest {
private final JavaLanguageSupport subject = new JavaLanguageSupport();
@Test
public void testValidImport() {
assertThat(subject.parseImport("import java.util.List;", 1)).first() | .isEqualTo(new ImportStatement("java.util.List", 1, false)); |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/analyze/PackagePattern.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Whitespaces.java
// public final class Whitespaces {
//
// private static final Pattern LEADING = Pattern.compile("^\\s+");
// private static final Pattern TRAILING = Pattern.compile("\\s+$");
//
// /**
// * Trims all leading and trailing whitespaces (regex pattern class <code>\s</code>)
// *
// * @param s The string to trim.
// * @return The trimmed string.
// */
// public static final String trimAll(String s) {
// final Matcher leadingMatcher = LEADING.matcher(s);
// final Matcher trailingMatcher = TRAILING.matcher(s);
// final boolean hasLeading = leadingMatcher.find();
// final boolean hasTrailing = trailingMatcher.find();
// if (!hasLeading && !hasTrailing) {
// return s;
// }
// final int start = hasLeading ? leadingMatcher.end() : 0;
// final int end = hasTrailing ? trailingMatcher.start() : s.length();
// return s.substring(start, end);
// }
//
// private Whitespaces() {
// // hidden
// }
// }
| import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import de.skuzzle.enforcer.restrictimports.util.Preconditions;
import de.skuzzle.enforcer.restrictimports.util.Whitespaces; | package de.skuzzle.enforcer.restrictimports.analyze;
/**
* Pattern class to match java style package and class names using wild card operators.
*
* @author Simon Taddiken
*/
public final class PackagePattern implements Comparable<PackagePattern> {
private static final String STATIC_PREFIX = "static";
private final String[] parts;
private final boolean staticc;
private PackagePattern(String s) {
final ParseResult parsed = ParseResult.parse(s);
this.staticc = parsed.staticc;
this.parts = parsed.parts;
checkParts(s, this.parts);
}
private static class ParseResult {
private static final Pattern STATIC_PREFIX_PATTERN = Pattern.compile("^" + STATIC_PREFIX + "\\s+");
private final String[] parts;
private final boolean staticc;
private ParseResult(String[] parts, boolean staticc) {
this.parts = parts;
this.staticc = staticc;
}
static ParseResult parse(String s) { | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Whitespaces.java
// public final class Whitespaces {
//
// private static final Pattern LEADING = Pattern.compile("^\\s+");
// private static final Pattern TRAILING = Pattern.compile("\\s+$");
//
// /**
// * Trims all leading and trailing whitespaces (regex pattern class <code>\s</code>)
// *
// * @param s The string to trim.
// * @return The trimmed string.
// */
// public static final String trimAll(String s) {
// final Matcher leadingMatcher = LEADING.matcher(s);
// final Matcher trailingMatcher = TRAILING.matcher(s);
// final boolean hasLeading = leadingMatcher.find();
// final boolean hasTrailing = trailingMatcher.find();
// if (!hasLeading && !hasTrailing) {
// return s;
// }
// final int start = hasLeading ? leadingMatcher.end() : 0;
// final int end = hasTrailing ? trailingMatcher.start() : s.length();
// return s.substring(start, end);
// }
//
// private Whitespaces() {
// // hidden
// }
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/analyze/PackagePattern.java
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import de.skuzzle.enforcer.restrictimports.util.Preconditions;
import de.skuzzle.enforcer.restrictimports.util.Whitespaces;
package de.skuzzle.enforcer.restrictimports.analyze;
/**
* Pattern class to match java style package and class names using wild card operators.
*
* @author Simon Taddiken
*/
public final class PackagePattern implements Comparable<PackagePattern> {
private static final String STATIC_PREFIX = "static";
private final String[] parts;
private final boolean staticc;
private PackagePattern(String s) {
final ParseResult parsed = ParseResult.parse(s);
this.staticc = parsed.staticc;
this.parts = parsed.parts;
checkParts(s, this.parts);
}
private static class ParseResult {
private static final Pattern STATIC_PREFIX_PATTERN = Pattern.compile("^" + STATIC_PREFIX + "\\s+");
private final String[] parts;
private final boolean staticc;
private ParseResult(String[] parts, boolean staticc) {
this.parts = parts;
this.staticc = staticc;
}
static ParseResult parse(String s) { | String trimmed = Whitespaces.trimAll(s); |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/analyze/PackagePattern.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Whitespaces.java
// public final class Whitespaces {
//
// private static final Pattern LEADING = Pattern.compile("^\\s+");
// private static final Pattern TRAILING = Pattern.compile("\\s+$");
//
// /**
// * Trims all leading and trailing whitespaces (regex pattern class <code>\s</code>)
// *
// * @param s The string to trim.
// * @return The trimmed string.
// */
// public static final String trimAll(String s) {
// final Matcher leadingMatcher = LEADING.matcher(s);
// final Matcher trailingMatcher = TRAILING.matcher(s);
// final boolean hasLeading = leadingMatcher.find();
// final boolean hasTrailing = trailingMatcher.find();
// if (!hasLeading && !hasTrailing) {
// return s;
// }
// final int start = hasLeading ? leadingMatcher.end() : 0;
// final int end = hasTrailing ? trailingMatcher.start() : s.length();
// return s.substring(start, end);
// }
//
// private Whitespaces() {
// // hidden
// }
// }
| import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import de.skuzzle.enforcer.restrictimports.util.Preconditions;
import de.skuzzle.enforcer.restrictimports.util.Whitespaces; | return;
} else if (part.contains("*")) {
throw new IllegalArgumentException(String.format(
"The pattern '%s' contains a part which mixes wildcards and normal characters", original));
} else if (partIndex == 0 && "static".equals(part)) {
return;
} else if (!Character.isJavaIdentifierStart(chars[0])) {
throw new IllegalArgumentException(String.format(
"The pattern '%s' contains a non-identifier character '%s' (0x%s)", original, chars[0],
Integer.toHexString(chars[0])));
}
for (int i = 1; i < chars.length; i++) {
final char c = chars[i];
if (!Character.isJavaIdentifierPart(c)) {
throw new IllegalArgumentException(String.format(
"The pattern '%s' contains a non-identifier character '%s' (0x%s)", original, chars[i],
Integer.toHexString(chars[i])));
}
}
}
/**
* Parses each string of the given collection into a {@link PackagePattern} and
* returns them in a list.
*
* @param patternStrings The Strings to parse.
* @return A list of parsed package patterns.
*/
public static List<PackagePattern> parseAll(Collection<String> patternStrings) { | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Whitespaces.java
// public final class Whitespaces {
//
// private static final Pattern LEADING = Pattern.compile("^\\s+");
// private static final Pattern TRAILING = Pattern.compile("\\s+$");
//
// /**
// * Trims all leading and trailing whitespaces (regex pattern class <code>\s</code>)
// *
// * @param s The string to trim.
// * @return The trimmed string.
// */
// public static final String trimAll(String s) {
// final Matcher leadingMatcher = LEADING.matcher(s);
// final Matcher trailingMatcher = TRAILING.matcher(s);
// final boolean hasLeading = leadingMatcher.find();
// final boolean hasTrailing = trailingMatcher.find();
// if (!hasLeading && !hasTrailing) {
// return s;
// }
// final int start = hasLeading ? leadingMatcher.end() : 0;
// final int end = hasTrailing ? trailingMatcher.start() : s.length();
// return s.substring(start, end);
// }
//
// private Whitespaces() {
// // hidden
// }
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/analyze/PackagePattern.java
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import de.skuzzle.enforcer.restrictimports.util.Preconditions;
import de.skuzzle.enforcer.restrictimports.util.Whitespaces;
return;
} else if (part.contains("*")) {
throw new IllegalArgumentException(String.format(
"The pattern '%s' contains a part which mixes wildcards and normal characters", original));
} else if (partIndex == 0 && "static".equals(part)) {
return;
} else if (!Character.isJavaIdentifierStart(chars[0])) {
throw new IllegalArgumentException(String.format(
"The pattern '%s' contains a non-identifier character '%s' (0x%s)", original, chars[0],
Integer.toHexString(chars[0])));
}
for (int i = 1; i < chars.length; i++) {
final char c = chars[i];
if (!Character.isJavaIdentifierPart(c)) {
throw new IllegalArgumentException(String.format(
"The pattern '%s' contains a non-identifier character '%s' (0x%s)", original, chars[i],
Integer.toHexString(chars[i])));
}
}
}
/**
* Parses each string of the given collection into a {@link PackagePattern} and
* returns them in a list.
*
* @param patternStrings The Strings to parse.
* @return A list of parsed package patterns.
*/
public static List<PackagePattern> parseAll(Collection<String> patternStrings) { | Preconditions.checkArgument(patternStrings != null); |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/parser/lang/KotlinGroovyLanguageSupport.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
// public final class ImportStatement {
//
// private static final String IMPORT_PREFIX = "import ";
// private static final String STATIC_PREFIX = "static ";
// private final String importName;
// private final int line;
// private final boolean staticImport;
//
// public ImportStatement(String importName, int line, boolean staticImport) {
// Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty");
// Preconditions.checkArgument(!importName.startsWith(IMPORT_PREFIX),
// "importName should be the raw package name without 'import ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(!importName.startsWith(STATIC_PREFIX),
// "importName should be the raw package name without 'static ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(importName.trim().equals(importName),
// "importName has leading or trailing spaces: '%s'", importName);
// Preconditions.checkArgument(line > 0, "line numbers should be 1-based and not start at 0");
//
// this.importName = importName;
// this.line = line;
// this.staticImport = staticImport;
// }
//
// /**
// * The physical line within the source file in which the import has occurred. Number
// * is always 1-based!
// *
// * @return The line number of the matched imports.
// */
// public int getLine() {
// return line;
// }
//
// /**
// * Returns the import name including the 'static ' prefix if this represents a static
// * import.
// *
// * @return The full import name.
// */
// public String getImportName() {
// if (staticImport) {
// return STATIC_PREFIX + importName;
// }
// return importName;
// }
//
// public String getFqcn() {
// return importName;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("import", importName)
// .add("line", line)
// .add("static", staticImport)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(importName, line, staticImport);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ImportStatement
// && Objects.equals(this.line, ((ImportStatement) obj).line)
// && Objects.equals(this.staticImport, ((ImportStatement) obj).staticImport)
// && Objects.equals(this.importName, ((ImportStatement) obj).importName);
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Whitespaces.java
// public final class Whitespaces {
//
// private static final Pattern LEADING = Pattern.compile("^\\s+");
// private static final Pattern TRAILING = Pattern.compile("\\s+$");
//
// /**
// * Trims all leading and trailing whitespaces (regex pattern class <code>\s</code>)
// *
// * @param s The string to trim.
// * @return The trimmed string.
// */
// public static final String trimAll(String s) {
// final Matcher leadingMatcher = LEADING.matcher(s);
// final Matcher trailingMatcher = TRAILING.matcher(s);
// final boolean hasLeading = leadingMatcher.find();
// final boolean hasTrailing = trailingMatcher.find();
// if (!hasLeading && !hasTrailing) {
// return s;
// }
// final int start = hasLeading ? leadingMatcher.end() : 0;
// final int end = hasTrailing ? trailingMatcher.start() : s.length();
// return s.substring(start, end);
// }
//
// private Whitespaces() {
// // hidden
// }
// }
| import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatement;
import de.skuzzle.enforcer.restrictimports.util.Whitespaces; | package de.skuzzle.enforcer.restrictimports.parser.lang;
public class KotlinGroovyLanguageSupport implements LanguageSupport {
private static final String STATIC_PREFIX = "static";
private static final String IMPORT_STATEMENT = "import ";
private static final String PACKAGE_STATEMENT = "package ";
private static final Set<String> EXTENSIONS = Collections
.unmodifiableSet(new HashSet<>(Arrays.asList("groovy", "kt")));
@Override
public Set<String> getSupportedFileExtensions() {
return EXTENSIONS;
}
@Override
public Optional<String> parsePackage(String line) {
if (!isPackage(line)) {
return Optional.empty();
}
return Optional.of(extractPackageName(line));
}
@Override | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
// public final class ImportStatement {
//
// private static final String IMPORT_PREFIX = "import ";
// private static final String STATIC_PREFIX = "static ";
// private final String importName;
// private final int line;
// private final boolean staticImport;
//
// public ImportStatement(String importName, int line, boolean staticImport) {
// Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty");
// Preconditions.checkArgument(!importName.startsWith(IMPORT_PREFIX),
// "importName should be the raw package name without 'import ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(!importName.startsWith(STATIC_PREFIX),
// "importName should be the raw package name without 'static ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(importName.trim().equals(importName),
// "importName has leading or trailing spaces: '%s'", importName);
// Preconditions.checkArgument(line > 0, "line numbers should be 1-based and not start at 0");
//
// this.importName = importName;
// this.line = line;
// this.staticImport = staticImport;
// }
//
// /**
// * The physical line within the source file in which the import has occurred. Number
// * is always 1-based!
// *
// * @return The line number of the matched imports.
// */
// public int getLine() {
// return line;
// }
//
// /**
// * Returns the import name including the 'static ' prefix if this represents a static
// * import.
// *
// * @return The full import name.
// */
// public String getImportName() {
// if (staticImport) {
// return STATIC_PREFIX + importName;
// }
// return importName;
// }
//
// public String getFqcn() {
// return importName;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("import", importName)
// .add("line", line)
// .add("static", staticImport)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(importName, line, staticImport);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ImportStatement
// && Objects.equals(this.line, ((ImportStatement) obj).line)
// && Objects.equals(this.staticImport, ((ImportStatement) obj).staticImport)
// && Objects.equals(this.importName, ((ImportStatement) obj).importName);
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Whitespaces.java
// public final class Whitespaces {
//
// private static final Pattern LEADING = Pattern.compile("^\\s+");
// private static final Pattern TRAILING = Pattern.compile("\\s+$");
//
// /**
// * Trims all leading and trailing whitespaces (regex pattern class <code>\s</code>)
// *
// * @param s The string to trim.
// * @return The trimmed string.
// */
// public static final String trimAll(String s) {
// final Matcher leadingMatcher = LEADING.matcher(s);
// final Matcher trailingMatcher = TRAILING.matcher(s);
// final boolean hasLeading = leadingMatcher.find();
// final boolean hasTrailing = trailingMatcher.find();
// if (!hasLeading && !hasTrailing) {
// return s;
// }
// final int start = hasLeading ? leadingMatcher.end() : 0;
// final int end = hasTrailing ? trailingMatcher.start() : s.length();
// return s.substring(start, end);
// }
//
// private Whitespaces() {
// // hidden
// }
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/lang/KotlinGroovyLanguageSupport.java
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatement;
import de.skuzzle.enforcer.restrictimports.util.Whitespaces;
package de.skuzzle.enforcer.restrictimports.parser.lang;
public class KotlinGroovyLanguageSupport implements LanguageSupport {
private static final String STATIC_PREFIX = "static";
private static final String IMPORT_STATEMENT = "import ";
private static final String PACKAGE_STATEMENT = "package ";
private static final Set<String> EXTENSIONS = Collections
.unmodifiableSet(new HashSet<>(Arrays.asList("groovy", "kt")));
@Override
public Set<String> getSupportedFileExtensions() {
return EXTENSIONS;
}
@Override
public Optional<String> parsePackage(String line) {
if (!isPackage(line)) {
return Optional.empty();
}
return Optional.of(extractPackageName(line));
}
@Override | public List<ImportStatement> parseImport(String line, int lineNumber) { |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/parser/lang/KotlinGroovyLanguageSupport.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
// public final class ImportStatement {
//
// private static final String IMPORT_PREFIX = "import ";
// private static final String STATIC_PREFIX = "static ";
// private final String importName;
// private final int line;
// private final boolean staticImport;
//
// public ImportStatement(String importName, int line, boolean staticImport) {
// Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty");
// Preconditions.checkArgument(!importName.startsWith(IMPORT_PREFIX),
// "importName should be the raw package name without 'import ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(!importName.startsWith(STATIC_PREFIX),
// "importName should be the raw package name without 'static ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(importName.trim().equals(importName),
// "importName has leading or trailing spaces: '%s'", importName);
// Preconditions.checkArgument(line > 0, "line numbers should be 1-based and not start at 0");
//
// this.importName = importName;
// this.line = line;
// this.staticImport = staticImport;
// }
//
// /**
// * The physical line within the source file in which the import has occurred. Number
// * is always 1-based!
// *
// * @return The line number of the matched imports.
// */
// public int getLine() {
// return line;
// }
//
// /**
// * Returns the import name including the 'static ' prefix if this represents a static
// * import.
// *
// * @return The full import name.
// */
// public String getImportName() {
// if (staticImport) {
// return STATIC_PREFIX + importName;
// }
// return importName;
// }
//
// public String getFqcn() {
// return importName;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("import", importName)
// .add("line", line)
// .add("static", staticImport)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(importName, line, staticImport);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ImportStatement
// && Objects.equals(this.line, ((ImportStatement) obj).line)
// && Objects.equals(this.staticImport, ((ImportStatement) obj).staticImport)
// && Objects.equals(this.importName, ((ImportStatement) obj).importName);
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Whitespaces.java
// public final class Whitespaces {
//
// private static final Pattern LEADING = Pattern.compile("^\\s+");
// private static final Pattern TRAILING = Pattern.compile("\\s+$");
//
// /**
// * Trims all leading and trailing whitespaces (regex pattern class <code>\s</code>)
// *
// * @param s The string to trim.
// * @return The trimmed string.
// */
// public static final String trimAll(String s) {
// final Matcher leadingMatcher = LEADING.matcher(s);
// final Matcher trailingMatcher = TRAILING.matcher(s);
// final boolean hasLeading = leadingMatcher.find();
// final boolean hasTrailing = trailingMatcher.find();
// if (!hasLeading && !hasTrailing) {
// return s;
// }
// final int start = hasLeading ? leadingMatcher.end() : 0;
// final int end = hasTrailing ? trailingMatcher.start() : s.length();
// return s.substring(start, end);
// }
//
// private Whitespaces() {
// // hidden
// }
// }
| import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatement;
import de.skuzzle.enforcer.restrictimports.util.Whitespaces; | @Override
public Optional<String> parsePackage(String line) {
if (!isPackage(line)) {
return Optional.empty();
}
return Optional.of(extractPackageName(line));
}
@Override
public List<ImportStatement> parseImport(String line, int lineNumber) {
if (!isImport(line)) {
return Collections.emptyList();
}
// There can be multiple import statements within the same line, so
// we simply split them at their ';'
final String[] parts = line.split(";");
return Arrays.stream(parts)
.map(String::trim)
.filter(s -> !s.isEmpty())
.map(s -> s.substring(IMPORT_STATEMENT.length()))
.map(String::trim)
.map(this::removeAlias)
.map(importName -> toImportStatement(importName, lineNumber))
.collect(Collectors.toList());
}
private ImportStatement toImportStatement(String importName, int lineNumber) {
if (importName.startsWith(STATIC_PREFIX)) { | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
// public final class ImportStatement {
//
// private static final String IMPORT_PREFIX = "import ";
// private static final String STATIC_PREFIX = "static ";
// private final String importName;
// private final int line;
// private final boolean staticImport;
//
// public ImportStatement(String importName, int line, boolean staticImport) {
// Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty");
// Preconditions.checkArgument(!importName.startsWith(IMPORT_PREFIX),
// "importName should be the raw package name without 'import ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(!importName.startsWith(STATIC_PREFIX),
// "importName should be the raw package name without 'static ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(importName.trim().equals(importName),
// "importName has leading or trailing spaces: '%s'", importName);
// Preconditions.checkArgument(line > 0, "line numbers should be 1-based and not start at 0");
//
// this.importName = importName;
// this.line = line;
// this.staticImport = staticImport;
// }
//
// /**
// * The physical line within the source file in which the import has occurred. Number
// * is always 1-based!
// *
// * @return The line number of the matched imports.
// */
// public int getLine() {
// return line;
// }
//
// /**
// * Returns the import name including the 'static ' prefix if this represents a static
// * import.
// *
// * @return The full import name.
// */
// public String getImportName() {
// if (staticImport) {
// return STATIC_PREFIX + importName;
// }
// return importName;
// }
//
// public String getFqcn() {
// return importName;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("import", importName)
// .add("line", line)
// .add("static", staticImport)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(importName, line, staticImport);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ImportStatement
// && Objects.equals(this.line, ((ImportStatement) obj).line)
// && Objects.equals(this.staticImport, ((ImportStatement) obj).staticImport)
// && Objects.equals(this.importName, ((ImportStatement) obj).importName);
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Whitespaces.java
// public final class Whitespaces {
//
// private static final Pattern LEADING = Pattern.compile("^\\s+");
// private static final Pattern TRAILING = Pattern.compile("\\s+$");
//
// /**
// * Trims all leading and trailing whitespaces (regex pattern class <code>\s</code>)
// *
// * @param s The string to trim.
// * @return The trimmed string.
// */
// public static final String trimAll(String s) {
// final Matcher leadingMatcher = LEADING.matcher(s);
// final Matcher trailingMatcher = TRAILING.matcher(s);
// final boolean hasLeading = leadingMatcher.find();
// final boolean hasTrailing = trailingMatcher.find();
// if (!hasLeading && !hasTrailing) {
// return s;
// }
// final int start = hasLeading ? leadingMatcher.end() : 0;
// final int end = hasTrailing ? trailingMatcher.start() : s.length();
// return s.substring(start, end);
// }
//
// private Whitespaces() {
// // hidden
// }
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/lang/KotlinGroovyLanguageSupport.java
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatement;
import de.skuzzle.enforcer.restrictimports.util.Whitespaces;
@Override
public Optional<String> parsePackage(String line) {
if (!isPackage(line)) {
return Optional.empty();
}
return Optional.of(extractPackageName(line));
}
@Override
public List<ImportStatement> parseImport(String line, int lineNumber) {
if (!isImport(line)) {
return Collections.emptyList();
}
// There can be multiple import statements within the same line, so
// we simply split them at their ';'
final String[] parts = line.split(";");
return Arrays.stream(parts)
.map(String::trim)
.filter(s -> !s.isEmpty())
.map(s -> s.substring(IMPORT_STATEMENT.length()))
.map(String::trim)
.map(this::removeAlias)
.map(importName -> toImportStatement(importName, lineNumber))
.collect(Collectors.toList());
}
private ImportStatement toImportStatement(String importName, int lineNumber) {
if (importName.startsWith(STATIC_PREFIX)) { | final String realImportName = Whitespaces.trimAll(importName.substring(STATIC_PREFIX.length())); |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/analyze/AnalyzerSettings.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/StringRepresentation.java
// public final class StringRepresentation {
//
// private final String name;
// private final List<Attribute> attributes = new ArrayList<>();
//
// private StringRepresentation(String name) {
// this.name = name;
// }
//
// public static StringRepresentation ofType(Class<?> type) {
// return new StringRepresentation(type.getSimpleName());
// }
//
// public static StringRepresentation ofInstance(Object instance) {
// return ofType(instance.getClass());
// }
//
// public StringRepresentation add(String attribute, Object value) {
// attributes.add(new Attribute(attribute, value));
// return this;
// }
//
// @Override
// public String toString() {
// return new StringBuilder(name)
// .append("{")
// .append(attributes.stream().map(Attribute::toString).collect(Collectors.joining(", ")))
// .append("}")
// .toString();
// }
//
// private static final class Attribute {
// private final String name;
// private final Object value;
//
// private Attribute(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public String toString() {
// return name + "=" + value;
// }
// }
// }
| import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import de.skuzzle.enforcer.restrictimports.util.StringRepresentation; | }
/**
* Returns the union of {@link #getSrcDirectories()} and getTestDirectories.
*
* @return All source directories that are subject to analysis.
*/
public Collection<Path> getAllDirectories() {
final Set<Path> result = new HashSet<>(srcDirectories.size() + testDirectories.size());
result.addAll(srcDirectories);
result.addAll(testDirectories);
return result;
}
@Override
public int hashCode() {
return Objects.hash(sourceFileCharset, srcDirectories, testDirectories, parallel);
}
@Override
public boolean equals(Object obj) {
return obj == this || obj instanceof AnalyzerSettings
&& Objects.equals(sourceFileCharset, ((AnalyzerSettings) obj).sourceFileCharset)
&& Objects.equals(srcDirectories, ((AnalyzerSettings) obj).srcDirectories)
&& Objects.equals(testDirectories, ((AnalyzerSettings) obj).testDirectories)
&& parallel == ((AnalyzerSettings) obj).parallel;
}
@Override
public String toString() { | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/StringRepresentation.java
// public final class StringRepresentation {
//
// private final String name;
// private final List<Attribute> attributes = new ArrayList<>();
//
// private StringRepresentation(String name) {
// this.name = name;
// }
//
// public static StringRepresentation ofType(Class<?> type) {
// return new StringRepresentation(type.getSimpleName());
// }
//
// public static StringRepresentation ofInstance(Object instance) {
// return ofType(instance.getClass());
// }
//
// public StringRepresentation add(String attribute, Object value) {
// attributes.add(new Attribute(attribute, value));
// return this;
// }
//
// @Override
// public String toString() {
// return new StringBuilder(name)
// .append("{")
// .append(attributes.stream().map(Attribute::toString).collect(Collectors.joining(", ")))
// .append("}")
// .toString();
// }
//
// private static final class Attribute {
// private final String name;
// private final Object value;
//
// private Attribute(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public String toString() {
// return name + "=" + value;
// }
// }
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/analyze/AnalyzerSettings.java
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import de.skuzzle.enforcer.restrictimports.util.StringRepresentation;
}
/**
* Returns the union of {@link #getSrcDirectories()} and getTestDirectories.
*
* @return All source directories that are subject to analysis.
*/
public Collection<Path> getAllDirectories() {
final Set<Path> result = new HashSet<>(srcDirectories.size() + testDirectories.size());
result.addAll(srcDirectories);
result.addAll(testDirectories);
return result;
}
@Override
public int hashCode() {
return Objects.hash(sourceFileCharset, srcDirectories, testDirectories, parallel);
}
@Override
public boolean equals(Object obj) {
return obj == this || obj instanceof AnalyzerSettings
&& Objects.equals(sourceFileCharset, ((AnalyzerSettings) obj).sourceFileCharset)
&& Objects.equals(srcDirectories, ((AnalyzerSettings) obj).srcDirectories)
&& Objects.equals(testDirectories, ((AnalyzerSettings) obj).testDirectories)
&& parallel == ((AnalyzerSettings) obj).parallel;
}
@Override
public String toString() { | return StringRepresentation.ofInstance(this) |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/analyze/BannedImportGroups.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
| import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import de.skuzzle.enforcer.restrictimports.util.Preconditions; |
public BannedImportGroup getGroup() {
return this.group;
}
@Override
public int compareTo(GroupMatch o) {
return o.basePackage.compareTo(basePackage);
}
}
public static final class Builder {
private final List<BannedImportGroup> groups = new ArrayList<>();
public Builder withGroups(Collection<BannedImportGroup> groups) {
this.groups.addAll(groups);
return this;
}
public Builder withGroup(BannedImportGroup group) {
this.groups.add(group);
return this;
}
public Builder withGroup(BannedImportGroup.Builder groupBuilder) {
groups.add(groupBuilder.build());
return this;
}
public BannedImportGroups build() { | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/analyze/BannedImportGroups.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import de.skuzzle.enforcer.restrictimports.util.Preconditions;
public BannedImportGroup getGroup() {
return this.group;
}
@Override
public int compareTo(GroupMatch o) {
return o.basePackage.compareTo(basePackage);
}
}
public static final class Builder {
private final List<BannedImportGroup> groups = new ArrayList<>();
public Builder withGroups(Collection<BannedImportGroup> groups) {
this.groups.addAll(groups);
return this;
}
public Builder withGroup(BannedImportGroup group) {
this.groups.add(group);
return this;
}
public Builder withGroup(BannedImportGroup.Builder groupBuilder) {
groups.add(groupBuilder.build());
return this;
}
public BannedImportGroups build() { | Preconditions.checkArgument(!groups.isEmpty(), "No BannedImportGroups have been specified"); |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/analyze/BannedImportGroup.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/StringRepresentation.java
// public final class StringRepresentation {
//
// private final String name;
// private final List<Attribute> attributes = new ArrayList<>();
//
// private StringRepresentation(String name) {
// this.name = name;
// }
//
// public static StringRepresentation ofType(Class<?> type) {
// return new StringRepresentation(type.getSimpleName());
// }
//
// public static StringRepresentation ofInstance(Object instance) {
// return ofType(instance.getClass());
// }
//
// public StringRepresentation add(String attribute, Object value) {
// attributes.add(new Attribute(attribute, value));
// return this;
// }
//
// @Override
// public String toString() {
// return new StringBuilder(name)
// .append("{")
// .append(attributes.stream().map(Attribute::toString).collect(Collectors.joining(", ")))
// .append("}")
// .toString();
// }
//
// private static final class Attribute {
// private final String name;
// private final Object value;
//
// private Attribute(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public String toString() {
// return name + "=" + value;
// }
// }
// }
| import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import de.skuzzle.enforcer.restrictimports.util.StringRepresentation; | return matchesAnyPattern(fqcn, exclusions);
}
private boolean matchesAnyPattern(String packageName,
Collection<PackagePattern> patterns) {
return patterns.stream()
.anyMatch(pattern -> pattern.matches(packageName));
}
public Optional<String> getReason() {
return Optional.ofNullable(this.reason).filter(s -> !s.isEmpty());
}
@Override
public int hashCode() {
return Objects.hash(basePackages, bannedImports, allowedImports, exclusions, reason);
}
@Override
public boolean equals(Object obj) {
return obj == this || obj instanceof BannedImportGroup
&& Objects.equals(basePackages, ((BannedImportGroup) obj).basePackages)
&& Objects.equals(bannedImports, ((BannedImportGroup) obj).bannedImports)
&& Objects.equals(allowedImports, ((BannedImportGroup) obj).allowedImports)
&& Objects.equals(exclusions, ((BannedImportGroup) obj).exclusions)
&& Objects.equals(reason, ((BannedImportGroup) obj).reason);
}
@Override
public String toString() { | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/StringRepresentation.java
// public final class StringRepresentation {
//
// private final String name;
// private final List<Attribute> attributes = new ArrayList<>();
//
// private StringRepresentation(String name) {
// this.name = name;
// }
//
// public static StringRepresentation ofType(Class<?> type) {
// return new StringRepresentation(type.getSimpleName());
// }
//
// public static StringRepresentation ofInstance(Object instance) {
// return ofType(instance.getClass());
// }
//
// public StringRepresentation add(String attribute, Object value) {
// attributes.add(new Attribute(attribute, value));
// return this;
// }
//
// @Override
// public String toString() {
// return new StringBuilder(name)
// .append("{")
// .append(attributes.stream().map(Attribute::toString).collect(Collectors.joining(", ")))
// .append("}")
// .toString();
// }
//
// private static final class Attribute {
// private final String name;
// private final Object value;
//
// private Attribute(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public String toString() {
// return name + "=" + value;
// }
// }
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/analyze/BannedImportGroup.java
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import de.skuzzle.enforcer.restrictimports.util.StringRepresentation;
return matchesAnyPattern(fqcn, exclusions);
}
private boolean matchesAnyPattern(String packageName,
Collection<PackagePattern> patterns) {
return patterns.stream()
.anyMatch(pattern -> pattern.matches(packageName));
}
public Optional<String> getReason() {
return Optional.ofNullable(this.reason).filter(s -> !s.isEmpty());
}
@Override
public int hashCode() {
return Objects.hash(basePackages, bannedImports, allowedImports, exclusions, reason);
}
@Override
public boolean equals(Object obj) {
return obj == this || obj instanceof BannedImportGroup
&& Objects.equals(basePackages, ((BannedImportGroup) obj).basePackages)
&& Objects.equals(bannedImports, ((BannedImportGroup) obj).bannedImports)
&& Objects.equals(allowedImports, ((BannedImportGroup) obj).allowedImports)
&& Objects.equals(exclusions, ((BannedImportGroup) obj).exclusions)
&& Objects.equals(reason, ((BannedImportGroup) obj).reason);
}
@Override
public String toString() { | return StringRepresentation.ofInstance(this) |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/StringRepresentation.java
// public final class StringRepresentation {
//
// private final String name;
// private final List<Attribute> attributes = new ArrayList<>();
//
// private StringRepresentation(String name) {
// this.name = name;
// }
//
// public static StringRepresentation ofType(Class<?> type) {
// return new StringRepresentation(type.getSimpleName());
// }
//
// public static StringRepresentation ofInstance(Object instance) {
// return ofType(instance.getClass());
// }
//
// public StringRepresentation add(String attribute, Object value) {
// attributes.add(new Attribute(attribute, value));
// return this;
// }
//
// @Override
// public String toString() {
// return new StringBuilder(name)
// .append("{")
// .append(attributes.stream().map(Attribute::toString).collect(Collectors.joining(", ")))
// .append("}")
// .toString();
// }
//
// private static final class Attribute {
// private final String name;
// private final Object value;
//
// private Attribute(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public String toString() {
// return name + "=" + value;
// }
// }
// }
| import java.util.Objects;
import de.skuzzle.enforcer.restrictimports.util.Preconditions;
import de.skuzzle.enforcer.restrictimports.util.StringRepresentation; | package de.skuzzle.enforcer.restrictimports.parser;
/**
* Represents an import statement that has been discovered while parsing a source file.
*/
public final class ImportStatement {
private static final String IMPORT_PREFIX = "import ";
private static final String STATIC_PREFIX = "static ";
private final String importName;
private final int line;
private final boolean staticImport;
public ImportStatement(String importName, int line, boolean staticImport) { | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/StringRepresentation.java
// public final class StringRepresentation {
//
// private final String name;
// private final List<Attribute> attributes = new ArrayList<>();
//
// private StringRepresentation(String name) {
// this.name = name;
// }
//
// public static StringRepresentation ofType(Class<?> type) {
// return new StringRepresentation(type.getSimpleName());
// }
//
// public static StringRepresentation ofInstance(Object instance) {
// return ofType(instance.getClass());
// }
//
// public StringRepresentation add(String attribute, Object value) {
// attributes.add(new Attribute(attribute, value));
// return this;
// }
//
// @Override
// public String toString() {
// return new StringBuilder(name)
// .append("{")
// .append(attributes.stream().map(Attribute::toString).collect(Collectors.joining(", ")))
// .append("}")
// .toString();
// }
//
// private static final class Attribute {
// private final String name;
// private final Object value;
//
// private Attribute(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public String toString() {
// return name + "=" + value;
// }
// }
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
import java.util.Objects;
import de.skuzzle.enforcer.restrictimports.util.Preconditions;
import de.skuzzle.enforcer.restrictimports.util.StringRepresentation;
package de.skuzzle.enforcer.restrictimports.parser;
/**
* Represents an import statement that has been discovered while parsing a source file.
*/
public final class ImportStatement {
private static final String IMPORT_PREFIX = "import ";
private static final String STATIC_PREFIX = "static ";
private final String importName;
private final int line;
private final boolean staticImport;
public ImportStatement(String importName, int line, boolean staticImport) { | Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty"); |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/StringRepresentation.java
// public final class StringRepresentation {
//
// private final String name;
// private final List<Attribute> attributes = new ArrayList<>();
//
// private StringRepresentation(String name) {
// this.name = name;
// }
//
// public static StringRepresentation ofType(Class<?> type) {
// return new StringRepresentation(type.getSimpleName());
// }
//
// public static StringRepresentation ofInstance(Object instance) {
// return ofType(instance.getClass());
// }
//
// public StringRepresentation add(String attribute, Object value) {
// attributes.add(new Attribute(attribute, value));
// return this;
// }
//
// @Override
// public String toString() {
// return new StringBuilder(name)
// .append("{")
// .append(attributes.stream().map(Attribute::toString).collect(Collectors.joining(", ")))
// .append("}")
// .toString();
// }
//
// private static final class Attribute {
// private final String name;
// private final Object value;
//
// private Attribute(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public String toString() {
// return name + "=" + value;
// }
// }
// }
| import java.util.Objects;
import de.skuzzle.enforcer.restrictimports.util.Preconditions;
import de.skuzzle.enforcer.restrictimports.util.StringRepresentation; |
/**
* The physical line within the source file in which the import has occurred. Number
* is always 1-based!
*
* @return The line number of the matched imports.
*/
public int getLine() {
return line;
}
/**
* Returns the import name including the 'static ' prefix if this represents a static
* import.
*
* @return The full import name.
*/
public String getImportName() {
if (staticImport) {
return STATIC_PREFIX + importName;
}
return importName;
}
public String getFqcn() {
return importName;
}
@Override
public String toString() { | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/StringRepresentation.java
// public final class StringRepresentation {
//
// private final String name;
// private final List<Attribute> attributes = new ArrayList<>();
//
// private StringRepresentation(String name) {
// this.name = name;
// }
//
// public static StringRepresentation ofType(Class<?> type) {
// return new StringRepresentation(type.getSimpleName());
// }
//
// public static StringRepresentation ofInstance(Object instance) {
// return ofType(instance.getClass());
// }
//
// public StringRepresentation add(String attribute, Object value) {
// attributes.add(new Attribute(attribute, value));
// return this;
// }
//
// @Override
// public String toString() {
// return new StringBuilder(name)
// .append("{")
// .append(attributes.stream().map(Attribute::toString).collect(Collectors.joining(", ")))
// .append("}")
// .toString();
// }
//
// private static final class Attribute {
// private final String name;
// private final Object value;
//
// private Attribute(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public String toString() {
// return name + "=" + value;
// }
// }
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
import java.util.Objects;
import de.skuzzle.enforcer.restrictimports.util.Preconditions;
import de.skuzzle.enforcer.restrictimports.util.StringRepresentation;
/**
* The physical line within the source file in which the import has occurred. Number
* is always 1-based!
*
* @return The line number of the matched imports.
*/
public int getLine() {
return line;
}
/**
* Returns the import name including the 'static ' prefix if this represents a static
* import.
*
* @return The full import name.
*/
public String getImportName() {
if (staticImport) {
return STATIC_PREFIX + importName;
}
return importName;
}
public String getFqcn() {
return importName;
}
@Override
public String toString() { | return StringRepresentation.ofInstance(this) |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatementParserImpl.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/lang/LanguageSupport.java
// public interface LanguageSupport {
//
// /**
// * Returns the {@link LanguageSupport} implementation for the given file.
// *
// * @param path The path to a file.
// * @return The {@link LanguageSupport} implementation or an empty optional if none was
// * found.
// */
// static LanguageSupport getLanguageSupport(Path path) {
// final String extension = FileExtension.fromPath(path);
// return SupportedLanguageHolder.getLanguageSupport(extension)
// .orElseThrow(() -> new IllegalArgumentException(String.format(
// "Could not find a LanguageSupport implementation for normalized file extension: '%s' (%s)",
// extension, path)));
// }
//
// /**
// * Determines whether there exists a {@link LanguageSupport} implementation for the
// * given path.
// *
// * @param path The path to a file.
// * @return Whether such implementation exists.
// * @since 1.1.0
// */
// static boolean isLanguageSupported(Path path) {
// final Path filename = path.getFileName();
// return !Files.isDirectory(path)
// && SupportedLanguageHolder.isLanguageSupported(FileExtension.fromPath(filename));
// }
//
// /**
// * The set of supported file extensions. Extensions returned here are case insensitive
// * and may or may not start with a '.' (dot).
// *
// * @return The set of file extensions.
// */
// Set<String> getSupportedFileExtensions();
//
// /**
// * Parses the given line and returns the declared package
// *
// * @param line Line in the source file
// * @return The package declared
// */
// Optional<String> parsePackage(String line);
//
// /**
// * Extract the package names that this import statement represents. As some languages
// * allow to specify multiple imports in a single line, this method returns a list.
// * <p>
// * e.g. import java.util.List; The above should return java.util.List in a Java source
// * file.
// *
// * @param importLine Line in the source file
// * @param lineNumber The line number of the import.
// * @return Fully qualified package name that this import represents
// */
// List<ImportStatement> parseImport(String importLine, int lineNumber);
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
| import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.skuzzle.enforcer.restrictimports.parser.lang.LanguageSupport;
import de.skuzzle.enforcer.restrictimports.util.Preconditions; | package de.skuzzle.enforcer.restrictimports.parser;
/**
* Parses a source file into a {@link ParsedFile} representation.
*/
final class ImportStatementParserImpl implements ImportStatementParser {
private static final Logger LOGGER = LoggerFactory.getLogger(ImportStatementParserImpl.class);
private final LineSupplier supplier;
/**
* Constructor just for testing purposes.
*
* @param supplier The line sources
*/
ImportStatementParserImpl(LineSupplier supplier) {
this.supplier = supplier;
}
@Override
public ParsedFile parse(Path sourceFilePath) {
LOGGER.trace("Analyzing {} for imports", sourceFilePath);
| // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/lang/LanguageSupport.java
// public interface LanguageSupport {
//
// /**
// * Returns the {@link LanguageSupport} implementation for the given file.
// *
// * @param path The path to a file.
// * @return The {@link LanguageSupport} implementation or an empty optional if none was
// * found.
// */
// static LanguageSupport getLanguageSupport(Path path) {
// final String extension = FileExtension.fromPath(path);
// return SupportedLanguageHolder.getLanguageSupport(extension)
// .orElseThrow(() -> new IllegalArgumentException(String.format(
// "Could not find a LanguageSupport implementation for normalized file extension: '%s' (%s)",
// extension, path)));
// }
//
// /**
// * Determines whether there exists a {@link LanguageSupport} implementation for the
// * given path.
// *
// * @param path The path to a file.
// * @return Whether such implementation exists.
// * @since 1.1.0
// */
// static boolean isLanguageSupported(Path path) {
// final Path filename = path.getFileName();
// return !Files.isDirectory(path)
// && SupportedLanguageHolder.isLanguageSupported(FileExtension.fromPath(filename));
// }
//
// /**
// * The set of supported file extensions. Extensions returned here are case insensitive
// * and may or may not start with a '.' (dot).
// *
// * @return The set of file extensions.
// */
// Set<String> getSupportedFileExtensions();
//
// /**
// * Parses the given line and returns the declared package
// *
// * @param line Line in the source file
// * @return The package declared
// */
// Optional<String> parsePackage(String line);
//
// /**
// * Extract the package names that this import statement represents. As some languages
// * allow to specify multiple imports in a single line, this method returns a list.
// * <p>
// * e.g. import java.util.List; The above should return java.util.List in a Java source
// * file.
// *
// * @param importLine Line in the source file
// * @param lineNumber The line number of the import.
// * @return Fully qualified package name that this import represents
// */
// List<ImportStatement> parseImport(String importLine, int lineNumber);
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatementParserImpl.java
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.skuzzle.enforcer.restrictimports.parser.lang.LanguageSupport;
import de.skuzzle.enforcer.restrictimports.util.Preconditions;
package de.skuzzle.enforcer.restrictimports.parser;
/**
* Parses a source file into a {@link ParsedFile} representation.
*/
final class ImportStatementParserImpl implements ImportStatementParser {
private static final Logger LOGGER = LoggerFactory.getLogger(ImportStatementParserImpl.class);
private final LineSupplier supplier;
/**
* Constructor just for testing purposes.
*
* @param supplier The line sources
*/
ImportStatementParserImpl(LineSupplier supplier) {
this.supplier = supplier;
}
@Override
public ParsedFile parse(Path sourceFilePath) {
LOGGER.trace("Analyzing {} for imports", sourceFilePath);
| final LanguageSupport languageSupport = LanguageSupport.getLanguageSupport(sourceFilePath); |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatementParserImpl.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/lang/LanguageSupport.java
// public interface LanguageSupport {
//
// /**
// * Returns the {@link LanguageSupport} implementation for the given file.
// *
// * @param path The path to a file.
// * @return The {@link LanguageSupport} implementation or an empty optional if none was
// * found.
// */
// static LanguageSupport getLanguageSupport(Path path) {
// final String extension = FileExtension.fromPath(path);
// return SupportedLanguageHolder.getLanguageSupport(extension)
// .orElseThrow(() -> new IllegalArgumentException(String.format(
// "Could not find a LanguageSupport implementation for normalized file extension: '%s' (%s)",
// extension, path)));
// }
//
// /**
// * Determines whether there exists a {@link LanguageSupport} implementation for the
// * given path.
// *
// * @param path The path to a file.
// * @return Whether such implementation exists.
// * @since 1.1.0
// */
// static boolean isLanguageSupported(Path path) {
// final Path filename = path.getFileName();
// return !Files.isDirectory(path)
// && SupportedLanguageHolder.isLanguageSupported(FileExtension.fromPath(filename));
// }
//
// /**
// * The set of supported file extensions. Extensions returned here are case insensitive
// * and may or may not start with a '.' (dot).
// *
// * @return The set of file extensions.
// */
// Set<String> getSupportedFileExtensions();
//
// /**
// * Parses the given line and returns the declared package
// *
// * @param line Line in the source file
// * @return The package declared
// */
// Optional<String> parsePackage(String line);
//
// /**
// * Extract the package names that this import statement represents. As some languages
// * allow to specify multiple imports in a single line, this method returns a list.
// * <p>
// * e.g. import java.util.List; The above should return java.util.List in a Java source
// * file.
// *
// * @param importLine Line in the source file
// * @param lineNumber The line number of the import.
// * @return Fully qualified package name that this import represents
// */
// List<ImportStatement> parseImport(String importLine, int lineNumber);
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
| import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.skuzzle.enforcer.restrictimports.parser.lang.LanguageSupport;
import de.skuzzle.enforcer.restrictimports.util.Preconditions; | package de.skuzzle.enforcer.restrictimports.parser;
/**
* Parses a source file into a {@link ParsedFile} representation.
*/
final class ImportStatementParserImpl implements ImportStatementParser {
private static final Logger LOGGER = LoggerFactory.getLogger(ImportStatementParserImpl.class);
private final LineSupplier supplier;
/**
* Constructor just for testing purposes.
*
* @param supplier The line sources
*/
ImportStatementParserImpl(LineSupplier supplier) {
this.supplier = supplier;
}
@Override
public ParsedFile parse(Path sourceFilePath) {
LOGGER.trace("Analyzing {} for imports", sourceFilePath);
final LanguageSupport languageSupport = LanguageSupport.getLanguageSupport(sourceFilePath);
final List<ImportStatement> imports = new ArrayList<>();
final String fileName = getFileNameWithoutExtension(sourceFilePath);
try (final Stream<String> lines = this.supplier.lines(sourceFilePath)) {
int row = 1;
String packageName = "";
String fqcn = fileName;
for (final Iterator<String> it = lines.map(String::trim).iterator(); it.hasNext(); ++row) {
final String line = it.next();
// Implementation note: We check for empty lines here (instead of in
// LineSupplier implementation)
// so that we are able to keep track of correct line numbers.
if (line.isEmpty()) {
continue;
}
final Optional<String> packageDeclaration = languageSupport.parsePackage(line);
if (packageDeclaration.isPresent()) { | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/lang/LanguageSupport.java
// public interface LanguageSupport {
//
// /**
// * Returns the {@link LanguageSupport} implementation for the given file.
// *
// * @param path The path to a file.
// * @return The {@link LanguageSupport} implementation or an empty optional if none was
// * found.
// */
// static LanguageSupport getLanguageSupport(Path path) {
// final String extension = FileExtension.fromPath(path);
// return SupportedLanguageHolder.getLanguageSupport(extension)
// .orElseThrow(() -> new IllegalArgumentException(String.format(
// "Could not find a LanguageSupport implementation for normalized file extension: '%s' (%s)",
// extension, path)));
// }
//
// /**
// * Determines whether there exists a {@link LanguageSupport} implementation for the
// * given path.
// *
// * @param path The path to a file.
// * @return Whether such implementation exists.
// * @since 1.1.0
// */
// static boolean isLanguageSupported(Path path) {
// final Path filename = path.getFileName();
// return !Files.isDirectory(path)
// && SupportedLanguageHolder.isLanguageSupported(FileExtension.fromPath(filename));
// }
//
// /**
// * The set of supported file extensions. Extensions returned here are case insensitive
// * and may or may not start with a '.' (dot).
// *
// * @return The set of file extensions.
// */
// Set<String> getSupportedFileExtensions();
//
// /**
// * Parses the given line and returns the declared package
// *
// * @param line Line in the source file
// * @return The package declared
// */
// Optional<String> parsePackage(String line);
//
// /**
// * Extract the package names that this import statement represents. As some languages
// * allow to specify multiple imports in a single line, this method returns a list.
// * <p>
// * e.g. import java.util.List; The above should return java.util.List in a Java source
// * file.
// *
// * @param importLine Line in the source file
// * @param lineNumber The line number of the import.
// * @return Fully qualified package name that this import represents
// */
// List<ImportStatement> parseImport(String importLine, int lineNumber);
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatementParserImpl.java
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.skuzzle.enforcer.restrictimports.parser.lang.LanguageSupport;
import de.skuzzle.enforcer.restrictimports.util.Preconditions;
package de.skuzzle.enforcer.restrictimports.parser;
/**
* Parses a source file into a {@link ParsedFile} representation.
*/
final class ImportStatementParserImpl implements ImportStatementParser {
private static final Logger LOGGER = LoggerFactory.getLogger(ImportStatementParserImpl.class);
private final LineSupplier supplier;
/**
* Constructor just for testing purposes.
*
* @param supplier The line sources
*/
ImportStatementParserImpl(LineSupplier supplier) {
this.supplier = supplier;
}
@Override
public ParsedFile parse(Path sourceFilePath) {
LOGGER.trace("Analyzing {} for imports", sourceFilePath);
final LanguageSupport languageSupport = LanguageSupport.getLanguageSupport(sourceFilePath);
final List<ImportStatement> imports = new ArrayList<>();
final String fileName = getFileNameWithoutExtension(sourceFilePath);
try (final Stream<String> lines = this.supplier.lines(sourceFilePath)) {
int row = 1;
String packageName = "";
String fqcn = fileName;
for (final Iterator<String> it = lines.map(String::trim).iterator(); it.hasNext(); ++row) {
final String line = it.next();
// Implementation note: We check for empty lines here (instead of in
// LineSupplier implementation)
// so that we are able to keep track of correct line numbers.
if (line.isEmpty()) {
continue;
}
final Optional<String> packageDeclaration = languageSupport.parsePackage(line);
if (packageDeclaration.isPresent()) { | Preconditions.checkState(packageName.isEmpty(), "found duplicate package statement in '%s'", |
skuzzle/restrict-imports-enforcer-rule | src/test/java/de/skuzzle/enforcer/restrictimports/analyze/ImportAnalyzerTest.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
// public final class ImportStatement {
//
// private static final String IMPORT_PREFIX = "import ";
// private static final String STATIC_PREFIX = "static ";
// private final String importName;
// private final int line;
// private final boolean staticImport;
//
// public ImportStatement(String importName, int line, boolean staticImport) {
// Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty");
// Preconditions.checkArgument(!importName.startsWith(IMPORT_PREFIX),
// "importName should be the raw package name without 'import ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(!importName.startsWith(STATIC_PREFIX),
// "importName should be the raw package name without 'static ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(importName.trim().equals(importName),
// "importName has leading or trailing spaces: '%s'", importName);
// Preconditions.checkArgument(line > 0, "line numbers should be 1-based and not start at 0");
//
// this.importName = importName;
// this.line = line;
// this.staticImport = staticImport;
// }
//
// /**
// * The physical line within the source file in which the import has occurred. Number
// * is always 1-based!
// *
// * @return The line number of the matched imports.
// */
// public int getLine() {
// return line;
// }
//
// /**
// * Returns the import name including the 'static ' prefix if this represents a static
// * import.
// *
// * @return The full import name.
// */
// public String getImportName() {
// if (staticImport) {
// return STATIC_PREFIX + importName;
// }
// return importName;
// }
//
// public String getFqcn() {
// return importName;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("import", importName)
// .add("line", line)
// .add("static", staticImport)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(importName, line, staticImport);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ImportStatement
// && Objects.equals(this.line, ((ImportStatement) obj).line)
// && Objects.equals(this.staticImport, ((ImportStatement) obj).staticImport)
// && Objects.equals(this.importName, ((ImportStatement) obj).importName);
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ParsedFile.java
// public final class ParsedFile {
//
// private final Path path;
// private final String declaredPackage;
// private final String fqcn;
// private final Collection<ImportStatement> imports;
//
// public ParsedFile(Path path, String declaredPackage, String fqcn, Collection<ImportStatement> imports) {
// this.path = path;
// this.declaredPackage = declaredPackage;
// this.fqcn = fqcn;
// this.imports = imports;
// }
//
// public Path getPath() {
// return path;
// }
//
// public Collection<ImportStatement> getImports() {
// return imports;
// }
//
// public String getFqcn() {
// return fqcn;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("path", path)
// .add("declaredPackage", declaredPackage)
// .add("fqcn", fqcn)
// .add("imports", imports)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(path, declaredPackage, fqcn, imports);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ParsedFile
// && Objects.equals(path, ((ParsedFile) obj).path)
// && Objects.equals(declaredPackage, ((ParsedFile) obj).declaredPackage)
// && Objects.equals(fqcn, ((ParsedFile) obj).fqcn)
// && Objects.equals(imports, ((ParsedFile) obj).imports);
// }
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatement;
import de.skuzzle.enforcer.restrictimports.parser.ParsedFile; | package de.skuzzle.enforcer.restrictimports.analyze;
class ImportAnalyzerTest {
private final ImportAnalyzer subject = new ImportAnalyzer();
| // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
// public final class ImportStatement {
//
// private static final String IMPORT_PREFIX = "import ";
// private static final String STATIC_PREFIX = "static ";
// private final String importName;
// private final int line;
// private final boolean staticImport;
//
// public ImportStatement(String importName, int line, boolean staticImport) {
// Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty");
// Preconditions.checkArgument(!importName.startsWith(IMPORT_PREFIX),
// "importName should be the raw package name without 'import ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(!importName.startsWith(STATIC_PREFIX),
// "importName should be the raw package name without 'static ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(importName.trim().equals(importName),
// "importName has leading or trailing spaces: '%s'", importName);
// Preconditions.checkArgument(line > 0, "line numbers should be 1-based and not start at 0");
//
// this.importName = importName;
// this.line = line;
// this.staticImport = staticImport;
// }
//
// /**
// * The physical line within the source file in which the import has occurred. Number
// * is always 1-based!
// *
// * @return The line number of the matched imports.
// */
// public int getLine() {
// return line;
// }
//
// /**
// * Returns the import name including the 'static ' prefix if this represents a static
// * import.
// *
// * @return The full import name.
// */
// public String getImportName() {
// if (staticImport) {
// return STATIC_PREFIX + importName;
// }
// return importName;
// }
//
// public String getFqcn() {
// return importName;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("import", importName)
// .add("line", line)
// .add("static", staticImport)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(importName, line, staticImport);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ImportStatement
// && Objects.equals(this.line, ((ImportStatement) obj).line)
// && Objects.equals(this.staticImport, ((ImportStatement) obj).staticImport)
// && Objects.equals(this.importName, ((ImportStatement) obj).importName);
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ParsedFile.java
// public final class ParsedFile {
//
// private final Path path;
// private final String declaredPackage;
// private final String fqcn;
// private final Collection<ImportStatement> imports;
//
// public ParsedFile(Path path, String declaredPackage, String fqcn, Collection<ImportStatement> imports) {
// this.path = path;
// this.declaredPackage = declaredPackage;
// this.fqcn = fqcn;
// this.imports = imports;
// }
//
// public Path getPath() {
// return path;
// }
//
// public Collection<ImportStatement> getImports() {
// return imports;
// }
//
// public String getFqcn() {
// return fqcn;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("path", path)
// .add("declaredPackage", declaredPackage)
// .add("fqcn", fqcn)
// .add("imports", imports)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(path, declaredPackage, fqcn, imports);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ParsedFile
// && Objects.equals(path, ((ParsedFile) obj).path)
// && Objects.equals(declaredPackage, ((ParsedFile) obj).declaredPackage)
// && Objects.equals(fqcn, ((ParsedFile) obj).fqcn)
// && Objects.equals(imports, ((ParsedFile) obj).imports);
// }
//
// }
// Path: src/test/java/de/skuzzle/enforcer/restrictimports/analyze/ImportAnalyzerTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatement;
import de.skuzzle.enforcer.restrictimports.parser.ParsedFile;
package de.skuzzle.enforcer.restrictimports.analyze;
class ImportAnalyzerTest {
private final ImportAnalyzer subject = new ImportAnalyzer();
| private final ParsedFile parsedFile = parsedFile("File", "de.skuzzle.test", |
skuzzle/restrict-imports-enforcer-rule | src/test/java/de/skuzzle/enforcer/restrictimports/analyze/ImportAnalyzerTest.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
// public final class ImportStatement {
//
// private static final String IMPORT_PREFIX = "import ";
// private static final String STATIC_PREFIX = "static ";
// private final String importName;
// private final int line;
// private final boolean staticImport;
//
// public ImportStatement(String importName, int line, boolean staticImport) {
// Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty");
// Preconditions.checkArgument(!importName.startsWith(IMPORT_PREFIX),
// "importName should be the raw package name without 'import ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(!importName.startsWith(STATIC_PREFIX),
// "importName should be the raw package name without 'static ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(importName.trim().equals(importName),
// "importName has leading or trailing spaces: '%s'", importName);
// Preconditions.checkArgument(line > 0, "line numbers should be 1-based and not start at 0");
//
// this.importName = importName;
// this.line = line;
// this.staticImport = staticImport;
// }
//
// /**
// * The physical line within the source file in which the import has occurred. Number
// * is always 1-based!
// *
// * @return The line number of the matched imports.
// */
// public int getLine() {
// return line;
// }
//
// /**
// * Returns the import name including the 'static ' prefix if this represents a static
// * import.
// *
// * @return The full import name.
// */
// public String getImportName() {
// if (staticImport) {
// return STATIC_PREFIX + importName;
// }
// return importName;
// }
//
// public String getFqcn() {
// return importName;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("import", importName)
// .add("line", line)
// .add("static", staticImport)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(importName, line, staticImport);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ImportStatement
// && Objects.equals(this.line, ((ImportStatement) obj).line)
// && Objects.equals(this.staticImport, ((ImportStatement) obj).staticImport)
// && Objects.equals(this.importName, ((ImportStatement) obj).importName);
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ParsedFile.java
// public final class ParsedFile {
//
// private final Path path;
// private final String declaredPackage;
// private final String fqcn;
// private final Collection<ImportStatement> imports;
//
// public ParsedFile(Path path, String declaredPackage, String fqcn, Collection<ImportStatement> imports) {
// this.path = path;
// this.declaredPackage = declaredPackage;
// this.fqcn = fqcn;
// this.imports = imports;
// }
//
// public Path getPath() {
// return path;
// }
//
// public Collection<ImportStatement> getImports() {
// return imports;
// }
//
// public String getFqcn() {
// return fqcn;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("path", path)
// .add("declaredPackage", declaredPackage)
// .add("fqcn", fqcn)
// .add("imports", imports)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(path, declaredPackage, fqcn, imports);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ParsedFile
// && Objects.equals(path, ((ParsedFile) obj).path)
// && Objects.equals(declaredPackage, ((ParsedFile) obj).declaredPackage)
// && Objects.equals(fqcn, ((ParsedFile) obj).fqcn)
// && Objects.equals(imports, ((ParsedFile) obj).imports);
// }
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatement;
import de.skuzzle.enforcer.restrictimports.parser.ParsedFile; | package de.skuzzle.enforcer.restrictimports.analyze;
class ImportAnalyzerTest {
private final ImportAnalyzer subject = new ImportAnalyzer();
private final ParsedFile parsedFile = parsedFile("File", "de.skuzzle.test",
"de.skuzzle.sample.Test",
"foo.bar.xyz",
"de.skuzzle.sample.Test2",
"de.skuzzle.sample.Test3",
"de.foo.bar.Test");
private ParsedFile parsedFile(String className, String packageName, String... lines) {
final String fqcn = packageName + "." + className;
final Path path = mock(Path.class);
final Path fileName = mock(Path.class);
when(path.getFileName()).thenReturn(fileName);
when(fileName.toString()).thenReturn(className + ".java"); | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
// public final class ImportStatement {
//
// private static final String IMPORT_PREFIX = "import ";
// private static final String STATIC_PREFIX = "static ";
// private final String importName;
// private final int line;
// private final boolean staticImport;
//
// public ImportStatement(String importName, int line, boolean staticImport) {
// Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty");
// Preconditions.checkArgument(!importName.startsWith(IMPORT_PREFIX),
// "importName should be the raw package name without 'import ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(!importName.startsWith(STATIC_PREFIX),
// "importName should be the raw package name without 'static ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(importName.trim().equals(importName),
// "importName has leading or trailing spaces: '%s'", importName);
// Preconditions.checkArgument(line > 0, "line numbers should be 1-based and not start at 0");
//
// this.importName = importName;
// this.line = line;
// this.staticImport = staticImport;
// }
//
// /**
// * The physical line within the source file in which the import has occurred. Number
// * is always 1-based!
// *
// * @return The line number of the matched imports.
// */
// public int getLine() {
// return line;
// }
//
// /**
// * Returns the import name including the 'static ' prefix if this represents a static
// * import.
// *
// * @return The full import name.
// */
// public String getImportName() {
// if (staticImport) {
// return STATIC_PREFIX + importName;
// }
// return importName;
// }
//
// public String getFqcn() {
// return importName;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("import", importName)
// .add("line", line)
// .add("static", staticImport)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(importName, line, staticImport);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ImportStatement
// && Objects.equals(this.line, ((ImportStatement) obj).line)
// && Objects.equals(this.staticImport, ((ImportStatement) obj).staticImport)
// && Objects.equals(this.importName, ((ImportStatement) obj).importName);
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ParsedFile.java
// public final class ParsedFile {
//
// private final Path path;
// private final String declaredPackage;
// private final String fqcn;
// private final Collection<ImportStatement> imports;
//
// public ParsedFile(Path path, String declaredPackage, String fqcn, Collection<ImportStatement> imports) {
// this.path = path;
// this.declaredPackage = declaredPackage;
// this.fqcn = fqcn;
// this.imports = imports;
// }
//
// public Path getPath() {
// return path;
// }
//
// public Collection<ImportStatement> getImports() {
// return imports;
// }
//
// public String getFqcn() {
// return fqcn;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("path", path)
// .add("declaredPackage", declaredPackage)
// .add("fqcn", fqcn)
// .add("imports", imports)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(path, declaredPackage, fqcn, imports);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ParsedFile
// && Objects.equals(path, ((ParsedFile) obj).path)
// && Objects.equals(declaredPackage, ((ParsedFile) obj).declaredPackage)
// && Objects.equals(fqcn, ((ParsedFile) obj).fqcn)
// && Objects.equals(imports, ((ParsedFile) obj).imports);
// }
//
// }
// Path: src/test/java/de/skuzzle/enforcer/restrictimports/analyze/ImportAnalyzerTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatement;
import de.skuzzle.enforcer.restrictimports.parser.ParsedFile;
package de.skuzzle.enforcer.restrictimports.analyze;
class ImportAnalyzerTest {
private final ImportAnalyzer subject = new ImportAnalyzer();
private final ParsedFile parsedFile = parsedFile("File", "de.skuzzle.test",
"de.skuzzle.sample.Test",
"foo.bar.xyz",
"de.skuzzle.sample.Test2",
"de.skuzzle.sample.Test3",
"de.foo.bar.Test");
private ParsedFile parsedFile(String className, String packageName, String... lines) {
final String fqcn = packageName + "." + className;
final Path path = mock(Path.class);
final Path fileName = mock(Path.class);
when(path.getFileName()).thenReturn(fileName);
when(fileName.toString()).thenReturn(className + ".java"); | final List<ImportStatement> imports = new ArrayList<>(); |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/analyze/ImportAnalyzer.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
// public final class ImportStatement {
//
// private static final String IMPORT_PREFIX = "import ";
// private static final String STATIC_PREFIX = "static ";
// private final String importName;
// private final int line;
// private final boolean staticImport;
//
// public ImportStatement(String importName, int line, boolean staticImport) {
// Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty");
// Preconditions.checkArgument(!importName.startsWith(IMPORT_PREFIX),
// "importName should be the raw package name without 'import ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(!importName.startsWith(STATIC_PREFIX),
// "importName should be the raw package name without 'static ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(importName.trim().equals(importName),
// "importName has leading or trailing spaces: '%s'", importName);
// Preconditions.checkArgument(line > 0, "line numbers should be 1-based and not start at 0");
//
// this.importName = importName;
// this.line = line;
// this.staticImport = staticImport;
// }
//
// /**
// * The physical line within the source file in which the import has occurred. Number
// * is always 1-based!
// *
// * @return The line number of the matched imports.
// */
// public int getLine() {
// return line;
// }
//
// /**
// * Returns the import name including the 'static ' prefix if this represents a static
// * import.
// *
// * @return The full import name.
// */
// public String getImportName() {
// if (staticImport) {
// return STATIC_PREFIX + importName;
// }
// return importName;
// }
//
// public String getFqcn() {
// return importName;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("import", importName)
// .add("line", line)
// .add("static", staticImport)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(importName, line, staticImport);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ImportStatement
// && Objects.equals(this.line, ((ImportStatement) obj).line)
// && Objects.equals(this.staticImport, ((ImportStatement) obj).staticImport)
// && Objects.equals(this.importName, ((ImportStatement) obj).importName);
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ParsedFile.java
// public final class ParsedFile {
//
// private final Path path;
// private final String declaredPackage;
// private final String fqcn;
// private final Collection<ImportStatement> imports;
//
// public ParsedFile(Path path, String declaredPackage, String fqcn, Collection<ImportStatement> imports) {
// this.path = path;
// this.declaredPackage = declaredPackage;
// this.fqcn = fqcn;
// this.imports = imports;
// }
//
// public Path getPath() {
// return path;
// }
//
// public Collection<ImportStatement> getImports() {
// return imports;
// }
//
// public String getFqcn() {
// return fqcn;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("path", path)
// .add("declaredPackage", declaredPackage)
// .add("fqcn", fqcn)
// .add("imports", imports)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(path, declaredPackage, fqcn, imports);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ParsedFile
// && Objects.equals(path, ((ParsedFile) obj).path)
// && Objects.equals(declaredPackage, ((ParsedFile) obj).declaredPackage)
// && Objects.equals(fqcn, ((ParsedFile) obj).fqcn)
// && Objects.equals(imports, ((ParsedFile) obj).imports);
// }
//
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatement;
import de.skuzzle.enforcer.restrictimports.parser.ParsedFile; | package de.skuzzle.enforcer.restrictimports.analyze;
/**
* Collects banned import matches from a single source file.
*
* @author Simon Taddiken
*/
class ImportAnalyzer {
private static final Logger LOGGER = LoggerFactory.getLogger(ImportAnalyzer.class);
/**
* Collects all imports that are banned within the given source file.
*
* @param sourceFile The parsed file to check for banned imports..
* @param groups The groups of banned imports to check the file against. From all
* groups, the one with the most specific base pattern match is chosen.
* @return a {@link MatchedFile} holds information about the found matches. Returns an
* empty optional if no matches were found.
*/ | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
// public final class ImportStatement {
//
// private static final String IMPORT_PREFIX = "import ";
// private static final String STATIC_PREFIX = "static ";
// private final String importName;
// private final int line;
// private final boolean staticImport;
//
// public ImportStatement(String importName, int line, boolean staticImport) {
// Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty");
// Preconditions.checkArgument(!importName.startsWith(IMPORT_PREFIX),
// "importName should be the raw package name without 'import ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(!importName.startsWith(STATIC_PREFIX),
// "importName should be the raw package name without 'static ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(importName.trim().equals(importName),
// "importName has leading or trailing spaces: '%s'", importName);
// Preconditions.checkArgument(line > 0, "line numbers should be 1-based and not start at 0");
//
// this.importName = importName;
// this.line = line;
// this.staticImport = staticImport;
// }
//
// /**
// * The physical line within the source file in which the import has occurred. Number
// * is always 1-based!
// *
// * @return The line number of the matched imports.
// */
// public int getLine() {
// return line;
// }
//
// /**
// * Returns the import name including the 'static ' prefix if this represents a static
// * import.
// *
// * @return The full import name.
// */
// public String getImportName() {
// if (staticImport) {
// return STATIC_PREFIX + importName;
// }
// return importName;
// }
//
// public String getFqcn() {
// return importName;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("import", importName)
// .add("line", line)
// .add("static", staticImport)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(importName, line, staticImport);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ImportStatement
// && Objects.equals(this.line, ((ImportStatement) obj).line)
// && Objects.equals(this.staticImport, ((ImportStatement) obj).staticImport)
// && Objects.equals(this.importName, ((ImportStatement) obj).importName);
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ParsedFile.java
// public final class ParsedFile {
//
// private final Path path;
// private final String declaredPackage;
// private final String fqcn;
// private final Collection<ImportStatement> imports;
//
// public ParsedFile(Path path, String declaredPackage, String fqcn, Collection<ImportStatement> imports) {
// this.path = path;
// this.declaredPackage = declaredPackage;
// this.fqcn = fqcn;
// this.imports = imports;
// }
//
// public Path getPath() {
// return path;
// }
//
// public Collection<ImportStatement> getImports() {
// return imports;
// }
//
// public String getFqcn() {
// return fqcn;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("path", path)
// .add("declaredPackage", declaredPackage)
// .add("fqcn", fqcn)
// .add("imports", imports)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(path, declaredPackage, fqcn, imports);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ParsedFile
// && Objects.equals(path, ((ParsedFile) obj).path)
// && Objects.equals(declaredPackage, ((ParsedFile) obj).declaredPackage)
// && Objects.equals(fqcn, ((ParsedFile) obj).fqcn)
// && Objects.equals(imports, ((ParsedFile) obj).imports);
// }
//
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/analyze/ImportAnalyzer.java
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatement;
import de.skuzzle.enforcer.restrictimports.parser.ParsedFile;
package de.skuzzle.enforcer.restrictimports.analyze;
/**
* Collects banned import matches from a single source file.
*
* @author Simon Taddiken
*/
class ImportAnalyzer {
private static final Logger LOGGER = LoggerFactory.getLogger(ImportAnalyzer.class);
/**
* Collects all imports that are banned within the given source file.
*
* @param sourceFile The parsed file to check for banned imports..
* @param groups The groups of banned imports to check the file against. From all
* groups, the one with the most specific base pattern match is chosen.
* @return a {@link MatchedFile} holds information about the found matches. Returns an
* empty optional if no matches were found.
*/ | Optional<MatchedFile> matchFile(ParsedFile sourceFile, BannedImportGroups groups) { |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/analyze/ImportAnalyzer.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
// public final class ImportStatement {
//
// private static final String IMPORT_PREFIX = "import ";
// private static final String STATIC_PREFIX = "static ";
// private final String importName;
// private final int line;
// private final boolean staticImport;
//
// public ImportStatement(String importName, int line, boolean staticImport) {
// Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty");
// Preconditions.checkArgument(!importName.startsWith(IMPORT_PREFIX),
// "importName should be the raw package name without 'import ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(!importName.startsWith(STATIC_PREFIX),
// "importName should be the raw package name without 'static ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(importName.trim().equals(importName),
// "importName has leading or trailing spaces: '%s'", importName);
// Preconditions.checkArgument(line > 0, "line numbers should be 1-based and not start at 0");
//
// this.importName = importName;
// this.line = line;
// this.staticImport = staticImport;
// }
//
// /**
// * The physical line within the source file in which the import has occurred. Number
// * is always 1-based!
// *
// * @return The line number of the matched imports.
// */
// public int getLine() {
// return line;
// }
//
// /**
// * Returns the import name including the 'static ' prefix if this represents a static
// * import.
// *
// * @return The full import name.
// */
// public String getImportName() {
// if (staticImport) {
// return STATIC_PREFIX + importName;
// }
// return importName;
// }
//
// public String getFqcn() {
// return importName;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("import", importName)
// .add("line", line)
// .add("static", staticImport)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(importName, line, staticImport);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ImportStatement
// && Objects.equals(this.line, ((ImportStatement) obj).line)
// && Objects.equals(this.staticImport, ((ImportStatement) obj).staticImport)
// && Objects.equals(this.importName, ((ImportStatement) obj).importName);
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ParsedFile.java
// public final class ParsedFile {
//
// private final Path path;
// private final String declaredPackage;
// private final String fqcn;
// private final Collection<ImportStatement> imports;
//
// public ParsedFile(Path path, String declaredPackage, String fqcn, Collection<ImportStatement> imports) {
// this.path = path;
// this.declaredPackage = declaredPackage;
// this.fqcn = fqcn;
// this.imports = imports;
// }
//
// public Path getPath() {
// return path;
// }
//
// public Collection<ImportStatement> getImports() {
// return imports;
// }
//
// public String getFqcn() {
// return fqcn;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("path", path)
// .add("declaredPackage", declaredPackage)
// .add("fqcn", fqcn)
// .add("imports", imports)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(path, declaredPackage, fqcn, imports);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ParsedFile
// && Objects.equals(path, ((ParsedFile) obj).path)
// && Objects.equals(declaredPackage, ((ParsedFile) obj).declaredPackage)
// && Objects.equals(fqcn, ((ParsedFile) obj).fqcn)
// && Objects.equals(imports, ((ParsedFile) obj).imports);
// }
//
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatement;
import de.skuzzle.enforcer.restrictimports.parser.ParsedFile; | package de.skuzzle.enforcer.restrictimports.analyze;
/**
* Collects banned import matches from a single source file.
*
* @author Simon Taddiken
*/
class ImportAnalyzer {
private static final Logger LOGGER = LoggerFactory.getLogger(ImportAnalyzer.class);
/**
* Collects all imports that are banned within the given source file.
*
* @param sourceFile The parsed file to check for banned imports..
* @param groups The groups of banned imports to check the file against. From all
* groups, the one with the most specific base pattern match is chosen.
* @return a {@link MatchedFile} holds information about the found matches. Returns an
* empty optional if no matches were found.
*/
Optional<MatchedFile> matchFile(ParsedFile sourceFile, BannedImportGroups groups) {
LOGGER.trace("Analyzing {} for banned imports", sourceFile);
final BannedImportGroup group = groups.selectGroupFor(sourceFile.getFqcn())
.orElse(null);
if (group == null) {
LOGGER.trace("No rule group matched {}", sourceFile);
return Optional.empty();
}
LOGGER.trace("Selected {} for {}", group, sourceFile);
final List<MatchedImport> matches = new ArrayList<>(); | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
// public final class ImportStatement {
//
// private static final String IMPORT_PREFIX = "import ";
// private static final String STATIC_PREFIX = "static ";
// private final String importName;
// private final int line;
// private final boolean staticImport;
//
// public ImportStatement(String importName, int line, boolean staticImport) {
// Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty");
// Preconditions.checkArgument(!importName.startsWith(IMPORT_PREFIX),
// "importName should be the raw package name without 'import ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(!importName.startsWith(STATIC_PREFIX),
// "importName should be the raw package name without 'static ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(importName.trim().equals(importName),
// "importName has leading or trailing spaces: '%s'", importName);
// Preconditions.checkArgument(line > 0, "line numbers should be 1-based and not start at 0");
//
// this.importName = importName;
// this.line = line;
// this.staticImport = staticImport;
// }
//
// /**
// * The physical line within the source file in which the import has occurred. Number
// * is always 1-based!
// *
// * @return The line number of the matched imports.
// */
// public int getLine() {
// return line;
// }
//
// /**
// * Returns the import name including the 'static ' prefix if this represents a static
// * import.
// *
// * @return The full import name.
// */
// public String getImportName() {
// if (staticImport) {
// return STATIC_PREFIX + importName;
// }
// return importName;
// }
//
// public String getFqcn() {
// return importName;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("import", importName)
// .add("line", line)
// .add("static", staticImport)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(importName, line, staticImport);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ImportStatement
// && Objects.equals(this.line, ((ImportStatement) obj).line)
// && Objects.equals(this.staticImport, ((ImportStatement) obj).staticImport)
// && Objects.equals(this.importName, ((ImportStatement) obj).importName);
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ParsedFile.java
// public final class ParsedFile {
//
// private final Path path;
// private final String declaredPackage;
// private final String fqcn;
// private final Collection<ImportStatement> imports;
//
// public ParsedFile(Path path, String declaredPackage, String fqcn, Collection<ImportStatement> imports) {
// this.path = path;
// this.declaredPackage = declaredPackage;
// this.fqcn = fqcn;
// this.imports = imports;
// }
//
// public Path getPath() {
// return path;
// }
//
// public Collection<ImportStatement> getImports() {
// return imports;
// }
//
// public String getFqcn() {
// return fqcn;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("path", path)
// .add("declaredPackage", declaredPackage)
// .add("fqcn", fqcn)
// .add("imports", imports)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(path, declaredPackage, fqcn, imports);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ParsedFile
// && Objects.equals(path, ((ParsedFile) obj).path)
// && Objects.equals(declaredPackage, ((ParsedFile) obj).declaredPackage)
// && Objects.equals(fqcn, ((ParsedFile) obj).fqcn)
// && Objects.equals(imports, ((ParsedFile) obj).imports);
// }
//
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/analyze/ImportAnalyzer.java
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatement;
import de.skuzzle.enforcer.restrictimports.parser.ParsedFile;
package de.skuzzle.enforcer.restrictimports.analyze;
/**
* Collects banned import matches from a single source file.
*
* @author Simon Taddiken
*/
class ImportAnalyzer {
private static final Logger LOGGER = LoggerFactory.getLogger(ImportAnalyzer.class);
/**
* Collects all imports that are banned within the given source file.
*
* @param sourceFile The parsed file to check for banned imports..
* @param groups The groups of banned imports to check the file against. From all
* groups, the one with the most specific base pattern match is chosen.
* @return a {@link MatchedFile} holds information about the found matches. Returns an
* empty optional if no matches were found.
*/
Optional<MatchedFile> matchFile(ParsedFile sourceFile, BannedImportGroups groups) {
LOGGER.trace("Analyzing {} for banned imports", sourceFile);
final BannedImportGroup group = groups.selectGroupFor(sourceFile.getFqcn())
.orElse(null);
if (group == null) {
LOGGER.trace("No rule group matched {}", sourceFile);
return Optional.empty();
}
LOGGER.trace("Selected {} for {}", group, sourceFile);
final List<MatchedImport> matches = new ArrayList<>(); | for (final ImportStatement importStmt : sourceFile.getImports()) { |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/analyze/MatchedImport.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/StringRepresentation.java
// public final class StringRepresentation {
//
// private final String name;
// private final List<Attribute> attributes = new ArrayList<>();
//
// private StringRepresentation(String name) {
// this.name = name;
// }
//
// public static StringRepresentation ofType(Class<?> type) {
// return new StringRepresentation(type.getSimpleName());
// }
//
// public static StringRepresentation ofInstance(Object instance) {
// return ofType(instance.getClass());
// }
//
// public StringRepresentation add(String attribute, Object value) {
// attributes.add(new Attribute(attribute, value));
// return this;
// }
//
// @Override
// public String toString() {
// return new StringBuilder(name)
// .append("{")
// .append(attributes.stream().map(Attribute::toString).collect(Collectors.joining(", ")))
// .append("}")
// .toString();
// }
//
// private static final class Attribute {
// private final String name;
// private final Object value;
//
// private Attribute(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public String toString() {
// return name + "=" + value;
// }
// }
// }
| import java.util.Objects;
import de.skuzzle.enforcer.restrictimports.util.Preconditions;
import de.skuzzle.enforcer.restrictimports.util.StringRepresentation; | package de.skuzzle.enforcer.restrictimports.analyze;
/**
* Represents a single match of a banned import within a java source file.
*
* @author Simon Taddiken
*/
public final class MatchedImport {
private final int importLine;
private final String matchedString;
private final PackagePattern matchedBy;
MatchedImport(int importLine, String matchedString, PackagePattern matchedBy) { | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/StringRepresentation.java
// public final class StringRepresentation {
//
// private final String name;
// private final List<Attribute> attributes = new ArrayList<>();
//
// private StringRepresentation(String name) {
// this.name = name;
// }
//
// public static StringRepresentation ofType(Class<?> type) {
// return new StringRepresentation(type.getSimpleName());
// }
//
// public static StringRepresentation ofInstance(Object instance) {
// return ofType(instance.getClass());
// }
//
// public StringRepresentation add(String attribute, Object value) {
// attributes.add(new Attribute(attribute, value));
// return this;
// }
//
// @Override
// public String toString() {
// return new StringBuilder(name)
// .append("{")
// .append(attributes.stream().map(Attribute::toString).collect(Collectors.joining(", ")))
// .append("}")
// .toString();
// }
//
// private static final class Attribute {
// private final String name;
// private final Object value;
//
// private Attribute(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public String toString() {
// return name + "=" + value;
// }
// }
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/analyze/MatchedImport.java
import java.util.Objects;
import de.skuzzle.enforcer.restrictimports.util.Preconditions;
import de.skuzzle.enforcer.restrictimports.util.StringRepresentation;
package de.skuzzle.enforcer.restrictimports.analyze;
/**
* Represents a single match of a banned import within a java source file.
*
* @author Simon Taddiken
*/
public final class MatchedImport {
private final int importLine;
private final String matchedString;
private final PackagePattern matchedBy;
MatchedImport(int importLine, String matchedString, PackagePattern matchedBy) { | Preconditions.checkArgument(matchedString != null && !matchedString.isEmpty(), |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/analyze/MatchedImport.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/StringRepresentation.java
// public final class StringRepresentation {
//
// private final String name;
// private final List<Attribute> attributes = new ArrayList<>();
//
// private StringRepresentation(String name) {
// this.name = name;
// }
//
// public static StringRepresentation ofType(Class<?> type) {
// return new StringRepresentation(type.getSimpleName());
// }
//
// public static StringRepresentation ofInstance(Object instance) {
// return ofType(instance.getClass());
// }
//
// public StringRepresentation add(String attribute, Object value) {
// attributes.add(new Attribute(attribute, value));
// return this;
// }
//
// @Override
// public String toString() {
// return new StringBuilder(name)
// .append("{")
// .append(attributes.stream().map(Attribute::toString).collect(Collectors.joining(", ")))
// .append("}")
// .toString();
// }
//
// private static final class Attribute {
// private final String name;
// private final Object value;
//
// private Attribute(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public String toString() {
// return name + "=" + value;
// }
// }
// }
| import java.util.Objects;
import de.skuzzle.enforcer.restrictimports.util.Preconditions;
import de.skuzzle.enforcer.restrictimports.util.StringRepresentation; | *
* @return The line number of the matched imports.
*/
public int getImportLine() {
return this.importLine;
}
public String getMatchedString() {
return this.matchedString;
}
public PackagePattern getMatchedBy() {
return this.matchedBy;
}
@Override
public int hashCode() {
return Objects.hash(this.importLine, this.matchedString, this.matchedBy);
}
@Override
public boolean equals(Object obj) {
return obj == this || obj instanceof MatchedImport
&& Objects.equals(this.importLine, ((MatchedImport) obj).importLine)
&& Objects.equals(this.matchedString, ((MatchedImport) obj).matchedString)
&& Objects.equals(this.matchedBy, ((MatchedImport) obj).matchedBy);
}
@Override
public String toString() { | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/StringRepresentation.java
// public final class StringRepresentation {
//
// private final String name;
// private final List<Attribute> attributes = new ArrayList<>();
//
// private StringRepresentation(String name) {
// this.name = name;
// }
//
// public static StringRepresentation ofType(Class<?> type) {
// return new StringRepresentation(type.getSimpleName());
// }
//
// public static StringRepresentation ofInstance(Object instance) {
// return ofType(instance.getClass());
// }
//
// public StringRepresentation add(String attribute, Object value) {
// attributes.add(new Attribute(attribute, value));
// return this;
// }
//
// @Override
// public String toString() {
// return new StringBuilder(name)
// .append("{")
// .append(attributes.stream().map(Attribute::toString).collect(Collectors.joining(", ")))
// .append("}")
// .toString();
// }
//
// private static final class Attribute {
// private final String name;
// private final Object value;
//
// private Attribute(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public String toString() {
// return name + "=" + value;
// }
// }
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/analyze/MatchedImport.java
import java.util.Objects;
import de.skuzzle.enforcer.restrictimports.util.Preconditions;
import de.skuzzle.enforcer.restrictimports.util.StringRepresentation;
*
* @return The line number of the matched imports.
*/
public int getImportLine() {
return this.importLine;
}
public String getMatchedString() {
return this.matchedString;
}
public PackagePattern getMatchedBy() {
return this.matchedBy;
}
@Override
public int hashCode() {
return Objects.hash(this.importLine, this.matchedString, this.matchedBy);
}
@Override
public boolean equals(Object obj) {
return obj == this || obj instanceof MatchedImport
&& Objects.equals(this.importLine, ((MatchedImport) obj).importLine)
&& Objects.equals(this.matchedString, ((MatchedImport) obj).matchedString)
&& Objects.equals(this.matchedBy, ((MatchedImport) obj).matchedBy);
}
@Override
public String toString() { | return StringRepresentation.ofInstance(this) |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/parser/lang/SupportedLanguageHolder.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
| import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.ServiceLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.skuzzle.enforcer.restrictimports.util.Preconditions; | package de.skuzzle.enforcer.restrictimports.parser.lang;
/**
* Helper class to list available {@link LanguageSupport} implementations from
* {@link ServiceLoader}.
*/
final class SupportedLanguageHolder {
private static final Logger logger = LoggerFactory.getLogger(SupportedLanguageHolder.class);
// maps from normalized extension to LanguageSupport instance
// normalized extensions are all lower case and have a leading '.'
static final Map<String, LanguageSupport> supportedLanguages = lookupImplementations();
static Optional<LanguageSupport> getLanguageSupport(String extension) {
final String normalizedExtension = determineNormalizedExtension(extension);
return Optional.ofNullable(supportedLanguages.get(normalizedExtension));
}
static boolean isLanguageSupported(String extension) {
final String normalizedExtension = determineNormalizedExtension(extension);
return supportedLanguages.containsKey(normalizedExtension);
}
/**
* Looks up the available {@link LanguageSupport} implementations that can be found
* using Java's {@link ServiceLoader}
*
* @return The implementations, mapped by their supported extensions.
*/
private static Map<String, LanguageSupport> lookupImplementations() {
final ServiceLoader<LanguageSupport> serviceProvider = ServiceLoader.load(LanguageSupport.class);
final Map<String, LanguageSupport> implementations = new HashMap<>();
serviceProvider.forEach(parser -> parser.getSupportedFileExtensions().stream()
.map(SupportedLanguageHolder::determineNormalizedExtension)
.forEach(normalizedExtension -> {
if (implementations.put(normalizedExtension, parser) != null) {
throw new IllegalStateException(
"There are multiple parsers to handle file extension: " + normalizedExtension);
}
logger.debug("Registered {} for extension '{}'", parser, normalizedExtension);
})); | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Preconditions.java
// public final class Preconditions {
//
// public static void checkArgument(boolean condition) {
// checkArgument(condition, "Unexpected argument");
// }
//
// public static void checkArgument(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void checkState(boolean condition) {
// checkState(condition, "Unexpected state");
// }
//
// public static void checkState(boolean condition, String message, Object... args) {
// if (!condition) {
// throw new IllegalStateException(String.format(message, args));
// }
// }
//
// private Preconditions() {
// throw new IllegalStateException("hidden");
// }
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/lang/SupportedLanguageHolder.java
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.ServiceLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.skuzzle.enforcer.restrictimports.util.Preconditions;
package de.skuzzle.enforcer.restrictimports.parser.lang;
/**
* Helper class to list available {@link LanguageSupport} implementations from
* {@link ServiceLoader}.
*/
final class SupportedLanguageHolder {
private static final Logger logger = LoggerFactory.getLogger(SupportedLanguageHolder.class);
// maps from normalized extension to LanguageSupport instance
// normalized extensions are all lower case and have a leading '.'
static final Map<String, LanguageSupport> supportedLanguages = lookupImplementations();
static Optional<LanguageSupport> getLanguageSupport(String extension) {
final String normalizedExtension = determineNormalizedExtension(extension);
return Optional.ofNullable(supportedLanguages.get(normalizedExtension));
}
static boolean isLanguageSupported(String extension) {
final String normalizedExtension = determineNormalizedExtension(extension);
return supportedLanguages.containsKey(normalizedExtension);
}
/**
* Looks up the available {@link LanguageSupport} implementations that can be found
* using Java's {@link ServiceLoader}
*
* @return The implementations, mapped by their supported extensions.
*/
private static Map<String, LanguageSupport> lookupImplementations() {
final ServiceLoader<LanguageSupport> serviceProvider = ServiceLoader.load(LanguageSupport.class);
final Map<String, LanguageSupport> implementations = new HashMap<>();
serviceProvider.forEach(parser -> parser.getSupportedFileExtensions().stream()
.map(SupportedLanguageHolder::determineNormalizedExtension)
.forEach(normalizedExtension -> {
if (implementations.put(normalizedExtension, parser) != null) {
throw new IllegalStateException(
"There are multiple parsers to handle file extension: " + normalizedExtension);
}
logger.debug("Registered {} for extension '{}'", parser, normalizedExtension);
})); | Preconditions.checkState(!implementations.isEmpty(), "No LanguageSupport instances found!"); |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/analyze/SourceTreeAnalyzerImpl.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatementParser.java
// public interface ImportStatementParser {
// /**
// * Constructs a default instance of the parser which uses the provided charset.
// *
// * @param charset The charset to use.
// * @return The parser instance.
// */
// static ImportStatementParser forCharset(Charset charset) {
// return new ImportStatementParserImpl(new SkipCommentsLineSupplier(charset));
// }
//
// /**
// * Parses the given source file using the given {@link LanguageSupport} implementation
// * to recognize import statements.
// *
// * @param sourceFilePath The path of the file to parse.
// * @return The parsed file.
// */
// ParsedFile parse(Path sourceFilePath);
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ParsedFile.java
// public final class ParsedFile {
//
// private final Path path;
// private final String declaredPackage;
// private final String fqcn;
// private final Collection<ImportStatement> imports;
//
// public ParsedFile(Path path, String declaredPackage, String fqcn, Collection<ImportStatement> imports) {
// this.path = path;
// this.declaredPackage = declaredPackage;
// this.fqcn = fqcn;
// this.imports = imports;
// }
//
// public Path getPath() {
// return path;
// }
//
// public Collection<ImportStatement> getImports() {
// return imports;
// }
//
// public String getFqcn() {
// return fqcn;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("path", path)
// .add("declaredPackage", declaredPackage)
// .add("fqcn", fqcn)
// .add("imports", imports)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(path, declaredPackage, fqcn, imports);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ParsedFile
// && Objects.equals(path, ((ParsedFile) obj).path)
// && Objects.equals(declaredPackage, ((ParsedFile) obj).declaredPackage)
// && Objects.equals(fqcn, ((ParsedFile) obj).fqcn)
// && Objects.equals(imports, ((ParsedFile) obj).imports);
// }
//
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/lang/LanguageSupport.java
// public interface LanguageSupport {
//
// /**
// * Returns the {@link LanguageSupport} implementation for the given file.
// *
// * @param path The path to a file.
// * @return The {@link LanguageSupport} implementation or an empty optional if none was
// * found.
// */
// static LanguageSupport getLanguageSupport(Path path) {
// final String extension = FileExtension.fromPath(path);
// return SupportedLanguageHolder.getLanguageSupport(extension)
// .orElseThrow(() -> new IllegalArgumentException(String.format(
// "Could not find a LanguageSupport implementation for normalized file extension: '%s' (%s)",
// extension, path)));
// }
//
// /**
// * Determines whether there exists a {@link LanguageSupport} implementation for the
// * given path.
// *
// * @param path The path to a file.
// * @return Whether such implementation exists.
// * @since 1.1.0
// */
// static boolean isLanguageSupported(Path path) {
// final Path filename = path.getFileName();
// return !Files.isDirectory(path)
// && SupportedLanguageHolder.isLanguageSupported(FileExtension.fromPath(filename));
// }
//
// /**
// * The set of supported file extensions. Extensions returned here are case insensitive
// * and may or may not start with a '.' (dot).
// *
// * @return The set of file extensions.
// */
// Set<String> getSupportedFileExtensions();
//
// /**
// * Parses the given line and returns the declared package
// *
// * @param line Line in the source file
// * @return The package declared
// */
// Optional<String> parsePackage(String line);
//
// /**
// * Extract the package names that this import statement represents. As some languages
// * allow to specify multiple imports in a single line, this method returns a list.
// * <p>
// * e.g. import java.util.List; The above should return java.util.List in a Java source
// * file.
// *
// * @param importLine Line in the source file
// * @param lineNumber The line number of the import.
// * @return Fully qualified package name that this import represents
// */
// List<ImportStatement> parseImport(String importLine, int lineNumber);
// }
| import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatementParser;
import de.skuzzle.enforcer.restrictimports.parser.ParsedFile;
import de.skuzzle.enforcer.restrictimports.parser.lang.LanguageSupport; | package de.skuzzle.enforcer.restrictimports.analyze;
final class SourceTreeAnalyzerImpl implements SourceTreeAnalyzer {
private static final Logger LOGGER = LoggerFactory.getLogger(SourceTreeAnalyzerImpl.class);
private final ImportAnalyzer importAnalyzer;
private final Predicate<Path> supportedFileTypes;
SourceTreeAnalyzerImpl() {
this.importAnalyzer = new ImportAnalyzer(); | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatementParser.java
// public interface ImportStatementParser {
// /**
// * Constructs a default instance of the parser which uses the provided charset.
// *
// * @param charset The charset to use.
// * @return The parser instance.
// */
// static ImportStatementParser forCharset(Charset charset) {
// return new ImportStatementParserImpl(new SkipCommentsLineSupplier(charset));
// }
//
// /**
// * Parses the given source file using the given {@link LanguageSupport} implementation
// * to recognize import statements.
// *
// * @param sourceFilePath The path of the file to parse.
// * @return The parsed file.
// */
// ParsedFile parse(Path sourceFilePath);
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ParsedFile.java
// public final class ParsedFile {
//
// private final Path path;
// private final String declaredPackage;
// private final String fqcn;
// private final Collection<ImportStatement> imports;
//
// public ParsedFile(Path path, String declaredPackage, String fqcn, Collection<ImportStatement> imports) {
// this.path = path;
// this.declaredPackage = declaredPackage;
// this.fqcn = fqcn;
// this.imports = imports;
// }
//
// public Path getPath() {
// return path;
// }
//
// public Collection<ImportStatement> getImports() {
// return imports;
// }
//
// public String getFqcn() {
// return fqcn;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("path", path)
// .add("declaredPackage", declaredPackage)
// .add("fqcn", fqcn)
// .add("imports", imports)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(path, declaredPackage, fqcn, imports);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ParsedFile
// && Objects.equals(path, ((ParsedFile) obj).path)
// && Objects.equals(declaredPackage, ((ParsedFile) obj).declaredPackage)
// && Objects.equals(fqcn, ((ParsedFile) obj).fqcn)
// && Objects.equals(imports, ((ParsedFile) obj).imports);
// }
//
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/lang/LanguageSupport.java
// public interface LanguageSupport {
//
// /**
// * Returns the {@link LanguageSupport} implementation for the given file.
// *
// * @param path The path to a file.
// * @return The {@link LanguageSupport} implementation or an empty optional if none was
// * found.
// */
// static LanguageSupport getLanguageSupport(Path path) {
// final String extension = FileExtension.fromPath(path);
// return SupportedLanguageHolder.getLanguageSupport(extension)
// .orElseThrow(() -> new IllegalArgumentException(String.format(
// "Could not find a LanguageSupport implementation for normalized file extension: '%s' (%s)",
// extension, path)));
// }
//
// /**
// * Determines whether there exists a {@link LanguageSupport} implementation for the
// * given path.
// *
// * @param path The path to a file.
// * @return Whether such implementation exists.
// * @since 1.1.0
// */
// static boolean isLanguageSupported(Path path) {
// final Path filename = path.getFileName();
// return !Files.isDirectory(path)
// && SupportedLanguageHolder.isLanguageSupported(FileExtension.fromPath(filename));
// }
//
// /**
// * The set of supported file extensions. Extensions returned here are case insensitive
// * and may or may not start with a '.' (dot).
// *
// * @return The set of file extensions.
// */
// Set<String> getSupportedFileExtensions();
//
// /**
// * Parses the given line and returns the declared package
// *
// * @param line Line in the source file
// * @return The package declared
// */
// Optional<String> parsePackage(String line);
//
// /**
// * Extract the package names that this import statement represents. As some languages
// * allow to specify multiple imports in a single line, this method returns a list.
// * <p>
// * e.g. import java.util.List; The above should return java.util.List in a Java source
// * file.
// *
// * @param importLine Line in the source file
// * @param lineNumber The line number of the import.
// * @return Fully qualified package name that this import represents
// */
// List<ImportStatement> parseImport(String importLine, int lineNumber);
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/analyze/SourceTreeAnalyzerImpl.java
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatementParser;
import de.skuzzle.enforcer.restrictimports.parser.ParsedFile;
import de.skuzzle.enforcer.restrictimports.parser.lang.LanguageSupport;
package de.skuzzle.enforcer.restrictimports.analyze;
final class SourceTreeAnalyzerImpl implements SourceTreeAnalyzer {
private static final Logger LOGGER = LoggerFactory.getLogger(SourceTreeAnalyzerImpl.class);
private final ImportAnalyzer importAnalyzer;
private final Predicate<Path> supportedFileTypes;
SourceTreeAnalyzerImpl() {
this.importAnalyzer = new ImportAnalyzer(); | this.supportedFileTypes = LanguageSupport::isLanguageSupported; |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/analyze/SourceTreeAnalyzerImpl.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatementParser.java
// public interface ImportStatementParser {
// /**
// * Constructs a default instance of the parser which uses the provided charset.
// *
// * @param charset The charset to use.
// * @return The parser instance.
// */
// static ImportStatementParser forCharset(Charset charset) {
// return new ImportStatementParserImpl(new SkipCommentsLineSupplier(charset));
// }
//
// /**
// * Parses the given source file using the given {@link LanguageSupport} implementation
// * to recognize import statements.
// *
// * @param sourceFilePath The path of the file to parse.
// * @return The parsed file.
// */
// ParsedFile parse(Path sourceFilePath);
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ParsedFile.java
// public final class ParsedFile {
//
// private final Path path;
// private final String declaredPackage;
// private final String fqcn;
// private final Collection<ImportStatement> imports;
//
// public ParsedFile(Path path, String declaredPackage, String fqcn, Collection<ImportStatement> imports) {
// this.path = path;
// this.declaredPackage = declaredPackage;
// this.fqcn = fqcn;
// this.imports = imports;
// }
//
// public Path getPath() {
// return path;
// }
//
// public Collection<ImportStatement> getImports() {
// return imports;
// }
//
// public String getFqcn() {
// return fqcn;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("path", path)
// .add("declaredPackage", declaredPackage)
// .add("fqcn", fqcn)
// .add("imports", imports)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(path, declaredPackage, fqcn, imports);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ParsedFile
// && Objects.equals(path, ((ParsedFile) obj).path)
// && Objects.equals(declaredPackage, ((ParsedFile) obj).declaredPackage)
// && Objects.equals(fqcn, ((ParsedFile) obj).fqcn)
// && Objects.equals(imports, ((ParsedFile) obj).imports);
// }
//
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/lang/LanguageSupport.java
// public interface LanguageSupport {
//
// /**
// * Returns the {@link LanguageSupport} implementation for the given file.
// *
// * @param path The path to a file.
// * @return The {@link LanguageSupport} implementation or an empty optional if none was
// * found.
// */
// static LanguageSupport getLanguageSupport(Path path) {
// final String extension = FileExtension.fromPath(path);
// return SupportedLanguageHolder.getLanguageSupport(extension)
// .orElseThrow(() -> new IllegalArgumentException(String.format(
// "Could not find a LanguageSupport implementation for normalized file extension: '%s' (%s)",
// extension, path)));
// }
//
// /**
// * Determines whether there exists a {@link LanguageSupport} implementation for the
// * given path.
// *
// * @param path The path to a file.
// * @return Whether such implementation exists.
// * @since 1.1.0
// */
// static boolean isLanguageSupported(Path path) {
// final Path filename = path.getFileName();
// return !Files.isDirectory(path)
// && SupportedLanguageHolder.isLanguageSupported(FileExtension.fromPath(filename));
// }
//
// /**
// * The set of supported file extensions. Extensions returned here are case insensitive
// * and may or may not start with a '.' (dot).
// *
// * @return The set of file extensions.
// */
// Set<String> getSupportedFileExtensions();
//
// /**
// * Parses the given line and returns the declared package
// *
// * @param line Line in the source file
// * @return The package declared
// */
// Optional<String> parsePackage(String line);
//
// /**
// * Extract the package names that this import statement represents. As some languages
// * allow to specify multiple imports in a single line, this method returns a list.
// * <p>
// * e.g. import java.util.List; The above should return java.util.List in a Java source
// * file.
// *
// * @param importLine Line in the source file
// * @param lineNumber The line number of the import.
// * @return Fully qualified package name that this import represents
// */
// List<ImportStatement> parseImport(String importLine, int lineNumber);
// }
| import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatementParser;
import de.skuzzle.enforcer.restrictimports.parser.ParsedFile;
import de.skuzzle.enforcer.restrictimports.parser.lang.LanguageSupport; | package de.skuzzle.enforcer.restrictimports.analyze;
final class SourceTreeAnalyzerImpl implements SourceTreeAnalyzer {
private static final Logger LOGGER = LoggerFactory.getLogger(SourceTreeAnalyzerImpl.class);
private final ImportAnalyzer importAnalyzer;
private final Predicate<Path> supportedFileTypes;
SourceTreeAnalyzerImpl() {
this.importAnalyzer = new ImportAnalyzer();
this.supportedFileTypes = LanguageSupport::isLanguageSupported;
}
@Override
public AnalyzeResult analyze(AnalyzerSettings settings, BannedImportGroups groups) {
final long start = System.currentTimeMillis(); | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatementParser.java
// public interface ImportStatementParser {
// /**
// * Constructs a default instance of the parser which uses the provided charset.
// *
// * @param charset The charset to use.
// * @return The parser instance.
// */
// static ImportStatementParser forCharset(Charset charset) {
// return new ImportStatementParserImpl(new SkipCommentsLineSupplier(charset));
// }
//
// /**
// * Parses the given source file using the given {@link LanguageSupport} implementation
// * to recognize import statements.
// *
// * @param sourceFilePath The path of the file to parse.
// * @return The parsed file.
// */
// ParsedFile parse(Path sourceFilePath);
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ParsedFile.java
// public final class ParsedFile {
//
// private final Path path;
// private final String declaredPackage;
// private final String fqcn;
// private final Collection<ImportStatement> imports;
//
// public ParsedFile(Path path, String declaredPackage, String fqcn, Collection<ImportStatement> imports) {
// this.path = path;
// this.declaredPackage = declaredPackage;
// this.fqcn = fqcn;
// this.imports = imports;
// }
//
// public Path getPath() {
// return path;
// }
//
// public Collection<ImportStatement> getImports() {
// return imports;
// }
//
// public String getFqcn() {
// return fqcn;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("path", path)
// .add("declaredPackage", declaredPackage)
// .add("fqcn", fqcn)
// .add("imports", imports)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(path, declaredPackage, fqcn, imports);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ParsedFile
// && Objects.equals(path, ((ParsedFile) obj).path)
// && Objects.equals(declaredPackage, ((ParsedFile) obj).declaredPackage)
// && Objects.equals(fqcn, ((ParsedFile) obj).fqcn)
// && Objects.equals(imports, ((ParsedFile) obj).imports);
// }
//
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/lang/LanguageSupport.java
// public interface LanguageSupport {
//
// /**
// * Returns the {@link LanguageSupport} implementation for the given file.
// *
// * @param path The path to a file.
// * @return The {@link LanguageSupport} implementation or an empty optional if none was
// * found.
// */
// static LanguageSupport getLanguageSupport(Path path) {
// final String extension = FileExtension.fromPath(path);
// return SupportedLanguageHolder.getLanguageSupport(extension)
// .orElseThrow(() -> new IllegalArgumentException(String.format(
// "Could not find a LanguageSupport implementation for normalized file extension: '%s' (%s)",
// extension, path)));
// }
//
// /**
// * Determines whether there exists a {@link LanguageSupport} implementation for the
// * given path.
// *
// * @param path The path to a file.
// * @return Whether such implementation exists.
// * @since 1.1.0
// */
// static boolean isLanguageSupported(Path path) {
// final Path filename = path.getFileName();
// return !Files.isDirectory(path)
// && SupportedLanguageHolder.isLanguageSupported(FileExtension.fromPath(filename));
// }
//
// /**
// * The set of supported file extensions. Extensions returned here are case insensitive
// * and may or may not start with a '.' (dot).
// *
// * @return The set of file extensions.
// */
// Set<String> getSupportedFileExtensions();
//
// /**
// * Parses the given line and returns the declared package
// *
// * @param line Line in the source file
// * @return The package declared
// */
// Optional<String> parsePackage(String line);
//
// /**
// * Extract the package names that this import statement represents. As some languages
// * allow to specify multiple imports in a single line, this method returns a list.
// * <p>
// * e.g. import java.util.List; The above should return java.util.List in a Java source
// * file.
// *
// * @param importLine Line in the source file
// * @param lineNumber The line number of the import.
// * @return Fully qualified package name that this import represents
// */
// List<ImportStatement> parseImport(String importLine, int lineNumber);
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/analyze/SourceTreeAnalyzerImpl.java
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatementParser;
import de.skuzzle.enforcer.restrictimports.parser.ParsedFile;
import de.skuzzle.enforcer.restrictimports.parser.lang.LanguageSupport;
package de.skuzzle.enforcer.restrictimports.analyze;
final class SourceTreeAnalyzerImpl implements SourceTreeAnalyzer {
private static final Logger LOGGER = LoggerFactory.getLogger(SourceTreeAnalyzerImpl.class);
private final ImportAnalyzer importAnalyzer;
private final Predicate<Path> supportedFileTypes;
SourceTreeAnalyzerImpl() {
this.importAnalyzer = new ImportAnalyzer();
this.supportedFileTypes = LanguageSupport::isLanguageSupported;
}
@Override
public AnalyzeResult analyze(AnalyzerSettings settings, BannedImportGroups groups) {
final long start = System.currentTimeMillis(); | final ImportStatementParser fileParser = ImportStatementParser.forCharset(settings.getSourceFileCharset()); |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/parser/lang/JavaLanguageSupport.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
// public final class ImportStatement {
//
// private static final String IMPORT_PREFIX = "import ";
// private static final String STATIC_PREFIX = "static ";
// private final String importName;
// private final int line;
// private final boolean staticImport;
//
// public ImportStatement(String importName, int line, boolean staticImport) {
// Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty");
// Preconditions.checkArgument(!importName.startsWith(IMPORT_PREFIX),
// "importName should be the raw package name without 'import ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(!importName.startsWith(STATIC_PREFIX),
// "importName should be the raw package name without 'static ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(importName.trim().equals(importName),
// "importName has leading or trailing spaces: '%s'", importName);
// Preconditions.checkArgument(line > 0, "line numbers should be 1-based and not start at 0");
//
// this.importName = importName;
// this.line = line;
// this.staticImport = staticImport;
// }
//
// /**
// * The physical line within the source file in which the import has occurred. Number
// * is always 1-based!
// *
// * @return The line number of the matched imports.
// */
// public int getLine() {
// return line;
// }
//
// /**
// * Returns the import name including the 'static ' prefix if this represents a static
// * import.
// *
// * @return The full import name.
// */
// public String getImportName() {
// if (staticImport) {
// return STATIC_PREFIX + importName;
// }
// return importName;
// }
//
// public String getFqcn() {
// return importName;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("import", importName)
// .add("line", line)
// .add("static", staticImport)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(importName, line, staticImport);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ImportStatement
// && Objects.equals(this.line, ((ImportStatement) obj).line)
// && Objects.equals(this.staticImport, ((ImportStatement) obj).staticImport)
// && Objects.equals(this.importName, ((ImportStatement) obj).importName);
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Whitespaces.java
// public final class Whitespaces {
//
// private static final Pattern LEADING = Pattern.compile("^\\s+");
// private static final Pattern TRAILING = Pattern.compile("\\s+$");
//
// /**
// * Trims all leading and trailing whitespaces (regex pattern class <code>\s</code>)
// *
// * @param s The string to trim.
// * @return The trimmed string.
// */
// public static final String trimAll(String s) {
// final Matcher leadingMatcher = LEADING.matcher(s);
// final Matcher trailingMatcher = TRAILING.matcher(s);
// final boolean hasLeading = leadingMatcher.find();
// final boolean hasTrailing = trailingMatcher.find();
// if (!hasLeading && !hasTrailing) {
// return s;
// }
// final int start = hasLeading ? leadingMatcher.end() : 0;
// final int end = hasTrailing ? trailingMatcher.start() : s.length();
// return s.substring(start, end);
// }
//
// private Whitespaces() {
// // hidden
// }
// }
| import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatement;
import de.skuzzle.enforcer.restrictimports.util.Whitespaces; | package de.skuzzle.enforcer.restrictimports.parser.lang;
public class JavaLanguageSupport implements LanguageSupport {
private static final String STATIC_PREFIX = "static";
private static final String IMPORT_STATEMENT = "import ";
private static final String PACKAGE_STATEMENT = "package ";
@Override
public Set<String> getSupportedFileExtensions() {
return Collections.singleton("java");
}
@Override
public Optional<String> parsePackage(String line) {
if (!isPackage(line)) {
return Optional.empty();
}
return Optional.of(extractPackageName(line));
}
@Override | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
// public final class ImportStatement {
//
// private static final String IMPORT_PREFIX = "import ";
// private static final String STATIC_PREFIX = "static ";
// private final String importName;
// private final int line;
// private final boolean staticImport;
//
// public ImportStatement(String importName, int line, boolean staticImport) {
// Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty");
// Preconditions.checkArgument(!importName.startsWith(IMPORT_PREFIX),
// "importName should be the raw package name without 'import ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(!importName.startsWith(STATIC_PREFIX),
// "importName should be the raw package name without 'static ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(importName.trim().equals(importName),
// "importName has leading or trailing spaces: '%s'", importName);
// Preconditions.checkArgument(line > 0, "line numbers should be 1-based and not start at 0");
//
// this.importName = importName;
// this.line = line;
// this.staticImport = staticImport;
// }
//
// /**
// * The physical line within the source file in which the import has occurred. Number
// * is always 1-based!
// *
// * @return The line number of the matched imports.
// */
// public int getLine() {
// return line;
// }
//
// /**
// * Returns the import name including the 'static ' prefix if this represents a static
// * import.
// *
// * @return The full import name.
// */
// public String getImportName() {
// if (staticImport) {
// return STATIC_PREFIX + importName;
// }
// return importName;
// }
//
// public String getFqcn() {
// return importName;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("import", importName)
// .add("line", line)
// .add("static", staticImport)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(importName, line, staticImport);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ImportStatement
// && Objects.equals(this.line, ((ImportStatement) obj).line)
// && Objects.equals(this.staticImport, ((ImportStatement) obj).staticImport)
// && Objects.equals(this.importName, ((ImportStatement) obj).importName);
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Whitespaces.java
// public final class Whitespaces {
//
// private static final Pattern LEADING = Pattern.compile("^\\s+");
// private static final Pattern TRAILING = Pattern.compile("\\s+$");
//
// /**
// * Trims all leading and trailing whitespaces (regex pattern class <code>\s</code>)
// *
// * @param s The string to trim.
// * @return The trimmed string.
// */
// public static final String trimAll(String s) {
// final Matcher leadingMatcher = LEADING.matcher(s);
// final Matcher trailingMatcher = TRAILING.matcher(s);
// final boolean hasLeading = leadingMatcher.find();
// final boolean hasTrailing = trailingMatcher.find();
// if (!hasLeading && !hasTrailing) {
// return s;
// }
// final int start = hasLeading ? leadingMatcher.end() : 0;
// final int end = hasTrailing ? trailingMatcher.start() : s.length();
// return s.substring(start, end);
// }
//
// private Whitespaces() {
// // hidden
// }
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/lang/JavaLanguageSupport.java
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatement;
import de.skuzzle.enforcer.restrictimports.util.Whitespaces;
package de.skuzzle.enforcer.restrictimports.parser.lang;
public class JavaLanguageSupport implements LanguageSupport {
private static final String STATIC_PREFIX = "static";
private static final String IMPORT_STATEMENT = "import ";
private static final String PACKAGE_STATEMENT = "package ";
@Override
public Set<String> getSupportedFileExtensions() {
return Collections.singleton("java");
}
@Override
public Optional<String> parsePackage(String line) {
if (!isPackage(line)) {
return Optional.empty();
}
return Optional.of(extractPackageName(line));
}
@Override | public List<ImportStatement> parseImport(String line, int lineNumber) { |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/parser/lang/JavaLanguageSupport.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
// public final class ImportStatement {
//
// private static final String IMPORT_PREFIX = "import ";
// private static final String STATIC_PREFIX = "static ";
// private final String importName;
// private final int line;
// private final boolean staticImport;
//
// public ImportStatement(String importName, int line, boolean staticImport) {
// Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty");
// Preconditions.checkArgument(!importName.startsWith(IMPORT_PREFIX),
// "importName should be the raw package name without 'import ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(!importName.startsWith(STATIC_PREFIX),
// "importName should be the raw package name without 'static ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(importName.trim().equals(importName),
// "importName has leading or trailing spaces: '%s'", importName);
// Preconditions.checkArgument(line > 0, "line numbers should be 1-based and not start at 0");
//
// this.importName = importName;
// this.line = line;
// this.staticImport = staticImport;
// }
//
// /**
// * The physical line within the source file in which the import has occurred. Number
// * is always 1-based!
// *
// * @return The line number of the matched imports.
// */
// public int getLine() {
// return line;
// }
//
// /**
// * Returns the import name including the 'static ' prefix if this represents a static
// * import.
// *
// * @return The full import name.
// */
// public String getImportName() {
// if (staticImport) {
// return STATIC_PREFIX + importName;
// }
// return importName;
// }
//
// public String getFqcn() {
// return importName;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("import", importName)
// .add("line", line)
// .add("static", staticImport)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(importName, line, staticImport);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ImportStatement
// && Objects.equals(this.line, ((ImportStatement) obj).line)
// && Objects.equals(this.staticImport, ((ImportStatement) obj).staticImport)
// && Objects.equals(this.importName, ((ImportStatement) obj).importName);
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Whitespaces.java
// public final class Whitespaces {
//
// private static final Pattern LEADING = Pattern.compile("^\\s+");
// private static final Pattern TRAILING = Pattern.compile("\\s+$");
//
// /**
// * Trims all leading and trailing whitespaces (regex pattern class <code>\s</code>)
// *
// * @param s The string to trim.
// * @return The trimmed string.
// */
// public static final String trimAll(String s) {
// final Matcher leadingMatcher = LEADING.matcher(s);
// final Matcher trailingMatcher = TRAILING.matcher(s);
// final boolean hasLeading = leadingMatcher.find();
// final boolean hasTrailing = trailingMatcher.find();
// if (!hasLeading && !hasTrailing) {
// return s;
// }
// final int start = hasLeading ? leadingMatcher.end() : 0;
// final int end = hasTrailing ? trailingMatcher.start() : s.length();
// return s.substring(start, end);
// }
//
// private Whitespaces() {
// // hidden
// }
// }
| import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatement;
import de.skuzzle.enforcer.restrictimports.util.Whitespaces; |
@Override
public Optional<String> parsePackage(String line) {
if (!isPackage(line)) {
return Optional.empty();
}
return Optional.of(extractPackageName(line));
}
@Override
public List<ImportStatement> parseImport(String line, int lineNumber) {
if (!isImport(line)) {
return Collections.emptyList();
}
// There can be multiple import statements within the same line, so
// we simply split them at their ';'
final String[] parts = line.split(";");
return Arrays.stream(parts)
.map(String::trim)
.filter(s -> !s.isEmpty())
.map(s -> s.substring(IMPORT_STATEMENT.length()))
.map(String::trim)
.map(importName -> toImportStatement(importName, lineNumber))
.collect(Collectors.toList());
}
private ImportStatement toImportStatement(String importName, int lineNumber) {
if (importName.startsWith(STATIC_PREFIX)) { | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
// public final class ImportStatement {
//
// private static final String IMPORT_PREFIX = "import ";
// private static final String STATIC_PREFIX = "static ";
// private final String importName;
// private final int line;
// private final boolean staticImport;
//
// public ImportStatement(String importName, int line, boolean staticImport) {
// Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty");
// Preconditions.checkArgument(!importName.startsWith(IMPORT_PREFIX),
// "importName should be the raw package name without 'import ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(!importName.startsWith(STATIC_PREFIX),
// "importName should be the raw package name without 'static ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(importName.trim().equals(importName),
// "importName has leading or trailing spaces: '%s'", importName);
// Preconditions.checkArgument(line > 0, "line numbers should be 1-based and not start at 0");
//
// this.importName = importName;
// this.line = line;
// this.staticImport = staticImport;
// }
//
// /**
// * The physical line within the source file in which the import has occurred. Number
// * is always 1-based!
// *
// * @return The line number of the matched imports.
// */
// public int getLine() {
// return line;
// }
//
// /**
// * Returns the import name including the 'static ' prefix if this represents a static
// * import.
// *
// * @return The full import name.
// */
// public String getImportName() {
// if (staticImport) {
// return STATIC_PREFIX + importName;
// }
// return importName;
// }
//
// public String getFqcn() {
// return importName;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("import", importName)
// .add("line", line)
// .add("static", staticImport)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(importName, line, staticImport);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ImportStatement
// && Objects.equals(this.line, ((ImportStatement) obj).line)
// && Objects.equals(this.staticImport, ((ImportStatement) obj).staticImport)
// && Objects.equals(this.importName, ((ImportStatement) obj).importName);
// }
// }
//
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/Whitespaces.java
// public final class Whitespaces {
//
// private static final Pattern LEADING = Pattern.compile("^\\s+");
// private static final Pattern TRAILING = Pattern.compile("\\s+$");
//
// /**
// * Trims all leading and trailing whitespaces (regex pattern class <code>\s</code>)
// *
// * @param s The string to trim.
// * @return The trimmed string.
// */
// public static final String trimAll(String s) {
// final Matcher leadingMatcher = LEADING.matcher(s);
// final Matcher trailingMatcher = TRAILING.matcher(s);
// final boolean hasLeading = leadingMatcher.find();
// final boolean hasTrailing = trailingMatcher.find();
// if (!hasLeading && !hasTrailing) {
// return s;
// }
// final int start = hasLeading ? leadingMatcher.end() : 0;
// final int end = hasTrailing ? trailingMatcher.start() : s.length();
// return s.substring(start, end);
// }
//
// private Whitespaces() {
// // hidden
// }
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/lang/JavaLanguageSupport.java
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatement;
import de.skuzzle.enforcer.restrictimports.util.Whitespaces;
@Override
public Optional<String> parsePackage(String line) {
if (!isPackage(line)) {
return Optional.empty();
}
return Optional.of(extractPackageName(line));
}
@Override
public List<ImportStatement> parseImport(String line, int lineNumber) {
if (!isImport(line)) {
return Collections.emptyList();
}
// There can be multiple import statements within the same line, so
// we simply split them at their ';'
final String[] parts = line.split(";");
return Arrays.stream(parts)
.map(String::trim)
.filter(s -> !s.isEmpty())
.map(s -> s.substring(IMPORT_STATEMENT.length()))
.map(String::trim)
.map(importName -> toImportStatement(importName, lineNumber))
.collect(Collectors.toList());
}
private ImportStatement toImportStatement(String importName, int lineNumber) {
if (importName.startsWith(STATIC_PREFIX)) { | final String realImportName = Whitespaces.trimAll(importName.substring(STATIC_PREFIX.length())); |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/formatting/MatchFormatter.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/analyze/AnalyzeResult.java
// public final class AnalyzeResult {
//
// private final List<MatchedFile> srcMatches;
// private final List<MatchedFile> testMatches;
// private final Duration duration;
// private final int analysedFiles;
//
// private AnalyzeResult(List<MatchedFile> srcMatches, List<MatchedFile> testMatches, long duration,
// int analysedFiles) {
// this.srcMatches = srcMatches;
// this.testMatches = testMatches;
// this.duration = Duration.ofMillis(duration);
// this.analysedFiles = analysedFiles;
// }
//
// public static Builder builder() {
// return new Builder();
// }
//
// /**
// * Contains all the matches that were found within the analyzed compile source files.
// *
// * @return The list of found banned imports.
// */
// public List<MatchedFile> getSrcMatches() {
// return this.srcMatches;
// }
//
// /**
// * Returns the matches that occurred in compile source files grouped by their
// * {@link BannedImportGroup}
// *
// * @return The matches grouped by {@link BannedImportGroup}
// */
// public Map<BannedImportGroup, List<MatchedFile>> srcMatchesByGroup() {
// return srcMatches.stream()
// .collect(Collectors.groupingBy(MatchedFile::getMatchedBy));
// }
//
// /**
// * Contains all the matches that were found within the analyzed test source files.
// *
// * @return The list of found banned imports.
// */
// public List<MatchedFile> getTestMatches() {
// return testMatches;
// }
//
// /**
// * Returns the matches that occurred in test source files grouped by their
// * {@link BannedImportGroup}
// *
// * @return The matches grouped by {@link BannedImportGroup}
// */
// public Map<BannedImportGroup, List<MatchedFile>> testMatchesByGroup() {
// return testMatches.stream()
// .collect(Collectors.groupingBy(MatchedFile::getMatchedBy));
// }
//
// /**
// * Returns whether at least one banned import has been found within the analyzed
// * compile OR test source files.
// *
// * @return Whether a banned import has been found.
// */
// public boolean bannedImportsFound() {
// return bannedImportsInCompileCode() || bannedImportsInTestCode();
// }
//
// /**
// * Returns whether at least one banned import has been found within the analyzed
// * compile source code.
// *
// * @return Whether a banned import has been found.
// */
// public boolean bannedImportsInCompileCode() {
// return !srcMatches.isEmpty();
// }
//
// /**
// * Returns whether at least one banned import has been found within the analyzed test
// * source code.
// *
// * @return Whether a banned import has been found.
// */
// public boolean bannedImportsInTestCode() {
// return !testMatches.isEmpty();
// }
//
// /**
// * How long the analysis took, in ms.
// *
// * @return Analysis duration in ms.
// */
// public Duration duration() {
// return this.duration;
// }
//
// /**
// * The number of files that have been analysed.
// *
// * @return Number of files.
// */
// public int analysedFiles() {
// return this.analysedFiles;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(srcMatches, testMatches);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof AnalyzeResult
// && Objects.equals(srcMatches, ((AnalyzeResult) obj).srcMatches)
// && Objects.equals(testMatches, ((AnalyzeResult) obj).testMatches);
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("srcMatches", this.srcMatches)
// .add("testMatches", this.testMatches)
// .add("duration", duration)
// .toString();
// }
//
// public static class Builder {
// private final List<MatchedFile> srcMatches = new ArrayList<>();
// private final List<MatchedFile> testMatches = new ArrayList<>();
// private long duration;
// private int analysedFiles;
//
// private Builder() {
// // hidden
// }
//
// public Builder withMatches(Collection<MatchedFile> matches) {
// this.srcMatches.addAll(matches);
// return this;
// }
//
// public Builder withMatches(MatchedFile.Builder... matches) {
// Arrays.stream(matches).map(MatchedFile.Builder::build)
// .forEach(this.srcMatches::add);
// return this;
// }
//
// public Builder withMatchesInTestCode(Collection<MatchedFile> matches) {
// this.testMatches.addAll(matches);
// return this;
// }
//
// public Builder withMatchesInTestCode(MatchedFile.Builder... matches) {
// Arrays.stream(matches).map(MatchedFile.Builder::build)
// .forEach(this.testMatches::add);
// return this;
// }
//
// public Builder withDuration(long duration) {
// this.duration = duration;
// return this;
// }
//
// public Builder withAnalysedFileCount(int analysedFiles) {
// this.analysedFiles = analysedFiles;
// return this;
// }
//
// public AnalyzeResult build() {
// return new AnalyzeResult(srcMatches, testMatches, duration, analysedFiles);
// }
//
// }
// }
| import java.nio.file.Path;
import java.util.Collection;
import de.skuzzle.enforcer.restrictimports.analyze.AnalyzeResult; | package de.skuzzle.enforcer.restrictimports.formatting;
/**
* For formatting the result of the banned import analysis.
*/
public interface MatchFormatter {
static MatchFormatter getInstance() {
return MatchFormatterImpl.INSTANCE;
}
| // Path: src/main/java/de/skuzzle/enforcer/restrictimports/analyze/AnalyzeResult.java
// public final class AnalyzeResult {
//
// private final List<MatchedFile> srcMatches;
// private final List<MatchedFile> testMatches;
// private final Duration duration;
// private final int analysedFiles;
//
// private AnalyzeResult(List<MatchedFile> srcMatches, List<MatchedFile> testMatches, long duration,
// int analysedFiles) {
// this.srcMatches = srcMatches;
// this.testMatches = testMatches;
// this.duration = Duration.ofMillis(duration);
// this.analysedFiles = analysedFiles;
// }
//
// public static Builder builder() {
// return new Builder();
// }
//
// /**
// * Contains all the matches that were found within the analyzed compile source files.
// *
// * @return The list of found banned imports.
// */
// public List<MatchedFile> getSrcMatches() {
// return this.srcMatches;
// }
//
// /**
// * Returns the matches that occurred in compile source files grouped by their
// * {@link BannedImportGroup}
// *
// * @return The matches grouped by {@link BannedImportGroup}
// */
// public Map<BannedImportGroup, List<MatchedFile>> srcMatchesByGroup() {
// return srcMatches.stream()
// .collect(Collectors.groupingBy(MatchedFile::getMatchedBy));
// }
//
// /**
// * Contains all the matches that were found within the analyzed test source files.
// *
// * @return The list of found banned imports.
// */
// public List<MatchedFile> getTestMatches() {
// return testMatches;
// }
//
// /**
// * Returns the matches that occurred in test source files grouped by their
// * {@link BannedImportGroup}
// *
// * @return The matches grouped by {@link BannedImportGroup}
// */
// public Map<BannedImportGroup, List<MatchedFile>> testMatchesByGroup() {
// return testMatches.stream()
// .collect(Collectors.groupingBy(MatchedFile::getMatchedBy));
// }
//
// /**
// * Returns whether at least one banned import has been found within the analyzed
// * compile OR test source files.
// *
// * @return Whether a banned import has been found.
// */
// public boolean bannedImportsFound() {
// return bannedImportsInCompileCode() || bannedImportsInTestCode();
// }
//
// /**
// * Returns whether at least one banned import has been found within the analyzed
// * compile source code.
// *
// * @return Whether a banned import has been found.
// */
// public boolean bannedImportsInCompileCode() {
// return !srcMatches.isEmpty();
// }
//
// /**
// * Returns whether at least one banned import has been found within the analyzed test
// * source code.
// *
// * @return Whether a banned import has been found.
// */
// public boolean bannedImportsInTestCode() {
// return !testMatches.isEmpty();
// }
//
// /**
// * How long the analysis took, in ms.
// *
// * @return Analysis duration in ms.
// */
// public Duration duration() {
// return this.duration;
// }
//
// /**
// * The number of files that have been analysed.
// *
// * @return Number of files.
// */
// public int analysedFiles() {
// return this.analysedFiles;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(srcMatches, testMatches);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof AnalyzeResult
// && Objects.equals(srcMatches, ((AnalyzeResult) obj).srcMatches)
// && Objects.equals(testMatches, ((AnalyzeResult) obj).testMatches);
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("srcMatches", this.srcMatches)
// .add("testMatches", this.testMatches)
// .add("duration", duration)
// .toString();
// }
//
// public static class Builder {
// private final List<MatchedFile> srcMatches = new ArrayList<>();
// private final List<MatchedFile> testMatches = new ArrayList<>();
// private long duration;
// private int analysedFiles;
//
// private Builder() {
// // hidden
// }
//
// public Builder withMatches(Collection<MatchedFile> matches) {
// this.srcMatches.addAll(matches);
// return this;
// }
//
// public Builder withMatches(MatchedFile.Builder... matches) {
// Arrays.stream(matches).map(MatchedFile.Builder::build)
// .forEach(this.srcMatches::add);
// return this;
// }
//
// public Builder withMatchesInTestCode(Collection<MatchedFile> matches) {
// this.testMatches.addAll(matches);
// return this;
// }
//
// public Builder withMatchesInTestCode(MatchedFile.Builder... matches) {
// Arrays.stream(matches).map(MatchedFile.Builder::build)
// .forEach(this.testMatches::add);
// return this;
// }
//
// public Builder withDuration(long duration) {
// this.duration = duration;
// return this;
// }
//
// public Builder withAnalysedFileCount(int analysedFiles) {
// this.analysedFiles = analysedFiles;
// return this;
// }
//
// public AnalyzeResult build() {
// return new AnalyzeResult(srcMatches, testMatches, duration, analysedFiles);
// }
//
// }
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/formatting/MatchFormatter.java
import java.nio.file.Path;
import java.util.Collection;
import de.skuzzle.enforcer.restrictimports.analyze.AnalyzeResult;
package de.skuzzle.enforcer.restrictimports.formatting;
/**
* For formatting the result of the banned import analysis.
*/
public interface MatchFormatter {
static MatchFormatter getInstance() {
return MatchFormatterImpl.INSTANCE;
}
| String formatMatches(Collection<Path> roots, AnalyzeResult analyzeResult); |
skuzzle/restrict-imports-enforcer-rule | src/main/java/de/skuzzle/enforcer/restrictimports/analyze/AnalyzeResult.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/StringRepresentation.java
// public final class StringRepresentation {
//
// private final String name;
// private final List<Attribute> attributes = new ArrayList<>();
//
// private StringRepresentation(String name) {
// this.name = name;
// }
//
// public static StringRepresentation ofType(Class<?> type) {
// return new StringRepresentation(type.getSimpleName());
// }
//
// public static StringRepresentation ofInstance(Object instance) {
// return ofType(instance.getClass());
// }
//
// public StringRepresentation add(String attribute, Object value) {
// attributes.add(new Attribute(attribute, value));
// return this;
// }
//
// @Override
// public String toString() {
// return new StringBuilder(name)
// .append("{")
// .append(attributes.stream().map(Attribute::toString).collect(Collectors.joining(", ")))
// .append("}")
// .toString();
// }
//
// private static final class Attribute {
// private final String name;
// private final Object value;
//
// private Attribute(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public String toString() {
// return name + "=" + value;
// }
// }
// }
| import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import de.skuzzle.enforcer.restrictimports.util.StringRepresentation; | *
* @return Analysis duration in ms.
*/
public Duration duration() {
return this.duration;
}
/**
* The number of files that have been analysed.
*
* @return Number of files.
*/
public int analysedFiles() {
return this.analysedFiles;
}
@Override
public int hashCode() {
return Objects.hash(srcMatches, testMatches);
}
@Override
public boolean equals(Object obj) {
return obj == this || obj instanceof AnalyzeResult
&& Objects.equals(srcMatches, ((AnalyzeResult) obj).srcMatches)
&& Objects.equals(testMatches, ((AnalyzeResult) obj).testMatches);
}
@Override
public String toString() { | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/util/StringRepresentation.java
// public final class StringRepresentation {
//
// private final String name;
// private final List<Attribute> attributes = new ArrayList<>();
//
// private StringRepresentation(String name) {
// this.name = name;
// }
//
// public static StringRepresentation ofType(Class<?> type) {
// return new StringRepresentation(type.getSimpleName());
// }
//
// public static StringRepresentation ofInstance(Object instance) {
// return ofType(instance.getClass());
// }
//
// public StringRepresentation add(String attribute, Object value) {
// attributes.add(new Attribute(attribute, value));
// return this;
// }
//
// @Override
// public String toString() {
// return new StringBuilder(name)
// .append("{")
// .append(attributes.stream().map(Attribute::toString).collect(Collectors.joining(", ")))
// .append("}")
// .toString();
// }
//
// private static final class Attribute {
// private final String name;
// private final Object value;
//
// private Attribute(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// @Override
// public String toString() {
// return name + "=" + value;
// }
// }
// }
// Path: src/main/java/de/skuzzle/enforcer/restrictimports/analyze/AnalyzeResult.java
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import de.skuzzle.enforcer.restrictimports.util.StringRepresentation;
*
* @return Analysis duration in ms.
*/
public Duration duration() {
return this.duration;
}
/**
* The number of files that have been analysed.
*
* @return Number of files.
*/
public int analysedFiles() {
return this.analysedFiles;
}
@Override
public int hashCode() {
return Objects.hash(srcMatches, testMatches);
}
@Override
public boolean equals(Object obj) {
return obj == this || obj instanceof AnalyzeResult
&& Objects.equals(srcMatches, ((AnalyzeResult) obj).srcMatches)
&& Objects.equals(testMatches, ((AnalyzeResult) obj).testMatches);
}
@Override
public String toString() { | return StringRepresentation.ofInstance(this) |
skuzzle/restrict-imports-enforcer-rule | src/test/java/de/skuzzle/enforcer/restrictimports/parser/lang/KotlinGroovyLanguageSupportTest.java | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
// public final class ImportStatement {
//
// private static final String IMPORT_PREFIX = "import ";
// private static final String STATIC_PREFIX = "static ";
// private final String importName;
// private final int line;
// private final boolean staticImport;
//
// public ImportStatement(String importName, int line, boolean staticImport) {
// Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty");
// Preconditions.checkArgument(!importName.startsWith(IMPORT_PREFIX),
// "importName should be the raw package name without 'import ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(!importName.startsWith(STATIC_PREFIX),
// "importName should be the raw package name without 'static ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(importName.trim().equals(importName),
// "importName has leading or trailing spaces: '%s'", importName);
// Preconditions.checkArgument(line > 0, "line numbers should be 1-based and not start at 0");
//
// this.importName = importName;
// this.line = line;
// this.staticImport = staticImport;
// }
//
// /**
// * The physical line within the source file in which the import has occurred. Number
// * is always 1-based!
// *
// * @return The line number of the matched imports.
// */
// public int getLine() {
// return line;
// }
//
// /**
// * Returns the import name including the 'static ' prefix if this represents a static
// * import.
// *
// * @return The full import name.
// */
// public String getImportName() {
// if (staticImport) {
// return STATIC_PREFIX + importName;
// }
// return importName;
// }
//
// public String getFqcn() {
// return importName;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("import", importName)
// .add("line", line)
// .add("static", staticImport)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(importName, line, staticImport);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ImportStatement
// && Objects.equals(this.line, ((ImportStatement) obj).line)
// && Objects.equals(this.staticImport, ((ImportStatement) obj).staticImport)
// && Objects.equals(this.importName, ((ImportStatement) obj).importName);
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatement; | package de.skuzzle.enforcer.restrictimports.parser.lang;
public class KotlinGroovyLanguageSupportTest {
private final KotlinGroovyLanguageSupport subject = new KotlinGroovyLanguageSupport();
@Test
public void testValidImport1() {
assertThat(subject.parseImport("import java.util.List;", 1)).first() | // Path: src/main/java/de/skuzzle/enforcer/restrictimports/parser/ImportStatement.java
// public final class ImportStatement {
//
// private static final String IMPORT_PREFIX = "import ";
// private static final String STATIC_PREFIX = "static ";
// private final String importName;
// private final int line;
// private final boolean staticImport;
//
// public ImportStatement(String importName, int line, boolean staticImport) {
// Preconditions.checkArgument(importName != null && !importName.isEmpty(), "importName must not be empty");
// Preconditions.checkArgument(!importName.startsWith(IMPORT_PREFIX),
// "importName should be the raw package name without 'import ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(!importName.startsWith(STATIC_PREFIX),
// "importName should be the raw package name without 'static ' prefix but was: '%s'", importName);
// Preconditions.checkArgument(importName.trim().equals(importName),
// "importName has leading or trailing spaces: '%s'", importName);
// Preconditions.checkArgument(line > 0, "line numbers should be 1-based and not start at 0");
//
// this.importName = importName;
// this.line = line;
// this.staticImport = staticImport;
// }
//
// /**
// * The physical line within the source file in which the import has occurred. Number
// * is always 1-based!
// *
// * @return The line number of the matched imports.
// */
// public int getLine() {
// return line;
// }
//
// /**
// * Returns the import name including the 'static ' prefix if this represents a static
// * import.
// *
// * @return The full import name.
// */
// public String getImportName() {
// if (staticImport) {
// return STATIC_PREFIX + importName;
// }
// return importName;
// }
//
// public String getFqcn() {
// return importName;
// }
//
// @Override
// public String toString() {
// return StringRepresentation.ofInstance(this)
// .add("import", importName)
// .add("line", line)
// .add("static", staticImport)
// .toString();
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(importName, line, staticImport);
// }
//
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof ImportStatement
// && Objects.equals(this.line, ((ImportStatement) obj).line)
// && Objects.equals(this.staticImport, ((ImportStatement) obj).staticImport)
// && Objects.equals(this.importName, ((ImportStatement) obj).importName);
// }
// }
// Path: src/test/java/de/skuzzle/enforcer/restrictimports/parser/lang/KotlinGroovyLanguageSupportTest.java
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import de.skuzzle.enforcer.restrictimports.parser.ImportStatement;
package de.skuzzle.enforcer.restrictimports.parser.lang;
public class KotlinGroovyLanguageSupportTest {
private final KotlinGroovyLanguageSupport subject = new KotlinGroovyLanguageSupport();
@Test
public void testValidImport1() {
assertThat(subject.parseImport("import java.util.List;", 1)).first() | .isEqualTo(new ImportStatement("java.util.List", 1, false)); |
skuzzle/restrict-imports-enforcer-rule | src/test/java/de/skuzzle/enforcer/restrictimports/parser/SkipCommentsLineSupplierTest.java | // Path: src/test/java/de/skuzzle/enforcer/restrictimports/analyze/SourceFileBuilder.java
// public class SourceFileBuilder {
//
// private final FileSystem mockFileSystem;
// private Path file;
// private Charset charset = StandardCharsets.UTF_8;
//
// public SourceFileBuilder(FileSystem mockFileSystem) {
// this.mockFileSystem = mockFileSystem;
// }
//
// public SourceFileBuilder atPath(String first)
// throws IOException {
//
// final String[] parts = first.split("/");
//
// file = mockFileSystem.getPath(parts[0],
// Arrays.copyOfRange(parts, 1, parts.length));
// Files.createDirectories(file.getParent());
// return this;
// }
//
// public SourceFileBuilder witchCharset(Charset charset) {
// this.charset = charset;
// return this;
// }
//
// public Path withLines(CharSequence... lines) throws IOException {
// final Iterable<? extends CharSequence> it = Arrays.stream(lines)::iterator;
// Files.write(file, it, charset);
// return file.toAbsolutePath();
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import de.skuzzle.enforcer.restrictimports.analyze.SourceFileBuilder; | package de.skuzzle.enforcer.restrictimports.parser;
public class SkipCommentsLineSupplierTest {
private final FileSystem fs = Jimfs.newFileSystem(Configuration.unix());
private final LineSupplier subject = new SkipCommentsLineSupplier(StandardCharsets.UTF_8);
@Test
void testNoComments() throws Exception { | // Path: src/test/java/de/skuzzle/enforcer/restrictimports/analyze/SourceFileBuilder.java
// public class SourceFileBuilder {
//
// private final FileSystem mockFileSystem;
// private Path file;
// private Charset charset = StandardCharsets.UTF_8;
//
// public SourceFileBuilder(FileSystem mockFileSystem) {
// this.mockFileSystem = mockFileSystem;
// }
//
// public SourceFileBuilder atPath(String first)
// throws IOException {
//
// final String[] parts = first.split("/");
//
// file = mockFileSystem.getPath(parts[0],
// Arrays.copyOfRange(parts, 1, parts.length));
// Files.createDirectories(file.getParent());
// return this;
// }
//
// public SourceFileBuilder witchCharset(Charset charset) {
// this.charset = charset;
// return this;
// }
//
// public Path withLines(CharSequence... lines) throws IOException {
// final Iterable<? extends CharSequence> it = Arrays.stream(lines)::iterator;
// Files.write(file, it, charset);
// return file.toAbsolutePath();
// }
// }
// Path: src/test/java/de/skuzzle/enforcer/restrictimports/parser/SkipCommentsLineSupplierTest.java
import static org.assertj.core.api.Assertions.assertThat;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import de.skuzzle.enforcer.restrictimports.analyze.SourceFileBuilder;
package de.skuzzle.enforcer.restrictimports.parser;
public class SkipCommentsLineSupplierTest {
private final FileSystem fs = Jimfs.newFileSystem(Configuration.unix());
private final LineSupplier subject = new SkipCommentsLineSupplier(StandardCharsets.UTF_8);
@Test
void testNoComments() throws Exception { | final Path file = new SourceFileBuilder(fs) |
mast-group/naturalize | src/main/java/renaming/renamers/AllPriorIdentifierRenaming.java | // Path: src/main/java/renaming/priors/JavaVariableGrammarPrior.java
// public class JavaVariableGrammarPrior implements
// IConditionalProbability<String, Pair<Integer, Integer>> {
//
// final DiscreteElementwiseConditionalDistribution<String, Integer> parentPrior = new DiscreteElementwiseConditionalDistribution<String, Integer>();
// final DiscreteElementwiseConditionalDistribution<String, Integer> grandParentPrior = new DiscreteElementwiseConditionalDistribution<String, Integer>();
//
// private static final Logger LOGGER = Logger
// .getLogger(JavaVariableNameTypeDistribution.class.getName());
//
// public static JavaVariableGrammarPrior buildFromFiles(
// final Collection<File> files) {
// final JavaVariableGrammarPrior gp = new JavaVariableGrammarPrior();
// for (final File f : files) {
// try {
// for (final Entry<Scope, String> variable : VariableScopeExtractor
// .getScopeSnippets(f).entries()) {
// gp.parentPrior.addElement(variable.getValue(),
// variable.getKey().astNodeType);
// gp.grandParentPrior.addElement(variable.getValue(),
// variable.getKey().astParentNodeType);
// }
// } catch (final IOException e) {
// LOGGER.warning(ExceptionUtils.getFullStackTrace(e));
// }
// }
//
// return gp;
// }
//
// private JavaVariableGrammarPrior() {
// }
//
// @Override
// public Optional<String> getMaximumLikelihoodElement(
// final Pair<Integer, Integer> given) {
// throw new NotImplementedException();
// }
//
// @Override
// public double getMLProbability(final String element,
// final Pair<Integer, Integer> given) {
// return parentPrior.getMLProbability(element, given.first)
// * grandParentPrior.getMLProbability(element, given.second);
// }
//
// }
//
// Path: src/main/java/renaming/priors/JavaVariableNameTypeDistribution.java
// public class JavaVariableNameTypeDistribution implements
// IConditionalProbability<String, String> {
//
// private static final Logger LOGGER = Logger
// .getLogger(JavaVariableNameTypeDistribution.class.getName());
//
// public static JavaVariableNameTypeDistribution buildFromFiles(
// final Collection<File> files) {
// final JavaVariableNameTypeDistribution tp = new JavaVariableNameTypeDistribution();
// for (final File f : files) {
// try {
// final JavaASTExtractor ex = new JavaASTExtractor(false);
// final CompilationUnit cu = ex.getAST(f);
// final JavaApproximateTypeInferencer typeInf = new JavaApproximateTypeInferencer(
// cu);
// typeInf.infer();
// final Map<String, String> varTypes = typeInf.getVariableTypes();
// for (final Entry<String, String> variable : varTypes.entrySet()) {
// tp.typePrior.addElement(variable.getKey(),
// variable.getValue());
// }
// } catch (final IOException e) {
// LOGGER.warning(ExceptionUtils.getFullStackTrace(e));
// }
// }
//
// return tp;
// }
//
// public static void main(final String args[]) throws SerializationException {
// if (args.length != 2) {
// System.err.println("Usage <folderWithTypes> <SerialzedTypePrior>");
// return;
// }
//
// final Collection<File> trainingFiles = FileUtils.listFiles(new File(
// args[0]), new RegexFileFilter(".*\\.java$"),
// DirectoryFileFilter.DIRECTORY);
//
// final JavaVariableNameTypeDistribution tp = JavaVariableNameTypeDistribution
// .buildFromFiles(trainingFiles);
// Serializer.getSerializer().serialize(tp, args[1]);
// }
//
// DiscreteElementwiseConditionalDistribution<String, String> typePrior = new DiscreteElementwiseConditionalDistribution<String, String>();
//
// /**
// *
// */
// private JavaVariableNameTypeDistribution() {
// }
//
// @Override
// public Optional<String> getMaximumLikelihoodElement(final String type) {
// return typePrior.getMaximumLikelihoodElement(type);
// }
//
// @Override
// public double getMLProbability(final String element, final String type) {
// if (type == null) {
// return 1;
// }
// return typePrior.getMLProbability(element, type);
// }
//
// }
| import java.io.File;
import java.util.Collection;
import java.util.logging.Logger;
import renaming.priors.JavaVariableGrammarPrior;
import renaming.priors.JavaVariableNameTypeDistribution;
import codemining.languagetools.ITokenizer;
import codemining.languagetools.Scope;
import codemining.util.SettingsLoader;
import codemining.util.data.Pair;
import com.google.common.math.DoubleMath; | /**
*
*/
package renaming.renamers;
/**
* A renaming class that uses both the grammar and the type prior.
*
* @author Miltos Allamanis <m.allamanis@ed.ac.uk>
*
*/
public class AllPriorIdentifierRenaming extends BaseIdentifierRenamings {
JavaVariableNameTypeDistribution tp;
| // Path: src/main/java/renaming/priors/JavaVariableGrammarPrior.java
// public class JavaVariableGrammarPrior implements
// IConditionalProbability<String, Pair<Integer, Integer>> {
//
// final DiscreteElementwiseConditionalDistribution<String, Integer> parentPrior = new DiscreteElementwiseConditionalDistribution<String, Integer>();
// final DiscreteElementwiseConditionalDistribution<String, Integer> grandParentPrior = new DiscreteElementwiseConditionalDistribution<String, Integer>();
//
// private static final Logger LOGGER = Logger
// .getLogger(JavaVariableNameTypeDistribution.class.getName());
//
// public static JavaVariableGrammarPrior buildFromFiles(
// final Collection<File> files) {
// final JavaVariableGrammarPrior gp = new JavaVariableGrammarPrior();
// for (final File f : files) {
// try {
// for (final Entry<Scope, String> variable : VariableScopeExtractor
// .getScopeSnippets(f).entries()) {
// gp.parentPrior.addElement(variable.getValue(),
// variable.getKey().astNodeType);
// gp.grandParentPrior.addElement(variable.getValue(),
// variable.getKey().astParentNodeType);
// }
// } catch (final IOException e) {
// LOGGER.warning(ExceptionUtils.getFullStackTrace(e));
// }
// }
//
// return gp;
// }
//
// private JavaVariableGrammarPrior() {
// }
//
// @Override
// public Optional<String> getMaximumLikelihoodElement(
// final Pair<Integer, Integer> given) {
// throw new NotImplementedException();
// }
//
// @Override
// public double getMLProbability(final String element,
// final Pair<Integer, Integer> given) {
// return parentPrior.getMLProbability(element, given.first)
// * grandParentPrior.getMLProbability(element, given.second);
// }
//
// }
//
// Path: src/main/java/renaming/priors/JavaVariableNameTypeDistribution.java
// public class JavaVariableNameTypeDistribution implements
// IConditionalProbability<String, String> {
//
// private static final Logger LOGGER = Logger
// .getLogger(JavaVariableNameTypeDistribution.class.getName());
//
// public static JavaVariableNameTypeDistribution buildFromFiles(
// final Collection<File> files) {
// final JavaVariableNameTypeDistribution tp = new JavaVariableNameTypeDistribution();
// for (final File f : files) {
// try {
// final JavaASTExtractor ex = new JavaASTExtractor(false);
// final CompilationUnit cu = ex.getAST(f);
// final JavaApproximateTypeInferencer typeInf = new JavaApproximateTypeInferencer(
// cu);
// typeInf.infer();
// final Map<String, String> varTypes = typeInf.getVariableTypes();
// for (final Entry<String, String> variable : varTypes.entrySet()) {
// tp.typePrior.addElement(variable.getKey(),
// variable.getValue());
// }
// } catch (final IOException e) {
// LOGGER.warning(ExceptionUtils.getFullStackTrace(e));
// }
// }
//
// return tp;
// }
//
// public static void main(final String args[]) throws SerializationException {
// if (args.length != 2) {
// System.err.println("Usage <folderWithTypes> <SerialzedTypePrior>");
// return;
// }
//
// final Collection<File> trainingFiles = FileUtils.listFiles(new File(
// args[0]), new RegexFileFilter(".*\\.java$"),
// DirectoryFileFilter.DIRECTORY);
//
// final JavaVariableNameTypeDistribution tp = JavaVariableNameTypeDistribution
// .buildFromFiles(trainingFiles);
// Serializer.getSerializer().serialize(tp, args[1]);
// }
//
// DiscreteElementwiseConditionalDistribution<String, String> typePrior = new DiscreteElementwiseConditionalDistribution<String, String>();
//
// /**
// *
// */
// private JavaVariableNameTypeDistribution() {
// }
//
// @Override
// public Optional<String> getMaximumLikelihoodElement(final String type) {
// return typePrior.getMaximumLikelihoodElement(type);
// }
//
// @Override
// public double getMLProbability(final String element, final String type) {
// if (type == null) {
// return 1;
// }
// return typePrior.getMLProbability(element, type);
// }
//
// }
// Path: src/main/java/renaming/renamers/AllPriorIdentifierRenaming.java
import java.io.File;
import java.util.Collection;
import java.util.logging.Logger;
import renaming.priors.JavaVariableGrammarPrior;
import renaming.priors.JavaVariableNameTypeDistribution;
import codemining.languagetools.ITokenizer;
import codemining.languagetools.Scope;
import codemining.util.SettingsLoader;
import codemining.util.data.Pair;
import com.google.common.math.DoubleMath;
/**
*
*/
package renaming.renamers;
/**
* A renaming class that uses both the grammar and the type prior.
*
* @author Miltos Allamanis <m.allamanis@ed.ac.uk>
*
*/
public class AllPriorIdentifierRenaming extends BaseIdentifierRenamings {
JavaVariableNameTypeDistribution tp;
| JavaVariableGrammarPrior gp; |
mast-group/naturalize | src/main/java/renaming/history/RenamingDatasetExtractor.java | // Path: src/main/java/renaming/history/RepentDataParser.java
// public static class Renaming {
// public String fromVersion;
// public String toVersion;
// String filename;
// String nameBefore;
// String nameAfter;
// public Range<Integer> linesBefore;
// public Range<Integer> linesAfter;
//
// /*
// * (non-Javadoc)
// *
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// final StringBuilder builder = new StringBuilder();
// builder.append("Renaming [fromVersion=");
// builder.append(fromVersion);
// builder.append(", toVersion=");
// builder.append(toVersion);
// builder.append(", filename=");
// builder.append(filename);
// builder.append(", nameBefore=");
// builder.append(nameBefore);
// builder.append(", nameAfter=");
// builder.append(nameAfter);
// builder.append(", linesBefore=");
// builder.append(linesBefore);
// builder.append(", linesAfter=");
// builder.append(linesAfter);
// builder.append("]");
// return builder.toString();
// }
//
// }
| import static com.google.common.base.Preconditions.checkArgument;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.NoHeadException;
import org.eclipse.jgit.errors.NoWorkTreeException;
import org.eclipse.jgit.revwalk.RevCommit;
import renaming.history.RepentDataParser.Renaming;
import codemining.java.codeutils.binding.JavaApproximateVariableBindingExtractor;
import codemining.java.codeutils.binding.JavaMethodDeclarationBindingExtractor;
import codemining.java.codeutils.binding.tui.JavaBindingsToJson.SerializableResolvedSourceCode;
import codemining.languagetools.bindings.ResolvedSourceCode;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import committools.data.RepositoryFileWalker; | package renaming.history;
public class RenamingDatasetExtractor {
public static class BindingExtractor extends RepositoryFileWalker {
List<RenamedSerializableResolvedSourceCode> renamedVariablesDatapoints = Lists
.newArrayList();
List<RenamedSerializableResolvedSourceCode> renamedMethodDeclarationsDatapoints = Lists
.newArrayList();
| // Path: src/main/java/renaming/history/RepentDataParser.java
// public static class Renaming {
// public String fromVersion;
// public String toVersion;
// String filename;
// String nameBefore;
// String nameAfter;
// public Range<Integer> linesBefore;
// public Range<Integer> linesAfter;
//
// /*
// * (non-Javadoc)
// *
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// final StringBuilder builder = new StringBuilder();
// builder.append("Renaming [fromVersion=");
// builder.append(fromVersion);
// builder.append(", toVersion=");
// builder.append(toVersion);
// builder.append(", filename=");
// builder.append(filename);
// builder.append(", nameBefore=");
// builder.append(nameBefore);
// builder.append(", nameAfter=");
// builder.append(nameAfter);
// builder.append(", linesBefore=");
// builder.append(linesBefore);
// builder.append(", linesAfter=");
// builder.append(linesAfter);
// builder.append("]");
// return builder.toString();
// }
//
// }
// Path: src/main/java/renaming/history/RenamingDatasetExtractor.java
import static com.google.common.base.Preconditions.checkArgument;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.NoHeadException;
import org.eclipse.jgit.errors.NoWorkTreeException;
import org.eclipse.jgit.revwalk.RevCommit;
import renaming.history.RepentDataParser.Renaming;
import codemining.java.codeutils.binding.JavaApproximateVariableBindingExtractor;
import codemining.java.codeutils.binding.JavaMethodDeclarationBindingExtractor;
import codemining.java.codeutils.binding.tui.JavaBindingsToJson.SerializableResolvedSourceCode;
import codemining.languagetools.bindings.ResolvedSourceCode;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import committools.data.RepositoryFileWalker;
package renaming.history;
public class RenamingDatasetExtractor {
public static class BindingExtractor extends RepositoryFileWalker {
List<RenamedSerializableResolvedSourceCode> renamedVariablesDatapoints = Lists
.newArrayList();
List<RenamedSerializableResolvedSourceCode> renamedMethodDeclarationsDatapoints = Lists
.newArrayList();
| final Multimap<String, Renaming> renamings; |
mast-group/naturalize | src/main/java/renaming/formatting/FormattingRenamingsEval.java | // Path: src/main/java/renaming/renamers/INGramIdentifierRenamer.java
// public static class Renaming implements Comparable<Renaming> {
// public final String name;
//
// public final double score;
//
// public final int nContexts;
//
// public final Scope scope;
//
// public Renaming(final String id, final double xEntropy,
// final int contexts, final Scope renamingScope) {
// name = id;
// score = xEntropy;
// nContexts = contexts;
// scope = renamingScope;
// }
//
// @Override
// public int compareTo(final Renaming other) {
// return ComparisonChain.start().compare(score, other.score)
// .compare(name, other.name).result();
// }
//
// @Override
// public boolean equals(final Object other) {
// if (!(other instanceof Renaming)) {
// return false;
// }
// final Renaming r = (Renaming) other;
// return Objects.equal(name, r.name) && Objects.equal(score, r.score);
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(name, score);
//
// }
//
// @Override
// public String toString() {
// return name + ":" + String.format("%.2f", score);
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import org.apache.commons.io.FileUtils;
import renaming.renamers.INGramIdentifierRenamer.Renaming;
import codemining.lm.ngram.AbstractNGramLM;
import codemining.lm.ngram.NGram;
import com.google.common.collect.Multiset;
import com.google.common.collect.Sets; | /**
*
*/
package renaming.formatting;
/**
* Evaluate Formatting Renamings.
*
* @author Miltos Allamanis <m.allamanis@ed.ac.uk>
*
*/
public class FormattingRenamingsEval {
/**
* Struct class containing results.
*
*/
public static class WhitespacePrecisionRecall {
static double[] THRESHOLD_VALUES = { .1, .2, .5, 1, 1.5, 2, 2.5, 3,
3.5, 4, 5, 6, 7, 8, 10, 12, 15, 20, 50, 100, Double.MAX_VALUE };
final long[] nGaveSuggestions = new long[THRESHOLD_VALUES.length];
final long[] nCorrect = new long[THRESHOLD_VALUES.length];
long total = 0;
/**
* Accumulate results to this object
*
* @param other
*/
public synchronized void accumulate(
final WhitespacePrecisionRecall other) {
for (int i = 0; i < THRESHOLD_VALUES.length; i++) {
nGaveSuggestions[i] += other.nGaveSuggestions[i];
nCorrect[i] += other.nCorrect[i];
}
total += other.total;
}
| // Path: src/main/java/renaming/renamers/INGramIdentifierRenamer.java
// public static class Renaming implements Comparable<Renaming> {
// public final String name;
//
// public final double score;
//
// public final int nContexts;
//
// public final Scope scope;
//
// public Renaming(final String id, final double xEntropy,
// final int contexts, final Scope renamingScope) {
// name = id;
// score = xEntropy;
// nContexts = contexts;
// scope = renamingScope;
// }
//
// @Override
// public int compareTo(final Renaming other) {
// return ComparisonChain.start().compare(score, other.score)
// .compare(name, other.name).result();
// }
//
// @Override
// public boolean equals(final Object other) {
// if (!(other instanceof Renaming)) {
// return false;
// }
// final Renaming r = (Renaming) other;
// return Objects.equal(name, r.name) && Objects.equal(score, r.score);
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(name, score);
//
// }
//
// @Override
// public String toString() {
// return name + ":" + String.format("%.2f", score);
// }
//
// }
// Path: src/main/java/renaming/formatting/FormattingRenamingsEval.java
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import org.apache.commons.io.FileUtils;
import renaming.renamers.INGramIdentifierRenamer.Renaming;
import codemining.lm.ngram.AbstractNGramLM;
import codemining.lm.ngram.NGram;
import com.google.common.collect.Multiset;
import com.google.common.collect.Sets;
/**
*
*/
package renaming.formatting;
/**
* Evaluate Formatting Renamings.
*
* @author Miltos Allamanis <m.allamanis@ed.ac.uk>
*
*/
public class FormattingRenamingsEval {
/**
* Struct class containing results.
*
*/
public static class WhitespacePrecisionRecall {
static double[] THRESHOLD_VALUES = { .1, .2, .5, 1, 1.5, 2, 2.5, 3,
3.5, 4, 5, 6, 7, 8, 10, 12, 15, 20, 50, 100, Double.MAX_VALUE };
final long[] nGaveSuggestions = new long[THRESHOLD_VALUES.length];
final long[] nCorrect = new long[THRESHOLD_VALUES.length];
long total = 0;
/**
* Accumulate results to this object
*
* @param other
*/
public synchronized void accumulate(
final WhitespacePrecisionRecall other) {
for (int i = 0; i < THRESHOLD_VALUES.length; i++) {
nGaveSuggestions[i] += other.nGaveSuggestions[i];
nCorrect[i] += other.nCorrect[i];
}
total += other.total;
}
| public void addSuggestion(final SortedSet<Renaming> suggestions, |
mast-group/naturalize | src/main/java/renaming/renamers/GrammarPriorIdentifierRenaming.java | // Path: src/main/java/renaming/priors/JavaVariableGrammarPrior.java
// public class JavaVariableGrammarPrior implements
// IConditionalProbability<String, Pair<Integer, Integer>> {
//
// final DiscreteElementwiseConditionalDistribution<String, Integer> parentPrior = new DiscreteElementwiseConditionalDistribution<String, Integer>();
// final DiscreteElementwiseConditionalDistribution<String, Integer> grandParentPrior = new DiscreteElementwiseConditionalDistribution<String, Integer>();
//
// private static final Logger LOGGER = Logger
// .getLogger(JavaVariableNameTypeDistribution.class.getName());
//
// public static JavaVariableGrammarPrior buildFromFiles(
// final Collection<File> files) {
// final JavaVariableGrammarPrior gp = new JavaVariableGrammarPrior();
// for (final File f : files) {
// try {
// for (final Entry<Scope, String> variable : VariableScopeExtractor
// .getScopeSnippets(f).entries()) {
// gp.parentPrior.addElement(variable.getValue(),
// variable.getKey().astNodeType);
// gp.grandParentPrior.addElement(variable.getValue(),
// variable.getKey().astParentNodeType);
// }
// } catch (final IOException e) {
// LOGGER.warning(ExceptionUtils.getFullStackTrace(e));
// }
// }
//
// return gp;
// }
//
// private JavaVariableGrammarPrior() {
// }
//
// @Override
// public Optional<String> getMaximumLikelihoodElement(
// final Pair<Integer, Integer> given) {
// throw new NotImplementedException();
// }
//
// @Override
// public double getMLProbability(final String element,
// final Pair<Integer, Integer> given) {
// return parentPrior.getMLProbability(element, given.first)
// * grandParentPrior.getMLProbability(element, given.second);
// }
//
// }
| import java.io.File;
import java.util.Collection;
import java.util.logging.Logger;
import renaming.priors.JavaVariableGrammarPrior;
import codemining.languagetools.ITokenizer;
import codemining.languagetools.Scope;
import codemining.util.data.Pair;
import com.google.common.math.DoubleMath; | /**
*
*/
package renaming.renamers;
/**
* Identifier Renaming with grammar priors.
*
* @author Miltos Allamanis <m.allamanis@ed.ac.uk>
*
*/
public class GrammarPriorIdentifierRenaming extends BaseIdentifierRenamings {
private static final Logger LOGGER = Logger
.getLogger(GrammarPriorIdentifierRenaming.class.getName());
| // Path: src/main/java/renaming/priors/JavaVariableGrammarPrior.java
// public class JavaVariableGrammarPrior implements
// IConditionalProbability<String, Pair<Integer, Integer>> {
//
// final DiscreteElementwiseConditionalDistribution<String, Integer> parentPrior = new DiscreteElementwiseConditionalDistribution<String, Integer>();
// final DiscreteElementwiseConditionalDistribution<String, Integer> grandParentPrior = new DiscreteElementwiseConditionalDistribution<String, Integer>();
//
// private static final Logger LOGGER = Logger
// .getLogger(JavaVariableNameTypeDistribution.class.getName());
//
// public static JavaVariableGrammarPrior buildFromFiles(
// final Collection<File> files) {
// final JavaVariableGrammarPrior gp = new JavaVariableGrammarPrior();
// for (final File f : files) {
// try {
// for (final Entry<Scope, String> variable : VariableScopeExtractor
// .getScopeSnippets(f).entries()) {
// gp.parentPrior.addElement(variable.getValue(),
// variable.getKey().astNodeType);
// gp.grandParentPrior.addElement(variable.getValue(),
// variable.getKey().astParentNodeType);
// }
// } catch (final IOException e) {
// LOGGER.warning(ExceptionUtils.getFullStackTrace(e));
// }
// }
//
// return gp;
// }
//
// private JavaVariableGrammarPrior() {
// }
//
// @Override
// public Optional<String> getMaximumLikelihoodElement(
// final Pair<Integer, Integer> given) {
// throw new NotImplementedException();
// }
//
// @Override
// public double getMLProbability(final String element,
// final Pair<Integer, Integer> given) {
// return parentPrior.getMLProbability(element, given.first)
// * grandParentPrior.getMLProbability(element, given.second);
// }
//
// }
// Path: src/main/java/renaming/renamers/GrammarPriorIdentifierRenaming.java
import java.io.File;
import java.util.Collection;
import java.util.logging.Logger;
import renaming.priors.JavaVariableGrammarPrior;
import codemining.languagetools.ITokenizer;
import codemining.languagetools.Scope;
import codemining.util.data.Pair;
import com.google.common.math.DoubleMath;
/**
*
*/
package renaming.renamers;
/**
* Identifier Renaming with grammar priors.
*
* @author Miltos Allamanis <m.allamanis@ed.ac.uk>
*
*/
public class GrammarPriorIdentifierRenaming extends BaseIdentifierRenamings {
private static final Logger LOGGER = Logger
.getLogger(GrammarPriorIdentifierRenaming.class.getName());
| JavaVariableGrammarPrior gp; |
mast-group/naturalize | src/test/java/renaming/ngram/PotentialRenamingsTest.java | // Path: src/main/java/renaming/renamers/INGramIdentifierRenamer.java
// public interface INGramIdentifierRenamer {
//
// public static class Renaming implements Comparable<Renaming> {
// public final String name;
//
// public final double score;
//
// public final int nContexts;
//
// public final Scope scope;
//
// public Renaming(final String id, final double xEntropy,
// final int contexts, final Scope renamingScope) {
// name = id;
// score = xEntropy;
// nContexts = contexts;
// scope = renamingScope;
// }
//
// @Override
// public int compareTo(final Renaming other) {
// return ComparisonChain.start().compare(score, other.score)
// .compare(name, other.name).result();
// }
//
// @Override
// public boolean equals(final Object other) {
// if (!(other instanceof Renaming)) {
// return false;
// }
// final Renaming r = (Renaming) other;
// return Objects.equal(name, r.name) && Objects.equal(score, r.score);
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(name, score);
//
// }
//
// @Override
// public String toString() {
// return name + ":" + String.format("%.2f", score);
// }
//
// }
//
// public static final String WILDCARD_TOKEN = "%WC%";
//
// /**
// * Calculate the scores for each renaming and return in sorted map. Each
// * n-gram should contain the WILDCARD_TOKEN at the position of the token to
// * be renamed.
// *
// * @param ngrams
// * @param renamings
// * @param type
// * @return
// */
// public abstract SortedSet<Renaming> calculateScores(
// Multiset<NGram<String>> ngrams, Set<String> alternatives,
// Scope scope);
//
// }
| import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import renaming.renamers.INGramIdentifierRenamer;
import codemining.lm.ngram.NGram;
import com.google.common.collect.Lists; | /**
*
*/
package renaming.ngram;
/**
* @author Miltos Allamanis <m.allamanis@ed.ac.uk>
*
*/
public class PotentialRenamingsTest {
@Test
public void testSubstitution() {
final List<String> lst = Lists.newArrayList();
lst.add("aa"); | // Path: src/main/java/renaming/renamers/INGramIdentifierRenamer.java
// public interface INGramIdentifierRenamer {
//
// public static class Renaming implements Comparable<Renaming> {
// public final String name;
//
// public final double score;
//
// public final int nContexts;
//
// public final Scope scope;
//
// public Renaming(final String id, final double xEntropy,
// final int contexts, final Scope renamingScope) {
// name = id;
// score = xEntropy;
// nContexts = contexts;
// scope = renamingScope;
// }
//
// @Override
// public int compareTo(final Renaming other) {
// return ComparisonChain.start().compare(score, other.score)
// .compare(name, other.name).result();
// }
//
// @Override
// public boolean equals(final Object other) {
// if (!(other instanceof Renaming)) {
// return false;
// }
// final Renaming r = (Renaming) other;
// return Objects.equal(name, r.name) && Objects.equal(score, r.score);
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(name, score);
//
// }
//
// @Override
// public String toString() {
// return name + ":" + String.format("%.2f", score);
// }
//
// }
//
// public static final String WILDCARD_TOKEN = "%WC%";
//
// /**
// * Calculate the scores for each renaming and return in sorted map. Each
// * n-gram should contain the WILDCARD_TOKEN at the position of the token to
// * be renamed.
// *
// * @param ngrams
// * @param renamings
// * @param type
// * @return
// */
// public abstract SortedSet<Renaming> calculateScores(
// Multiset<NGram<String>> ngrams, Set<String> alternatives,
// Scope scope);
//
// }
// Path: src/test/java/renaming/ngram/PotentialRenamingsTest.java
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import renaming.renamers.INGramIdentifierRenamer;
import codemining.lm.ngram.NGram;
import com.google.common.collect.Lists;
/**
*
*/
package renaming.ngram;
/**
* @author Miltos Allamanis <m.allamanis@ed.ac.uk>
*
*/
public class PotentialRenamingsTest {
@Test
public void testSubstitution() {
final List<String> lst = Lists.newArrayList();
lst.add("aa"); | lst.add(INGramIdentifierRenamer.WILDCARD_TOKEN); |
optimaize/command4j | src/main/java/com/optimaize/command4j/commands/CompoundCommand.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
| import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import java.util.List; | package com.optimaize.command4j.commands;
/**
* @author Eike Kettner
*/
class CompoundCommand<A, R> extends AbstractCompoundCommand<Iterable<A>, A, R, List<R>> {
CompoundCommand(Iterable<? extends Command<A, R>> commands) {
super(commands);
}
@Override
protected List<R> createResult() {
return Lists.newArrayList();
}
@Override | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
// Path: src/main/java/com/optimaize/command4j/commands/CompoundCommand.java
import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import java.util.List;
package com.optimaize.command4j.commands;
/**
* @author Eike Kettner
*/
class CompoundCommand<A, R> extends AbstractCompoundCommand<Iterable<A>, A, R, List<R>> {
CompoundCommand(Iterable<? extends Command<A, R>> commands) {
super(commands);
}
@Override
protected List<R> createResult() {
return Lists.newArrayList();
}
@Override | protected void executeCommand(List<R> result, int i, Command<A, R> cmd, ExecutionContext ec, Optional<Iterable<A>> arg) throws Exception { |
optimaize/command4j | src/main/java/com/optimaize/command4j/commands/AndCommand.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
| import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import java.util.List; | package com.optimaize.command4j.commands;
/**
* @author Eike Kettner
*/
class AndCommand<A, R> extends AbstractCompoundCommand<A, A, R, List<R>> {
public AndCommand(Iterable<? extends Command<A, R>> commands) {
super(commands);
}
@Override
protected List<R> createResult() {
return Lists.newArrayList();
}
@Override | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
// Path: src/main/java/com/optimaize/command4j/commands/AndCommand.java
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import java.util.List;
package com.optimaize.command4j.commands;
/**
* @author Eike Kettner
*/
class AndCommand<A, R> extends AbstractCompoundCommand<A, A, R, List<R>> {
public AndCommand(Iterable<? extends Command<A, R>> commands) {
super(commands);
}
@Override
protected List<R> createResult() {
return Lists.newArrayList();
}
@Override | protected void executeCommand(List<R> result, int i, Command<A, R> cmd, ExecutionContext ec, Optional<A> arg) throws Exception { |
optimaize/command4j | src/main/java/com/optimaize/command4j/Mode.java | // Path: src/main/java/com/optimaize/command4j/lang/Key.java
// @Immutable
// public final class Key<V> {
//
// @NotNull
// private final String name;
// @NotNull
// private final Class<V> type;
//
// private Key(@NotNull String name, @NotNull Class<V> type) {
// this.name = name;
// this.type = type;
// }
//
// /**
// * Creates a new key of the specified name and type.
// *
// * @see #stringKey(String)
// * @see #integerKey(String)
// * @see #booleanKey(String)
// */
// @NotNull
// public static <T> Key<T> create(@NotNull String name, @NotNull Class<T> type) {
// return new Key<>(name, type);
// }
//
// /**
// * Creates a new key of type String.
// */
// @NotNull
// public static Key<String> stringKey(@NotNull String name) {
// return create(name, String.class);
// }
//
// /**
// * Creates a new key of type Integer.
// */
// @NotNull
// public static Key<Integer> integerKey(@NotNull String name) {
// return create(name, Integer.class);
// }
//
// /**
// * Creates a new key of type Boolean.
// */
// @NotNull
// public static Key<Boolean> booleanKey(@NotNull String name) {
// return create(name, Boolean.class);
// }
//
// @NotNull
// public String name() {
// return name;
// }
//
// @NotNull
// public Class<V> type() {
// return type;
// }
//
// @Override
// public String toString() {
// return "Key[" + name + ":" + type.getSimpleName() + "]";
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Key key = (Key) o;
//
// if (!name.equals(key.name)) return false;
// if (!type.equals(key.type)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = name.hashCode();
// result = 31 * result + type.hashCode();
// return result;
// }
//
// }
| import com.google.common.base.Optional;
import com.google.common.collect.Maps;
import com.optimaize.command4j.lang.Immutable;
import com.optimaize.command4j.lang.Key;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Map; | package com.optimaize.command4j;
/**
* The mode contains definitions that apply to a whole execution of
* a command. They may control the behaviour of the executor by defining
* values that can be accessed by all commands and
* {@link ModeExtension extensions} in a chain of execution.
*
* <p>A Mode may be reused for multiple command executions, or it may be created
* completely new for each call, or an existing one may serve as a base where
* only little change is applied for a new command execution.</p>
*
* <p>The object is immutable; all "modification" methods return a new instance
* and leave the old one untouched.</p>
*
* @author Eike Kettner
* @author Fabian Kessler
*/
@Immutable
public final class Mode {
/**
* Because it's immutable anyway it does not need to be created over and over again.
*/
private static final Mode INITIAL_MODE = new Mode();
/**
* Does not contain null values.
*/
@NotNull | // Path: src/main/java/com/optimaize/command4j/lang/Key.java
// @Immutable
// public final class Key<V> {
//
// @NotNull
// private final String name;
// @NotNull
// private final Class<V> type;
//
// private Key(@NotNull String name, @NotNull Class<V> type) {
// this.name = name;
// this.type = type;
// }
//
// /**
// * Creates a new key of the specified name and type.
// *
// * @see #stringKey(String)
// * @see #integerKey(String)
// * @see #booleanKey(String)
// */
// @NotNull
// public static <T> Key<T> create(@NotNull String name, @NotNull Class<T> type) {
// return new Key<>(name, type);
// }
//
// /**
// * Creates a new key of type String.
// */
// @NotNull
// public static Key<String> stringKey(@NotNull String name) {
// return create(name, String.class);
// }
//
// /**
// * Creates a new key of type Integer.
// */
// @NotNull
// public static Key<Integer> integerKey(@NotNull String name) {
// return create(name, Integer.class);
// }
//
// /**
// * Creates a new key of type Boolean.
// */
// @NotNull
// public static Key<Boolean> booleanKey(@NotNull String name) {
// return create(name, Boolean.class);
// }
//
// @NotNull
// public String name() {
// return name;
// }
//
// @NotNull
// public Class<V> type() {
// return type;
// }
//
// @Override
// public String toString() {
// return "Key[" + name + ":" + type.getSimpleName() + "]";
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Key key = (Key) o;
//
// if (!name.equals(key.name)) return false;
// if (!type.equals(key.type)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = name.hashCode();
// result = 31 * result + type.hashCode();
// return result;
// }
//
// }
// Path: src/main/java/com/optimaize/command4j/Mode.java
import com.google.common.base.Optional;
import com.google.common.collect.Maps;
import com.optimaize.command4j.lang.Immutable;
import com.optimaize.command4j.lang.Key;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
package com.optimaize.command4j;
/**
* The mode contains definitions that apply to a whole execution of
* a command. They may control the behaviour of the executor by defining
* values that can be accessed by all commands and
* {@link ModeExtension extensions} in a chain of execution.
*
* <p>A Mode may be reused for multiple command executions, or it may be created
* completely new for each call, or an existing one may serve as a base where
* only little change is applied for a new command execution.</p>
*
* <p>The object is immutable; all "modification" methods return a new instance
* and leave the old one untouched.</p>
*
* @author Eike Kettner
* @author Fabian Kessler
*/
@Immutable
public final class Mode {
/**
* Because it's immutable anyway it does not need to be created over and over again.
*/
private static final Mode INITIAL_MODE = new Mode();
/**
* Does not contain null values.
*/
@NotNull | private final Map<Key<?>, Object> defs = Maps.newHashMap(); |
optimaize/command4j | src/main/java/com/optimaize/command4j/ext/util/eventbasedextension/CommandListener.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
| import com.google.common.base.Optional;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | package com.optimaize.command4j.ext.util.eventbasedextension;
/**
* Is informed {@link #before before} and after a {@link #afterSuccess successful} and {@link #afterFailure failed}
* command execution.
*
* @author Fabian Kessler
*/
public interface CommandListener<A,R> {
public void before(@NotNull Command<A, R> command, | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
// Path: src/main/java/com/optimaize/command4j/ext/util/eventbasedextension/CommandListener.java
import com.google.common.base.Optional;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
package com.optimaize.command4j.ext.util.eventbasedextension;
/**
* Is informed {@link #before before} and after a {@link #afterSuccess successful} and {@link #afterFailure failed}
* command execution.
*
* @author Fabian Kessler
*/
public interface CommandListener<A,R> {
public void before(@NotNull Command<A, R> command, | @NotNull ExecutionContext ec, |
optimaize/command4j | src/main/java/com/optimaize/command4j/commands/ConditionCommand.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
| import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | package com.optimaize.command4j.commands;
/**
* Executes the first, and if the result matches the condition then the result is returned.
* Otherwise the second is executed and its result is returned.
*
* @param <A> the optional Argument's data type
* @param <R> the Result's data type
* @author Eike Kettner
* @author Fabian Kessler
*/
final class ConditionCommand<A, R> extends BaseCommand<A, R> {
@NotNull | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
// Path: src/main/java/com/optimaize/command4j/commands/ConditionCommand.java
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
package com.optimaize.command4j.commands;
/**
* Executes the first, and if the result matches the condition then the result is returned.
* Otherwise the second is executed and its result is returned.
*
* @param <A> the optional Argument's data type
* @param <R> the Result's data type
* @author Eike Kettner
* @author Fabian Kessler
*/
final class ConditionCommand<A, R> extends BaseCommand<A, R> {
@NotNull | private final Command<A, R> primary; |
optimaize/command4j | src/main/java/com/optimaize/command4j/commands/ConditionCommand.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
| import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | package com.optimaize.command4j.commands;
/**
* Executes the first, and if the result matches the condition then the result is returned.
* Otherwise the second is executed and its result is returned.
*
* @param <A> the optional Argument's data type
* @param <R> the Result's data type
* @author Eike Kettner
* @author Fabian Kessler
*/
final class ConditionCommand<A, R> extends BaseCommand<A, R> {
@NotNull
private final Command<A, R> primary;
@NotNull
private final Command<A, R> secondary;
@NotNull
private final Predicate<R> condition;
ConditionCommand(@NotNull Command<A, R> primary, @NotNull Command<A, R> secondary, @NotNull Predicate<R> condition) {
this.primary = primary;
this.secondary = secondary;
this.condition = condition;
}
@Override @Nullable | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
// Path: src/main/java/com/optimaize/command4j/commands/ConditionCommand.java
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
package com.optimaize.command4j.commands;
/**
* Executes the first, and if the result matches the condition then the result is returned.
* Otherwise the second is executed and its result is returned.
*
* @param <A> the optional Argument's data type
* @param <R> the Result's data type
* @author Eike Kettner
* @author Fabian Kessler
*/
final class ConditionCommand<A, R> extends BaseCommand<A, R> {
@NotNull
private final Command<A, R> primary;
@NotNull
private final Command<A, R> secondary;
@NotNull
private final Predicate<R> condition;
ConditionCommand(@NotNull Command<A, R> primary, @NotNull Command<A, R> secondary, @NotNull Predicate<R> condition) {
this.primary = primary;
this.secondary = secondary;
this.condition = condition;
}
@Override @Nullable | public R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception { |
optimaize/command4j | src/main/java/com/optimaize/command4j/commands/BaseCommand.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/lang/Key.java
// @Immutable
// public final class Key<V> {
//
// @NotNull
// private final String name;
// @NotNull
// private final Class<V> type;
//
// private Key(@NotNull String name, @NotNull Class<V> type) {
// this.name = name;
// this.type = type;
// }
//
// /**
// * Creates a new key of the specified name and type.
// *
// * @see #stringKey(String)
// * @see #integerKey(String)
// * @see #booleanKey(String)
// */
// @NotNull
// public static <T> Key<T> create(@NotNull String name, @NotNull Class<T> type) {
// return new Key<>(name, type);
// }
//
// /**
// * Creates a new key of type String.
// */
// @NotNull
// public static Key<String> stringKey(@NotNull String name) {
// return create(name, String.class);
// }
//
// /**
// * Creates a new key of type Integer.
// */
// @NotNull
// public static Key<Integer> integerKey(@NotNull String name) {
// return create(name, Integer.class);
// }
//
// /**
// * Creates a new key of type Boolean.
// */
// @NotNull
// public static Key<Boolean> booleanKey(@NotNull String name) {
// return create(name, Boolean.class);
// }
//
// @NotNull
// public String name() {
// return name;
// }
//
// @NotNull
// public Class<V> type() {
// return type;
// }
//
// @Override
// public String toString() {
// return "Key[" + name + ":" + type.getSimpleName() + "]";
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Key key = (Key) o;
//
// if (!name.equals(key.name)) return false;
// if (!type.equals(key.type)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = name.hashCode();
// result = 31 * result + type.hashCode();
// return result;
// }
//
// }
| import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.lang.Key;
import org.jetbrains.annotations.NotNull; | package com.optimaize.command4j.commands;
/**
* A base class for users wanting to implement a {@link Command}.
*
* @param <A> the optional Argument's data type
* @param <R> the Result's data type
* @author Eike Kettner
*/
public abstract class BaseCommand<A, R> implements CombinableCommand<A,R> {
@NotNull @Override | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/lang/Key.java
// @Immutable
// public final class Key<V> {
//
// @NotNull
// private final String name;
// @NotNull
// private final Class<V> type;
//
// private Key(@NotNull String name, @NotNull Class<V> type) {
// this.name = name;
// this.type = type;
// }
//
// /**
// * Creates a new key of the specified name and type.
// *
// * @see #stringKey(String)
// * @see #integerKey(String)
// * @see #booleanKey(String)
// */
// @NotNull
// public static <T> Key<T> create(@NotNull String name, @NotNull Class<T> type) {
// return new Key<>(name, type);
// }
//
// /**
// * Creates a new key of type String.
// */
// @NotNull
// public static Key<String> stringKey(@NotNull String name) {
// return create(name, String.class);
// }
//
// /**
// * Creates a new key of type Integer.
// */
// @NotNull
// public static Key<Integer> integerKey(@NotNull String name) {
// return create(name, Integer.class);
// }
//
// /**
// * Creates a new key of type Boolean.
// */
// @NotNull
// public static Key<Boolean> booleanKey(@NotNull String name) {
// return create(name, Boolean.class);
// }
//
// @NotNull
// public String name() {
// return name;
// }
//
// @NotNull
// public Class<V> type() {
// return type;
// }
//
// @Override
// public String toString() {
// return "Key[" + name + ":" + type.getSimpleName() + "]";
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Key key = (Key) o;
//
// if (!name.equals(key.name)) return false;
// if (!type.equals(key.type)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = name.hashCode();
// result = 31 * result + type.hashCode();
// return result;
// }
//
// }
// Path: src/main/java/com/optimaize/command4j/commands/BaseCommand.java
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.lang.Key;
import org.jetbrains.annotations.NotNull;
package com.optimaize.command4j.commands;
/**
* A base class for users wanting to implement a {@link Command}.
*
* @param <A> the optional Argument's data type
* @param <R> the Result's data type
* @author Eike Kettner
*/
public abstract class BaseCommand<A, R> implements CombinableCommand<A,R> {
@NotNull @Override | public final <C> BaseCommand<A, C> andThen(@NotNull Command<R, C> cmd) { |
optimaize/command4j | src/main/java/com/optimaize/command4j/commands/BaseCommand.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/lang/Key.java
// @Immutable
// public final class Key<V> {
//
// @NotNull
// private final String name;
// @NotNull
// private final Class<V> type;
//
// private Key(@NotNull String name, @NotNull Class<V> type) {
// this.name = name;
// this.type = type;
// }
//
// /**
// * Creates a new key of the specified name and type.
// *
// * @see #stringKey(String)
// * @see #integerKey(String)
// * @see #booleanKey(String)
// */
// @NotNull
// public static <T> Key<T> create(@NotNull String name, @NotNull Class<T> type) {
// return new Key<>(name, type);
// }
//
// /**
// * Creates a new key of type String.
// */
// @NotNull
// public static Key<String> stringKey(@NotNull String name) {
// return create(name, String.class);
// }
//
// /**
// * Creates a new key of type Integer.
// */
// @NotNull
// public static Key<Integer> integerKey(@NotNull String name) {
// return create(name, Integer.class);
// }
//
// /**
// * Creates a new key of type Boolean.
// */
// @NotNull
// public static Key<Boolean> booleanKey(@NotNull String name) {
// return create(name, Boolean.class);
// }
//
// @NotNull
// public String name() {
// return name;
// }
//
// @NotNull
// public Class<V> type() {
// return type;
// }
//
// @Override
// public String toString() {
// return "Key[" + name + ":" + type.getSimpleName() + "]";
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Key key = (Key) o;
//
// if (!name.equals(key.name)) return false;
// if (!type.equals(key.type)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = name.hashCode();
// result = 31 * result + type.hashCode();
// return result;
// }
//
// }
| import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.lang.Key;
import org.jetbrains.annotations.NotNull; | package com.optimaize.command4j.commands;
/**
* A base class for users wanting to implement a {@link Command}.
*
* @param <A> the optional Argument's data type
* @param <R> the Result's data type
* @author Eike Kettner
*/
public abstract class BaseCommand<A, R> implements CombinableCommand<A,R> {
@NotNull @Override
public final <C> BaseCommand<A, C> andThen(@NotNull Command<R, C> cmd) {
return new ComposedCommand<>(this, cmd);
}
@NotNull @Override
public final BaseCommand<A, R> ifTrueOr(Predicate<R> cond, Command<A, R> alternative) {
return Commands.firstIfTrue(this, cond, alternative);
}
@NotNull @Override
public final BaseCommand<A, R> ifNotNullOr(Command<A, R> alternative) {
return Commands.firstIfTrue(this, Predicates.<R>notNull(), alternative);
}
@NotNull @Override
public final BaseListCommand<A, R> and(Command<A, R> cmd) {
return Commands.and(this, cmd);
}
@NotNull @Override
public final BaseListCommand<Iterable<A>, R> concat(Command<A, R> cmd) {
return Commands.concat(this, cmd);
}
/**
* @see Commands#withValue(Command, Key, Object)
*/ | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/lang/Key.java
// @Immutable
// public final class Key<V> {
//
// @NotNull
// private final String name;
// @NotNull
// private final Class<V> type;
//
// private Key(@NotNull String name, @NotNull Class<V> type) {
// this.name = name;
// this.type = type;
// }
//
// /**
// * Creates a new key of the specified name and type.
// *
// * @see #stringKey(String)
// * @see #integerKey(String)
// * @see #booleanKey(String)
// */
// @NotNull
// public static <T> Key<T> create(@NotNull String name, @NotNull Class<T> type) {
// return new Key<>(name, type);
// }
//
// /**
// * Creates a new key of type String.
// */
// @NotNull
// public static Key<String> stringKey(@NotNull String name) {
// return create(name, String.class);
// }
//
// /**
// * Creates a new key of type Integer.
// */
// @NotNull
// public static Key<Integer> integerKey(@NotNull String name) {
// return create(name, Integer.class);
// }
//
// /**
// * Creates a new key of type Boolean.
// */
// @NotNull
// public static Key<Boolean> booleanKey(@NotNull String name) {
// return create(name, Boolean.class);
// }
//
// @NotNull
// public String name() {
// return name;
// }
//
// @NotNull
// public Class<V> type() {
// return type;
// }
//
// @Override
// public String toString() {
// return "Key[" + name + ":" + type.getSimpleName() + "]";
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Key key = (Key) o;
//
// if (!name.equals(key.name)) return false;
// if (!type.equals(key.type)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = name.hashCode();
// result = 31 * result + type.hashCode();
// return result;
// }
//
// }
// Path: src/main/java/com/optimaize/command4j/commands/BaseCommand.java
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.lang.Key;
import org.jetbrains.annotations.NotNull;
package com.optimaize.command4j.commands;
/**
* A base class for users wanting to implement a {@link Command}.
*
* @param <A> the optional Argument's data type
* @param <R> the Result's data type
* @author Eike Kettner
*/
public abstract class BaseCommand<A, R> implements CombinableCommand<A,R> {
@NotNull @Override
public final <C> BaseCommand<A, C> andThen(@NotNull Command<R, C> cmd) {
return new ComposedCommand<>(this, cmd);
}
@NotNull @Override
public final BaseCommand<A, R> ifTrueOr(Predicate<R> cond, Command<A, R> alternative) {
return Commands.firstIfTrue(this, cond, alternative);
}
@NotNull @Override
public final BaseCommand<A, R> ifNotNullOr(Command<A, R> alternative) {
return Commands.firstIfTrue(this, Predicates.<R>notNull(), alternative);
}
@NotNull @Override
public final BaseListCommand<A, R> and(Command<A, R> cmd) {
return Commands.and(this, cmd);
}
@NotNull @Override
public final BaseListCommand<Iterable<A>, R> concat(Command<A, R> cmd) {
return Commands.concat(this, cmd);
}
/**
* @see Commands#withValue(Command, Key, Object)
*/ | public final <V> BaseCommand<A, R> withValue(@NotNull Key<V> key, V value) { |
optimaize/command4j | src/main/java/com/optimaize/command4j/CommandExecutorService.java | // Path: src/main/java/com/optimaize/command4j/lang/Duration.java
// @Immutable
// public final class Duration {
//
// private final long time;
// @NotNull
// private final TimeUnit timeUnit;
//
// @NotNull
// public static Duration of(long time, @NotNull TimeUnit unit) {
// return new Duration(time, unit);
// }
//
// @NotNull
// public static Duration millis(long time) {
// return of(time, TimeUnit.MILLISECONDS);
// }
//
// @NotNull
// public static Duration seconds(long time) {
// return of(time, TimeUnit.SECONDS);
// }
//
// private Duration(long time, @NotNull TimeUnit timeUnit) {
// this.time = time;
// this.timeUnit = timeUnit;
// }
//
//
// public long getTime() {
// return time;
// }
//
// @NotNull
// public TimeUnit getTimeUnit() {
// return timeUnit;
// }
//
// public long toMillis() {
// return timeUnit.toMillis(time);
// }
//
// public boolean isZero() {
// return time==0;
// }
//
// @Override
// public String toString() {
// return "Duration[" + time + toString(timeUnit) + ']';
// }
//
// @NotNull
// private String toString(@NotNull TimeUnit timeUnit) {
// switch (timeUnit) {
// case MILLISECONDS:
// return "ms";
// case SECONDS:
// return "s";
// case MINUTES:
// return "m";
// case HOURS:
// return "h";
// case DAYS:
// return "d";
// default:
// return timeUnit.name();
// }
// }
// }
| import com.google.common.annotations.Beta;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.optimaize.command4j.lang.Duration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; | package com.optimaize.command4j;
/**
* An executor service for executing {@link Command}s.
*
* <p>This does not extend java.util.concurrent.ExecutorService, but it uses one
* (actually a Guava {@link ListeningExecutorService}). It offers just a fraction of Guava's interface.</p>
*
* @author Eike Kettner
* @author Fabian Kessler
*/
public interface CommandExecutorService {
/**
* Submits a command and returns instantly with a Future as the result.
*/
@NotNull
<A, V> ListenableFuture<Optional<V>> submit(@NotNull Command<A, V> cmd,
@NotNull Mode mode,
@Nullable A arg);
/**
* Executes a command and blocks until the command finishes successfully, aborts by throwing an exception,
* the timeout occurs (which throws an exception too), or the command is cancelled before any of these occur.
*/
@NotNull
<A, V> Optional<V> submitAndWait(@NotNull Command<A, V> cmd,
@NotNull Mode mode,
@Nullable A arg, | // Path: src/main/java/com/optimaize/command4j/lang/Duration.java
// @Immutable
// public final class Duration {
//
// private final long time;
// @NotNull
// private final TimeUnit timeUnit;
//
// @NotNull
// public static Duration of(long time, @NotNull TimeUnit unit) {
// return new Duration(time, unit);
// }
//
// @NotNull
// public static Duration millis(long time) {
// return of(time, TimeUnit.MILLISECONDS);
// }
//
// @NotNull
// public static Duration seconds(long time) {
// return of(time, TimeUnit.SECONDS);
// }
//
// private Duration(long time, @NotNull TimeUnit timeUnit) {
// this.time = time;
// this.timeUnit = timeUnit;
// }
//
//
// public long getTime() {
// return time;
// }
//
// @NotNull
// public TimeUnit getTimeUnit() {
// return timeUnit;
// }
//
// public long toMillis() {
// return timeUnit.toMillis(time);
// }
//
// public boolean isZero() {
// return time==0;
// }
//
// @Override
// public String toString() {
// return "Duration[" + time + toString(timeUnit) + ']';
// }
//
// @NotNull
// private String toString(@NotNull TimeUnit timeUnit) {
// switch (timeUnit) {
// case MILLISECONDS:
// return "ms";
// case SECONDS:
// return "s";
// case MINUTES:
// return "m";
// case HOURS:
// return "h";
// case DAYS:
// return "d";
// default:
// return timeUnit.name();
// }
// }
// }
// Path: src/main/java/com/optimaize/command4j/CommandExecutorService.java
import com.google.common.annotations.Beta;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.optimaize.command4j.lang.Duration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
package com.optimaize.command4j;
/**
* An executor service for executing {@link Command}s.
*
* <p>This does not extend java.util.concurrent.ExecutorService, but it uses one
* (actually a Guava {@link ListeningExecutorService}). It offers just a fraction of Guava's interface.</p>
*
* @author Eike Kettner
* @author Fabian Kessler
*/
public interface CommandExecutorService {
/**
* Submits a command and returns instantly with a Future as the result.
*/
@NotNull
<A, V> ListenableFuture<Optional<V>> submit(@NotNull Command<A, V> cmd,
@NotNull Mode mode,
@Nullable A arg);
/**
* Executes a command and blocks until the command finishes successfully, aborts by throwing an exception,
* the timeout occurs (which throws an exception too), or the command is cancelled before any of these occur.
*/
@NotNull
<A, V> Optional<V> submitAndWait(@NotNull Command<A, V> cmd,
@NotNull Mode mode,
@Nullable A arg, | @NotNull Duration timeout) throws InterruptedException, TimeoutException, Exception; |
optimaize/command4j | src/test/java/com/optimaize/command4j/commands/ReturnNull.java | // Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
| import com.google.common.base.Optional;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull; | package com.optimaize.command4j.commands;
/**
* Always returns null.
*
* @author Fabian Kessler
*/
public class ReturnNull extends BaseCommand<Void, Void> {
@Override | // Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
// Path: src/test/java/com/optimaize/command4j/commands/ReturnNull.java
import com.google.common.base.Optional;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
package com.optimaize.command4j.commands;
/**
* Always returns null.
*
* @author Fabian Kessler
*/
public class ReturnNull extends BaseCommand<Void, Void> {
@Override | public Void call(@NotNull Optional<Void> arg, @NotNull ExecutionContext ec) throws Exception { |
optimaize/command4j | src/main/java/com/optimaize/command4j/ext/extensions/failover/autoretry/DefaultAutoRetryStrategy.java | // Path: src/main/java/com/optimaize/command4j/lang/Duration.java
// @Immutable
// public final class Duration {
//
// private final long time;
// @NotNull
// private final TimeUnit timeUnit;
//
// @NotNull
// public static Duration of(long time, @NotNull TimeUnit unit) {
// return new Duration(time, unit);
// }
//
// @NotNull
// public static Duration millis(long time) {
// return of(time, TimeUnit.MILLISECONDS);
// }
//
// @NotNull
// public static Duration seconds(long time) {
// return of(time, TimeUnit.SECONDS);
// }
//
// private Duration(long time, @NotNull TimeUnit timeUnit) {
// this.time = time;
// this.timeUnit = timeUnit;
// }
//
//
// public long getTime() {
// return time;
// }
//
// @NotNull
// public TimeUnit getTimeUnit() {
// return timeUnit;
// }
//
// public long toMillis() {
// return timeUnit.toMillis(time);
// }
//
// public boolean isZero() {
// return time==0;
// }
//
// @Override
// public String toString() {
// return "Duration[" + time + toString(timeUnit) + ']';
// }
//
// @NotNull
// private String toString(@NotNull TimeUnit timeUnit) {
// switch (timeUnit) {
// case MILLISECONDS:
// return "ms";
// case SECONDS:
// return "s";
// case MINUTES:
// return "m";
// case HOURS:
// return "h";
// case DAYS:
// return "d";
// default:
// return timeUnit.name();
// }
// }
// }
| import com.optimaize.command4j.lang.Duration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | package com.optimaize.command4j.ext.extensions.failover.autoretry;
/**
* @author Fabian Kessler
*/
public class DefaultAutoRetryStrategy implements AutoRetryStrategy {
public static final AutoRetryStrategy INSTANCE = new DefaultAutoRetryStrategy();
@Override @Nullable | // Path: src/main/java/com/optimaize/command4j/lang/Duration.java
// @Immutable
// public final class Duration {
//
// private final long time;
// @NotNull
// private final TimeUnit timeUnit;
//
// @NotNull
// public static Duration of(long time, @NotNull TimeUnit unit) {
// return new Duration(time, unit);
// }
//
// @NotNull
// public static Duration millis(long time) {
// return of(time, TimeUnit.MILLISECONDS);
// }
//
// @NotNull
// public static Duration seconds(long time) {
// return of(time, TimeUnit.SECONDS);
// }
//
// private Duration(long time, @NotNull TimeUnit timeUnit) {
// this.time = time;
// this.timeUnit = timeUnit;
// }
//
//
// public long getTime() {
// return time;
// }
//
// @NotNull
// public TimeUnit getTimeUnit() {
// return timeUnit;
// }
//
// public long toMillis() {
// return timeUnit.toMillis(time);
// }
//
// public boolean isZero() {
// return time==0;
// }
//
// @Override
// public String toString() {
// return "Duration[" + time + toString(timeUnit) + ']';
// }
//
// @NotNull
// private String toString(@NotNull TimeUnit timeUnit) {
// switch (timeUnit) {
// case MILLISECONDS:
// return "ms";
// case SECONDS:
// return "s";
// case MINUTES:
// return "m";
// case HOURS:
// return "h";
// case DAYS:
// return "d";
// default:
// return timeUnit.name();
// }
// }
// }
// Path: src/main/java/com/optimaize/command4j/ext/extensions/failover/autoretry/DefaultAutoRetryStrategy.java
import com.optimaize.command4j.lang.Duration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
package com.optimaize.command4j.ext.extensions.failover.autoretry;
/**
* @author Fabian Kessler
*/
public class DefaultAutoRetryStrategy implements AutoRetryStrategy {
public static final AutoRetryStrategy INSTANCE = new DefaultAutoRetryStrategy();
@Override @Nullable | public Duration doRetry(int executionCounter, @NotNull Exception exception) { |
optimaize/command4j | src/main/java/com/optimaize/command4j/ext/util/eventbasedextension/CommandListenerWrapper.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
| import com.google.common.base.Optional;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | package com.optimaize.command4j.ext.util.eventbasedextension;
/**
* @author Fabian Kessler
*/
public class CommandListenerWrapper<A,R> implements CommandListener<A, R> {
@NotNull
protected final CommandListener<A, R> wrapped;
public CommandListenerWrapper(@NotNull CommandListener<A, R> wrapped) {
this.wrapped = wrapped;
}
@Override | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
// Path: src/main/java/com/optimaize/command4j/ext/util/eventbasedextension/CommandListenerWrapper.java
import com.google.common.base.Optional;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
package com.optimaize.command4j.ext.util.eventbasedextension;
/**
* @author Fabian Kessler
*/
public class CommandListenerWrapper<A,R> implements CommandListener<A, R> {
@NotNull
protected final CommandListener<A, R> wrapped;
public CommandListenerWrapper(@NotNull CommandListener<A, R> wrapped) {
this.wrapped = wrapped;
}
@Override | public void before(@NotNull Command<A, R> command, @NotNull ExecutionContext ec, @NotNull Optional<A> arg) throws Exception { |
optimaize/command4j | src/main/java/com/optimaize/command4j/ext/util/eventbasedextension/CommandListenerWrapper.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
| import com.google.common.base.Optional;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | package com.optimaize.command4j.ext.util.eventbasedextension;
/**
* @author Fabian Kessler
*/
public class CommandListenerWrapper<A,R> implements CommandListener<A, R> {
@NotNull
protected final CommandListener<A, R> wrapped;
public CommandListenerWrapper(@NotNull CommandListener<A, R> wrapped) {
this.wrapped = wrapped;
}
@Override | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
// Path: src/main/java/com/optimaize/command4j/ext/util/eventbasedextension/CommandListenerWrapper.java
import com.google.common.base.Optional;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
package com.optimaize.command4j.ext.util.eventbasedextension;
/**
* @author Fabian Kessler
*/
public class CommandListenerWrapper<A,R> implements CommandListener<A, R> {
@NotNull
protected final CommandListener<A, R> wrapped;
public CommandListenerWrapper(@NotNull CommandListener<A, R> wrapped) {
this.wrapped = wrapped;
}
@Override | public void before(@NotNull Command<A, R> command, @NotNull ExecutionContext ec, @NotNull Optional<A> arg) throws Exception { |
optimaize/command4j | src/main/java/com/optimaize/command4j/ExecutionContext.java | // Path: src/main/java/com/optimaize/command4j/cache/ExecutorCache.java
// public final class ExecutorCache {
//
// private final Cache<ExecutorCacheKey, Object> cache;
//
// /**
// * Creates a cache with the given Guava cache.
// */
// public ExecutorCache(@NotNull Cache<ExecutorCacheKey, Object> cache) {
// this.cache = cache;
// }
//
// /**
// * Creates a cache with a default Guava cache that works for most scenarios.
// */
// public ExecutorCache() {
// this.cache = CacheBuilder
// .newBuilder()
// .softValues() //disputable.
// .maximumSize(500)
// .build();
// }
//
// @Nullable
// public <V> V getIfPresent(@NotNull ExecutorCacheKey<V> key) {
// //noinspection unchecked
// return (V) cache.getIfPresent(key);
// }
//
// public <V> V get(@NotNull ExecutorCacheKey<V> key, @NotNull Callable<? extends V> valueLoader) throws Exception {
// //to understand this, see what cache.get() throws. we want to unwrap the throwable, whatever it was.
// try {
// //noinspection unchecked
// return (V) cache.get(key, valueLoader);
// } catch (UncheckedExecutionException | ExecutionError e) {
// throw Throwables.propagate(e.getCause());
// } catch (ExecutionException e) {
// Throwables.propagateIfInstanceOf(e.getCause(), Exception.class);
// throw Throwables.propagate(e.getCause());
// }
// }
//
// public <V> void put(@NotNull ExecutorCacheKey<V> key, V value) {
// cache.put(key, value);
// }
//
// public void invalidate(@NotNull ExecutorCacheKey<?> key) {
// cache.invalidate(key);
// }
//
// public long size() {
// return cache.size();
// }
//
// public void invalidateAll() {
// cache.invalidateAll();
// }
//
// public ImmutableMap<ExecutorCacheKey, Object> getAllPresent(@NotNull Iterable<?> keys) {
// return cache.getAllPresent(keys);
// }
// }
| import com.google.common.base.Optional;
import com.optimaize.command4j.cache.ExecutorCache;
import org.jetbrains.annotations.NotNull; | package com.optimaize.command4j;
/**
* The execution context is an object created by the executor that lives
* as long as the command is executing. It gives the command implementation
* access to the command framework and a global {@link ExecutorCache cache}.
*
* @author Eike Kettner
* @author Fabian Kessler
*/
public interface ExecutionContext {
/**
* @return the mode that was supplied to the initial invocation.
*/
@NotNull
Mode getMode();
/**
* @return the global cache to store/retrieve objects to/from.
*/
@NotNull | // Path: src/main/java/com/optimaize/command4j/cache/ExecutorCache.java
// public final class ExecutorCache {
//
// private final Cache<ExecutorCacheKey, Object> cache;
//
// /**
// * Creates a cache with the given Guava cache.
// */
// public ExecutorCache(@NotNull Cache<ExecutorCacheKey, Object> cache) {
// this.cache = cache;
// }
//
// /**
// * Creates a cache with a default Guava cache that works for most scenarios.
// */
// public ExecutorCache() {
// this.cache = CacheBuilder
// .newBuilder()
// .softValues() //disputable.
// .maximumSize(500)
// .build();
// }
//
// @Nullable
// public <V> V getIfPresent(@NotNull ExecutorCacheKey<V> key) {
// //noinspection unchecked
// return (V) cache.getIfPresent(key);
// }
//
// public <V> V get(@NotNull ExecutorCacheKey<V> key, @NotNull Callable<? extends V> valueLoader) throws Exception {
// //to understand this, see what cache.get() throws. we want to unwrap the throwable, whatever it was.
// try {
// //noinspection unchecked
// return (V) cache.get(key, valueLoader);
// } catch (UncheckedExecutionException | ExecutionError e) {
// throw Throwables.propagate(e.getCause());
// } catch (ExecutionException e) {
// Throwables.propagateIfInstanceOf(e.getCause(), Exception.class);
// throw Throwables.propagate(e.getCause());
// }
// }
//
// public <V> void put(@NotNull ExecutorCacheKey<V> key, V value) {
// cache.put(key, value);
// }
//
// public void invalidate(@NotNull ExecutorCacheKey<?> key) {
// cache.invalidate(key);
// }
//
// public long size() {
// return cache.size();
// }
//
// public void invalidateAll() {
// cache.invalidateAll();
// }
//
// public ImmutableMap<ExecutorCacheKey, Object> getAllPresent(@NotNull Iterable<?> keys) {
// return cache.getAllPresent(keys);
// }
// }
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
import com.google.common.base.Optional;
import com.optimaize.command4j.cache.ExecutorCache;
import org.jetbrains.annotations.NotNull;
package com.optimaize.command4j;
/**
* The execution context is an object created by the executor that lives
* as long as the command is executing. It gives the command implementation
* access to the command framework and a global {@link ExecutorCache cache}.
*
* @author Eike Kettner
* @author Fabian Kessler
*/
public interface ExecutionContext {
/**
* @return the mode that was supplied to the initial invocation.
*/
@NotNull
Mode getMode();
/**
* @return the global cache to store/retrieve objects to/from.
*/
@NotNull | ExecutorCache getCache(); |
optimaize/command4j | src/main/java/com/optimaize/command4j/commands/Commands.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/lang/Key.java
// @Immutable
// public final class Key<V> {
//
// @NotNull
// private final String name;
// @NotNull
// private final Class<V> type;
//
// private Key(@NotNull String name, @NotNull Class<V> type) {
// this.name = name;
// this.type = type;
// }
//
// /**
// * Creates a new key of the specified name and type.
// *
// * @see #stringKey(String)
// * @see #integerKey(String)
// * @see #booleanKey(String)
// */
// @NotNull
// public static <T> Key<T> create(@NotNull String name, @NotNull Class<T> type) {
// return new Key<>(name, type);
// }
//
// /**
// * Creates a new key of type String.
// */
// @NotNull
// public static Key<String> stringKey(@NotNull String name) {
// return create(name, String.class);
// }
//
// /**
// * Creates a new key of type Integer.
// */
// @NotNull
// public static Key<Integer> integerKey(@NotNull String name) {
// return create(name, Integer.class);
// }
//
// /**
// * Creates a new key of type Boolean.
// */
// @NotNull
// public static Key<Boolean> booleanKey(@NotNull String name) {
// return create(name, Boolean.class);
// }
//
// @NotNull
// public String name() {
// return name;
// }
//
// @NotNull
// public Class<V> type() {
// return type;
// }
//
// @Override
// public String toString() {
// return "Key[" + name + ":" + type.getSimpleName() + "]";
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Key key = (Key) o;
//
// if (!name.equals(key.name)) return false;
// if (!type.equals(key.type)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = name.hashCode();
// result = 31 * result + type.hashCode();
// return result;
// }
//
// }
| import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.lang.Key;
import org.jetbrains.annotations.NotNull;
import java.util.List; | package com.optimaize.command4j.commands;
/**
* A hub-class for easy access to common command combinators for command chaining and such.
*
* @author Eike Kettner
* @author Fabian Kessler
*/
public final class Commands {
private Commands(){}
/**
* Returns a command that will return the result of this command
* if the result applies to the given condition, or otherwise, the
* result of the alternative command (the condition is not applied there).
*
* <p>If any of the two commands throws then the whole thing aborts with the exception.</p>
*/ | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/lang/Key.java
// @Immutable
// public final class Key<V> {
//
// @NotNull
// private final String name;
// @NotNull
// private final Class<V> type;
//
// private Key(@NotNull String name, @NotNull Class<V> type) {
// this.name = name;
// this.type = type;
// }
//
// /**
// * Creates a new key of the specified name and type.
// *
// * @see #stringKey(String)
// * @see #integerKey(String)
// * @see #booleanKey(String)
// */
// @NotNull
// public static <T> Key<T> create(@NotNull String name, @NotNull Class<T> type) {
// return new Key<>(name, type);
// }
//
// /**
// * Creates a new key of type String.
// */
// @NotNull
// public static Key<String> stringKey(@NotNull String name) {
// return create(name, String.class);
// }
//
// /**
// * Creates a new key of type Integer.
// */
// @NotNull
// public static Key<Integer> integerKey(@NotNull String name) {
// return create(name, Integer.class);
// }
//
// /**
// * Creates a new key of type Boolean.
// */
// @NotNull
// public static Key<Boolean> booleanKey(@NotNull String name) {
// return create(name, Boolean.class);
// }
//
// @NotNull
// public String name() {
// return name;
// }
//
// @NotNull
// public Class<V> type() {
// return type;
// }
//
// @Override
// public String toString() {
// return "Key[" + name + ":" + type.getSimpleName() + "]";
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Key key = (Key) o;
//
// if (!name.equals(key.name)) return false;
// if (!type.equals(key.type)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = name.hashCode();
// result = 31 * result + type.hashCode();
// return result;
// }
//
// }
// Path: src/main/java/com/optimaize/command4j/commands/Commands.java
import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.lang.Key;
import org.jetbrains.annotations.NotNull;
import java.util.List;
package com.optimaize.command4j.commands;
/**
* A hub-class for easy access to common command combinators for command chaining and such.
*
* @author Eike Kettner
* @author Fabian Kessler
*/
public final class Commands {
private Commands(){}
/**
* Returns a command that will return the result of this command
* if the result applies to the given condition, or otherwise, the
* result of the alternative command (the condition is not applied there).
*
* <p>If any of the two commands throws then the whole thing aborts with the exception.</p>
*/ | public static <A, B> BaseCommand<A, B> firstIfTrue(Command<A, B> first, Predicate<B> cond, Command<A, B> secondary) { |
optimaize/command4j | src/main/java/com/optimaize/command4j/commands/Commands.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/lang/Key.java
// @Immutable
// public final class Key<V> {
//
// @NotNull
// private final String name;
// @NotNull
// private final Class<V> type;
//
// private Key(@NotNull String name, @NotNull Class<V> type) {
// this.name = name;
// this.type = type;
// }
//
// /**
// * Creates a new key of the specified name and type.
// *
// * @see #stringKey(String)
// * @see #integerKey(String)
// * @see #booleanKey(String)
// */
// @NotNull
// public static <T> Key<T> create(@NotNull String name, @NotNull Class<T> type) {
// return new Key<>(name, type);
// }
//
// /**
// * Creates a new key of type String.
// */
// @NotNull
// public static Key<String> stringKey(@NotNull String name) {
// return create(name, String.class);
// }
//
// /**
// * Creates a new key of type Integer.
// */
// @NotNull
// public static Key<Integer> integerKey(@NotNull String name) {
// return create(name, Integer.class);
// }
//
// /**
// * Creates a new key of type Boolean.
// */
// @NotNull
// public static Key<Boolean> booleanKey(@NotNull String name) {
// return create(name, Boolean.class);
// }
//
// @NotNull
// public String name() {
// return name;
// }
//
// @NotNull
// public Class<V> type() {
// return type;
// }
//
// @Override
// public String toString() {
// return "Key[" + name + ":" + type.getSimpleName() + "]";
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Key key = (Key) o;
//
// if (!name.equals(key.name)) return false;
// if (!type.equals(key.type)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = name.hashCode();
// result = 31 * result + type.hashCode();
// return result;
// }
//
// }
| import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.lang.Key;
import org.jetbrains.annotations.NotNull;
import java.util.List; | package com.optimaize.command4j.commands;
/**
* A hub-class for easy access to common command combinators for command chaining and such.
*
* @author Eike Kettner
* @author Fabian Kessler
*/
public final class Commands {
private Commands(){}
/**
* Returns a command that will return the result of this command
* if the result applies to the given condition, or otherwise, the
* result of the alternative command (the condition is not applied there).
*
* <p>If any of the two commands throws then the whole thing aborts with the exception.</p>
*/
public static <A, B> BaseCommand<A, B> firstIfTrue(Command<A, B> first, Predicate<B> cond, Command<A, B> secondary) {
return new ConditionCommand<>(first, secondary, cond);
}
/**
* Returns a task that executes both tasks sequentially, applying the same argument on both.
* The result of the execution is an ArrayList containing two elements (0 and 1).
*/
public static <A, B> BaseListCommand<A, B> and(Command<A, B> first, Command<A, B> second) {
List<Command<A, B>> list = Lists.newArrayList();
list.add(first);
list.add(second);
return new AndCommand<>(list);
}
/**
* Returns a task that executes all tasks sequentially applying the same argument
* to each. The result of the execution is an ArrayList containing one element per command
* in the order the commands were specified here.
*/
public static <A, B> BaseListCommand<A, B> and(Iterable<? extends Command<A, B>> commands) {
return new AndCommand<>(commands);
}
/**
* Creates a new task that will append the result of the second task to the result-list
* of the first.
* TODO Fabian: test behavior and explain here.
*/
public static <A, B> BaseListCommand<A, B> flatAnd(Command<A, ? extends Iterable<B>> first, Command<A, B> second) {
return new FlatAndCommand<>(first, second);
}
/**
* Creates a task that will set the given key-value pair into the mode prior to
* executing {@code cmd}.
*/ | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/lang/Key.java
// @Immutable
// public final class Key<V> {
//
// @NotNull
// private final String name;
// @NotNull
// private final Class<V> type;
//
// private Key(@NotNull String name, @NotNull Class<V> type) {
// this.name = name;
// this.type = type;
// }
//
// /**
// * Creates a new key of the specified name and type.
// *
// * @see #stringKey(String)
// * @see #integerKey(String)
// * @see #booleanKey(String)
// */
// @NotNull
// public static <T> Key<T> create(@NotNull String name, @NotNull Class<T> type) {
// return new Key<>(name, type);
// }
//
// /**
// * Creates a new key of type String.
// */
// @NotNull
// public static Key<String> stringKey(@NotNull String name) {
// return create(name, String.class);
// }
//
// /**
// * Creates a new key of type Integer.
// */
// @NotNull
// public static Key<Integer> integerKey(@NotNull String name) {
// return create(name, Integer.class);
// }
//
// /**
// * Creates a new key of type Boolean.
// */
// @NotNull
// public static Key<Boolean> booleanKey(@NotNull String name) {
// return create(name, Boolean.class);
// }
//
// @NotNull
// public String name() {
// return name;
// }
//
// @NotNull
// public Class<V> type() {
// return type;
// }
//
// @Override
// public String toString() {
// return "Key[" + name + ":" + type.getSimpleName() + "]";
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Key key = (Key) o;
//
// if (!name.equals(key.name)) return false;
// if (!type.equals(key.type)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = name.hashCode();
// result = 31 * result + type.hashCode();
// return result;
// }
//
// }
// Path: src/main/java/com/optimaize/command4j/commands/Commands.java
import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.lang.Key;
import org.jetbrains.annotations.NotNull;
import java.util.List;
package com.optimaize.command4j.commands;
/**
* A hub-class for easy access to common command combinators for command chaining and such.
*
* @author Eike Kettner
* @author Fabian Kessler
*/
public final class Commands {
private Commands(){}
/**
* Returns a command that will return the result of this command
* if the result applies to the given condition, or otherwise, the
* result of the alternative command (the condition is not applied there).
*
* <p>If any of the two commands throws then the whole thing aborts with the exception.</p>
*/
public static <A, B> BaseCommand<A, B> firstIfTrue(Command<A, B> first, Predicate<B> cond, Command<A, B> secondary) {
return new ConditionCommand<>(first, secondary, cond);
}
/**
* Returns a task that executes both tasks sequentially, applying the same argument on both.
* The result of the execution is an ArrayList containing two elements (0 and 1).
*/
public static <A, B> BaseListCommand<A, B> and(Command<A, B> first, Command<A, B> second) {
List<Command<A, B>> list = Lists.newArrayList();
list.add(first);
list.add(second);
return new AndCommand<>(list);
}
/**
* Returns a task that executes all tasks sequentially applying the same argument
* to each. The result of the execution is an ArrayList containing one element per command
* in the order the commands were specified here.
*/
public static <A, B> BaseListCommand<A, B> and(Iterable<? extends Command<A, B>> commands) {
return new AndCommand<>(commands);
}
/**
* Creates a new task that will append the result of the second task to the result-list
* of the first.
* TODO Fabian: test behavior and explain here.
*/
public static <A, B> BaseListCommand<A, B> flatAnd(Command<A, ? extends Iterable<B>> first, Command<A, B> second) {
return new FlatAndCommand<>(first, second);
}
/**
* Creates a task that will set the given key-value pair into the mode prior to
* executing {@code cmd}.
*/ | public static <A, B, V> BaseCommand<A, B> withValue(@NotNull Command<A, B> cmd, Key<V> key, V value) { |
optimaize/command4j | src/main/java/com/optimaize/command4j/commands/ComposedCommand.java | // Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
//
// Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
| import com.google.common.base.Optional;
import com.optimaize.command4j.ExecutionContext;
import com.optimaize.command4j.Command;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | package com.optimaize.command4j.commands;
/**
* A command that is the composition of two commands.
*
* <p>When executing then at first the 1st command gets executed, then its result is fed to the 2nd command, and
* finally the result of the 2nd command is returned.</p>
*
* <p>As soon as an exception occurs (either when executing the first or second command)
* then the whole thing aborts with the exception.</p>
*
* @param <A> the optional Argument's data type for the first command.
* @param <B> The type of the result of the first command as well as the argument type of the second command.
* @param <R> the final Result's data type (result of second command).
* @author Eike Kettner
* @author Fabian Kessler
*/
final class ComposedCommand<A, B, R> extends BaseCommand<A, R> {
private final Command<A, B> f;
private final Command<B, R> g;
ComposedCommand(Command<A, B> f, Command<B, R> g) {
this.f = f;
this.g = g;
}
@Override @Nullable | // Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
//
// Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
// Path: src/main/java/com/optimaize/command4j/commands/ComposedCommand.java
import com.google.common.base.Optional;
import com.optimaize.command4j.ExecutionContext;
import com.optimaize.command4j.Command;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
package com.optimaize.command4j.commands;
/**
* A command that is the composition of two commands.
*
* <p>When executing then at first the 1st command gets executed, then its result is fed to the 2nd command, and
* finally the result of the 2nd command is returned.</p>
*
* <p>As soon as an exception occurs (either when executing the first or second command)
* then the whole thing aborts with the exception.</p>
*
* @param <A> the optional Argument's data type for the first command.
* @param <B> The type of the result of the first command as well as the argument type of the second command.
* @param <R> the final Result's data type (result of second command).
* @author Eike Kettner
* @author Fabian Kessler
*/
final class ComposedCommand<A, B, R> extends BaseCommand<A, R> {
private final Command<A, B> f;
private final Command<B, R> g;
ComposedCommand(Command<A, B> f, Command<B, R> g) {
this.f = f;
this.g = g;
}
@Override @Nullable | public R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception { |
optimaize/command4j | src/main/java/com/optimaize/command4j/commands/FlatAndCommand.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
| import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import java.util.List; | package com.optimaize.command4j.commands;
/**
* @see Commands#flatAnd
* @author Eike Kettner
*/
class FlatAndCommand<A, R> extends BaseListCommand<A, R> {
@NotNull | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
// Path: src/main/java/com/optimaize/command4j/commands/FlatAndCommand.java
import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import java.util.List;
package com.optimaize.command4j.commands;
/**
* @see Commands#flatAnd
* @author Eike Kettner
*/
class FlatAndCommand<A, R> extends BaseListCommand<A, R> {
@NotNull | private final Command<A, ? extends Iterable<R>> first; |
optimaize/command4j | src/main/java/com/optimaize/command4j/commands/FlatAndCommand.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
| import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import java.util.List; | package com.optimaize.command4j.commands;
/**
* @see Commands#flatAnd
* @author Eike Kettner
*/
class FlatAndCommand<A, R> extends BaseListCommand<A, R> {
@NotNull
private final Command<A, ? extends Iterable<R>> first;
@NotNull
private final Command<A, R> second;
FlatAndCommand(@NotNull Command<A, ? extends Iterable<R>> first, @NotNull Command<A, R> second) {
this.first = first;
this.second = second;
}
@Override | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
// Path: src/main/java/com/optimaize/command4j/commands/FlatAndCommand.java
import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import java.util.List;
package com.optimaize.command4j.commands;
/**
* @see Commands#flatAnd
* @author Eike Kettner
*/
class FlatAndCommand<A, R> extends BaseListCommand<A, R> {
@NotNull
private final Command<A, ? extends Iterable<R>> first;
@NotNull
private final Command<A, R> second;
FlatAndCommand(@NotNull Command<A, ? extends Iterable<R>> first, @NotNull Command<A, R> second) {
this.first = first;
this.second = second;
}
@Override | public List<R> call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception { |
optimaize/command4j | src/main/java/com/optimaize/command4j/commands/BaseCommandInterceptor.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
| import com.optimaize.command4j.Command;
import org.jetbrains.annotations.NotNull; | package com.optimaize.command4j.commands;
/**
* Base class for interceptors.
*
* @author aa
*/
public abstract class BaseCommandInterceptor<A, R> extends BaseCommand<A, R> {
@NotNull | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
// Path: src/main/java/com/optimaize/command4j/commands/BaseCommandInterceptor.java
import com.optimaize.command4j.Command;
import org.jetbrains.annotations.NotNull;
package com.optimaize.command4j.commands;
/**
* Base class for interceptors.
*
* @author aa
*/
public abstract class BaseCommandInterceptor<A, R> extends BaseCommand<A, R> {
@NotNull | protected final Command<A, R> delegate; |
optimaize/command4j | src/test/java/com/optimaize/command4j/commands/Multiply.java | // Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
| import com.google.common.base.Optional;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull; | package com.optimaize.command4j.commands;
/**
* Multiplies numbers.
*
* @author Fabian Kessler
*/
public class Multiply extends BaseCommand<Long, Long> {
private final long multiplier;
public Multiply(long multiplier) {
this.multiplier = multiplier;
}
@Override | // Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
// Path: src/test/java/com/optimaize/command4j/commands/Multiply.java
import com.google.common.base.Optional;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
package com.optimaize.command4j.commands;
/**
* Multiplies numbers.
*
* @author Fabian Kessler
*/
public class Multiply extends BaseCommand<Long, Long> {
private final long multiplier;
public Multiply(long multiplier) {
this.multiplier = multiplier;
}
@Override | public Long call(@NotNull Optional<Long> arg, @NotNull ExecutionContext ec) throws Exception { |
optimaize/command4j | src/main/java/com/optimaize/command4j/ext/extensions/logging/customlogging/CommandExecutionLoggerImpl.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
| import com.google.common.base.Optional;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger; | package com.optimaize.command4j.ext.extensions.logging.customlogging;
/**
* You are encouraged to override the methods to change the logging.
* You may also override the {@link #before} method with an empty one to not log before at all.
*
* @author Fabian Kessler
*/
public class CommandExecutionLoggerImpl<A,R> implements CommandExecutionLogger<A, R> {
@NotNull
private final Logger logger;
private final boolean logArgumentInResult;
/**
* Uses logArgumentInResult=false.
*/
public CommandExecutionLoggerImpl(@NotNull Logger logger) {
this(logger, false);
}
/**
* @param logArgumentInResult Optionally writes the argument with the result line again.
* This is useful when either you only log results (and not requests), or you want it more convenient and don't mind generating larger log files.
*/
public CommandExecutionLoggerImpl(@NotNull Logger logger, boolean logArgumentInResult) {
this.logger = logger;
this.logArgumentInResult = logArgumentInResult;
}
@Override | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
// Path: src/main/java/com/optimaize/command4j/ext/extensions/logging/customlogging/CommandExecutionLoggerImpl.java
import com.google.common.base.Optional;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
package com.optimaize.command4j.ext.extensions.logging.customlogging;
/**
* You are encouraged to override the methods to change the logging.
* You may also override the {@link #before} method with an empty one to not log before at all.
*
* @author Fabian Kessler
*/
public class CommandExecutionLoggerImpl<A,R> implements CommandExecutionLogger<A, R> {
@NotNull
private final Logger logger;
private final boolean logArgumentInResult;
/**
* Uses logArgumentInResult=false.
*/
public CommandExecutionLoggerImpl(@NotNull Logger logger) {
this(logger, false);
}
/**
* @param logArgumentInResult Optionally writes the argument with the result line again.
* This is useful when either you only log results (and not requests), or you want it more convenient and don't mind generating larger log files.
*/
public CommandExecutionLoggerImpl(@NotNull Logger logger, boolean logArgumentInResult) {
this.logger = logger;
this.logArgumentInResult = logArgumentInResult;
}
@Override | public void before(@NotNull Command<A, R> command, @NotNull ExecutionContext ec, @NotNull Optional<A> arg) { |
optimaize/command4j | src/main/java/com/optimaize/command4j/ext/extensions/logging/customlogging/CommandExecutionLoggerImpl.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
| import com.google.common.base.Optional;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger; | package com.optimaize.command4j.ext.extensions.logging.customlogging;
/**
* You are encouraged to override the methods to change the logging.
* You may also override the {@link #before} method with an empty one to not log before at all.
*
* @author Fabian Kessler
*/
public class CommandExecutionLoggerImpl<A,R> implements CommandExecutionLogger<A, R> {
@NotNull
private final Logger logger;
private final boolean logArgumentInResult;
/**
* Uses logArgumentInResult=false.
*/
public CommandExecutionLoggerImpl(@NotNull Logger logger) {
this(logger, false);
}
/**
* @param logArgumentInResult Optionally writes the argument with the result line again.
* This is useful when either you only log results (and not requests), or you want it more convenient and don't mind generating larger log files.
*/
public CommandExecutionLoggerImpl(@NotNull Logger logger, boolean logArgumentInResult) {
this.logger = logger;
this.logArgumentInResult = logArgumentInResult;
}
@Override | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
// Path: src/main/java/com/optimaize/command4j/ext/extensions/logging/customlogging/CommandExecutionLoggerImpl.java
import com.google.common.base.Optional;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
package com.optimaize.command4j.ext.extensions.logging.customlogging;
/**
* You are encouraged to override the methods to change the logging.
* You may also override the {@link #before} method with an empty one to not log before at all.
*
* @author Fabian Kessler
*/
public class CommandExecutionLoggerImpl<A,R> implements CommandExecutionLogger<A, R> {
@NotNull
private final Logger logger;
private final boolean logArgumentInResult;
/**
* Uses logArgumentInResult=false.
*/
public CommandExecutionLoggerImpl(@NotNull Logger logger) {
this(logger, false);
}
/**
* @param logArgumentInResult Optionally writes the argument with the result line again.
* This is useful when either you only log results (and not requests), or you want it more convenient and don't mind generating larger log files.
*/
public CommandExecutionLoggerImpl(@NotNull Logger logger, boolean logArgumentInResult) {
this.logger = logger;
this.logArgumentInResult = logArgumentInResult;
}
@Override | public void before(@NotNull Command<A, R> command, @NotNull ExecutionContext ec, @NotNull Optional<A> arg) { |
optimaize/command4j | src/main/java/com/optimaize/command4j/commands/AbstractCompoundCommand.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
| import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List; | package com.optimaize.command4j.commands;
/**
* @author Eike Kettner
*/
abstract class AbstractCompoundCommand<A, B, T, E extends Iterable<T>> extends BaseListCommand<A, T> {
private static final Joiner joiner = Joiner.on(", "); | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
// Path: src/main/java/com/optimaize/command4j/commands/AbstractCompoundCommand.java
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
package com.optimaize.command4j.commands;
/**
* @author Eike Kettner
*/
abstract class AbstractCompoundCommand<A, B, T, E extends Iterable<T>> extends BaseListCommand<A, T> {
private static final Joiner joiner = Joiner.on(", "); | private final Iterable<? extends Command<B, T>> commands; |
optimaize/command4j | src/main/java/com/optimaize/command4j/commands/AbstractCompoundCommand.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
| import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List; | package com.optimaize.command4j.commands;
/**
* @author Eike Kettner
*/
abstract class AbstractCompoundCommand<A, B, T, E extends Iterable<T>> extends BaseListCommand<A, T> {
private static final Joiner joiner = Joiner.on(", ");
private final Iterable<? extends Command<B, T>> commands;
public AbstractCompoundCommand(Iterable<? extends Command<B, T>> commands) {
this.commands = commands;
}
@Override | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
// Path: src/main/java/com/optimaize/command4j/commands/AbstractCompoundCommand.java
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
package com.optimaize.command4j.commands;
/**
* @author Eike Kettner
*/
abstract class AbstractCompoundCommand<A, B, T, E extends Iterable<T>> extends BaseListCommand<A, T> {
private static final Joiner joiner = Joiner.on(", ");
private final Iterable<? extends Command<B, T>> commands;
public AbstractCompoundCommand(Iterable<? extends Command<B, T>> commands) {
this.commands = commands;
}
@Override | public E call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception { |
optimaize/command4j | src/test/java/com/optimaize/command4j/commands/ThrowUnsupportedOperation.java | // Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
| import com.google.common.base.Optional;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull; | package com.optimaize.command4j.commands;
/**
* Always throws an UnsupportedOperationException.
*
* @author Fabian Kessler
*/
public class ThrowUnsupportedOperation extends BaseCommand<Void, Void> {
@Override | // Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
// Path: src/test/java/com/optimaize/command4j/commands/ThrowUnsupportedOperation.java
import com.google.common.base.Optional;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
package com.optimaize.command4j.commands;
/**
* Always throws an UnsupportedOperationException.
*
* @author Fabian Kessler
*/
public class ThrowUnsupportedOperation extends BaseCommand<Void, Void> {
@Override | public Void call(@NotNull Optional<Void> arg, @NotNull ExecutionContext ec) throws Exception { |
optimaize/command4j | src/main/java/com/optimaize/command4j/ext/extensions/failover/autoretry/NeverAutoRetryStrategy.java | // Path: src/main/java/com/optimaize/command4j/lang/Duration.java
// @Immutable
// public final class Duration {
//
// private final long time;
// @NotNull
// private final TimeUnit timeUnit;
//
// @NotNull
// public static Duration of(long time, @NotNull TimeUnit unit) {
// return new Duration(time, unit);
// }
//
// @NotNull
// public static Duration millis(long time) {
// return of(time, TimeUnit.MILLISECONDS);
// }
//
// @NotNull
// public static Duration seconds(long time) {
// return of(time, TimeUnit.SECONDS);
// }
//
// private Duration(long time, @NotNull TimeUnit timeUnit) {
// this.time = time;
// this.timeUnit = timeUnit;
// }
//
//
// public long getTime() {
// return time;
// }
//
// @NotNull
// public TimeUnit getTimeUnit() {
// return timeUnit;
// }
//
// public long toMillis() {
// return timeUnit.toMillis(time);
// }
//
// public boolean isZero() {
// return time==0;
// }
//
// @Override
// public String toString() {
// return "Duration[" + time + toString(timeUnit) + ']';
// }
//
// @NotNull
// private String toString(@NotNull TimeUnit timeUnit) {
// switch (timeUnit) {
// case MILLISECONDS:
// return "ms";
// case SECONDS:
// return "s";
// case MINUTES:
// return "m";
// case HOURS:
// return "h";
// case DAYS:
// return "d";
// default:
// return timeUnit.name();
// }
// }
// }
| import com.optimaize.command4j.lang.Duration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | package com.optimaize.command4j.ext.extensions.failover.autoretry;
/**
* @author Fabian Kessler
*/
class NeverAutoRetryStrategy implements AutoRetryStrategy {
public static final AutoRetryStrategy INSTANCE = new NeverAutoRetryStrategy();
private NeverAutoRetryStrategy(){}
@Override @Nullable | // Path: src/main/java/com/optimaize/command4j/lang/Duration.java
// @Immutable
// public final class Duration {
//
// private final long time;
// @NotNull
// private final TimeUnit timeUnit;
//
// @NotNull
// public static Duration of(long time, @NotNull TimeUnit unit) {
// return new Duration(time, unit);
// }
//
// @NotNull
// public static Duration millis(long time) {
// return of(time, TimeUnit.MILLISECONDS);
// }
//
// @NotNull
// public static Duration seconds(long time) {
// return of(time, TimeUnit.SECONDS);
// }
//
// private Duration(long time, @NotNull TimeUnit timeUnit) {
// this.time = time;
// this.timeUnit = timeUnit;
// }
//
//
// public long getTime() {
// return time;
// }
//
// @NotNull
// public TimeUnit getTimeUnit() {
// return timeUnit;
// }
//
// public long toMillis() {
// return timeUnit.toMillis(time);
// }
//
// public boolean isZero() {
// return time==0;
// }
//
// @Override
// public String toString() {
// return "Duration[" + time + toString(timeUnit) + ']';
// }
//
// @NotNull
// private String toString(@NotNull TimeUnit timeUnit) {
// switch (timeUnit) {
// case MILLISECONDS:
// return "ms";
// case SECONDS:
// return "s";
// case MINUTES:
// return "m";
// case HOURS:
// return "h";
// case DAYS:
// return "d";
// default:
// return timeUnit.name();
// }
// }
// }
// Path: src/main/java/com/optimaize/command4j/ext/extensions/failover/autoretry/NeverAutoRetryStrategy.java
import com.optimaize.command4j.lang.Duration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
package com.optimaize.command4j.ext.extensions.failover.autoretry;
/**
* @author Fabian Kessler
*/
class NeverAutoRetryStrategy implements AutoRetryStrategy {
public static final AutoRetryStrategy INSTANCE = new NeverAutoRetryStrategy();
private NeverAutoRetryStrategy(){}
@Override @Nullable | public Duration doRetry(int executionCounter, @NotNull Exception exception) { |
optimaize/command4j | src/main/java/com/optimaize/command4j/ext/Extensions.java | // Path: src/main/java/com/optimaize/command4j/ext/extensions/exception/ExceptionExtensions.java
// public class ExceptionExtensions {
//
// public static final ExceptionExtensions INSTANCE = new ExceptionExtensions();
// private ExceptionExtensions(){}
//
//
// /**
// * @see ExceptionTranslationExtension
// */
// public static <A, R> BaseCommand<A, R> withExceptionTranslation(@NotNull Command<A, R> cmd,
// @NotNull ExceptionTranslator exceptionTranslator) {
// return new ExceptionTranslationExtension.Interceptor<>(cmd, exceptionTranslator);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/failover/FailoverExtensions.java
// public class FailoverExtensions {
//
// public static final FailoverExtensions INSTANCE = new FailoverExtensions();
// private FailoverExtensions(){}
//
//
//
// /**
// * Uses the {@link AutoRetryExtension}.
// * @see AutoRetryExtension
// */
// public static <A, V> BaseCommand<A, V> withAutoRetry(@NotNull Command<A, V> cmd) {
// return new AutoRetryExtension.Interceptor<>(cmd);
// }
//
// /**
// * @see AutoRetryExtension
// */
// public static <A, V> BaseCommand<A, V> withAutoRetry(@NotNull Command<A, V> cmd,
// @NotNull AutoRetryStrategy strategy) {
// return new AutoRetryExtension.Interceptor<>(cmd, strategy);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/logging/LoggingExtensions.java
// public class LoggingExtensions {
//
// public static final LoggingExtensions INSTANCE = new LoggingExtensions();
// private LoggingExtensions(){}
//
//
// /**
// * @see StdoutLoggingExtension
// */
// public static <A, R> BaseCommand<A, R> withStdoutLogging(@NotNull Command<A, R> cmd) {
// return new StdoutLoggingExtension.Interceptor<>(cmd);
// }
//
// /**
// * @see CustomLoggingExtension
// */
// public static <A, R> BaseCommand<A, R> withCustomLogging(@NotNull Command<A, R> cmd,
// @NotNull CommandExecutionLogger<A, R> commandExecutionLogger) {
// return new CustomLoggingExtension.Interceptor<>(cmd, commandExecutionLogger);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/timeout/TimeoutExtensions.java
// public class TimeoutExtensions {
//
// public static final TimeoutExtensions INSTANCE = new TimeoutExtensions();
// private TimeoutExtensions(){}
//
//
// /**
// * @see TimeoutExtension
// */
// public static <A, V> BaseCommand<A, V> withTimeout(@NotNull Command<A, V> cmd, @NotNull Duration duration) {
// return new TimeoutExtension.Interceptor<>(cmd, duration);
// }
//
// }
| import com.optimaize.command4j.ext.extensions.exception.ExceptionExtensions;
import com.optimaize.command4j.ext.extensions.failover.FailoverExtensions;
import com.optimaize.command4j.ext.extensions.logging.LoggingExtensions;
import com.optimaize.command4j.ext.extensions.timeout.TimeoutExtensions;
import org.jetbrains.annotations.NotNull; | package com.optimaize.command4j.ext;
/**
* A hub-class for easy access to common built-in extensions.
*
* @author Fabian Kessler
*/
public class Extensions {
public static final Extensions INSTANCE = new Extensions();
private Extensions(){}
@NotNull | // Path: src/main/java/com/optimaize/command4j/ext/extensions/exception/ExceptionExtensions.java
// public class ExceptionExtensions {
//
// public static final ExceptionExtensions INSTANCE = new ExceptionExtensions();
// private ExceptionExtensions(){}
//
//
// /**
// * @see ExceptionTranslationExtension
// */
// public static <A, R> BaseCommand<A, R> withExceptionTranslation(@NotNull Command<A, R> cmd,
// @NotNull ExceptionTranslator exceptionTranslator) {
// return new ExceptionTranslationExtension.Interceptor<>(cmd, exceptionTranslator);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/failover/FailoverExtensions.java
// public class FailoverExtensions {
//
// public static final FailoverExtensions INSTANCE = new FailoverExtensions();
// private FailoverExtensions(){}
//
//
//
// /**
// * Uses the {@link AutoRetryExtension}.
// * @see AutoRetryExtension
// */
// public static <A, V> BaseCommand<A, V> withAutoRetry(@NotNull Command<A, V> cmd) {
// return new AutoRetryExtension.Interceptor<>(cmd);
// }
//
// /**
// * @see AutoRetryExtension
// */
// public static <A, V> BaseCommand<A, V> withAutoRetry(@NotNull Command<A, V> cmd,
// @NotNull AutoRetryStrategy strategy) {
// return new AutoRetryExtension.Interceptor<>(cmd, strategy);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/logging/LoggingExtensions.java
// public class LoggingExtensions {
//
// public static final LoggingExtensions INSTANCE = new LoggingExtensions();
// private LoggingExtensions(){}
//
//
// /**
// * @see StdoutLoggingExtension
// */
// public static <A, R> BaseCommand<A, R> withStdoutLogging(@NotNull Command<A, R> cmd) {
// return new StdoutLoggingExtension.Interceptor<>(cmd);
// }
//
// /**
// * @see CustomLoggingExtension
// */
// public static <A, R> BaseCommand<A, R> withCustomLogging(@NotNull Command<A, R> cmd,
// @NotNull CommandExecutionLogger<A, R> commandExecutionLogger) {
// return new CustomLoggingExtension.Interceptor<>(cmd, commandExecutionLogger);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/timeout/TimeoutExtensions.java
// public class TimeoutExtensions {
//
// public static final TimeoutExtensions INSTANCE = new TimeoutExtensions();
// private TimeoutExtensions(){}
//
//
// /**
// * @see TimeoutExtension
// */
// public static <A, V> BaseCommand<A, V> withTimeout(@NotNull Command<A, V> cmd, @NotNull Duration duration) {
// return new TimeoutExtension.Interceptor<>(cmd, duration);
// }
//
// }
// Path: src/main/java/com/optimaize/command4j/ext/Extensions.java
import com.optimaize.command4j.ext.extensions.exception.ExceptionExtensions;
import com.optimaize.command4j.ext.extensions.failover.FailoverExtensions;
import com.optimaize.command4j.ext.extensions.logging.LoggingExtensions;
import com.optimaize.command4j.ext.extensions.timeout.TimeoutExtensions;
import org.jetbrains.annotations.NotNull;
package com.optimaize.command4j.ext;
/**
* A hub-class for easy access to common built-in extensions.
*
* @author Fabian Kessler
*/
public class Extensions {
public static final Extensions INSTANCE = new Extensions();
private Extensions(){}
@NotNull | public static LoggingExtensions logging() { |
optimaize/command4j | src/main/java/com/optimaize/command4j/ext/Extensions.java | // Path: src/main/java/com/optimaize/command4j/ext/extensions/exception/ExceptionExtensions.java
// public class ExceptionExtensions {
//
// public static final ExceptionExtensions INSTANCE = new ExceptionExtensions();
// private ExceptionExtensions(){}
//
//
// /**
// * @see ExceptionTranslationExtension
// */
// public static <A, R> BaseCommand<A, R> withExceptionTranslation(@NotNull Command<A, R> cmd,
// @NotNull ExceptionTranslator exceptionTranslator) {
// return new ExceptionTranslationExtension.Interceptor<>(cmd, exceptionTranslator);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/failover/FailoverExtensions.java
// public class FailoverExtensions {
//
// public static final FailoverExtensions INSTANCE = new FailoverExtensions();
// private FailoverExtensions(){}
//
//
//
// /**
// * Uses the {@link AutoRetryExtension}.
// * @see AutoRetryExtension
// */
// public static <A, V> BaseCommand<A, V> withAutoRetry(@NotNull Command<A, V> cmd) {
// return new AutoRetryExtension.Interceptor<>(cmd);
// }
//
// /**
// * @see AutoRetryExtension
// */
// public static <A, V> BaseCommand<A, V> withAutoRetry(@NotNull Command<A, V> cmd,
// @NotNull AutoRetryStrategy strategy) {
// return new AutoRetryExtension.Interceptor<>(cmd, strategy);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/logging/LoggingExtensions.java
// public class LoggingExtensions {
//
// public static final LoggingExtensions INSTANCE = new LoggingExtensions();
// private LoggingExtensions(){}
//
//
// /**
// * @see StdoutLoggingExtension
// */
// public static <A, R> BaseCommand<A, R> withStdoutLogging(@NotNull Command<A, R> cmd) {
// return new StdoutLoggingExtension.Interceptor<>(cmd);
// }
//
// /**
// * @see CustomLoggingExtension
// */
// public static <A, R> BaseCommand<A, R> withCustomLogging(@NotNull Command<A, R> cmd,
// @NotNull CommandExecutionLogger<A, R> commandExecutionLogger) {
// return new CustomLoggingExtension.Interceptor<>(cmd, commandExecutionLogger);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/timeout/TimeoutExtensions.java
// public class TimeoutExtensions {
//
// public static final TimeoutExtensions INSTANCE = new TimeoutExtensions();
// private TimeoutExtensions(){}
//
//
// /**
// * @see TimeoutExtension
// */
// public static <A, V> BaseCommand<A, V> withTimeout(@NotNull Command<A, V> cmd, @NotNull Duration duration) {
// return new TimeoutExtension.Interceptor<>(cmd, duration);
// }
//
// }
| import com.optimaize.command4j.ext.extensions.exception.ExceptionExtensions;
import com.optimaize.command4j.ext.extensions.failover.FailoverExtensions;
import com.optimaize.command4j.ext.extensions.logging.LoggingExtensions;
import com.optimaize.command4j.ext.extensions.timeout.TimeoutExtensions;
import org.jetbrains.annotations.NotNull; | package com.optimaize.command4j.ext;
/**
* A hub-class for easy access to common built-in extensions.
*
* @author Fabian Kessler
*/
public class Extensions {
public static final Extensions INSTANCE = new Extensions();
private Extensions(){}
@NotNull
public static LoggingExtensions logging() {
return LoggingExtensions.INSTANCE;
}
@NotNull | // Path: src/main/java/com/optimaize/command4j/ext/extensions/exception/ExceptionExtensions.java
// public class ExceptionExtensions {
//
// public static final ExceptionExtensions INSTANCE = new ExceptionExtensions();
// private ExceptionExtensions(){}
//
//
// /**
// * @see ExceptionTranslationExtension
// */
// public static <A, R> BaseCommand<A, R> withExceptionTranslation(@NotNull Command<A, R> cmd,
// @NotNull ExceptionTranslator exceptionTranslator) {
// return new ExceptionTranslationExtension.Interceptor<>(cmd, exceptionTranslator);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/failover/FailoverExtensions.java
// public class FailoverExtensions {
//
// public static final FailoverExtensions INSTANCE = new FailoverExtensions();
// private FailoverExtensions(){}
//
//
//
// /**
// * Uses the {@link AutoRetryExtension}.
// * @see AutoRetryExtension
// */
// public static <A, V> BaseCommand<A, V> withAutoRetry(@NotNull Command<A, V> cmd) {
// return new AutoRetryExtension.Interceptor<>(cmd);
// }
//
// /**
// * @see AutoRetryExtension
// */
// public static <A, V> BaseCommand<A, V> withAutoRetry(@NotNull Command<A, V> cmd,
// @NotNull AutoRetryStrategy strategy) {
// return new AutoRetryExtension.Interceptor<>(cmd, strategy);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/logging/LoggingExtensions.java
// public class LoggingExtensions {
//
// public static final LoggingExtensions INSTANCE = new LoggingExtensions();
// private LoggingExtensions(){}
//
//
// /**
// * @see StdoutLoggingExtension
// */
// public static <A, R> BaseCommand<A, R> withStdoutLogging(@NotNull Command<A, R> cmd) {
// return new StdoutLoggingExtension.Interceptor<>(cmd);
// }
//
// /**
// * @see CustomLoggingExtension
// */
// public static <A, R> BaseCommand<A, R> withCustomLogging(@NotNull Command<A, R> cmd,
// @NotNull CommandExecutionLogger<A, R> commandExecutionLogger) {
// return new CustomLoggingExtension.Interceptor<>(cmd, commandExecutionLogger);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/timeout/TimeoutExtensions.java
// public class TimeoutExtensions {
//
// public static final TimeoutExtensions INSTANCE = new TimeoutExtensions();
// private TimeoutExtensions(){}
//
//
// /**
// * @see TimeoutExtension
// */
// public static <A, V> BaseCommand<A, V> withTimeout(@NotNull Command<A, V> cmd, @NotNull Duration duration) {
// return new TimeoutExtension.Interceptor<>(cmd, duration);
// }
//
// }
// Path: src/main/java/com/optimaize/command4j/ext/Extensions.java
import com.optimaize.command4j.ext.extensions.exception.ExceptionExtensions;
import com.optimaize.command4j.ext.extensions.failover.FailoverExtensions;
import com.optimaize.command4j.ext.extensions.logging.LoggingExtensions;
import com.optimaize.command4j.ext.extensions.timeout.TimeoutExtensions;
import org.jetbrains.annotations.NotNull;
package com.optimaize.command4j.ext;
/**
* A hub-class for easy access to common built-in extensions.
*
* @author Fabian Kessler
*/
public class Extensions {
public static final Extensions INSTANCE = new Extensions();
private Extensions(){}
@NotNull
public static LoggingExtensions logging() {
return LoggingExtensions.INSTANCE;
}
@NotNull | public static ExceptionExtensions exception() { |
optimaize/command4j | src/main/java/com/optimaize/command4j/ext/Extensions.java | // Path: src/main/java/com/optimaize/command4j/ext/extensions/exception/ExceptionExtensions.java
// public class ExceptionExtensions {
//
// public static final ExceptionExtensions INSTANCE = new ExceptionExtensions();
// private ExceptionExtensions(){}
//
//
// /**
// * @see ExceptionTranslationExtension
// */
// public static <A, R> BaseCommand<A, R> withExceptionTranslation(@NotNull Command<A, R> cmd,
// @NotNull ExceptionTranslator exceptionTranslator) {
// return new ExceptionTranslationExtension.Interceptor<>(cmd, exceptionTranslator);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/failover/FailoverExtensions.java
// public class FailoverExtensions {
//
// public static final FailoverExtensions INSTANCE = new FailoverExtensions();
// private FailoverExtensions(){}
//
//
//
// /**
// * Uses the {@link AutoRetryExtension}.
// * @see AutoRetryExtension
// */
// public static <A, V> BaseCommand<A, V> withAutoRetry(@NotNull Command<A, V> cmd) {
// return new AutoRetryExtension.Interceptor<>(cmd);
// }
//
// /**
// * @see AutoRetryExtension
// */
// public static <A, V> BaseCommand<A, V> withAutoRetry(@NotNull Command<A, V> cmd,
// @NotNull AutoRetryStrategy strategy) {
// return new AutoRetryExtension.Interceptor<>(cmd, strategy);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/logging/LoggingExtensions.java
// public class LoggingExtensions {
//
// public static final LoggingExtensions INSTANCE = new LoggingExtensions();
// private LoggingExtensions(){}
//
//
// /**
// * @see StdoutLoggingExtension
// */
// public static <A, R> BaseCommand<A, R> withStdoutLogging(@NotNull Command<A, R> cmd) {
// return new StdoutLoggingExtension.Interceptor<>(cmd);
// }
//
// /**
// * @see CustomLoggingExtension
// */
// public static <A, R> BaseCommand<A, R> withCustomLogging(@NotNull Command<A, R> cmd,
// @NotNull CommandExecutionLogger<A, R> commandExecutionLogger) {
// return new CustomLoggingExtension.Interceptor<>(cmd, commandExecutionLogger);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/timeout/TimeoutExtensions.java
// public class TimeoutExtensions {
//
// public static final TimeoutExtensions INSTANCE = new TimeoutExtensions();
// private TimeoutExtensions(){}
//
//
// /**
// * @see TimeoutExtension
// */
// public static <A, V> BaseCommand<A, V> withTimeout(@NotNull Command<A, V> cmd, @NotNull Duration duration) {
// return new TimeoutExtension.Interceptor<>(cmd, duration);
// }
//
// }
| import com.optimaize.command4j.ext.extensions.exception.ExceptionExtensions;
import com.optimaize.command4j.ext.extensions.failover.FailoverExtensions;
import com.optimaize.command4j.ext.extensions.logging.LoggingExtensions;
import com.optimaize.command4j.ext.extensions.timeout.TimeoutExtensions;
import org.jetbrains.annotations.NotNull; | package com.optimaize.command4j.ext;
/**
* A hub-class for easy access to common built-in extensions.
*
* @author Fabian Kessler
*/
public class Extensions {
public static final Extensions INSTANCE = new Extensions();
private Extensions(){}
@NotNull
public static LoggingExtensions logging() {
return LoggingExtensions.INSTANCE;
}
@NotNull
public static ExceptionExtensions exception() {
return ExceptionExtensions.INSTANCE;
}
@NotNull | // Path: src/main/java/com/optimaize/command4j/ext/extensions/exception/ExceptionExtensions.java
// public class ExceptionExtensions {
//
// public static final ExceptionExtensions INSTANCE = new ExceptionExtensions();
// private ExceptionExtensions(){}
//
//
// /**
// * @see ExceptionTranslationExtension
// */
// public static <A, R> BaseCommand<A, R> withExceptionTranslation(@NotNull Command<A, R> cmd,
// @NotNull ExceptionTranslator exceptionTranslator) {
// return new ExceptionTranslationExtension.Interceptor<>(cmd, exceptionTranslator);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/failover/FailoverExtensions.java
// public class FailoverExtensions {
//
// public static final FailoverExtensions INSTANCE = new FailoverExtensions();
// private FailoverExtensions(){}
//
//
//
// /**
// * Uses the {@link AutoRetryExtension}.
// * @see AutoRetryExtension
// */
// public static <A, V> BaseCommand<A, V> withAutoRetry(@NotNull Command<A, V> cmd) {
// return new AutoRetryExtension.Interceptor<>(cmd);
// }
//
// /**
// * @see AutoRetryExtension
// */
// public static <A, V> BaseCommand<A, V> withAutoRetry(@NotNull Command<A, V> cmd,
// @NotNull AutoRetryStrategy strategy) {
// return new AutoRetryExtension.Interceptor<>(cmd, strategy);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/logging/LoggingExtensions.java
// public class LoggingExtensions {
//
// public static final LoggingExtensions INSTANCE = new LoggingExtensions();
// private LoggingExtensions(){}
//
//
// /**
// * @see StdoutLoggingExtension
// */
// public static <A, R> BaseCommand<A, R> withStdoutLogging(@NotNull Command<A, R> cmd) {
// return new StdoutLoggingExtension.Interceptor<>(cmd);
// }
//
// /**
// * @see CustomLoggingExtension
// */
// public static <A, R> BaseCommand<A, R> withCustomLogging(@NotNull Command<A, R> cmd,
// @NotNull CommandExecutionLogger<A, R> commandExecutionLogger) {
// return new CustomLoggingExtension.Interceptor<>(cmd, commandExecutionLogger);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/timeout/TimeoutExtensions.java
// public class TimeoutExtensions {
//
// public static final TimeoutExtensions INSTANCE = new TimeoutExtensions();
// private TimeoutExtensions(){}
//
//
// /**
// * @see TimeoutExtension
// */
// public static <A, V> BaseCommand<A, V> withTimeout(@NotNull Command<A, V> cmd, @NotNull Duration duration) {
// return new TimeoutExtension.Interceptor<>(cmd, duration);
// }
//
// }
// Path: src/main/java/com/optimaize/command4j/ext/Extensions.java
import com.optimaize.command4j.ext.extensions.exception.ExceptionExtensions;
import com.optimaize.command4j.ext.extensions.failover.FailoverExtensions;
import com.optimaize.command4j.ext.extensions.logging.LoggingExtensions;
import com.optimaize.command4j.ext.extensions.timeout.TimeoutExtensions;
import org.jetbrains.annotations.NotNull;
package com.optimaize.command4j.ext;
/**
* A hub-class for easy access to common built-in extensions.
*
* @author Fabian Kessler
*/
public class Extensions {
public static final Extensions INSTANCE = new Extensions();
private Extensions(){}
@NotNull
public static LoggingExtensions logging() {
return LoggingExtensions.INSTANCE;
}
@NotNull
public static ExceptionExtensions exception() {
return ExceptionExtensions.INSTANCE;
}
@NotNull | public static TimeoutExtensions timeout() { |
optimaize/command4j | src/main/java/com/optimaize/command4j/ext/Extensions.java | // Path: src/main/java/com/optimaize/command4j/ext/extensions/exception/ExceptionExtensions.java
// public class ExceptionExtensions {
//
// public static final ExceptionExtensions INSTANCE = new ExceptionExtensions();
// private ExceptionExtensions(){}
//
//
// /**
// * @see ExceptionTranslationExtension
// */
// public static <A, R> BaseCommand<A, R> withExceptionTranslation(@NotNull Command<A, R> cmd,
// @NotNull ExceptionTranslator exceptionTranslator) {
// return new ExceptionTranslationExtension.Interceptor<>(cmd, exceptionTranslator);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/failover/FailoverExtensions.java
// public class FailoverExtensions {
//
// public static final FailoverExtensions INSTANCE = new FailoverExtensions();
// private FailoverExtensions(){}
//
//
//
// /**
// * Uses the {@link AutoRetryExtension}.
// * @see AutoRetryExtension
// */
// public static <A, V> BaseCommand<A, V> withAutoRetry(@NotNull Command<A, V> cmd) {
// return new AutoRetryExtension.Interceptor<>(cmd);
// }
//
// /**
// * @see AutoRetryExtension
// */
// public static <A, V> BaseCommand<A, V> withAutoRetry(@NotNull Command<A, V> cmd,
// @NotNull AutoRetryStrategy strategy) {
// return new AutoRetryExtension.Interceptor<>(cmd, strategy);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/logging/LoggingExtensions.java
// public class LoggingExtensions {
//
// public static final LoggingExtensions INSTANCE = new LoggingExtensions();
// private LoggingExtensions(){}
//
//
// /**
// * @see StdoutLoggingExtension
// */
// public static <A, R> BaseCommand<A, R> withStdoutLogging(@NotNull Command<A, R> cmd) {
// return new StdoutLoggingExtension.Interceptor<>(cmd);
// }
//
// /**
// * @see CustomLoggingExtension
// */
// public static <A, R> BaseCommand<A, R> withCustomLogging(@NotNull Command<A, R> cmd,
// @NotNull CommandExecutionLogger<A, R> commandExecutionLogger) {
// return new CustomLoggingExtension.Interceptor<>(cmd, commandExecutionLogger);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/timeout/TimeoutExtensions.java
// public class TimeoutExtensions {
//
// public static final TimeoutExtensions INSTANCE = new TimeoutExtensions();
// private TimeoutExtensions(){}
//
//
// /**
// * @see TimeoutExtension
// */
// public static <A, V> BaseCommand<A, V> withTimeout(@NotNull Command<A, V> cmd, @NotNull Duration duration) {
// return new TimeoutExtension.Interceptor<>(cmd, duration);
// }
//
// }
| import com.optimaize.command4j.ext.extensions.exception.ExceptionExtensions;
import com.optimaize.command4j.ext.extensions.failover.FailoverExtensions;
import com.optimaize.command4j.ext.extensions.logging.LoggingExtensions;
import com.optimaize.command4j.ext.extensions.timeout.TimeoutExtensions;
import org.jetbrains.annotations.NotNull; | package com.optimaize.command4j.ext;
/**
* A hub-class for easy access to common built-in extensions.
*
* @author Fabian Kessler
*/
public class Extensions {
public static final Extensions INSTANCE = new Extensions();
private Extensions(){}
@NotNull
public static LoggingExtensions logging() {
return LoggingExtensions.INSTANCE;
}
@NotNull
public static ExceptionExtensions exception() {
return ExceptionExtensions.INSTANCE;
}
@NotNull
public static TimeoutExtensions timeout() {
return TimeoutExtensions.INSTANCE;
}
@NotNull | // Path: src/main/java/com/optimaize/command4j/ext/extensions/exception/ExceptionExtensions.java
// public class ExceptionExtensions {
//
// public static final ExceptionExtensions INSTANCE = new ExceptionExtensions();
// private ExceptionExtensions(){}
//
//
// /**
// * @see ExceptionTranslationExtension
// */
// public static <A, R> BaseCommand<A, R> withExceptionTranslation(@NotNull Command<A, R> cmd,
// @NotNull ExceptionTranslator exceptionTranslator) {
// return new ExceptionTranslationExtension.Interceptor<>(cmd, exceptionTranslator);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/failover/FailoverExtensions.java
// public class FailoverExtensions {
//
// public static final FailoverExtensions INSTANCE = new FailoverExtensions();
// private FailoverExtensions(){}
//
//
//
// /**
// * Uses the {@link AutoRetryExtension}.
// * @see AutoRetryExtension
// */
// public static <A, V> BaseCommand<A, V> withAutoRetry(@NotNull Command<A, V> cmd) {
// return new AutoRetryExtension.Interceptor<>(cmd);
// }
//
// /**
// * @see AutoRetryExtension
// */
// public static <A, V> BaseCommand<A, V> withAutoRetry(@NotNull Command<A, V> cmd,
// @NotNull AutoRetryStrategy strategy) {
// return new AutoRetryExtension.Interceptor<>(cmd, strategy);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/logging/LoggingExtensions.java
// public class LoggingExtensions {
//
// public static final LoggingExtensions INSTANCE = new LoggingExtensions();
// private LoggingExtensions(){}
//
//
// /**
// * @see StdoutLoggingExtension
// */
// public static <A, R> BaseCommand<A, R> withStdoutLogging(@NotNull Command<A, R> cmd) {
// return new StdoutLoggingExtension.Interceptor<>(cmd);
// }
//
// /**
// * @see CustomLoggingExtension
// */
// public static <A, R> BaseCommand<A, R> withCustomLogging(@NotNull Command<A, R> cmd,
// @NotNull CommandExecutionLogger<A, R> commandExecutionLogger) {
// return new CustomLoggingExtension.Interceptor<>(cmd, commandExecutionLogger);
// }
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ext/extensions/timeout/TimeoutExtensions.java
// public class TimeoutExtensions {
//
// public static final TimeoutExtensions INSTANCE = new TimeoutExtensions();
// private TimeoutExtensions(){}
//
//
// /**
// * @see TimeoutExtension
// */
// public static <A, V> BaseCommand<A, V> withTimeout(@NotNull Command<A, V> cmd, @NotNull Duration duration) {
// return new TimeoutExtension.Interceptor<>(cmd, duration);
// }
//
// }
// Path: src/main/java/com/optimaize/command4j/ext/Extensions.java
import com.optimaize.command4j.ext.extensions.exception.ExceptionExtensions;
import com.optimaize.command4j.ext.extensions.failover.FailoverExtensions;
import com.optimaize.command4j.ext.extensions.logging.LoggingExtensions;
import com.optimaize.command4j.ext.extensions.timeout.TimeoutExtensions;
import org.jetbrains.annotations.NotNull;
package com.optimaize.command4j.ext;
/**
* A hub-class for easy access to common built-in extensions.
*
* @author Fabian Kessler
*/
public class Extensions {
public static final Extensions INSTANCE = new Extensions();
private Extensions(){}
@NotNull
public static LoggingExtensions logging() {
return LoggingExtensions.INSTANCE;
}
@NotNull
public static ExceptionExtensions exception() {
return ExceptionExtensions.INSTANCE;
}
@NotNull
public static TimeoutExtensions timeout() {
return TimeoutExtensions.INSTANCE;
}
@NotNull | public static FailoverExtensions failover() { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.