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
irufus/gdax-java
api/src/test/java/com/coinbase/exchange/api/orders/OrderIntegrationTest.java
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // } // // Path: api/src/main/java/com/coinbase/exchange/api/products/ProductService.java // public class ProductService { // // public static final String PRODUCTS_ENDPOINT = "/products"; // // final CoinbaseExchange exchange; // // public ProductService(final CoinbaseExchange exchange) { // this.exchange = exchange; // } // // // no paged products necessary // public List<Product> getProducts() { // return exchange.getAsList(PRODUCTS_ENDPOINT, new ParameterizedTypeReference<Product[]>() { // }); // } // // public Candles getCandles(String productId) { // return new Candles(exchange.get(PRODUCTS_ENDPOINT + "/" + productId + "/candles", new ParameterizedTypeReference<List<String[]>>() { // })); // } // // public Candles getCandles(String productId, Map<String, String> queryParams) { // StringBuffer url = new StringBuffer(PRODUCTS_ENDPOINT + "/" + productId + "/candles"); // if (queryParams != null && queryParams.size() != 0) { // url.append("?"); // url.append(queryParams.entrySet().stream() // .map(entry -> entry.getKey() + "=" + entry.getValue()) // .collect(joining("&"))); // } // return new Candles(exchange.get(url.toString(), new ParameterizedTypeReference<List<String[]>>() {})); // } // // /** // * If either one of the start or end fields are not provided then both fields will be ignored. // * If a custom time range is not declared then one ending now is selected. // */ // public Candles getCandles(String productId, Instant startTime, Instant endTime, Granularity granularity) { // // Map<String, String> queryParams = new HashMap<>(); // // if (startTime != null) { // queryParams.put("start", startTime.toString()); // } // if (endTime != null) { // queryParams.put("end", endTime.toString()); // } // if (granularity != null) { // queryParams.put("granularity", granularity.get()); // } // // return getCandles(productId, queryParams); // } // // /** // * The granularity field must be one of the following values: {60, 300, 900, 3600, 21600, 86400} // */ // public Candles getCandles(String productId, Granularity granularity) { // return getCandles(productId, null, null, granularity); // } // // /** // * If either one of the start or end fields are not provided then both fields will be ignored. // */ // public Candles getCandles(String productId, Instant start, Instant end) { // return getCandles(productId, start, end, null); // } // }
import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.accounts.Account; import com.coinbase.exchange.api.accounts.AccountService; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import com.coinbase.exchange.api.marketdata.MarketData; import com.coinbase.exchange.api.marketdata.MarketDataService; import com.coinbase.exchange.api.products.ProductService; import com.coinbase.exchange.model.Fill; import com.coinbase.exchange.model.NewLimitOrderSingle; import com.coinbase.exchange.model.NewMarketOrderSingle; import org.junit.Ignore; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue;
package com.coinbase.exchange.api.orders; /** * See class doc for BaseIntegrationTest * * Created by Ishmael (sakamura@gmail.com) on 6/18/2016. */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class}) public class OrderIntegrationTest extends BaseIntegrationTest { private static final Logger log = LoggerFactory.getLogger(OrderIntegrationTest.class);
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // } // // Path: api/src/main/java/com/coinbase/exchange/api/products/ProductService.java // public class ProductService { // // public static final String PRODUCTS_ENDPOINT = "/products"; // // final CoinbaseExchange exchange; // // public ProductService(final CoinbaseExchange exchange) { // this.exchange = exchange; // } // // // no paged products necessary // public List<Product> getProducts() { // return exchange.getAsList(PRODUCTS_ENDPOINT, new ParameterizedTypeReference<Product[]>() { // }); // } // // public Candles getCandles(String productId) { // return new Candles(exchange.get(PRODUCTS_ENDPOINT + "/" + productId + "/candles", new ParameterizedTypeReference<List<String[]>>() { // })); // } // // public Candles getCandles(String productId, Map<String, String> queryParams) { // StringBuffer url = new StringBuffer(PRODUCTS_ENDPOINT + "/" + productId + "/candles"); // if (queryParams != null && queryParams.size() != 0) { // url.append("?"); // url.append(queryParams.entrySet().stream() // .map(entry -> entry.getKey() + "=" + entry.getValue()) // .collect(joining("&"))); // } // return new Candles(exchange.get(url.toString(), new ParameterizedTypeReference<List<String[]>>() {})); // } // // /** // * If either one of the start or end fields are not provided then both fields will be ignored. // * If a custom time range is not declared then one ending now is selected. // */ // public Candles getCandles(String productId, Instant startTime, Instant endTime, Granularity granularity) { // // Map<String, String> queryParams = new HashMap<>(); // // if (startTime != null) { // queryParams.put("start", startTime.toString()); // } // if (endTime != null) { // queryParams.put("end", endTime.toString()); // } // if (granularity != null) { // queryParams.put("granularity", granularity.get()); // } // // return getCandles(productId, queryParams); // } // // /** // * The granularity field must be one of the following values: {60, 300, 900, 3600, 21600, 86400} // */ // public Candles getCandles(String productId, Granularity granularity) { // return getCandles(productId, null, null, granularity); // } // // /** // * If either one of the start or end fields are not provided then both fields will be ignored. // */ // public Candles getCandles(String productId, Instant start, Instant end) { // return getCandles(productId, start, end, null); // } // } // Path: api/src/test/java/com/coinbase/exchange/api/orders/OrderIntegrationTest.java import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.accounts.Account; import com.coinbase.exchange.api.accounts.AccountService; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import com.coinbase.exchange.api.marketdata.MarketData; import com.coinbase.exchange.api.marketdata.MarketDataService; import com.coinbase.exchange.api.products.ProductService; import com.coinbase.exchange.model.Fill; import com.coinbase.exchange.model.NewLimitOrderSingle; import com.coinbase.exchange.model.NewMarketOrderSingle; import org.junit.Ignore; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; package com.coinbase.exchange.api.orders; /** * See class doc for BaseIntegrationTest * * Created by Ishmael (sakamura@gmail.com) on 6/18/2016. */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class}) public class OrderIntegrationTest extends BaseIntegrationTest { private static final Logger log = LoggerFactory.getLogger(OrderIntegrationTest.class);
ProductService productService;
irufus/gdax-java
api/src/test/java/com/coinbase/exchange/api/products/ProductsIntegrationTest.java
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // } // // Path: model/src/main/java/com/coinbase/exchange/model/Candles.java // public class Candles { // // List<Candle> candleList; // // public Candles(List<String[]> candles) { // this.candleList = candles.stream().map(Candle::new).collect(Collectors.toList()); // } // // public List<Candle> getCandleList() { // return candleList; // } // } // // Path: model/src/main/java/com/coinbase/exchange/model/Granularity.java // public enum Granularity { // ONE_DAY("1d"), // SIX_HOURS("6h"), // ONE_HOUR("1h"), // FIFTEEN_MIN("15m"), // FIVE_MIN("5m"), // ONE_MIN("1m"); // // private String granularity; // // Granularity(String granularity) { // this.granularity = granularity; // } // // /** // * The granularity field must be one of the following values: // * {60, 300, 900, 3600, 21600, 86400}. // */ // public String get(){ // switch(granularity) { // case "1d": return "86400"; // case "6h": return "21600"; // case "1h": return "3600"; // case "15m": return "900"; // case "5m": return "300"; // case "1m": return "60"; // } // return ""; // } // }
import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import com.coinbase.exchange.model.Candles; import com.coinbase.exchange.model.Granularity; import com.coinbase.exchange.model.Product; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue;
package com.coinbase.exchange.api.products; /** * See class doc for BaseIntegrationTest * <p> * Created by robevansuk on 08/02/2017. */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class})
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // } // // Path: model/src/main/java/com/coinbase/exchange/model/Candles.java // public class Candles { // // List<Candle> candleList; // // public Candles(List<String[]> candles) { // this.candleList = candles.stream().map(Candle::new).collect(Collectors.toList()); // } // // public List<Candle> getCandleList() { // return candleList; // } // } // // Path: model/src/main/java/com/coinbase/exchange/model/Granularity.java // public enum Granularity { // ONE_DAY("1d"), // SIX_HOURS("6h"), // ONE_HOUR("1h"), // FIFTEEN_MIN("15m"), // FIVE_MIN("5m"), // ONE_MIN("1m"); // // private String granularity; // // Granularity(String granularity) { // this.granularity = granularity; // } // // /** // * The granularity field must be one of the following values: // * {60, 300, 900, 3600, 21600, 86400}. // */ // public String get(){ // switch(granularity) { // case "1d": return "86400"; // case "6h": return "21600"; // case "1h": return "3600"; // case "15m": return "900"; // case "5m": return "300"; // case "1m": return "60"; // } // return ""; // } // } // Path: api/src/test/java/com/coinbase/exchange/api/products/ProductsIntegrationTest.java import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import com.coinbase.exchange.model.Candles; import com.coinbase.exchange.model.Granularity; import com.coinbase.exchange.model.Product; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; package com.coinbase.exchange.api.products; /** * See class doc for BaseIntegrationTest * <p> * Created by robevansuk on 08/02/2017. */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class})
public class ProductsIntegrationTest extends BaseIntegrationTest {
irufus/gdax-java
api/src/test/java/com/coinbase/exchange/api/products/ProductsIntegrationTest.java
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // } // // Path: model/src/main/java/com/coinbase/exchange/model/Candles.java // public class Candles { // // List<Candle> candleList; // // public Candles(List<String[]> candles) { // this.candleList = candles.stream().map(Candle::new).collect(Collectors.toList()); // } // // public List<Candle> getCandleList() { // return candleList; // } // } // // Path: model/src/main/java/com/coinbase/exchange/model/Granularity.java // public enum Granularity { // ONE_DAY("1d"), // SIX_HOURS("6h"), // ONE_HOUR("1h"), // FIFTEEN_MIN("15m"), // FIVE_MIN("5m"), // ONE_MIN("1m"); // // private String granularity; // // Granularity(String granularity) { // this.granularity = granularity; // } // // /** // * The granularity field must be one of the following values: // * {60, 300, 900, 3600, 21600, 86400}. // */ // public String get(){ // switch(granularity) { // case "1d": return "86400"; // case "6h": return "21600"; // case "1h": return "3600"; // case "15m": return "900"; // case "5m": return "300"; // case "1m": return "60"; // } // return ""; // } // }
import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import com.coinbase.exchange.model.Candles; import com.coinbase.exchange.model.Granularity; import com.coinbase.exchange.model.Product; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue;
package com.coinbase.exchange.api.products; /** * See class doc for BaseIntegrationTest * <p> * Created by robevansuk on 08/02/2017. */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class}) public class ProductsIntegrationTest extends BaseIntegrationTest { private static final String TEST_PRODUCT_ID = "BTC-GBP"; public static final int ONE_DAY_IN_SECONDS = 60 * 60 * 24; public static final int SIX_HOURS_IN_SECONDS = 60 * 60 * 6; public static final int ONE_HOUR_IN_SECONDS = 60 * 60; public static final int FIFTEEN_MINS_IN_SECONDS = 60 * 15; public static final int FIVE_MINS_IN_SECONDS = 60 * 5; public static final int ONE_MIN_IN_SECONDS = 60; private ProductService productService; @BeforeEach void setUp() { this.productService = new ProductService(exchange); } @Test public void canGetProducts() { List<Product> products = productService.getProducts(); products.forEach(item -> System.out.println(item.getId())); assertTrue(products.size() >= 0); } @Test void shouldGetCandles() {
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // } // // Path: model/src/main/java/com/coinbase/exchange/model/Candles.java // public class Candles { // // List<Candle> candleList; // // public Candles(List<String[]> candles) { // this.candleList = candles.stream().map(Candle::new).collect(Collectors.toList()); // } // // public List<Candle> getCandleList() { // return candleList; // } // } // // Path: model/src/main/java/com/coinbase/exchange/model/Granularity.java // public enum Granularity { // ONE_DAY("1d"), // SIX_HOURS("6h"), // ONE_HOUR("1h"), // FIFTEEN_MIN("15m"), // FIVE_MIN("5m"), // ONE_MIN("1m"); // // private String granularity; // // Granularity(String granularity) { // this.granularity = granularity; // } // // /** // * The granularity field must be one of the following values: // * {60, 300, 900, 3600, 21600, 86400}. // */ // public String get(){ // switch(granularity) { // case "1d": return "86400"; // case "6h": return "21600"; // case "1h": return "3600"; // case "15m": return "900"; // case "5m": return "300"; // case "1m": return "60"; // } // return ""; // } // } // Path: api/src/test/java/com/coinbase/exchange/api/products/ProductsIntegrationTest.java import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import com.coinbase.exchange.model.Candles; import com.coinbase.exchange.model.Granularity; import com.coinbase.exchange.model.Product; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; package com.coinbase.exchange.api.products; /** * See class doc for BaseIntegrationTest * <p> * Created by robevansuk on 08/02/2017. */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class}) public class ProductsIntegrationTest extends BaseIntegrationTest { private static final String TEST_PRODUCT_ID = "BTC-GBP"; public static final int ONE_DAY_IN_SECONDS = 60 * 60 * 24; public static final int SIX_HOURS_IN_SECONDS = 60 * 60 * 6; public static final int ONE_HOUR_IN_SECONDS = 60 * 60; public static final int FIFTEEN_MINS_IN_SECONDS = 60 * 15; public static final int FIVE_MINS_IN_SECONDS = 60 * 5; public static final int ONE_MIN_IN_SECONDS = 60; private ProductService productService; @BeforeEach void setUp() { this.productService = new ProductService(exchange); } @Test public void canGetProducts() { List<Product> products = productService.getProducts(); products.forEach(item -> System.out.println(item.getId())); assertTrue(products.size() >= 0); } @Test void shouldGetCandles() {
Candles candles = productService.getCandles(TEST_PRODUCT_ID);
irufus/gdax-java
api/src/test/java/com/coinbase/exchange/api/products/ProductsIntegrationTest.java
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // } // // Path: model/src/main/java/com/coinbase/exchange/model/Candles.java // public class Candles { // // List<Candle> candleList; // // public Candles(List<String[]> candles) { // this.candleList = candles.stream().map(Candle::new).collect(Collectors.toList()); // } // // public List<Candle> getCandleList() { // return candleList; // } // } // // Path: model/src/main/java/com/coinbase/exchange/model/Granularity.java // public enum Granularity { // ONE_DAY("1d"), // SIX_HOURS("6h"), // ONE_HOUR("1h"), // FIFTEEN_MIN("15m"), // FIVE_MIN("5m"), // ONE_MIN("1m"); // // private String granularity; // // Granularity(String granularity) { // this.granularity = granularity; // } // // /** // * The granularity field must be one of the following values: // * {60, 300, 900, 3600, 21600, 86400}. // */ // public String get(){ // switch(granularity) { // case "1d": return "86400"; // case "6h": return "21600"; // case "1h": return "3600"; // case "15m": return "900"; // case "5m": return "300"; // case "1m": return "60"; // } // return ""; // } // }
import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import com.coinbase.exchange.model.Candles; import com.coinbase.exchange.model.Granularity; import com.coinbase.exchange.model.Product; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue;
package com.coinbase.exchange.api.products; /** * See class doc for BaseIntegrationTest * <p> * Created by robevansuk on 08/02/2017. */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class}) public class ProductsIntegrationTest extends BaseIntegrationTest { private static final String TEST_PRODUCT_ID = "BTC-GBP"; public static final int ONE_DAY_IN_SECONDS = 60 * 60 * 24; public static final int SIX_HOURS_IN_SECONDS = 60 * 60 * 6; public static final int ONE_HOUR_IN_SECONDS = 60 * 60; public static final int FIFTEEN_MINS_IN_SECONDS = 60 * 15; public static final int FIVE_MINS_IN_SECONDS = 60 * 5; public static final int ONE_MIN_IN_SECONDS = 60; private ProductService productService; @BeforeEach void setUp() { this.productService = new ProductService(exchange); } @Test public void canGetProducts() { List<Product> products = productService.getProducts(); products.forEach(item -> System.out.println(item.getId())); assertTrue(products.size() >= 0); } @Test void shouldGetCandles() { Candles candles = productService.getCandles(TEST_PRODUCT_ID); assertEquals(300, candles.getCandleList().size()); } @Test void shouldGetCandlesForAGanularityOf_OneDay() {
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // } // // Path: model/src/main/java/com/coinbase/exchange/model/Candles.java // public class Candles { // // List<Candle> candleList; // // public Candles(List<String[]> candles) { // this.candleList = candles.stream().map(Candle::new).collect(Collectors.toList()); // } // // public List<Candle> getCandleList() { // return candleList; // } // } // // Path: model/src/main/java/com/coinbase/exchange/model/Granularity.java // public enum Granularity { // ONE_DAY("1d"), // SIX_HOURS("6h"), // ONE_HOUR("1h"), // FIFTEEN_MIN("15m"), // FIVE_MIN("5m"), // ONE_MIN("1m"); // // private String granularity; // // Granularity(String granularity) { // this.granularity = granularity; // } // // /** // * The granularity field must be one of the following values: // * {60, 300, 900, 3600, 21600, 86400}. // */ // public String get(){ // switch(granularity) { // case "1d": return "86400"; // case "6h": return "21600"; // case "1h": return "3600"; // case "15m": return "900"; // case "5m": return "300"; // case "1m": return "60"; // } // return ""; // } // } // Path: api/src/test/java/com/coinbase/exchange/api/products/ProductsIntegrationTest.java import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import com.coinbase.exchange.model.Candles; import com.coinbase.exchange.model.Granularity; import com.coinbase.exchange.model.Product; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; package com.coinbase.exchange.api.products; /** * See class doc for BaseIntegrationTest * <p> * Created by robevansuk on 08/02/2017. */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class}) public class ProductsIntegrationTest extends BaseIntegrationTest { private static final String TEST_PRODUCT_ID = "BTC-GBP"; public static final int ONE_DAY_IN_SECONDS = 60 * 60 * 24; public static final int SIX_HOURS_IN_SECONDS = 60 * 60 * 6; public static final int ONE_HOUR_IN_SECONDS = 60 * 60; public static final int FIFTEEN_MINS_IN_SECONDS = 60 * 15; public static final int FIVE_MINS_IN_SECONDS = 60 * 5; public static final int ONE_MIN_IN_SECONDS = 60; private ProductService productService; @BeforeEach void setUp() { this.productService = new ProductService(exchange); } @Test public void canGetProducts() { List<Product> products = productService.getProducts(); products.forEach(item -> System.out.println(item.getId())); assertTrue(products.size() >= 0); } @Test void shouldGetCandles() { Candles candles = productService.getCandles(TEST_PRODUCT_ID); assertEquals(300, candles.getCandleList().size()); } @Test void shouldGetCandlesForAGanularityOf_OneDay() {
Candles candles = productService.getCandles(TEST_PRODUCT_ID, Granularity.ONE_DAY);
irufus/gdax-java
api/src/test/java/com/coinbase/exchange/api/authentication/AuthenticationIntegrationIntegrationTest.java
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // }
import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.accounts.Account; import com.coinbase.exchange.api.accounts.AccountService; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.List; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue;
package com.coinbase.exchange.api.authentication; /** * See class doc for BaseIntegrationTest * * Created by irufus (sakamura@gmail.com) * @Description The primary function of this class is to run through basic tests for the Authentication and GdaxExchange classes */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class})
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // } // Path: api/src/test/java/com/coinbase/exchange/api/authentication/AuthenticationIntegrationIntegrationTest.java import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.accounts.Account; import com.coinbase.exchange.api.accounts.AccountService; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.List; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; package com.coinbase.exchange.api.authentication; /** * See class doc for BaseIntegrationTest * * Created by irufus (sakamura@gmail.com) * @Description The primary function of this class is to run through basic tests for the Authentication and GdaxExchange classes */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class})
public class AuthenticationIntegrationIntegrationTest extends BaseIntegrationTest {
irufus/gdax-java
api/src/main/java/com/coinbase/exchange/api/accounts/AccountHistory.java
// Path: model/src/main/java/com/coinbase/exchange/model/Detail.java // public class Detail { // private String order_id; // private Integer trade_id; // private String product_id; // // public String getOrder_id() { // return order_id; // } // // public void setOrder_id(String order_id) { // this.order_id = order_id; // } // // public Integer getTrade_id() { // return trade_id; // } // // public void setTrade_id(Integer trade_id) { // this.trade_id = trade_id; // } // // public String getProduct_id() { // return product_id; // } // // public void setProduct_id(String product_id) { // this.product_id = product_id; // } // }
import com.coinbase.exchange.model.Detail; import java.math.BigDecimal;
package com.coinbase.exchange.api.accounts; /** * Created by irufus on 2/18/15. */ public class AccountHistory { private Integer id; private String created_at; private BigDecimal amount; private BigDecimal balance; private String type;
// Path: model/src/main/java/com/coinbase/exchange/model/Detail.java // public class Detail { // private String order_id; // private Integer trade_id; // private String product_id; // // public String getOrder_id() { // return order_id; // } // // public void setOrder_id(String order_id) { // this.order_id = order_id; // } // // public Integer getTrade_id() { // return trade_id; // } // // public void setTrade_id(Integer trade_id) { // this.trade_id = trade_id; // } // // public String getProduct_id() { // return product_id; // } // // public void setProduct_id(String product_id) { // this.product_id = product_id; // } // } // Path: api/src/main/java/com/coinbase/exchange/api/accounts/AccountHistory.java import com.coinbase.exchange.model.Detail; import java.math.BigDecimal; package com.coinbase.exchange.api.accounts; /** * Created by irufus on 2/18/15. */ public class AccountHistory { private Integer id; private String created_at; private BigDecimal amount; private BigDecimal balance; private String type;
private Detail detail;
irufus/gdax-java
api/src/test/java/com/coinbase/exchange/api/transfers/TransferServiceIntegrationTest.java
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // }
import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import org.junit.Ignore; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension;
package com.coinbase.exchange.api.transfers; /** * See class doc for BaseIntegrationTest * * Created by robevansuk on 15/02/2017. */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class})
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // } // Path: api/src/test/java/com/coinbase/exchange/api/transfers/TransferServiceIntegrationTest.java import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import org.junit.Ignore; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; package com.coinbase.exchange.api.transfers; /** * See class doc for BaseIntegrationTest * * Created by robevansuk on 15/02/2017. */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class})
public class TransferServiceIntegrationTest extends BaseIntegrationTest {
irufus/gdax-java
api/src/test/java/com/coinbase/exchange/api/payments/PaymentIntegrationTest.java
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // }
import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.List; import static org.junit.jupiter.api.Assertions.assertTrue;
package com.coinbase.exchange.api.payments; @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class})
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // } // Path: api/src/test/java/com/coinbase/exchange/api/payments/PaymentIntegrationTest.java import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.List; import static org.junit.jupiter.api.Assertions.assertTrue; package com.coinbase.exchange.api.payments; @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class})
public class PaymentIntegrationTest extends BaseIntegrationTest {
irufus/gdax-java
api/src/test/java/com/coinbase/exchange/api/accounts/DepositIntegrationTest.java
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // }
import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import com.coinbase.exchange.api.deposits.DepositService; import com.coinbase.exchange.api.payments.CoinbaseAccount; import com.coinbase.exchange.api.payments.PaymentService; import com.coinbase.exchange.model.PaymentResponse; import org.junit.Ignore; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.math.BigDecimal; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue;
package com.coinbase.exchange.api.accounts; /** * See class doc for BaseIntegrationTest */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class}) @Ignore
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // } // Path: api/src/test/java/com/coinbase/exchange/api/accounts/DepositIntegrationTest.java import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import com.coinbase.exchange.api.deposits.DepositService; import com.coinbase.exchange.api.payments.CoinbaseAccount; import com.coinbase.exchange.api.payments.PaymentService; import com.coinbase.exchange.model.PaymentResponse; import org.junit.Ignore; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.math.BigDecimal; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; package com.coinbase.exchange.api.accounts; /** * See class doc for BaseIntegrationTest */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class}) @Ignore
public class DepositIntegrationTest extends BaseIntegrationTest {
irufus/gdax-java
api/src/test/java/com/coinbase/exchange/api/marketdata/MarketDataIntegrationTest.java
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // } // // Path: api/src/main/java/com/coinbase/exchange/api/products/ProductService.java // public class ProductService { // // public static final String PRODUCTS_ENDPOINT = "/products"; // // final CoinbaseExchange exchange; // // public ProductService(final CoinbaseExchange exchange) { // this.exchange = exchange; // } // // // no paged products necessary // public List<Product> getProducts() { // return exchange.getAsList(PRODUCTS_ENDPOINT, new ParameterizedTypeReference<Product[]>() { // }); // } // // public Candles getCandles(String productId) { // return new Candles(exchange.get(PRODUCTS_ENDPOINT + "/" + productId + "/candles", new ParameterizedTypeReference<List<String[]>>() { // })); // } // // public Candles getCandles(String productId, Map<String, String> queryParams) { // StringBuffer url = new StringBuffer(PRODUCTS_ENDPOINT + "/" + productId + "/candles"); // if (queryParams != null && queryParams.size() != 0) { // url.append("?"); // url.append(queryParams.entrySet().stream() // .map(entry -> entry.getKey() + "=" + entry.getValue()) // .collect(joining("&"))); // } // return new Candles(exchange.get(url.toString(), new ParameterizedTypeReference<List<String[]>>() {})); // } // // /** // * If either one of the start or end fields are not provided then both fields will be ignored. // * If a custom time range is not declared then one ending now is selected. // */ // public Candles getCandles(String productId, Instant startTime, Instant endTime, Granularity granularity) { // // Map<String, String> queryParams = new HashMap<>(); // // if (startTime != null) { // queryParams.put("start", startTime.toString()); // } // if (endTime != null) { // queryParams.put("end", endTime.toString()); // } // if (granularity != null) { // queryParams.put("granularity", granularity.get()); // } // // return getCandles(productId, queryParams); // } // // /** // * The granularity field must be one of the following values: {60, 300, 900, 3600, 21600, 86400} // */ // public Candles getCandles(String productId, Granularity granularity) { // return getCandles(productId, null, null, granularity); // } // // /** // * If either one of the start or end fields are not provided then both fields will be ignored. // */ // public Candles getCandles(String productId, Instant start, Instant end) { // return getCandles(productId, start, end, null); // } // }
import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import com.coinbase.exchange.api.products.ProductService; import com.coinbase.exchange.model.Product; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.List; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue;
package com.coinbase.exchange.api.marketdata; /** * See class doc for BaseIntegrationTest * * Created by robevansuk on 14/02/2017. */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class})
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // } // // Path: api/src/main/java/com/coinbase/exchange/api/products/ProductService.java // public class ProductService { // // public static final String PRODUCTS_ENDPOINT = "/products"; // // final CoinbaseExchange exchange; // // public ProductService(final CoinbaseExchange exchange) { // this.exchange = exchange; // } // // // no paged products necessary // public List<Product> getProducts() { // return exchange.getAsList(PRODUCTS_ENDPOINT, new ParameterizedTypeReference<Product[]>() { // }); // } // // public Candles getCandles(String productId) { // return new Candles(exchange.get(PRODUCTS_ENDPOINT + "/" + productId + "/candles", new ParameterizedTypeReference<List<String[]>>() { // })); // } // // public Candles getCandles(String productId, Map<String, String> queryParams) { // StringBuffer url = new StringBuffer(PRODUCTS_ENDPOINT + "/" + productId + "/candles"); // if (queryParams != null && queryParams.size() != 0) { // url.append("?"); // url.append(queryParams.entrySet().stream() // .map(entry -> entry.getKey() + "=" + entry.getValue()) // .collect(joining("&"))); // } // return new Candles(exchange.get(url.toString(), new ParameterizedTypeReference<List<String[]>>() {})); // } // // /** // * If either one of the start or end fields are not provided then both fields will be ignored. // * If a custom time range is not declared then one ending now is selected. // */ // public Candles getCandles(String productId, Instant startTime, Instant endTime, Granularity granularity) { // // Map<String, String> queryParams = new HashMap<>(); // // if (startTime != null) { // queryParams.put("start", startTime.toString()); // } // if (endTime != null) { // queryParams.put("end", endTime.toString()); // } // if (granularity != null) { // queryParams.put("granularity", granularity.get()); // } // // return getCandles(productId, queryParams); // } // // /** // * The granularity field must be one of the following values: {60, 300, 900, 3600, 21600, 86400} // */ // public Candles getCandles(String productId, Granularity granularity) { // return getCandles(productId, null, null, granularity); // } // // /** // * If either one of the start or end fields are not provided then both fields will be ignored. // */ // public Candles getCandles(String productId, Instant start, Instant end) { // return getCandles(productId, start, end, null); // } // } // Path: api/src/test/java/com/coinbase/exchange/api/marketdata/MarketDataIntegrationTest.java import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import com.coinbase.exchange.api.products.ProductService; import com.coinbase.exchange.model.Product; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.List; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; package com.coinbase.exchange.api.marketdata; /** * See class doc for BaseIntegrationTest * * Created by robevansuk on 14/02/2017. */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class})
public class MarketDataIntegrationTest extends BaseIntegrationTest {
irufus/gdax-java
api/src/test/java/com/coinbase/exchange/api/marketdata/MarketDataIntegrationTest.java
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // } // // Path: api/src/main/java/com/coinbase/exchange/api/products/ProductService.java // public class ProductService { // // public static final String PRODUCTS_ENDPOINT = "/products"; // // final CoinbaseExchange exchange; // // public ProductService(final CoinbaseExchange exchange) { // this.exchange = exchange; // } // // // no paged products necessary // public List<Product> getProducts() { // return exchange.getAsList(PRODUCTS_ENDPOINT, new ParameterizedTypeReference<Product[]>() { // }); // } // // public Candles getCandles(String productId) { // return new Candles(exchange.get(PRODUCTS_ENDPOINT + "/" + productId + "/candles", new ParameterizedTypeReference<List<String[]>>() { // })); // } // // public Candles getCandles(String productId, Map<String, String> queryParams) { // StringBuffer url = new StringBuffer(PRODUCTS_ENDPOINT + "/" + productId + "/candles"); // if (queryParams != null && queryParams.size() != 0) { // url.append("?"); // url.append(queryParams.entrySet().stream() // .map(entry -> entry.getKey() + "=" + entry.getValue()) // .collect(joining("&"))); // } // return new Candles(exchange.get(url.toString(), new ParameterizedTypeReference<List<String[]>>() {})); // } // // /** // * If either one of the start or end fields are not provided then both fields will be ignored. // * If a custom time range is not declared then one ending now is selected. // */ // public Candles getCandles(String productId, Instant startTime, Instant endTime, Granularity granularity) { // // Map<String, String> queryParams = new HashMap<>(); // // if (startTime != null) { // queryParams.put("start", startTime.toString()); // } // if (endTime != null) { // queryParams.put("end", endTime.toString()); // } // if (granularity != null) { // queryParams.put("granularity", granularity.get()); // } // // return getCandles(productId, queryParams); // } // // /** // * The granularity field must be one of the following values: {60, 300, 900, 3600, 21600, 86400} // */ // public Candles getCandles(String productId, Granularity granularity) { // return getCandles(productId, null, null, granularity); // } // // /** // * If either one of the start or end fields are not provided then both fields will be ignored. // */ // public Candles getCandles(String productId, Instant start, Instant end) { // return getCandles(productId, start, end, null); // } // }
import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import com.coinbase.exchange.api.products.ProductService; import com.coinbase.exchange.model.Product; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.List; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue;
package com.coinbase.exchange.api.marketdata; /** * See class doc for BaseIntegrationTest * * Created by robevansuk on 14/02/2017. */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class}) public class MarketDataIntegrationTest extends BaseIntegrationTest {
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // } // // Path: api/src/main/java/com/coinbase/exchange/api/products/ProductService.java // public class ProductService { // // public static final String PRODUCTS_ENDPOINT = "/products"; // // final CoinbaseExchange exchange; // // public ProductService(final CoinbaseExchange exchange) { // this.exchange = exchange; // } // // // no paged products necessary // public List<Product> getProducts() { // return exchange.getAsList(PRODUCTS_ENDPOINT, new ParameterizedTypeReference<Product[]>() { // }); // } // // public Candles getCandles(String productId) { // return new Candles(exchange.get(PRODUCTS_ENDPOINT + "/" + productId + "/candles", new ParameterizedTypeReference<List<String[]>>() { // })); // } // // public Candles getCandles(String productId, Map<String, String> queryParams) { // StringBuffer url = new StringBuffer(PRODUCTS_ENDPOINT + "/" + productId + "/candles"); // if (queryParams != null && queryParams.size() != 0) { // url.append("?"); // url.append(queryParams.entrySet().stream() // .map(entry -> entry.getKey() + "=" + entry.getValue()) // .collect(joining("&"))); // } // return new Candles(exchange.get(url.toString(), new ParameterizedTypeReference<List<String[]>>() {})); // } // // /** // * If either one of the start or end fields are not provided then both fields will be ignored. // * If a custom time range is not declared then one ending now is selected. // */ // public Candles getCandles(String productId, Instant startTime, Instant endTime, Granularity granularity) { // // Map<String, String> queryParams = new HashMap<>(); // // if (startTime != null) { // queryParams.put("start", startTime.toString()); // } // if (endTime != null) { // queryParams.put("end", endTime.toString()); // } // if (granularity != null) { // queryParams.put("granularity", granularity.get()); // } // // return getCandles(productId, queryParams); // } // // /** // * The granularity field must be one of the following values: {60, 300, 900, 3600, 21600, 86400} // */ // public Candles getCandles(String productId, Granularity granularity) { // return getCandles(productId, null, null, granularity); // } // // /** // * If either one of the start or end fields are not provided then both fields will be ignored. // */ // public Candles getCandles(String productId, Instant start, Instant end) { // return getCandles(productId, start, end, null); // } // } // Path: api/src/test/java/com/coinbase/exchange/api/marketdata/MarketDataIntegrationTest.java import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import com.coinbase.exchange.api.products.ProductService; import com.coinbase.exchange.model.Product; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.List; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; package com.coinbase.exchange.api.marketdata; /** * See class doc for BaseIntegrationTest * * Created by robevansuk on 14/02/2017. */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class}) public class MarketDataIntegrationTest extends BaseIntegrationTest {
ProductService productService;
irufus/gdax-java
api/src/test/java/com/coinbase/exchange/api/accounts/UserAccountServiceIntegrationTest.java
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // } // // Path: api/src/main/java/com/coinbase/exchange/api/useraccount/UserAccountData.java // public class UserAccountData { // // String product_id; // BigDecimal exchange_volume; // BigDecimal volume; // String recorded_at; // // public UserAccountData() {} // // public UserAccountData(String product_id, BigDecimal exchange_volume, BigDecimal volume, String recorded_at) { // this.product_id = product_id; // this.exchange_volume = exchange_volume; // this.volume = volume; // this.recorded_at = recorded_at; // } // // public String getProduct_id() { // return product_id; // } // // public void setProduct_id(String product_id) { // this.product_id = product_id; // } // // public BigDecimal getExchange_volume() { // return exchange_volume; // } // // public void setExchange_volume(BigDecimal exchange_volume) { // this.exchange_volume = exchange_volume; // } // // public BigDecimal getVolume() { // return volume; // } // // public void setVolume(BigDecimal volume) { // this.volume = volume; // } // // public String getRecorded_at() { // return recorded_at; // } // // public void setRecorded_at(String recorded_at) { // this.recorded_at = recorded_at; // } // }
import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import com.coinbase.exchange.api.useraccount.UserAccountData; import com.coinbase.exchange.api.useraccount.UserAccountService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.List; import static org.junit.jupiter.api.Assertions.assertNotNull;
package com.coinbase.exchange.api.accounts; /** * See class doc for BaseIntegrationTest */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class})
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // } // // Path: api/src/main/java/com/coinbase/exchange/api/useraccount/UserAccountData.java // public class UserAccountData { // // String product_id; // BigDecimal exchange_volume; // BigDecimal volume; // String recorded_at; // // public UserAccountData() {} // // public UserAccountData(String product_id, BigDecimal exchange_volume, BigDecimal volume, String recorded_at) { // this.product_id = product_id; // this.exchange_volume = exchange_volume; // this.volume = volume; // this.recorded_at = recorded_at; // } // // public String getProduct_id() { // return product_id; // } // // public void setProduct_id(String product_id) { // this.product_id = product_id; // } // // public BigDecimal getExchange_volume() { // return exchange_volume; // } // // public void setExchange_volume(BigDecimal exchange_volume) { // this.exchange_volume = exchange_volume; // } // // public BigDecimal getVolume() { // return volume; // } // // public void setVolume(BigDecimal volume) { // this.volume = volume; // } // // public String getRecorded_at() { // return recorded_at; // } // // public void setRecorded_at(String recorded_at) { // this.recorded_at = recorded_at; // } // } // Path: api/src/test/java/com/coinbase/exchange/api/accounts/UserAccountServiceIntegrationTest.java import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import com.coinbase.exchange.api.useraccount.UserAccountData; import com.coinbase.exchange.api.useraccount.UserAccountService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.List; import static org.junit.jupiter.api.Assertions.assertNotNull; package com.coinbase.exchange.api.accounts; /** * See class doc for BaseIntegrationTest */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class})
public class UserAccountServiceIntegrationTest extends BaseIntegrationTest {
irufus/gdax-java
api/src/test/java/com/coinbase/exchange/api/accounts/UserAccountServiceIntegrationTest.java
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // } // // Path: api/src/main/java/com/coinbase/exchange/api/useraccount/UserAccountData.java // public class UserAccountData { // // String product_id; // BigDecimal exchange_volume; // BigDecimal volume; // String recorded_at; // // public UserAccountData() {} // // public UserAccountData(String product_id, BigDecimal exchange_volume, BigDecimal volume, String recorded_at) { // this.product_id = product_id; // this.exchange_volume = exchange_volume; // this.volume = volume; // this.recorded_at = recorded_at; // } // // public String getProduct_id() { // return product_id; // } // // public void setProduct_id(String product_id) { // this.product_id = product_id; // } // // public BigDecimal getExchange_volume() { // return exchange_volume; // } // // public void setExchange_volume(BigDecimal exchange_volume) { // this.exchange_volume = exchange_volume; // } // // public BigDecimal getVolume() { // return volume; // } // // public void setVolume(BigDecimal volume) { // this.volume = volume; // } // // public String getRecorded_at() { // return recorded_at; // } // // public void setRecorded_at(String recorded_at) { // this.recorded_at = recorded_at; // } // }
import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import com.coinbase.exchange.api.useraccount.UserAccountData; import com.coinbase.exchange.api.useraccount.UserAccountService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.List; import static org.junit.jupiter.api.Assertions.assertNotNull;
package com.coinbase.exchange.api.accounts; /** * See class doc for BaseIntegrationTest */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class}) public class UserAccountServiceIntegrationTest extends BaseIntegrationTest { UserAccountService userAccountService; @BeforeEach void setUp() { this.userAccountService = new UserAccountService(exchange); } /** * Trailing volume could be empty so all we have to do is make sure it's not returning null */ @Test public void getTrailingVolume(){
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // } // // Path: api/src/main/java/com/coinbase/exchange/api/useraccount/UserAccountData.java // public class UserAccountData { // // String product_id; // BigDecimal exchange_volume; // BigDecimal volume; // String recorded_at; // // public UserAccountData() {} // // public UserAccountData(String product_id, BigDecimal exchange_volume, BigDecimal volume, String recorded_at) { // this.product_id = product_id; // this.exchange_volume = exchange_volume; // this.volume = volume; // this.recorded_at = recorded_at; // } // // public String getProduct_id() { // return product_id; // } // // public void setProduct_id(String product_id) { // this.product_id = product_id; // } // // public BigDecimal getExchange_volume() { // return exchange_volume; // } // // public void setExchange_volume(BigDecimal exchange_volume) { // this.exchange_volume = exchange_volume; // } // // public BigDecimal getVolume() { // return volume; // } // // public void setVolume(BigDecimal volume) { // this.volume = volume; // } // // public String getRecorded_at() { // return recorded_at; // } // // public void setRecorded_at(String recorded_at) { // this.recorded_at = recorded_at; // } // } // Path: api/src/test/java/com/coinbase/exchange/api/accounts/UserAccountServiceIntegrationTest.java import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import com.coinbase.exchange.api.useraccount.UserAccountData; import com.coinbase.exchange.api.useraccount.UserAccountService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.List; import static org.junit.jupiter.api.Assertions.assertNotNull; package com.coinbase.exchange.api.accounts; /** * See class doc for BaseIntegrationTest */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class}) public class UserAccountServiceIntegrationTest extends BaseIntegrationTest { UserAccountService userAccountService; @BeforeEach void setUp() { this.userAccountService = new UserAccountService(exchange); } /** * Trailing volume could be empty so all we have to do is make sure it's not returning null */ @Test public void getTrailingVolume(){
List<UserAccountData> data = userAccountService.getTrailingVolume();
irufus/gdax-java
api/src/test/java/com/coinbase/exchange/api/accounts/WithdrawalIntegrationTest.java
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // }
import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import com.coinbase.exchange.api.payments.CoinbaseAccount; import com.coinbase.exchange.api.payments.PaymentService; import com.coinbase.exchange.api.payments.PaymentType; import com.coinbase.exchange.api.withdrawals.WithdrawalsService; import com.coinbase.exchange.model.PaymentResponse; import org.junit.Ignore; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.math.BigDecimal; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue;
package com.coinbase.exchange.api.accounts; /** * See class doc for BaseIntegrationTest */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class}) @Ignore
// Path: api/src/test/java/com/coinbase/exchange/api/BaseIntegrationTest.java // @SpringBootTest(properties = { // "spring.profiles.active=test" // }) // public abstract class BaseIntegrationTest { // // @Autowired // public CoinbaseExchange exchange; // } // // Path: api/src/test/java/com/coinbase/exchange/api/config/IntegrationTestConfiguration.java // @SpringBootConfiguration // public class IntegrationTestConfiguration { // // @Bean // public ObjectMapper objectMapper() { // return new ObjectMapper().registerModule(new JavaTimeModule()); // } // // @Bean // public CoinbaseExchange coinbaseExchange(@Value("${exchange.key}") String apiKey, // @Value("${exchange.passphrase}") String passphrase, // @Value("${exchange.api.baseUrl}") String baseUrl, // @Value("${exchange.secret}") String secretKey, // ObjectMapper objectMapper) { // return new CoinbaseExchangeImpl(apiKey, // passphrase, // baseUrl, // new Signature(secretKey), // objectMapper); // } // // } // Path: api/src/test/java/com/coinbase/exchange/api/accounts/WithdrawalIntegrationTest.java import com.coinbase.exchange.api.BaseIntegrationTest; import com.coinbase.exchange.api.config.IntegrationTestConfiguration; import com.coinbase.exchange.api.payments.CoinbaseAccount; import com.coinbase.exchange.api.payments.PaymentService; import com.coinbase.exchange.api.payments.PaymentType; import com.coinbase.exchange.api.withdrawals.WithdrawalsService; import com.coinbase.exchange.model.PaymentResponse; import org.junit.Ignore; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.math.BigDecimal; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; package com.coinbase.exchange.api.accounts; /** * See class doc for BaseIntegrationTest */ @ExtendWith(SpringExtension.class) @Import({IntegrationTestConfiguration.class}) @Ignore
public class WithdrawalIntegrationTest extends BaseIntegrationTest {
ZerothAngel/ToHPluginUtils
src/main/java/org/tyrannyofheaven/bukkit/util/command/OptionMetaData.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // }
import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import java.util.Arrays;
/* * Copyright 2011 ZerothAngel <zerothangel@tyrannyofheaven.org> * * 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 org.tyrannyofheaven.bukkit.util.command; /** * Metadata for mapped parameters. * * @author zerothangel */ final class OptionMetaData implements MethodParameter { private static final String DEFAULT_VALUE_NAME = "value"; private final String[] names; private final String valueName; private final Class<?> type; private final boolean optional; private final boolean nullable; private final String completer; /** * Create an OptionMetaData. * * @param names the name of the mapping along with any aliases * @param type the parameter type * @param optional true if optional */ public OptionMetaData(String[] names, String valueName, Class<?> type, boolean optional, boolean nullable, String completer) { if (names == null || names.length == 0) throw new IllegalArgumentException("names must be given");
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // } // Path: src/main/java/org/tyrannyofheaven/bukkit/util/command/OptionMetaData.java import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import java.util.Arrays; /* * Copyright 2011 ZerothAngel <zerothangel@tyrannyofheaven.org> * * 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 org.tyrannyofheaven.bukkit.util.command; /** * Metadata for mapped parameters. * * @author zerothangel */ final class OptionMetaData implements MethodParameter { private static final String DEFAULT_VALUE_NAME = "value"; private final String[] names; private final String valueName; private final Class<?> type; private final boolean optional; private final boolean nullable; private final String completer; /** * Create an OptionMetaData. * * @param names the name of the mapping along with any aliases * @param type the parameter type * @param optional true if optional */ public OptionMetaData(String[] names, String valueName, Class<?> type, boolean optional, boolean nullable, String completer) { if (names == null || names.length == 0) throw new IllegalArgumentException("names must be given");
if (!hasText(valueName))
ZerothAngel/ToHPluginUtils
src/test/java/org/tyrannyofheaven/bukkit/util/command/MyHandler.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/command/ParseException.java // public class ParseException extends CommandException { // // private static final long serialVersionUID = 6379096495842869497L; // // public ParseException() { // } // // public ParseException(String message) { // super(message); // } // // public ParseException(String format, Object... args) { // super(format, args); // } // // }
import org.bukkit.command.CommandSender; import org.tyrannyofheaven.bukkit.util.command.Command; import org.tyrannyofheaven.bukkit.util.command.Option; import org.tyrannyofheaven.bukkit.util.command.ParseException; import org.tyrannyofheaven.bukkit.util.command.Require;
/* * Copyright 2011 ZerothAngel <zerothangel@tyrannyofheaven.org> * * 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 org.tyrannyofheaven.bukkit.util.command; public class MyHandler { private final FooHandler fooHandler = new FooHandler(); private final BarHandler barHandler = new BarHandler(); @Command({"hello", "greetings"}) public void hello(CommandSender sender, @Option("-f") boolean flag) { sender.sendMessage("Hello World!"); if (flag) sender.sendMessage("With flag!"); } @Command("greet") public void greet(CommandSender sender, @Option(value="name", completer="myCompleter") String name, @Option("-o") String opt, String[] args) { sender.sendMessage("Hello, " + name); if (opt != null) sender.sendMessage("With option = " + opt + "!"); } @Command(value="say", completer="myCompleter") public void say(CommandSender sender, String[] args) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < args.length; i++) { sb.append(args[i]); if (i < (args.length - 1)) sb.append(' '); } sender.sendMessage(sb.toString()); } @Command("foo") public FooHandler foo(String[] args) { if (args.length == 0)
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/command/ParseException.java // public class ParseException extends CommandException { // // private static final long serialVersionUID = 6379096495842869497L; // // public ParseException() { // } // // public ParseException(String message) { // super(message); // } // // public ParseException(String format, Object... args) { // super(format, args); // } // // } // Path: src/test/java/org/tyrannyofheaven/bukkit/util/command/MyHandler.java import org.bukkit.command.CommandSender; import org.tyrannyofheaven.bukkit.util.command.Command; import org.tyrannyofheaven.bukkit.util.command.Option; import org.tyrannyofheaven.bukkit.util.command.ParseException; import org.tyrannyofheaven.bukkit.util.command.Require; /* * Copyright 2011 ZerothAngel <zerothangel@tyrannyofheaven.org> * * 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 org.tyrannyofheaven.bukkit.util.command; public class MyHandler { private final FooHandler fooHandler = new FooHandler(); private final BarHandler barHandler = new BarHandler(); @Command({"hello", "greetings"}) public void hello(CommandSender sender, @Option("-f") boolean flag) { sender.sendMessage("Hello World!"); if (flag) sender.sendMessage("With flag!"); } @Command("greet") public void greet(CommandSender sender, @Option(value="name", completer="myCompleter") String name, @Option("-o") String opt, String[] args) { sender.sendMessage("Hello, " + name); if (opt != null) sender.sendMessage("With option = " + opt + "!"); } @Command(value="say", completer="myCompleter") public void say(CommandSender sender, String[] args) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < args.length; i++) { sb.append(args[i]); if (i < (args.length - 1)) sb.append(' '); } sender.sendMessage(sb.toString()); } @Command("foo") public FooHandler foo(String[] args) { if (args.length == 0)
throw new ParseException("Missing sub-command");
ZerothAngel/ToHPluginUtils
src/test/java/org/tyrannyofheaven/bukkit/util/ToHUtilsTest.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static String delimitedString(String delimiter, Collection<?> coll) { // StringBuilder sb = new StringBuilder(); // for (Iterator<?> i = coll.iterator(); i.hasNext();) { // sb.append(i.next()); // if (i.hasNext()) // sb.append(delimiter); // } // return sb.toString(); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static String colorize(String text) { // if (text == null) return null; // // // Works best with interned strings // String cacheResult = colorizeCache.get(text); // if (cacheResult != null) return cacheResult; // // StringBuilder out = new StringBuilder(); // // ColorizeState state = ColorizeState.TEXT; // StringBuilder color = null; // // for (int i = 0; i < text.length(); i++) { // char c = text.charAt(i); // // if (state == ColorizeState.TEXT) { // if (c == '{') { // state = ColorizeState.COLOR_OPEN; // } // else if (c == '}') { // state = ColorizeState.COLOR_CLOSE; // } // else if (c == '`') { // state = ColorizeState.COLOR_ESCAPE; // } // else { // out.append(c); // } // } // else if (state == ColorizeState.COLOR_OPEN) { // if (c == '{') { // Escaped bracket // out.append('{'); // state = ColorizeState.TEXT; // } // else if (Character.isUpperCase(c)) { // // First character of color name // color = new StringBuilder(); // color.append(c); // state = ColorizeState.COLOR_NAME; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_NAME) { // if (Character.isUpperCase(c) || c == '_') { // color.append(c); // } // else if (c == '}') { // ChatColor chatColor = ChatColor.valueOf(color.toString()); // out.append(chatColor); // state = ColorizeState.TEXT; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_CLOSE) { // // Optional, but for sanity's sake, to keep brackets matched // if (c == '}') { // out.append('}'); // Collapse to single bracket // } // else { // out.append('}'); // out.append(c); // } // state = ColorizeState.TEXT; // } // else if (state == ColorizeState.COLOR_ESCAPE) { // out.append(decodeColor(c)); // state = ColorizeState.TEXT; // } // else // throw new AssertionError("Unknown ColorizeState"); // } // // // End of string // if (state == ColorizeState.COLOR_CLOSE) { // out.append('}'); // } // else if (state != ColorizeState.TEXT) { // // Was in the middle of color name // throw new IllegalArgumentException("Invalid color name"); // } // // cacheResult = out.toString(); // colorizeCache.putIfAbsent(text, cacheResult); // // return cacheResult; // }
import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.fail; import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.delimitedString; import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.colorize; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.bukkit.ChatColor; import org.junit.Test;
/* * Copyright 2011 ZerothAngel <zerothangel@tyrannyofheaven.org> * * 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 org.tyrannyofheaven.bukkit.util; public class ToHUtilsTest { @Test public void testColorizeBasics() { // null
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static String delimitedString(String delimiter, Collection<?> coll) { // StringBuilder sb = new StringBuilder(); // for (Iterator<?> i = coll.iterator(); i.hasNext();) { // sb.append(i.next()); // if (i.hasNext()) // sb.append(delimiter); // } // return sb.toString(); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static String colorize(String text) { // if (text == null) return null; // // // Works best with interned strings // String cacheResult = colorizeCache.get(text); // if (cacheResult != null) return cacheResult; // // StringBuilder out = new StringBuilder(); // // ColorizeState state = ColorizeState.TEXT; // StringBuilder color = null; // // for (int i = 0; i < text.length(); i++) { // char c = text.charAt(i); // // if (state == ColorizeState.TEXT) { // if (c == '{') { // state = ColorizeState.COLOR_OPEN; // } // else if (c == '}') { // state = ColorizeState.COLOR_CLOSE; // } // else if (c == '`') { // state = ColorizeState.COLOR_ESCAPE; // } // else { // out.append(c); // } // } // else if (state == ColorizeState.COLOR_OPEN) { // if (c == '{') { // Escaped bracket // out.append('{'); // state = ColorizeState.TEXT; // } // else if (Character.isUpperCase(c)) { // // First character of color name // color = new StringBuilder(); // color.append(c); // state = ColorizeState.COLOR_NAME; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_NAME) { // if (Character.isUpperCase(c) || c == '_') { // color.append(c); // } // else if (c == '}') { // ChatColor chatColor = ChatColor.valueOf(color.toString()); // out.append(chatColor); // state = ColorizeState.TEXT; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_CLOSE) { // // Optional, but for sanity's sake, to keep brackets matched // if (c == '}') { // out.append('}'); // Collapse to single bracket // } // else { // out.append('}'); // out.append(c); // } // state = ColorizeState.TEXT; // } // else if (state == ColorizeState.COLOR_ESCAPE) { // out.append(decodeColor(c)); // state = ColorizeState.TEXT; // } // else // throw new AssertionError("Unknown ColorizeState"); // } // // // End of string // if (state == ColorizeState.COLOR_CLOSE) { // out.append('}'); // } // else if (state != ColorizeState.TEXT) { // // Was in the middle of color name // throw new IllegalArgumentException("Invalid color name"); // } // // cacheResult = out.toString(); // colorizeCache.putIfAbsent(text, cacheResult); // // return cacheResult; // } // Path: src/test/java/org/tyrannyofheaven/bukkit/util/ToHUtilsTest.java import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.fail; import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.delimitedString; import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.colorize; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.bukkit.ChatColor; import org.junit.Test; /* * Copyright 2011 ZerothAngel <zerothangel@tyrannyofheaven.org> * * 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 org.tyrannyofheaven.bukkit.util; public class ToHUtilsTest { @Test public void testColorizeBasics() { // null
assertNull(colorize(null));
ZerothAngel/ToHPluginUtils
src/test/java/org/tyrannyofheaven/bukkit/util/ToHUtilsTest.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static String delimitedString(String delimiter, Collection<?> coll) { // StringBuilder sb = new StringBuilder(); // for (Iterator<?> i = coll.iterator(); i.hasNext();) { // sb.append(i.next()); // if (i.hasNext()) // sb.append(delimiter); // } // return sb.toString(); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static String colorize(String text) { // if (text == null) return null; // // // Works best with interned strings // String cacheResult = colorizeCache.get(text); // if (cacheResult != null) return cacheResult; // // StringBuilder out = new StringBuilder(); // // ColorizeState state = ColorizeState.TEXT; // StringBuilder color = null; // // for (int i = 0; i < text.length(); i++) { // char c = text.charAt(i); // // if (state == ColorizeState.TEXT) { // if (c == '{') { // state = ColorizeState.COLOR_OPEN; // } // else if (c == '}') { // state = ColorizeState.COLOR_CLOSE; // } // else if (c == '`') { // state = ColorizeState.COLOR_ESCAPE; // } // else { // out.append(c); // } // } // else if (state == ColorizeState.COLOR_OPEN) { // if (c == '{') { // Escaped bracket // out.append('{'); // state = ColorizeState.TEXT; // } // else if (Character.isUpperCase(c)) { // // First character of color name // color = new StringBuilder(); // color.append(c); // state = ColorizeState.COLOR_NAME; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_NAME) { // if (Character.isUpperCase(c) || c == '_') { // color.append(c); // } // else if (c == '}') { // ChatColor chatColor = ChatColor.valueOf(color.toString()); // out.append(chatColor); // state = ColorizeState.TEXT; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_CLOSE) { // // Optional, but for sanity's sake, to keep brackets matched // if (c == '}') { // out.append('}'); // Collapse to single bracket // } // else { // out.append('}'); // out.append(c); // } // state = ColorizeState.TEXT; // } // else if (state == ColorizeState.COLOR_ESCAPE) { // out.append(decodeColor(c)); // state = ColorizeState.TEXT; // } // else // throw new AssertionError("Unknown ColorizeState"); // } // // // End of string // if (state == ColorizeState.COLOR_CLOSE) { // out.append('}'); // } // else if (state != ColorizeState.TEXT) { // // Was in the middle of color name // throw new IllegalArgumentException("Invalid color name"); // } // // cacheResult = out.toString(); // colorizeCache.putIfAbsent(text, cacheResult); // // return cacheResult; // }
import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.fail; import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.delimitedString; import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.colorize; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.bukkit.ChatColor; import org.junit.Test;
} catch (IllegalArgumentException e) { return; } fail(); } @Test public void testColorizeInvalid2() { try { colorize("hello world{WHITE"); } catch (IllegalArgumentException e) { return; } fail(); } @Test public void testColorizeInvalid3() { try { colorize("h{_BLUE}ello world"); } catch (IllegalArgumentException e) { return; } fail(); } @Test public void testDelimitedString() {
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static String delimitedString(String delimiter, Collection<?> coll) { // StringBuilder sb = new StringBuilder(); // for (Iterator<?> i = coll.iterator(); i.hasNext();) { // sb.append(i.next()); // if (i.hasNext()) // sb.append(delimiter); // } // return sb.toString(); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static String colorize(String text) { // if (text == null) return null; // // // Works best with interned strings // String cacheResult = colorizeCache.get(text); // if (cacheResult != null) return cacheResult; // // StringBuilder out = new StringBuilder(); // // ColorizeState state = ColorizeState.TEXT; // StringBuilder color = null; // // for (int i = 0; i < text.length(); i++) { // char c = text.charAt(i); // // if (state == ColorizeState.TEXT) { // if (c == '{') { // state = ColorizeState.COLOR_OPEN; // } // else if (c == '}') { // state = ColorizeState.COLOR_CLOSE; // } // else if (c == '`') { // state = ColorizeState.COLOR_ESCAPE; // } // else { // out.append(c); // } // } // else if (state == ColorizeState.COLOR_OPEN) { // if (c == '{') { // Escaped bracket // out.append('{'); // state = ColorizeState.TEXT; // } // else if (Character.isUpperCase(c)) { // // First character of color name // color = new StringBuilder(); // color.append(c); // state = ColorizeState.COLOR_NAME; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_NAME) { // if (Character.isUpperCase(c) || c == '_') { // color.append(c); // } // else if (c == '}') { // ChatColor chatColor = ChatColor.valueOf(color.toString()); // out.append(chatColor); // state = ColorizeState.TEXT; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_CLOSE) { // // Optional, but for sanity's sake, to keep brackets matched // if (c == '}') { // out.append('}'); // Collapse to single bracket // } // else { // out.append('}'); // out.append(c); // } // state = ColorizeState.TEXT; // } // else if (state == ColorizeState.COLOR_ESCAPE) { // out.append(decodeColor(c)); // state = ColorizeState.TEXT; // } // else // throw new AssertionError("Unknown ColorizeState"); // } // // // End of string // if (state == ColorizeState.COLOR_CLOSE) { // out.append('}'); // } // else if (state != ColorizeState.TEXT) { // // Was in the middle of color name // throw new IllegalArgumentException("Invalid color name"); // } // // cacheResult = out.toString(); // colorizeCache.putIfAbsent(text, cacheResult); // // return cacheResult; // } // Path: src/test/java/org/tyrannyofheaven/bukkit/util/ToHUtilsTest.java import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.fail; import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.delimitedString; import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.colorize; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.bukkit.ChatColor; import org.junit.Test; } catch (IllegalArgumentException e) { return; } fail(); } @Test public void testColorizeInvalid2() { try { colorize("hello world{WHITE"); } catch (IllegalArgumentException e) { return; } fail(); } @Test public void testColorizeInvalid3() { try { colorize("h{_BLUE}ello world"); } catch (IllegalArgumentException e) { return; } fail(); } @Test public void testDelimitedString() {
assertEquals("blah", delimitedString(", ", (List<String>)Collections.singletonList("blah")));
ZerothAngel/ToHPluginUtils
src/main/java/org/tyrannyofheaven/bukkit/util/command/HandlerExecutor.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/permissions/PermissionUtils.java // public static void requireAllPermissions(Permissible permissible, String... permissions) { // if (!hasAllPermissions(permissible, permissions)) // throw new PermissionException(true, false, permissions); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/permissions/PermissionUtils.java // public static void requireOnePermission(Permissible permissible, String... permissions) { // requireOnePermission(permissible, false, permissions); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHLoggingUtils.java // public class ToHLoggingUtils { // // private ToHLoggingUtils() { // throw new AssertionError("Don't instantiate me!"); // } // // // Create a log message // private static String createLogMessage(String format, Object... args) { // if (format == null) // return null; // else // return String.format(format, args); // } // // /** // * Log a message. // * // * @param plugin the plugin // * @param level the log level // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void log(Plugin plugin, Level level, String format, Object... args) { // Logger logger = plugin.getLogger(); // if (logger.isLoggable(level)) { // Avoid unnecessary String.format() calls // if (args.length > 0 && args[args.length - 1] instanceof Throwable) { // // Last argument is a Throwable, treat accordingly // logger.log(level, createLogMessage(format, Arrays.copyOf(args, args.length - 1)), (Throwable)args[args.length - 1]); // } // else { // logger.log(level, createLogMessage(format, args)); // } // } // } // // /** // * Log a message at INFO level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void log(Plugin plugin, String format, Object... args) { // log(plugin, Level.INFO, format, args); // } // // /** // * Log a message at CONFIG level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void debug(Plugin plugin, String format, Object... args) { // log(plugin, Level.CONFIG, format, args); // } // // /** // * Log a message at WARNING level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void warn(Plugin plugin, String format, Object... args) { // log(plugin, Level.WARNING, format, args); // } // // /** // * Log a message at SEVERE level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void error(Plugin plugin, String format, Object... args) { // log(plugin, Level.SEVERE, format, args); // } // // }
import static org.tyrannyofheaven.bukkit.util.permissions.PermissionUtils.requireAllPermissions; import static org.tyrannyofheaven.bukkit.util.permissions.PermissionUtils.requireOnePermission; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.WeakHashMap; import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginCommand; import org.bukkit.command.TabExecutor; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.util.StringUtil; import org.tyrannyofheaven.bukkit.util.ToHLoggingUtils;
* * @param sender the command sender * @param name the name of the command to execute * @param args command arguments */ void execute(CommandSender sender, String name, String label, String[] args) throws Throwable { execute(sender, name, label, args, null, null); } /** * Executes the named command. * * @param sender the command sender * @param name the name of the command to execute * @param args command arguments * @param invChain an InvocationChain or null * @param session a CommandSession or null */ void execute(CommandSender sender, String name, String label, String[] args, InvocationChain invChain, CommandSession session) throws Throwable { if (invChain == null) invChain = new InvocationChain(); if (session == null) session = new CommandSession(); CommandMetaData cmd = commandMap.get(name); if (cmd == null) throw new ParseException("Unknown command: %s", name); // Check permissions if (cmd.isRequireAll()) {
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/permissions/PermissionUtils.java // public static void requireAllPermissions(Permissible permissible, String... permissions) { // if (!hasAllPermissions(permissible, permissions)) // throw new PermissionException(true, false, permissions); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/permissions/PermissionUtils.java // public static void requireOnePermission(Permissible permissible, String... permissions) { // requireOnePermission(permissible, false, permissions); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHLoggingUtils.java // public class ToHLoggingUtils { // // private ToHLoggingUtils() { // throw new AssertionError("Don't instantiate me!"); // } // // // Create a log message // private static String createLogMessage(String format, Object... args) { // if (format == null) // return null; // else // return String.format(format, args); // } // // /** // * Log a message. // * // * @param plugin the plugin // * @param level the log level // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void log(Plugin plugin, Level level, String format, Object... args) { // Logger logger = plugin.getLogger(); // if (logger.isLoggable(level)) { // Avoid unnecessary String.format() calls // if (args.length > 0 && args[args.length - 1] instanceof Throwable) { // // Last argument is a Throwable, treat accordingly // logger.log(level, createLogMessage(format, Arrays.copyOf(args, args.length - 1)), (Throwable)args[args.length - 1]); // } // else { // logger.log(level, createLogMessage(format, args)); // } // } // } // // /** // * Log a message at INFO level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void log(Plugin plugin, String format, Object... args) { // log(plugin, Level.INFO, format, args); // } // // /** // * Log a message at CONFIG level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void debug(Plugin plugin, String format, Object... args) { // log(plugin, Level.CONFIG, format, args); // } // // /** // * Log a message at WARNING level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void warn(Plugin plugin, String format, Object... args) { // log(plugin, Level.WARNING, format, args); // } // // /** // * Log a message at SEVERE level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void error(Plugin plugin, String format, Object... args) { // log(plugin, Level.SEVERE, format, args); // } // // } // Path: src/main/java/org/tyrannyofheaven/bukkit/util/command/HandlerExecutor.java import static org.tyrannyofheaven.bukkit.util.permissions.PermissionUtils.requireAllPermissions; import static org.tyrannyofheaven.bukkit.util.permissions.PermissionUtils.requireOnePermission; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.WeakHashMap; import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginCommand; import org.bukkit.command.TabExecutor; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.util.StringUtil; import org.tyrannyofheaven.bukkit.util.ToHLoggingUtils; * * @param sender the command sender * @param name the name of the command to execute * @param args command arguments */ void execute(CommandSender sender, String name, String label, String[] args) throws Throwable { execute(sender, name, label, args, null, null); } /** * Executes the named command. * * @param sender the command sender * @param name the name of the command to execute * @param args command arguments * @param invChain an InvocationChain or null * @param session a CommandSession or null */ void execute(CommandSender sender, String name, String label, String[] args, InvocationChain invChain, CommandSession session) throws Throwable { if (invChain == null) invChain = new InvocationChain(); if (session == null) session = new CommandSession(); CommandMetaData cmd = commandMap.get(name); if (cmd == null) throw new ParseException("Unknown command: %s", name); // Check permissions if (cmd.isRequireAll()) {
requireAllPermissions(sender, cmd.getPermissions());
ZerothAngel/ToHPluginUtils
src/main/java/org/tyrannyofheaven/bukkit/util/command/HandlerExecutor.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/permissions/PermissionUtils.java // public static void requireAllPermissions(Permissible permissible, String... permissions) { // if (!hasAllPermissions(permissible, permissions)) // throw new PermissionException(true, false, permissions); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/permissions/PermissionUtils.java // public static void requireOnePermission(Permissible permissible, String... permissions) { // requireOnePermission(permissible, false, permissions); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHLoggingUtils.java // public class ToHLoggingUtils { // // private ToHLoggingUtils() { // throw new AssertionError("Don't instantiate me!"); // } // // // Create a log message // private static String createLogMessage(String format, Object... args) { // if (format == null) // return null; // else // return String.format(format, args); // } // // /** // * Log a message. // * // * @param plugin the plugin // * @param level the log level // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void log(Plugin plugin, Level level, String format, Object... args) { // Logger logger = plugin.getLogger(); // if (logger.isLoggable(level)) { // Avoid unnecessary String.format() calls // if (args.length > 0 && args[args.length - 1] instanceof Throwable) { // // Last argument is a Throwable, treat accordingly // logger.log(level, createLogMessage(format, Arrays.copyOf(args, args.length - 1)), (Throwable)args[args.length - 1]); // } // else { // logger.log(level, createLogMessage(format, args)); // } // } // } // // /** // * Log a message at INFO level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void log(Plugin plugin, String format, Object... args) { // log(plugin, Level.INFO, format, args); // } // // /** // * Log a message at CONFIG level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void debug(Plugin plugin, String format, Object... args) { // log(plugin, Level.CONFIG, format, args); // } // // /** // * Log a message at WARNING level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void warn(Plugin plugin, String format, Object... args) { // log(plugin, Level.WARNING, format, args); // } // // /** // * Log a message at SEVERE level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void error(Plugin plugin, String format, Object... args) { // log(plugin, Level.SEVERE, format, args); // } // // }
import static org.tyrannyofheaven.bukkit.util.permissions.PermissionUtils.requireAllPermissions; import static org.tyrannyofheaven.bukkit.util.permissions.PermissionUtils.requireOnePermission; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.WeakHashMap; import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginCommand; import org.bukkit.command.TabExecutor; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.util.StringUtil; import org.tyrannyofheaven.bukkit.util.ToHLoggingUtils;
* @param args command arguments */ void execute(CommandSender sender, String name, String label, String[] args) throws Throwable { execute(sender, name, label, args, null, null); } /** * Executes the named command. * * @param sender the command sender * @param name the name of the command to execute * @param args command arguments * @param invChain an InvocationChain or null * @param session a CommandSession or null */ void execute(CommandSender sender, String name, String label, String[] args, InvocationChain invChain, CommandSession session) throws Throwable { if (invChain == null) invChain = new InvocationChain(); if (session == null) session = new CommandSession(); CommandMetaData cmd = commandMap.get(name); if (cmd == null) throw new ParseException("Unknown command: %s", name); // Check permissions if (cmd.isRequireAll()) { requireAllPermissions(sender, cmd.getPermissions()); } else {
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/permissions/PermissionUtils.java // public static void requireAllPermissions(Permissible permissible, String... permissions) { // if (!hasAllPermissions(permissible, permissions)) // throw new PermissionException(true, false, permissions); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/permissions/PermissionUtils.java // public static void requireOnePermission(Permissible permissible, String... permissions) { // requireOnePermission(permissible, false, permissions); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHLoggingUtils.java // public class ToHLoggingUtils { // // private ToHLoggingUtils() { // throw new AssertionError("Don't instantiate me!"); // } // // // Create a log message // private static String createLogMessage(String format, Object... args) { // if (format == null) // return null; // else // return String.format(format, args); // } // // /** // * Log a message. // * // * @param plugin the plugin // * @param level the log level // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void log(Plugin plugin, Level level, String format, Object... args) { // Logger logger = plugin.getLogger(); // if (logger.isLoggable(level)) { // Avoid unnecessary String.format() calls // if (args.length > 0 && args[args.length - 1] instanceof Throwable) { // // Last argument is a Throwable, treat accordingly // logger.log(level, createLogMessage(format, Arrays.copyOf(args, args.length - 1)), (Throwable)args[args.length - 1]); // } // else { // logger.log(level, createLogMessage(format, args)); // } // } // } // // /** // * Log a message at INFO level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void log(Plugin plugin, String format, Object... args) { // log(plugin, Level.INFO, format, args); // } // // /** // * Log a message at CONFIG level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void debug(Plugin plugin, String format, Object... args) { // log(plugin, Level.CONFIG, format, args); // } // // /** // * Log a message at WARNING level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void warn(Plugin plugin, String format, Object... args) { // log(plugin, Level.WARNING, format, args); // } // // /** // * Log a message at SEVERE level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void error(Plugin plugin, String format, Object... args) { // log(plugin, Level.SEVERE, format, args); // } // // } // Path: src/main/java/org/tyrannyofheaven/bukkit/util/command/HandlerExecutor.java import static org.tyrannyofheaven.bukkit.util.permissions.PermissionUtils.requireAllPermissions; import static org.tyrannyofheaven.bukkit.util.permissions.PermissionUtils.requireOnePermission; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.WeakHashMap; import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginCommand; import org.bukkit.command.TabExecutor; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.util.StringUtil; import org.tyrannyofheaven.bukkit.util.ToHLoggingUtils; * @param args command arguments */ void execute(CommandSender sender, String name, String label, String[] args) throws Throwable { execute(sender, name, label, args, null, null); } /** * Executes the named command. * * @param sender the command sender * @param name the name of the command to execute * @param args command arguments * @param invChain an InvocationChain or null * @param session a CommandSession or null */ void execute(CommandSender sender, String name, String label, String[] args, InvocationChain invChain, CommandSession session) throws Throwable { if (invChain == null) invChain = new InvocationChain(); if (session == null) session = new CommandSession(); CommandMetaData cmd = commandMap.get(name); if (cmd == null) throw new ParseException("Unknown command: %s", name); // Check permissions if (cmd.isRequireAll()) { requireAllPermissions(sender, cmd.getPermissions()); } else {
requireOnePermission(sender, cmd.isCheckNegations(), cmd.getPermissions());
ZerothAngel/ToHPluginUtils
src/main/java/org/tyrannyofheaven/bukkit/util/command/HandlerExecutor.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/permissions/PermissionUtils.java // public static void requireAllPermissions(Permissible permissible, String... permissions) { // if (!hasAllPermissions(permissible, permissions)) // throw new PermissionException(true, false, permissions); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/permissions/PermissionUtils.java // public static void requireOnePermission(Permissible permissible, String... permissions) { // requireOnePermission(permissible, false, permissions); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHLoggingUtils.java // public class ToHLoggingUtils { // // private ToHLoggingUtils() { // throw new AssertionError("Don't instantiate me!"); // } // // // Create a log message // private static String createLogMessage(String format, Object... args) { // if (format == null) // return null; // else // return String.format(format, args); // } // // /** // * Log a message. // * // * @param plugin the plugin // * @param level the log level // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void log(Plugin plugin, Level level, String format, Object... args) { // Logger logger = plugin.getLogger(); // if (logger.isLoggable(level)) { // Avoid unnecessary String.format() calls // if (args.length > 0 && args[args.length - 1] instanceof Throwable) { // // Last argument is a Throwable, treat accordingly // logger.log(level, createLogMessage(format, Arrays.copyOf(args, args.length - 1)), (Throwable)args[args.length - 1]); // } // else { // logger.log(level, createLogMessage(format, args)); // } // } // } // // /** // * Log a message at INFO level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void log(Plugin plugin, String format, Object... args) { // log(plugin, Level.INFO, format, args); // } // // /** // * Log a message at CONFIG level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void debug(Plugin plugin, String format, Object... args) { // log(plugin, Level.CONFIG, format, args); // } // // /** // * Log a message at WARNING level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void warn(Plugin plugin, String format, Object... args) { // log(plugin, Level.WARNING, format, args); // } // // /** // * Log a message at SEVERE level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void error(Plugin plugin, String format, Object... args) { // log(plugin, Level.SEVERE, format, args); // } // // }
import static org.tyrannyofheaven.bukkit.util.permissions.PermissionUtils.requireAllPermissions; import static org.tyrannyofheaven.bukkit.util.permissions.PermissionUtils.requireOnePermission; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.WeakHashMap; import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginCommand; import org.bukkit.command.TabExecutor; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.util.StringUtil; import org.tyrannyofheaven.bukkit.util.ToHLoggingUtils;
void fillInvocationChain(InvocationChain invChain, String label) { CommandMetaData cmd = commandMap.get(label); if (cmd == null) throw new IllegalArgumentException("Unknown command: " + label); invChain.addInvocation(label, cmd); } // Retrieve cached HandlerExecutor for given handler object, creating // one if it doesn't exist synchronized HandlerExecutor<T> handlerExecutorFor(Object handler) { // Check HandlerExecutor cache HandlerExecutor<T> he = subCommandMap.get(handler); if (he == null) { // No HandlerExecutor yet, create a new one he = new HandlerExecutor<>(plugin, usageOptions, handler); subCommandMap.put(handler, he); } return he; } // Create a HelpBuilder associated with this HandlerExecutor HelpBuilder getHelpBuilder(InvocationChain rootInvocationChain, Set<String> possibleCommands) { return new HelpBuilder(this, rootInvocationChain, usageOptions, possibleCommands); } // Register top-level commands void registerCommands(TabExecutor executor) { for (String name : commandList) { PluginCommand command = ((JavaPlugin)plugin).getCommand(name); if (command == null) {
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/permissions/PermissionUtils.java // public static void requireAllPermissions(Permissible permissible, String... permissions) { // if (!hasAllPermissions(permissible, permissions)) // throw new PermissionException(true, false, permissions); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/permissions/PermissionUtils.java // public static void requireOnePermission(Permissible permissible, String... permissions) { // requireOnePermission(permissible, false, permissions); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHLoggingUtils.java // public class ToHLoggingUtils { // // private ToHLoggingUtils() { // throw new AssertionError("Don't instantiate me!"); // } // // // Create a log message // private static String createLogMessage(String format, Object... args) { // if (format == null) // return null; // else // return String.format(format, args); // } // // /** // * Log a message. // * // * @param plugin the plugin // * @param level the log level // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void log(Plugin plugin, Level level, String format, Object... args) { // Logger logger = plugin.getLogger(); // if (logger.isLoggable(level)) { // Avoid unnecessary String.format() calls // if (args.length > 0 && args[args.length - 1] instanceof Throwable) { // // Last argument is a Throwable, treat accordingly // logger.log(level, createLogMessage(format, Arrays.copyOf(args, args.length - 1)), (Throwable)args[args.length - 1]); // } // else { // logger.log(level, createLogMessage(format, args)); // } // } // } // // /** // * Log a message at INFO level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void log(Plugin plugin, String format, Object... args) { // log(plugin, Level.INFO, format, args); // } // // /** // * Log a message at CONFIG level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void debug(Plugin plugin, String format, Object... args) { // log(plugin, Level.CONFIG, format, args); // } // // /** // * Log a message at WARNING level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void warn(Plugin plugin, String format, Object... args) { // log(plugin, Level.WARNING, format, args); // } // // /** // * Log a message at SEVERE level. // * // * @param plugin the plugin // * @param format the format message // * @param args the format args. Note that if the last argument is a // * Throwable, it is removed and passed to {@link java.util.logging.Logger#log(Level, String, Throwable)}. // * It will not be available for the format. // */ // public static void error(Plugin plugin, String format, Object... args) { // log(plugin, Level.SEVERE, format, args); // } // // } // Path: src/main/java/org/tyrannyofheaven/bukkit/util/command/HandlerExecutor.java import static org.tyrannyofheaven.bukkit.util.permissions.PermissionUtils.requireAllPermissions; import static org.tyrannyofheaven.bukkit.util.permissions.PermissionUtils.requireOnePermission; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.WeakHashMap; import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginCommand; import org.bukkit.command.TabExecutor; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.util.StringUtil; import org.tyrannyofheaven.bukkit.util.ToHLoggingUtils; void fillInvocationChain(InvocationChain invChain, String label) { CommandMetaData cmd = commandMap.get(label); if (cmd == null) throw new IllegalArgumentException("Unknown command: " + label); invChain.addInvocation(label, cmd); } // Retrieve cached HandlerExecutor for given handler object, creating // one if it doesn't exist synchronized HandlerExecutor<T> handlerExecutorFor(Object handler) { // Check HandlerExecutor cache HandlerExecutor<T> he = subCommandMap.get(handler); if (he == null) { // No HandlerExecutor yet, create a new one he = new HandlerExecutor<>(plugin, usageOptions, handler); subCommandMap.put(handler, he); } return he; } // Create a HelpBuilder associated with this HandlerExecutor HelpBuilder getHelpBuilder(InvocationChain rootInvocationChain, Set<String> possibleCommands) { return new HelpBuilder(this, rootInvocationChain, usageOptions, possibleCommands); } // Register top-level commands void registerCommands(TabExecutor executor) { for (String name : commandList) { PluginCommand command = ((JavaPlugin)plugin).getCommand(name); if (command == null) {
ToHLoggingUtils.warn(plugin, "Command '%s' not found in plugin.yml -- ignoring", name);
ZerothAngel/ToHPluginUtils
src/main/java/org/tyrannyofheaven/bukkit/util/command/CommandMetaData.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // }
import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List;
/* * Copyright 2011 ZerothAngel <zerothangel@tyrannyofheaven.org> * * 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 org.tyrannyofheaven.bukkit.util.command; /** * Metadata for a command. * * @author zerothangel */ final class CommandMetaData { private final Object handler; private final Method method; private final List<MethodParameter> parameters; private final String[] permissions; private final boolean requireAll; private final boolean checkNegations; private final String description; private final boolean hasRest; private final String rest; private final String completer; private final List<OptionMetaData> flagOptions; private final List<OptionMetaData> positionalArguments; /** * Create a CommandMetaData with the given arguments. * * @param handler the handler object * @param method the associated method in the handler object * @param options method parameters * @param permissions required permissions, if any * @param requireAll true if all permissions are required */ public CommandMetaData(Object handler, Method method, List<MethodParameter> options, String[] permissions, boolean requireAll, boolean checkNegations, String description, boolean hasRest, String rest, String completer) { if (handler == null) throw new IllegalArgumentException("handler cannot be null"); if (method == null) throw new IllegalArgumentException("method cannot be null"); if (options == null) options = Collections.emptyList(); if (permissions == null) permissions = new String[0];
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // } // Path: src/main/java/org/tyrannyofheaven/bukkit/util/command/CommandMetaData.java import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /* * Copyright 2011 ZerothAngel <zerothangel@tyrannyofheaven.org> * * 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 org.tyrannyofheaven.bukkit.util.command; /** * Metadata for a command. * * @author zerothangel */ final class CommandMetaData { private final Object handler; private final Method method; private final List<MethodParameter> parameters; private final String[] permissions; private final boolean requireAll; private final boolean checkNegations; private final String description; private final boolean hasRest; private final String rest; private final String completer; private final List<OptionMetaData> flagOptions; private final List<OptionMetaData> positionalArguments; /** * Create a CommandMetaData with the given arguments. * * @param handler the handler object * @param method the associated method in the handler object * @param options method parameters * @param permissions required permissions, if any * @param requireAll true if all permissions are required */ public CommandMetaData(Object handler, Method method, List<MethodParameter> options, String[] permissions, boolean requireAll, boolean checkNegations, String description, boolean hasRest, String rest, String completer) { if (handler == null) throw new IllegalArgumentException("handler cannot be null"); if (method == null) throw new IllegalArgumentException("method cannot be null"); if (options == null) options = Collections.emptyList(); if (permissions == null) permissions = new String[0];
if (!hasText(description))
ZerothAngel/ToHPluginUtils
src/main/java/org/tyrannyofheaven/bukkit/util/ToHDatabaseUtils.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHLoggingUtils.java // public static void log(Plugin plugin, Level level, String format, Object... args) { // Logger logger = plugin.getLogger(); // if (logger.isLoggable(level)) { // Avoid unnecessary String.format() calls // if (args.length > 0 && args[args.length - 1] instanceof Throwable) { // // Last argument is a Throwable, treat accordingly // logger.log(level, createLogMessage(format, Arrays.copyOf(args, args.length - 1)), (Throwable)args[args.length - 1]); // } // else { // logger.log(level, createLogMessage(format, args)); // } // } // }
import static org.tyrannyofheaven.bukkit.util.ToHLoggingUtils.log; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.logging.Level; import javax.persistence.PersistenceException; import org.bukkit.configuration.Configuration; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import com.avaje.ebean.EbeanServer; import com.avaje.ebean.EbeanServerFactory; import com.avaje.ebean.config.DataSourceConfig; import com.avaje.ebean.config.NamingConvention; import com.avaje.ebean.config.ServerConfig; import com.avaje.ebean.config.dbplatform.DatabasePlatform; import com.avaje.ebean.config.dbplatform.SQLitePlatform; import com.avaje.ebeaninternal.api.SpiEbeanServer; import com.avaje.ebeaninternal.server.ddl.CreateSequenceVisitor; import com.avaje.ebeaninternal.server.ddl.CreateTableVisitor; import com.avaje.ebeaninternal.server.ddl.DdlGenContext; import com.avaje.ebeaninternal.server.ddl.DdlGenerator; import com.avaje.ebeaninternal.server.ddl.VisitorUtil; import com.avaje.ebeaninternal.server.deploy.BeanDescriptor; import com.avaje.ebeaninternal.server.lib.sql.TransactionIsolation; import com.google.common.io.CharStreams;
* * @param ebeanServer the EbeanServer * @param namingConvention the associated NamingConvention * @param classLoader the plugin's class loader * @param pluginEntity any entity class (aside from ToHSchemaVersion) used by the plugin * @param updatePath path to the root of the update scripts */ public static void upgradeDatabase(JavaPlugin plugin, NamingConvention namingConvention, ClassLoader classLoader, String updatePath) throws IOException { if (plugin == null) throw new IllegalArgumentException("plugin cannot be null"); if (namingConvention == null) throw new IllegalArgumentException("namingConvention cannot be null"); if (classLoader == null) throw new IllegalArgumentException("classLoader cannot be null"); if (!ToHStringUtils.hasText(updatePath)) throw new IllegalArgumentException("updatePath must have a value"); // Find an entity class that is not ToHSchemaVersion. We'll select the // first one that matches from getDatabaseClasses(). This class will be // used to determine if the full schema should be generated. Class<?> pluginEntity = null; for (Class<?> clazz : plugin.getDatabaseClasses()) { // Use anything except ToHSchemaVersion if (clazz != ToHSchemaVersion.class) { pluginEntity = clazz; break; } } if (pluginEntity == null) throw new IllegalArgumentException("plugin.getDatabaseClasses() must have a non-ToHSchemaVersion class");
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHLoggingUtils.java // public static void log(Plugin plugin, Level level, String format, Object... args) { // Logger logger = plugin.getLogger(); // if (logger.isLoggable(level)) { // Avoid unnecessary String.format() calls // if (args.length > 0 && args[args.length - 1] instanceof Throwable) { // // Last argument is a Throwable, treat accordingly // logger.log(level, createLogMessage(format, Arrays.copyOf(args, args.length - 1)), (Throwable)args[args.length - 1]); // } // else { // logger.log(level, createLogMessage(format, args)); // } // } // } // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHDatabaseUtils.java import static org.tyrannyofheaven.bukkit.util.ToHLoggingUtils.log; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.logging.Level; import javax.persistence.PersistenceException; import org.bukkit.configuration.Configuration; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import com.avaje.ebean.EbeanServer; import com.avaje.ebean.EbeanServerFactory; import com.avaje.ebean.config.DataSourceConfig; import com.avaje.ebean.config.NamingConvention; import com.avaje.ebean.config.ServerConfig; import com.avaje.ebean.config.dbplatform.DatabasePlatform; import com.avaje.ebean.config.dbplatform.SQLitePlatform; import com.avaje.ebeaninternal.api.SpiEbeanServer; import com.avaje.ebeaninternal.server.ddl.CreateSequenceVisitor; import com.avaje.ebeaninternal.server.ddl.CreateTableVisitor; import com.avaje.ebeaninternal.server.ddl.DdlGenContext; import com.avaje.ebeaninternal.server.ddl.DdlGenerator; import com.avaje.ebeaninternal.server.ddl.VisitorUtil; import com.avaje.ebeaninternal.server.deploy.BeanDescriptor; import com.avaje.ebeaninternal.server.lib.sql.TransactionIsolation; import com.google.common.io.CharStreams; * * @param ebeanServer the EbeanServer * @param namingConvention the associated NamingConvention * @param classLoader the plugin's class loader * @param pluginEntity any entity class (aside from ToHSchemaVersion) used by the plugin * @param updatePath path to the root of the update scripts */ public static void upgradeDatabase(JavaPlugin plugin, NamingConvention namingConvention, ClassLoader classLoader, String updatePath) throws IOException { if (plugin == null) throw new IllegalArgumentException("plugin cannot be null"); if (namingConvention == null) throw new IllegalArgumentException("namingConvention cannot be null"); if (classLoader == null) throw new IllegalArgumentException("classLoader cannot be null"); if (!ToHStringUtils.hasText(updatePath)) throw new IllegalArgumentException("updatePath must have a value"); // Find an entity class that is not ToHSchemaVersion. We'll select the // first one that matches from getDatabaseClasses(). This class will be // used to determine if the full schema should be generated. Class<?> pluginEntity = null; for (Class<?> clazz : plugin.getDatabaseClasses()) { // Use anything except ToHSchemaVersion if (clazz != ToHSchemaVersion.class) { pluginEntity = clazz; break; } } if (pluginEntity == null) throw new IllegalArgumentException("plugin.getDatabaseClasses() must have a non-ToHSchemaVersion class");
log(plugin, Level.CONFIG, "Selected %s as plugin-specific entity", pluginEntity.getSimpleName());
ZerothAngel/ToHPluginUtils
src/main/java/org/tyrannyofheaven/bukkit/util/permissions/PermissionUtils.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static void sendMessage(CommandSender sender, String format, Object... args) { // String message = String.format(format, args); // for (String line : message.split("\n")) { // sender.sendMessage(line); // } // }
import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.sendMessage; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.permissions.Permissible;
/* * Copyright 2011 ZerothAngel <zerothangel@tyrannyofheaven.org> * * 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 org.tyrannyofheaven.bukkit.util.permissions; /** * Utilities for checking permissions and displaying error messages. * * @author zerothangel */ public class PermissionUtils { private PermissionUtils() { throw new AssertionError("Don't instantiate me!"); } /** * Test if a permissible has multiple permissions. * * @param permissible the permissible * @param all true if all permissions are required * @param permissions the permissions * @return true if conditions are met */ public static boolean hasPermissions(Permissible permissible, boolean all, String... permissions) { return hasPermissions(permissible, all, false, permissions); } /** * Test if a permissible has multiple permissions. * * @param permissible the permissible * @param all true if all permissions are required * @param checkNegations true if any explicitly false permission should mean * the check fails. Only valid when all is false. * @param permissions the permissions * @return true if conditions are met */ public static boolean hasPermissions(Permissible permissible, boolean all, boolean checkNegations, String... permissions) { if (permissions == null || permissions.length == 0) return true; if (all) { for (String permission : permissions) {
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static void sendMessage(CommandSender sender, String format, Object... args) { // String message = String.format(format, args); // for (String line : message.split("\n")) { // sender.sendMessage(line); // } // } // Path: src/main/java/org/tyrannyofheaven/bukkit/util/permissions/PermissionUtils.java import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.sendMessage; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.permissions.Permissible; /* * Copyright 2011 ZerothAngel <zerothangel@tyrannyofheaven.org> * * 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 org.tyrannyofheaven.bukkit.util.permissions; /** * Utilities for checking permissions and displaying error messages. * * @author zerothangel */ public class PermissionUtils { private PermissionUtils() { throw new AssertionError("Don't instantiate me!"); } /** * Test if a permissible has multiple permissions. * * @param permissible the permissible * @param all true if all permissions are required * @param permissions the permissions * @return true if conditions are met */ public static boolean hasPermissions(Permissible permissible, boolean all, String... permissions) { return hasPermissions(permissible, all, false, permissions); } /** * Test if a permissible has multiple permissions. * * @param permissible the permissible * @param all true if all permissions are required * @param checkNegations true if any explicitly false permission should mean * the check fails. Only valid when all is false. * @param permissions the permissions * @return true if conditions are met */ public static boolean hasPermissions(Permissible permissible, boolean all, boolean checkNegations, String... permissions) { if (permissions == null || permissions.length == 0) return true; if (all) { for (String permission : permissions) {
if (!hasText(permission))
ZerothAngel/ToHPluginUtils
src/main/java/org/tyrannyofheaven/bukkit/util/permissions/PermissionUtils.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static void sendMessage(CommandSender sender, String format, Object... args) { // String message = String.format(format, args); // for (String line : message.split("\n")) { // sender.sendMessage(line); // } // }
import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.sendMessage; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.permissions.Permissible;
public static void requireOnePermission(Permissible permissible, String... permissions) { requireOnePermission(permissible, false, permissions); } /** * Require one of multiple permissions. * * @param permissible the permissible to check * @param checkNegations true if any explicitly false permission should mean * the check fails * @param permissions the names of the permissions */ public static void requireOnePermission(Permissible permissible, boolean checkNegations, String... permissions) { if (!hasOnePermission(permissible, checkNegations, permissions)) throw new PermissionException(false, checkNegations, permissions); } /** * Display a helpful error message when a permission check fails. * * @param sender the command sender * @param permissionException the associated PermissionException */ public static void displayPermissionException(CommandSender sender, PermissionException permissionException) { if (sender == null) throw new IllegalArgumentException("sender cannot be null"); if (permissionException == null) throw new IllegalArgumentException("permissionException cannot be null"); if (permissionException.getPermissions().size() == 1) {
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static void sendMessage(CommandSender sender, String format, Object... args) { // String message = String.format(format, args); // for (String line : message.split("\n")) { // sender.sendMessage(line); // } // } // Path: src/main/java/org/tyrannyofheaven/bukkit/util/permissions/PermissionUtils.java import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.sendMessage; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.permissions.Permissible; public static void requireOnePermission(Permissible permissible, String... permissions) { requireOnePermission(permissible, false, permissions); } /** * Require one of multiple permissions. * * @param permissible the permissible to check * @param checkNegations true if any explicitly false permission should mean * the check fails * @param permissions the names of the permissions */ public static void requireOnePermission(Permissible permissible, boolean checkNegations, String... permissions) { if (!hasOnePermission(permissible, checkNegations, permissions)) throw new PermissionException(false, checkNegations, permissions); } /** * Display a helpful error message when a permission check fails. * * @param sender the command sender * @param permissionException the associated PermissionException */ public static void displayPermissionException(CommandSender sender, PermissionException permissionException) { if (sender == null) throw new IllegalArgumentException("sender cannot be null"); if (permissionException == null) throw new IllegalArgumentException("permissionException cannot be null"); if (permissionException.getPermissions().size() == 1) {
sendMessage(sender, ChatColor.RED + "You need the following permission to do this:");
ZerothAngel/ToHPluginUtils
src/main/java/org/tyrannyofheaven/bukkit/util/ToHNamingConvention.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public class ToHStringUtils { // // private ToHStringUtils() { // throw new AssertionError("Don't instantiate me!"); // } // // /** // * Returns true if text is non-null and contains non-whitespace characters. // * // * @param text the string to test // * @return true if text is non-null and contains non-whitespace characters // */ // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // } // // /** // * Returns a string representation of each object, with each object delimited // * by the given delimiter. Similar to "string join" in other languages. // * // * @param delimiter the string delimiter // * @param coll a collection of objects // * @return the delimited string // */ // public static String delimitedString(String delimiter, Collection<?> coll) { // StringBuilder sb = new StringBuilder(); // for (Iterator<?> i = coll.iterator(); i.hasNext();) { // sb.append(i.next()); // if (i.hasNext()) // sb.append(delimiter); // } // return sb.toString(); // } // // /** // * Returns a string representation of each object, with each object delimited // * by the given delimiter. Similar to "string join" in other languages. // * // * @param delimiter the string delimiter // * @param objs an array of objects // * @return the delimited string // */ // public static String delimitedString(String delimiter, Object... objs) { // return delimitedString(delimiter, Arrays.asList(objs)); // } // // /** // * Quote a string suitable for the "quote aware" parser of {@link ToHCommandExecutor}. // * // * @param input the input string // * @return the possibly escaped and quoted string // */ // public static String quoteArgForCommand(String input) { // input = input.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\""); // if (input.matches(".*\\s.*")) // return "\"" + input + "\""; // Enclose in quotes // else // return input; // } // // }
import java.util.HashMap; import java.util.Map; import org.bukkit.plugin.java.JavaPlugin; import org.tyrannyofheaven.bukkit.util.ToHStringUtils; import com.avaje.ebean.config.NamingConvention; import com.avaje.ebean.config.TableName; import com.avaje.ebean.config.UnderscoreNamingConvention;
/* * Copyright 2013 ZerothAngel <zerothangel@tyrannyofheaven.org> * * 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 org.tyrannyofheaven.bukkit.util; /** * Avaje {@link NamingConvention} implementation that accepts custom names for * mapped beans. Otherwise behaves the same as {@link UnderscoreNamingConvention}, * the default used by Avaje. * * @author zerothangel */ public class ToHNamingConvention extends UnderscoreNamingConvention { private final Map<String, String> tableNames = new HashMap<>(); private final String defaultSchemaTableName; /** * Construct a new instance and configure it so it only accepts table name * mappings of the classes specified by {@link JavaPlugin#getDatabaseClasses()}. * * @param plugin the JavaPlugin subclass */ public ToHNamingConvention(JavaPlugin plugin, String defaultSchemaTableName) { // Set up null placeholders for (Class<?> clazz : plugin.getDatabaseClasses()) { tableNames.put(clazz.getSimpleName(), null); } this.defaultSchemaTableName = defaultSchemaTableName; } /** * Clear all table name mappings. */ public void clearTableNames() { for (Map.Entry<String, String> me : tableNames.entrySet()) { me.setValue(null); } } /** * Add a table name mapping for the given class. * * @param className the simple name of the class * @param tableName the table name. May be qualified with catalog/schema. May be null. */ public void setTableName(String className, String tableName) {
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public class ToHStringUtils { // // private ToHStringUtils() { // throw new AssertionError("Don't instantiate me!"); // } // // /** // * Returns true if text is non-null and contains non-whitespace characters. // * // * @param text the string to test // * @return true if text is non-null and contains non-whitespace characters // */ // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // } // // /** // * Returns a string representation of each object, with each object delimited // * by the given delimiter. Similar to "string join" in other languages. // * // * @param delimiter the string delimiter // * @param coll a collection of objects // * @return the delimited string // */ // public static String delimitedString(String delimiter, Collection<?> coll) { // StringBuilder sb = new StringBuilder(); // for (Iterator<?> i = coll.iterator(); i.hasNext();) { // sb.append(i.next()); // if (i.hasNext()) // sb.append(delimiter); // } // return sb.toString(); // } // // /** // * Returns a string representation of each object, with each object delimited // * by the given delimiter. Similar to "string join" in other languages. // * // * @param delimiter the string delimiter // * @param objs an array of objects // * @return the delimited string // */ // public static String delimitedString(String delimiter, Object... objs) { // return delimitedString(delimiter, Arrays.asList(objs)); // } // // /** // * Quote a string suitable for the "quote aware" parser of {@link ToHCommandExecutor}. // * // * @param input the input string // * @return the possibly escaped and quoted string // */ // public static String quoteArgForCommand(String input) { // input = input.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\""); // if (input.matches(".*\\s.*")) // return "\"" + input + "\""; // Enclose in quotes // else // return input; // } // // } // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHNamingConvention.java import java.util.HashMap; import java.util.Map; import org.bukkit.plugin.java.JavaPlugin; import org.tyrannyofheaven.bukkit.util.ToHStringUtils; import com.avaje.ebean.config.NamingConvention; import com.avaje.ebean.config.TableName; import com.avaje.ebean.config.UnderscoreNamingConvention; /* * Copyright 2013 ZerothAngel <zerothangel@tyrannyofheaven.org> * * 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 org.tyrannyofheaven.bukkit.util; /** * Avaje {@link NamingConvention} implementation that accepts custom names for * mapped beans. Otherwise behaves the same as {@link UnderscoreNamingConvention}, * the default used by Avaje. * * @author zerothangel */ public class ToHNamingConvention extends UnderscoreNamingConvention { private final Map<String, String> tableNames = new HashMap<>(); private final String defaultSchemaTableName; /** * Construct a new instance and configure it so it only accepts table name * mappings of the classes specified by {@link JavaPlugin#getDatabaseClasses()}. * * @param plugin the JavaPlugin subclass */ public ToHNamingConvention(JavaPlugin plugin, String defaultSchemaTableName) { // Set up null placeholders for (Class<?> clazz : plugin.getDatabaseClasses()) { tableNames.put(clazz.getSimpleName(), null); } this.defaultSchemaTableName = defaultSchemaTableName; } /** * Clear all table name mappings. */ public void clearTableNames() { for (Map.Entry<String, String> me : tableNames.entrySet()) { me.setValue(null); } } /** * Add a table name mapping for the given class. * * @param className the simple name of the class * @param tableName the table name. May be qualified with catalog/schema. May be null. */ public void setTableName(String className, String tableName) {
if (!ToHStringUtils.hasText(tableName))
ZerothAngel/ToHPluginUtils
src/main/java/org/tyrannyofheaven/bukkit/util/uuid/MojangUuidResolver.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/UuidUtils.java // public static UUID uncanonicalizeUuid(String shortUuid) { // return UUID.fromString(shortUuidToLong(shortUuid)); // }
import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.uncanonicalizeUuid; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import com.google.common.base.Charsets; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.collect.Lists;
/* * Largely based off Mojang's AccountsClient code. * https://github.com/Mojang/AccountsClient */ package org.tyrannyofheaven.bukkit.util.uuid; public class MojangUuidResolver implements UuidResolver { private static final String AGENT = "minecraft"; private static final UuidDisplayName NULL_UDN = new UuidDisplayName(UUID.randomUUID(), "NOT FOUND"); private final Cache<String, UuidDisplayName> cache; public MojangUuidResolver(int cacheMaxSize, long cacheTtl, TimeUnit cacheTtlUnits) { cache = CacheBuilder.newBuilder() .maximumSize(cacheMaxSize) .expireAfterWrite(cacheTtl, cacheTtlUnits) .build(new CacheLoader<String, UuidDisplayName>() { @Override public UuidDisplayName load(String key) throws Exception { UuidDisplayName udn = _resolve(key); return udn != null ? udn : NULL_UDN; // Doesn't like nulls, so we use a marker object instead } }); } @Override public UuidDisplayName resolve(String username) {
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/UuidUtils.java // public static UUID uncanonicalizeUuid(String shortUuid) { // return UUID.fromString(shortUuidToLong(shortUuid)); // } // Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/MojangUuidResolver.java import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.uncanonicalizeUuid; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import com.google.common.base.Charsets; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.collect.Lists; /* * Largely based off Mojang's AccountsClient code. * https://github.com/Mojang/AccountsClient */ package org.tyrannyofheaven.bukkit.util.uuid; public class MojangUuidResolver implements UuidResolver { private static final String AGENT = "minecraft"; private static final UuidDisplayName NULL_UDN = new UuidDisplayName(UUID.randomUUID(), "NOT FOUND"); private final Cache<String, UuidDisplayName> cache; public MojangUuidResolver(int cacheMaxSize, long cacheTtl, TimeUnit cacheTtlUnits) { cache = CacheBuilder.newBuilder() .maximumSize(cacheMaxSize) .expireAfterWrite(cacheTtl, cacheTtlUnits) .build(new CacheLoader<String, UuidDisplayName>() { @Override public UuidDisplayName load(String key) throws Exception { UuidDisplayName udn = _resolve(key); return udn != null ? udn : NULL_UDN; // Doesn't like nulls, so we use a marker object instead } }); } @Override public UuidDisplayName resolve(String username) {
if (!hasText(username))
ZerothAngel/ToHPluginUtils
src/main/java/org/tyrannyofheaven/bukkit/util/uuid/MojangUuidResolver.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/UuidUtils.java // public static UUID uncanonicalizeUuid(String shortUuid) { // return UUID.fromString(shortUuidToLong(shortUuid)); // }
import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.uncanonicalizeUuid; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import com.google.common.base.Charsets; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.collect.Lists;
return null; } } @Override public UuidDisplayName resolve(String username, boolean cacheOnly) { if (!hasText(username)) throw new IllegalArgumentException("username must have a value"); if (cacheOnly) { UuidDisplayName udn = cache.asMap().get(username.toLowerCase()); if (udn == null) return null; return udn != NULL_UDN ? udn : null; // NB Can't tell between "not cached" and "maps to null" } else return resolve(username); // Same as normal version } @Override public Map<String, UuidDisplayName> resolve(Collection<String> usernames) throws Exception { if (usernames == null) throw new IllegalArgumentException("usernames cannot be null"); Map<String, UuidDisplayName> result = new LinkedHashMap<>(); final int BATCH_SIZE = 97; // Should be <= Mojang's AccountsClient's PROFILES_PER_REQUEST (100) for (List<String> sublist : Lists.partition(new ArrayList<>(usernames), BATCH_SIZE)) { List<Profile> searchResult = searchProfiles(sublist); for (Profile profile : searchResult) { String username = profile.getName();
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/UuidUtils.java // public static UUID uncanonicalizeUuid(String shortUuid) { // return UUID.fromString(shortUuidToLong(shortUuid)); // } // Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/MojangUuidResolver.java import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.uncanonicalizeUuid; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import com.google.common.base.Charsets; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.collect.Lists; return null; } } @Override public UuidDisplayName resolve(String username, boolean cacheOnly) { if (!hasText(username)) throw new IllegalArgumentException("username must have a value"); if (cacheOnly) { UuidDisplayName udn = cache.asMap().get(username.toLowerCase()); if (udn == null) return null; return udn != NULL_UDN ? udn : null; // NB Can't tell between "not cached" and "maps to null" } else return resolve(username); // Same as normal version } @Override public Map<String, UuidDisplayName> resolve(Collection<String> usernames) throws Exception { if (usernames == null) throw new IllegalArgumentException("usernames cannot be null"); Map<String, UuidDisplayName> result = new LinkedHashMap<>(); final int BATCH_SIZE = 97; // Should be <= Mojang's AccountsClient's PROFILES_PER_REQUEST (100) for (List<String> sublist : Lists.partition(new ArrayList<>(usernames), BATCH_SIZE)) { List<Profile> searchResult = searchProfiles(sublist); for (Profile profile : searchResult) { String username = profile.getName();
UUID uuid = uncanonicalizeUuid(profile.getId());
ZerothAngel/ToHPluginUtils
src/main/java/org/tyrannyofheaven/bukkit/util/transaction/TransactionRunnable.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/transaction/TransactionCallback.java // public interface TransactionCallback<T> { // // /** // * Perform operations within a transaction. // * @return the result of the operation // * @throws Exception any thrown exception will result in a rollback // */ // public T doInTransaction() throws Exception; // // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/transaction/TransactionStrategy.java // public interface TransactionStrategy { // // /** // * Execute the given callback within a transaction suitable for this // * implementation. The transaction is considered read-write. // * // * @param callback the callback // * @return the result of the callback // */ // public <T> T execute(TransactionCallback<T> callback); // // /** // * Execute the given callback within a transaction suitable for this // * implementation. // * // * @param callback the callback // * @param readOnly true if this transaction should be considered read-only // * @return the result of the callback // */ // public <T> T execute(TransactionCallback<T> callback, boolean readOnly); // // }
import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.tyrannyofheaven.bukkit.util.transaction.TransactionCallback; import org.tyrannyofheaven.bukkit.util.transaction.TransactionStrategy;
/* * Copyright 2012 ZerothAngel <zerothangel@tyrannyofheaven.org> * * 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 org.tyrannyofheaven.bukkit.util.transaction; /** * A Runnable that holds a sequence of writing Runnables to be executed * transactionally. * * @author zerothangel */ class TransactionRunnable implements Runnable, TransactionCallback<Object> { private final Logger logger = Logger.getLogger(getClass().getName());
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/transaction/TransactionCallback.java // public interface TransactionCallback<T> { // // /** // * Perform operations within a transaction. // * @return the result of the operation // * @throws Exception any thrown exception will result in a rollback // */ // public T doInTransaction() throws Exception; // // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/transaction/TransactionStrategy.java // public interface TransactionStrategy { // // /** // * Execute the given callback within a transaction suitable for this // * implementation. The transaction is considered read-write. // * // * @param callback the callback // * @return the result of the callback // */ // public <T> T execute(TransactionCallback<T> callback); // // /** // * Execute the given callback within a transaction suitable for this // * implementation. // * // * @param callback the callback // * @param readOnly true if this transaction should be considered read-only // * @return the result of the callback // */ // public <T> T execute(TransactionCallback<T> callback, boolean readOnly); // // } // Path: src/main/java/org/tyrannyofheaven/bukkit/util/transaction/TransactionRunnable.java import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.tyrannyofheaven.bukkit.util.transaction.TransactionCallback; import org.tyrannyofheaven.bukkit.util.transaction.TransactionStrategy; /* * Copyright 2012 ZerothAngel <zerothangel@tyrannyofheaven.org> * * 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 org.tyrannyofheaven.bukkit.util.transaction; /** * A Runnable that holds a sequence of writing Runnables to be executed * transactionally. * * @author zerothangel */ class TransactionRunnable implements Runnable, TransactionCallback<Object> { private final Logger logger = Logger.getLogger(getClass().getName());
private final TransactionStrategy transactionStrategy;
ZerothAngel/ToHPluginUtils
src/main/java/org/tyrannyofheaven/bukkit/util/command/InvocationChain.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/permissions/PermissionUtils.java // public static boolean hasPermissions(Permissible permissible, boolean all, String... permissions) { // return hasPermissions(permissible, all, false, permissions); // }
import static org.tyrannyofheaven.bukkit.util.permissions.PermissionUtils.hasPermissions; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.bukkit.permissions.Permissible;
// Add varargs description, if any if (cmd.getRest() != null) { usage.append(usageOptions.getVarargsStart()); usage.append(cmd.getRest()); usage.append(usageOptions.getVarargsEnd()); } if (i.hasNext()) usage.append(' '); } // Attach description if (withDescription && !chain.isEmpty()) { // Pull out last CommandMetaData CommandMetaData cmd = chain.get(chain.size() - 1).getCommandMetaData(); if (cmd.getDescription() != null) { usage.append(usageOptions.getDescriptionDelimiter()); usage.append(cmd.getDescription()); } } usage.append(usageOptions.getPostamble()); return usage.toString(); } // Tests whether the given permissible can execute this entire chain boolean canBeExecutedBy(Permissible permissible) { for (CommandInvocation ci : chain) {
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/permissions/PermissionUtils.java // public static boolean hasPermissions(Permissible permissible, boolean all, String... permissions) { // return hasPermissions(permissible, all, false, permissions); // } // Path: src/main/java/org/tyrannyofheaven/bukkit/util/command/InvocationChain.java import static org.tyrannyofheaven.bukkit.util.permissions.PermissionUtils.hasPermissions; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.bukkit.permissions.Permissible; // Add varargs description, if any if (cmd.getRest() != null) { usage.append(usageOptions.getVarargsStart()); usage.append(cmd.getRest()); usage.append(usageOptions.getVarargsEnd()); } if (i.hasNext()) usage.append(' '); } // Attach description if (withDescription && !chain.isEmpty()) { // Pull out last CommandMetaData CommandMetaData cmd = chain.get(chain.size() - 1).getCommandMetaData(); if (cmd.getDescription() != null) { usage.append(usageOptions.getDescriptionDelimiter()); usage.append(cmd.getDescription()); } } usage.append(usageOptions.getPostamble()); return usage.toString(); } // Tests whether the given permissible can execute this entire chain boolean canBeExecutedBy(Permissible permissible) { for (CommandInvocation ci : chain) {
if (!hasPermissions(permissible, ci.getCommandMetaData().isRequireAll(), ci.getCommandMetaData().isCheckNegations(), ci.getCommandMetaData().getPermissions()))
ZerothAngel/ToHPluginUtils
src/test/java/org/tyrannyofheaven/bukkit/util/command/CommandTest.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/permissions/PermissionException.java // public class PermissionException extends RuntimeException { // // private static final long serialVersionUID = 4064063141792654633L; // // private final List<String> permissions; // // private final boolean all; // // private final boolean checkNegations; // // /** // * Create a PermissionException for a single permission. // * // * @param permission name of the permission // */ // public PermissionException(String permission) { // this.permissions = Collections.singletonList(permission); // this.all = true; // this.checkNegations = false; // } // // /** // * Create a PermissionException for multiple permissions. // * // * @param all true if all permissions are required // * @param permissions name of permissions // */ // public PermissionException(boolean all, boolean checkNegations, String... permissions) { // this.permissions = Collections.unmodifiableList(new ArrayList<>(Arrays.asList(permissions))); // this.all = all; // this.checkNegations = checkNegations; // } // // /** // * Retrieve the associated permissions. // * // * @return the permissions // */ // public List<String> getPermissions() { // return permissions; // } // // /** // * Retrieve whether or not all permissions are required. // * // * @return true if all permissions are required // */ // public boolean isAll() { // return all; // } // // /** // * Retrieve whether or not negations were checked. // * // * @return true if negations were checked // */ // public boolean isCheckNegations() { // return checkNegations; // } // // }
import org.bukkit.util.StringUtil; import org.junit.Before; import org.junit.Test; import org.tyrannyofheaven.bukkit.util.permissions.PermissionException; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import junit.framework.Assert; import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionAttachment; import org.bukkit.permissions.PermissionAttachmentInfo; import org.bukkit.plugin.Plugin;
// Positional argument that starts with - he.execute(dummySender, "greet", "greet", new String[] { "--", "-garply" }); Assert.assertEquals("Hello, -garply\n", out.toString()); out.delete(0, out.length()); // String[] parameter he.execute(dummySender, "say", "say", new String[] { "Hello", "there" }); Assert.assertEquals("Hello there\n", out.toString()); out.delete(0, out.length()); // No flags, so should not parse -Hello as one. he.execute(dummySender, "say", "say", new String[] { "-Hello", "there" }); Assert.assertEquals("-Hello there\n", out.toString()); out.delete(0, out.length()); // Sub-command good = false; try { he.execute(dummySender, "foo", "foo", new String[0]); } catch (ParseException e) { good = true; } Assert.assertTrue(good); he.execute(dummySender, "foo", "foo", new String[] { "hello" }); Assert.assertEquals("Hello from the foo sub-command!\n", out.toString()); out.delete(0, out.length()); good = false; try { he.execute(dummySender, "foo", "foo", new String[] { "hello", "extra" }); } catch (ParseException e) { good = true; } Assert.assertTrue(good); good = false; permissions.clear(); try { he.execute(dummySender, "secret", "secret", new String[0]); }
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/permissions/PermissionException.java // public class PermissionException extends RuntimeException { // // private static final long serialVersionUID = 4064063141792654633L; // // private final List<String> permissions; // // private final boolean all; // // private final boolean checkNegations; // // /** // * Create a PermissionException for a single permission. // * // * @param permission name of the permission // */ // public PermissionException(String permission) { // this.permissions = Collections.singletonList(permission); // this.all = true; // this.checkNegations = false; // } // // /** // * Create a PermissionException for multiple permissions. // * // * @param all true if all permissions are required // * @param permissions name of permissions // */ // public PermissionException(boolean all, boolean checkNegations, String... permissions) { // this.permissions = Collections.unmodifiableList(new ArrayList<>(Arrays.asList(permissions))); // this.all = all; // this.checkNegations = checkNegations; // } // // /** // * Retrieve the associated permissions. // * // * @return the permissions // */ // public List<String> getPermissions() { // return permissions; // } // // /** // * Retrieve whether or not all permissions are required. // * // * @return true if all permissions are required // */ // public boolean isAll() { // return all; // } // // /** // * Retrieve whether or not negations were checked. // * // * @return true if negations were checked // */ // public boolean isCheckNegations() { // return checkNegations; // } // // } // Path: src/test/java/org/tyrannyofheaven/bukkit/util/command/CommandTest.java import org.bukkit.util.StringUtil; import org.junit.Before; import org.junit.Test; import org.tyrannyofheaven.bukkit.util.permissions.PermissionException; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import junit.framework.Assert; import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionAttachment; import org.bukkit.permissions.PermissionAttachmentInfo; import org.bukkit.plugin.Plugin; // Positional argument that starts with - he.execute(dummySender, "greet", "greet", new String[] { "--", "-garply" }); Assert.assertEquals("Hello, -garply\n", out.toString()); out.delete(0, out.length()); // String[] parameter he.execute(dummySender, "say", "say", new String[] { "Hello", "there" }); Assert.assertEquals("Hello there\n", out.toString()); out.delete(0, out.length()); // No flags, so should not parse -Hello as one. he.execute(dummySender, "say", "say", new String[] { "-Hello", "there" }); Assert.assertEquals("-Hello there\n", out.toString()); out.delete(0, out.length()); // Sub-command good = false; try { he.execute(dummySender, "foo", "foo", new String[0]); } catch (ParseException e) { good = true; } Assert.assertTrue(good); he.execute(dummySender, "foo", "foo", new String[] { "hello" }); Assert.assertEquals("Hello from the foo sub-command!\n", out.toString()); out.delete(0, out.length()); good = false; try { he.execute(dummySender, "foo", "foo", new String[] { "hello", "extra" }); } catch (ParseException e) { good = true; } Assert.assertTrue(good); good = false; permissions.clear(); try { he.execute(dummySender, "secret", "secret", new String[0]); }
catch (PermissionException e) {
ZerothAngel/ToHPluginUtils
src/main/java/org/tyrannyofheaven/bukkit/util/command/ParsedArgs.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // }
import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map;
} } else { options.put(omd.getName(), args[pos++]); parsedPositional = true; } } else { if (pos >= args.length) { // No more args, this and the rest should be optional unparsedArgument = omd; break; } else { options.put(omd.getName(), args[pos++]); parsedPositional = true; } } } rest = Arrays.copyOfRange(args, pos, args.length); } /** * Retrieve associated value for an option. * * @param name the option name * @return the associated String value */ public String getOption(String name) {
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // } // Path: src/main/java/org/tyrannyofheaven/bukkit/util/command/ParsedArgs.java import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; } } else { options.put(omd.getName(), args[pos++]); parsedPositional = true; } } else { if (pos >= args.length) { // No more args, this and the rest should be optional unparsedArgument = omd; break; } else { options.put(omd.getName(), args[pos++]); parsedPositional = true; } } } rest = Arrays.copyOfRange(args, pos, args.length); } /** * Retrieve associated value for an option. * * @param name the option name * @return the associated String value */ public String getOption(String name) {
if (!hasText(name))
ZerothAngel/ToHPluginUtils
src/main/java/org/tyrannyofheaven/bukkit/util/command/HelpBuilder.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // }
import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.bukkit.command.CommandSender;
/** * Set the current handler object. * * @param handler the handler object * @return this HelpBuilder */ public HelpBuilder withHandler(Object handler) { if (handler == null) throw new IllegalArgumentException("handler cannot be null"); this.handler = handler; return this; } // Retrieve the current handler object, complaining if one hasn't been set private Object getHandler() { if (handler == null) throw new IllegalStateException("handler has not been set"); return handler; } /** * Generate a usage message for a particular sibling command. * * @param command the sibling command * @param usePermissions true if permissions should be checked. If the current * sender fails the check, no usage is generated. * @return this HelpBuilder */ public HelpBuilder forSiblingCommand(String command, boolean usePermissions) {
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // } // Path: src/main/java/org/tyrannyofheaven/bukkit/util/command/HelpBuilder.java import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.bukkit.command.CommandSender; /** * Set the current handler object. * * @param handler the handler object * @return this HelpBuilder */ public HelpBuilder withHandler(Object handler) { if (handler == null) throw new IllegalArgumentException("handler cannot be null"); this.handler = handler; return this; } // Retrieve the current handler object, complaining if one hasn't been set private Object getHandler() { if (handler == null) throw new IllegalStateException("handler has not been set"); return handler; } /** * Generate a usage message for a particular sibling command. * * @param command the sibling command * @param usePermissions true if permissions should be checked. If the current * sender fails the check, no usage is generated. * @return this HelpBuilder */ public HelpBuilder forSiblingCommand(String command, boolean usePermissions) {
if (!hasText(command))
ZerothAngel/ToHPluginUtils
src/main/java/org/tyrannyofheaven/bukkit/util/ToHFileUtils.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHLoggingUtils.java // public static void log(Plugin plugin, Level level, String format, Object... args) { // Logger logger = plugin.getLogger(); // if (logger.isLoggable(level)) { // Avoid unnecessary String.format() calls // if (args.length > 0 && args[args.length - 1] instanceof Throwable) { // // Last argument is a Throwable, treat accordingly // logger.log(level, createLogMessage(format, Arrays.copyOf(args, args.length - 1)), (Throwable)args[args.length - 1]); // } // else { // logger.log(level, createLogMessage(format, args)); // } // } // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/configuration/AnnotatedYamlConfiguration.java // public class AnnotatedYamlConfiguration extends YamlConfiguration { // // private final DumperOptions yamlOptions = new DumperOptions(); // // private final Representer yamlRepresenter = new YamlRepresenter(); // // private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions); // // // Map from property key to comment. Comment may have multiple lines that are newline-separated. // private final Map<String, String> comments = new HashMap<>(); // // @Override // public String saveToString() { // // Wish these were protected... // yamlOptions.setIndent(options().indent()); // yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); // yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); // // StringBuilder builder = new StringBuilder(); // builder.append(buildHeader()); // if (builder.length() > 0) // builder.append('\n'); // Newline after header, if present // // // Iterate over each root-level property and dump // for (Iterator<Map.Entry<String, Object>> i = getValues(false).entrySet().iterator(); i.hasNext();) { // Map.Entry<String, Object> entry = i.next(); // // // Output comment, if present // String comment = comments.get(entry.getKey()); // if (comment != null) { // builder.append(buildComment(comment)); // } // // // Dump property // builder.append(yaml.dump(Collections.singletonMap(entry.getKey(), entry.getValue()))); // // // Output newline, if not the last // if (i.hasNext()) // builder.append('\n'); // } // // String dump = builder.toString(); // // if (dump.equals(BLANK_CONFIG)) { // dump = ""; // } // // return dump; // } // // /** // * Format a multi-line property comment. // * // * @param comment the original comment string // * @return the formatted comment string // */ // protected String buildComment(String comment) { // StringBuilder builder = new StringBuilder(); // for (String line : comment.split("\r?\n")) { // builder.append(COMMENT_PREFIX); // builder.append(line); // builder.append('\n'); // } // return builder.toString(); // } // // /** // * Returns a root-level comment. // * // * @param key the property key // * @return the comment or <code>null</code> // */ // public String getComment(String key) { // return comments.get(key); // } // // /** // * Set a root-level comment. // * // * @param key the property key // * @param comment the comment. May be <code>null</code>, in which case the comment // * is removed. // */ // public void setComment(String key, String... comment) { // if (comment != null && comment.length > 0) { // String s = Joiner.on('\n').join(comment); // comments.put(key, s); // } // else { // comments.remove(key); // } // } // // /** // * Returns root-level comments. // * // * @return map of root-level comments // */ // public Map<String, String> getComments() { // return Collections.unmodifiableMap(comments); // } // // /** // * Set root-level comments from a map. // * // * @param comments comment map // */ // public void setComments(Map<String, String> comments) { // this.comments.clear(); // if (comments != null) // this.comments.putAll(comments); // } // // }
import static org.tyrannyofheaven.bukkit.util.ToHLoggingUtils.log; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import org.bukkit.configuration.Configuration; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.Plugin; import org.tyrannyofheaven.bukkit.util.configuration.AnnotatedYamlConfiguration; import com.google.common.base.Charsets;
* * @param clazz the class * @param resourceName resource name relative to the class * @param outFile the output File * @throws IOException */ public static void copyResourceToFile(Class<?> clazz, String resourceName, File outFile) throws IOException { InputStream is = clazz.getResourceAsStream(resourceName); try { copyFile(is, outFile); } finally { is.close(); } } /** * Copies a resource relative to the Plugin class to a file. * * @param plugin the plugin * @param resourceName resource name relative to plugin's class * @param outFile the output file * @return true if successful, false otherwise */ public static boolean copyResourceToFile(Plugin plugin, String resourceName, File outFile) { try { copyResourceToFile(plugin.getClass(), resourceName, outFile); return true; } catch (IOException e) {
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHLoggingUtils.java // public static void log(Plugin plugin, Level level, String format, Object... args) { // Logger logger = plugin.getLogger(); // if (logger.isLoggable(level)) { // Avoid unnecessary String.format() calls // if (args.length > 0 && args[args.length - 1] instanceof Throwable) { // // Last argument is a Throwable, treat accordingly // logger.log(level, createLogMessage(format, Arrays.copyOf(args, args.length - 1)), (Throwable)args[args.length - 1]); // } // else { // logger.log(level, createLogMessage(format, args)); // } // } // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/configuration/AnnotatedYamlConfiguration.java // public class AnnotatedYamlConfiguration extends YamlConfiguration { // // private final DumperOptions yamlOptions = new DumperOptions(); // // private final Representer yamlRepresenter = new YamlRepresenter(); // // private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions); // // // Map from property key to comment. Comment may have multiple lines that are newline-separated. // private final Map<String, String> comments = new HashMap<>(); // // @Override // public String saveToString() { // // Wish these were protected... // yamlOptions.setIndent(options().indent()); // yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); // yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); // // StringBuilder builder = new StringBuilder(); // builder.append(buildHeader()); // if (builder.length() > 0) // builder.append('\n'); // Newline after header, if present // // // Iterate over each root-level property and dump // for (Iterator<Map.Entry<String, Object>> i = getValues(false).entrySet().iterator(); i.hasNext();) { // Map.Entry<String, Object> entry = i.next(); // // // Output comment, if present // String comment = comments.get(entry.getKey()); // if (comment != null) { // builder.append(buildComment(comment)); // } // // // Dump property // builder.append(yaml.dump(Collections.singletonMap(entry.getKey(), entry.getValue()))); // // // Output newline, if not the last // if (i.hasNext()) // builder.append('\n'); // } // // String dump = builder.toString(); // // if (dump.equals(BLANK_CONFIG)) { // dump = ""; // } // // return dump; // } // // /** // * Format a multi-line property comment. // * // * @param comment the original comment string // * @return the formatted comment string // */ // protected String buildComment(String comment) { // StringBuilder builder = new StringBuilder(); // for (String line : comment.split("\r?\n")) { // builder.append(COMMENT_PREFIX); // builder.append(line); // builder.append('\n'); // } // return builder.toString(); // } // // /** // * Returns a root-level comment. // * // * @param key the property key // * @return the comment or <code>null</code> // */ // public String getComment(String key) { // return comments.get(key); // } // // /** // * Set a root-level comment. // * // * @param key the property key // * @param comment the comment. May be <code>null</code>, in which case the comment // * is removed. // */ // public void setComment(String key, String... comment) { // if (comment != null && comment.length > 0) { // String s = Joiner.on('\n').join(comment); // comments.put(key, s); // } // else { // comments.remove(key); // } // } // // /** // * Returns root-level comments. // * // * @return map of root-level comments // */ // public Map<String, String> getComments() { // return Collections.unmodifiableMap(comments); // } // // /** // * Set root-level comments from a map. // * // * @param comments comment map // */ // public void setComments(Map<String, String> comments) { // this.comments.clear(); // if (comments != null) // this.comments.putAll(comments); // } // // } // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHFileUtils.java import static org.tyrannyofheaven.bukkit.util.ToHLoggingUtils.log; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import org.bukkit.configuration.Configuration; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.Plugin; import org.tyrannyofheaven.bukkit.util.configuration.AnnotatedYamlConfiguration; import com.google.common.base.Charsets; * * @param clazz the class * @param resourceName resource name relative to the class * @param outFile the output File * @throws IOException */ public static void copyResourceToFile(Class<?> clazz, String resourceName, File outFile) throws IOException { InputStream is = clazz.getResourceAsStream(resourceName); try { copyFile(is, outFile); } finally { is.close(); } } /** * Copies a resource relative to the Plugin class to a file. * * @param plugin the plugin * @param resourceName resource name relative to plugin's class * @param outFile the output file * @return true if successful, false otherwise */ public static boolean copyResourceToFile(Plugin plugin, String resourceName, File outFile) { try { copyResourceToFile(plugin.getClass(), resourceName, outFile); return true; } catch (IOException e) {
log(plugin, Level.SEVERE, "Error copying %s to %s", resourceName, outFile, e);
ZerothAngel/ToHPluginUtils
src/main/java/org/tyrannyofheaven/bukkit/util/command/reader/CommandReader.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static String colorize(String text) { // if (text == null) return null; // // // Works best with interned strings // String cacheResult = colorizeCache.get(text); // if (cacheResult != null) return cacheResult; // // StringBuilder out = new StringBuilder(); // // ColorizeState state = ColorizeState.TEXT; // StringBuilder color = null; // // for (int i = 0; i < text.length(); i++) { // char c = text.charAt(i); // // if (state == ColorizeState.TEXT) { // if (c == '{') { // state = ColorizeState.COLOR_OPEN; // } // else if (c == '}') { // state = ColorizeState.COLOR_CLOSE; // } // else if (c == '`') { // state = ColorizeState.COLOR_ESCAPE; // } // else { // out.append(c); // } // } // else if (state == ColorizeState.COLOR_OPEN) { // if (c == '{') { // Escaped bracket // out.append('{'); // state = ColorizeState.TEXT; // } // else if (Character.isUpperCase(c)) { // // First character of color name // color = new StringBuilder(); // color.append(c); // state = ColorizeState.COLOR_NAME; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_NAME) { // if (Character.isUpperCase(c) || c == '_') { // color.append(c); // } // else if (c == '}') { // ChatColor chatColor = ChatColor.valueOf(color.toString()); // out.append(chatColor); // state = ColorizeState.TEXT; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_CLOSE) { // // Optional, but for sanity's sake, to keep brackets matched // if (c == '}') { // out.append('}'); // Collapse to single bracket // } // else { // out.append('}'); // out.append(c); // } // state = ColorizeState.TEXT; // } // else if (state == ColorizeState.COLOR_ESCAPE) { // out.append(decodeColor(c)); // state = ColorizeState.TEXT; // } // else // throw new AssertionError("Unknown ColorizeState"); // } // // // End of string // if (state == ColorizeState.COLOR_CLOSE) { // out.append('}'); // } // else if (state != ColorizeState.TEXT) { // // Was in the middle of color name // throw new IllegalArgumentException("Invalid color name"); // } // // cacheResult = out.toString(); // colorizeCache.putIfAbsent(text, cacheResult); // // return cacheResult; // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static void sendMessage(CommandSender sender, String format, Object... args) { // String message = String.format(format, args); // for (String line : message.split("\n")) { // sender.sendMessage(line); // } // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static String delimitedString(String delimiter, Collection<?> coll) { // StringBuilder sb = new StringBuilder(); // for (Iterator<?> i = coll.iterator(); i.hasNext();) { // sb.append(i.next()); // if (i.hasNext()) // sb.append(delimiter); // } // return sb.toString(); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // }
import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.colorize; import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.sendMessage; import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.delimitedString; import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.bukkit.Server; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginCommand; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin;
} // Break up into args String[] args = line.split(" "); // Strip leading slash if present String c = args[0].toLowerCase(); if (c.startsWith("/")) c = c.substring(1); Command command = getCommand(server, c, plugins); if (command == null) { throw new CommandReaderException(String.format("Unknown command at line %d", lineNo)); } calls.add(new CommandCall(command, c, Arrays.copyOfRange(args, 1, args.length))); } } finally { in.close(); } // Set up abort flag abortFlags.set(Boolean.FALSE); try { // Execute each call for (CommandCall call : calls) { try { if (echo) {
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static String colorize(String text) { // if (text == null) return null; // // // Works best with interned strings // String cacheResult = colorizeCache.get(text); // if (cacheResult != null) return cacheResult; // // StringBuilder out = new StringBuilder(); // // ColorizeState state = ColorizeState.TEXT; // StringBuilder color = null; // // for (int i = 0; i < text.length(); i++) { // char c = text.charAt(i); // // if (state == ColorizeState.TEXT) { // if (c == '{') { // state = ColorizeState.COLOR_OPEN; // } // else if (c == '}') { // state = ColorizeState.COLOR_CLOSE; // } // else if (c == '`') { // state = ColorizeState.COLOR_ESCAPE; // } // else { // out.append(c); // } // } // else if (state == ColorizeState.COLOR_OPEN) { // if (c == '{') { // Escaped bracket // out.append('{'); // state = ColorizeState.TEXT; // } // else if (Character.isUpperCase(c)) { // // First character of color name // color = new StringBuilder(); // color.append(c); // state = ColorizeState.COLOR_NAME; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_NAME) { // if (Character.isUpperCase(c) || c == '_') { // color.append(c); // } // else if (c == '}') { // ChatColor chatColor = ChatColor.valueOf(color.toString()); // out.append(chatColor); // state = ColorizeState.TEXT; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_CLOSE) { // // Optional, but for sanity's sake, to keep brackets matched // if (c == '}') { // out.append('}'); // Collapse to single bracket // } // else { // out.append('}'); // out.append(c); // } // state = ColorizeState.TEXT; // } // else if (state == ColorizeState.COLOR_ESCAPE) { // out.append(decodeColor(c)); // state = ColorizeState.TEXT; // } // else // throw new AssertionError("Unknown ColorizeState"); // } // // // End of string // if (state == ColorizeState.COLOR_CLOSE) { // out.append('}'); // } // else if (state != ColorizeState.TEXT) { // // Was in the middle of color name // throw new IllegalArgumentException("Invalid color name"); // } // // cacheResult = out.toString(); // colorizeCache.putIfAbsent(text, cacheResult); // // return cacheResult; // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static void sendMessage(CommandSender sender, String format, Object... args) { // String message = String.format(format, args); // for (String line : message.split("\n")) { // sender.sendMessage(line); // } // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static String delimitedString(String delimiter, Collection<?> coll) { // StringBuilder sb = new StringBuilder(); // for (Iterator<?> i = coll.iterator(); i.hasNext();) { // sb.append(i.next()); // if (i.hasNext()) // sb.append(delimiter); // } // return sb.toString(); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // } // Path: src/main/java/org/tyrannyofheaven/bukkit/util/command/reader/CommandReader.java import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.colorize; import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.sendMessage; import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.delimitedString; import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.bukkit.Server; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginCommand; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; } // Break up into args String[] args = line.split(" "); // Strip leading slash if present String c = args[0].toLowerCase(); if (c.startsWith("/")) c = c.substring(1); Command command = getCommand(server, c, plugins); if (command == null) { throw new CommandReaderException(String.format("Unknown command at line %d", lineNo)); } calls.add(new CommandCall(command, c, Arrays.copyOfRange(args, 1, args.length))); } } finally { in.close(); } // Set up abort flag abortFlags.set(Boolean.FALSE); try { // Execute each call for (CommandCall call : calls) { try { if (echo) {
sendMessage(sender, colorize("{GRAY}%s%s%s%s"),
ZerothAngel/ToHPluginUtils
src/main/java/org/tyrannyofheaven/bukkit/util/command/reader/CommandReader.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static String colorize(String text) { // if (text == null) return null; // // // Works best with interned strings // String cacheResult = colorizeCache.get(text); // if (cacheResult != null) return cacheResult; // // StringBuilder out = new StringBuilder(); // // ColorizeState state = ColorizeState.TEXT; // StringBuilder color = null; // // for (int i = 0; i < text.length(); i++) { // char c = text.charAt(i); // // if (state == ColorizeState.TEXT) { // if (c == '{') { // state = ColorizeState.COLOR_OPEN; // } // else if (c == '}') { // state = ColorizeState.COLOR_CLOSE; // } // else if (c == '`') { // state = ColorizeState.COLOR_ESCAPE; // } // else { // out.append(c); // } // } // else if (state == ColorizeState.COLOR_OPEN) { // if (c == '{') { // Escaped bracket // out.append('{'); // state = ColorizeState.TEXT; // } // else if (Character.isUpperCase(c)) { // // First character of color name // color = new StringBuilder(); // color.append(c); // state = ColorizeState.COLOR_NAME; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_NAME) { // if (Character.isUpperCase(c) || c == '_') { // color.append(c); // } // else if (c == '}') { // ChatColor chatColor = ChatColor.valueOf(color.toString()); // out.append(chatColor); // state = ColorizeState.TEXT; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_CLOSE) { // // Optional, but for sanity's sake, to keep brackets matched // if (c == '}') { // out.append('}'); // Collapse to single bracket // } // else { // out.append('}'); // out.append(c); // } // state = ColorizeState.TEXT; // } // else if (state == ColorizeState.COLOR_ESCAPE) { // out.append(decodeColor(c)); // state = ColorizeState.TEXT; // } // else // throw new AssertionError("Unknown ColorizeState"); // } // // // End of string // if (state == ColorizeState.COLOR_CLOSE) { // out.append('}'); // } // else if (state != ColorizeState.TEXT) { // // Was in the middle of color name // throw new IllegalArgumentException("Invalid color name"); // } // // cacheResult = out.toString(); // colorizeCache.putIfAbsent(text, cacheResult); // // return cacheResult; // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static void sendMessage(CommandSender sender, String format, Object... args) { // String message = String.format(format, args); // for (String line : message.split("\n")) { // sender.sendMessage(line); // } // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static String delimitedString(String delimiter, Collection<?> coll) { // StringBuilder sb = new StringBuilder(); // for (Iterator<?> i = coll.iterator(); i.hasNext();) { // sb.append(i.next()); // if (i.hasNext()) // sb.append(delimiter); // } // return sb.toString(); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // }
import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.colorize; import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.sendMessage; import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.delimitedString; import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.bukkit.Server; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginCommand; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin;
} // Break up into args String[] args = line.split(" "); // Strip leading slash if present String c = args[0].toLowerCase(); if (c.startsWith("/")) c = c.substring(1); Command command = getCommand(server, c, plugins); if (command == null) { throw new CommandReaderException(String.format("Unknown command at line %d", lineNo)); } calls.add(new CommandCall(command, c, Arrays.copyOfRange(args, 1, args.length))); } } finally { in.close(); } // Set up abort flag abortFlags.set(Boolean.FALSE); try { // Execute each call for (CommandCall call : calls) { try { if (echo) {
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static String colorize(String text) { // if (text == null) return null; // // // Works best with interned strings // String cacheResult = colorizeCache.get(text); // if (cacheResult != null) return cacheResult; // // StringBuilder out = new StringBuilder(); // // ColorizeState state = ColorizeState.TEXT; // StringBuilder color = null; // // for (int i = 0; i < text.length(); i++) { // char c = text.charAt(i); // // if (state == ColorizeState.TEXT) { // if (c == '{') { // state = ColorizeState.COLOR_OPEN; // } // else if (c == '}') { // state = ColorizeState.COLOR_CLOSE; // } // else if (c == '`') { // state = ColorizeState.COLOR_ESCAPE; // } // else { // out.append(c); // } // } // else if (state == ColorizeState.COLOR_OPEN) { // if (c == '{') { // Escaped bracket // out.append('{'); // state = ColorizeState.TEXT; // } // else if (Character.isUpperCase(c)) { // // First character of color name // color = new StringBuilder(); // color.append(c); // state = ColorizeState.COLOR_NAME; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_NAME) { // if (Character.isUpperCase(c) || c == '_') { // color.append(c); // } // else if (c == '}') { // ChatColor chatColor = ChatColor.valueOf(color.toString()); // out.append(chatColor); // state = ColorizeState.TEXT; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_CLOSE) { // // Optional, but for sanity's sake, to keep brackets matched // if (c == '}') { // out.append('}'); // Collapse to single bracket // } // else { // out.append('}'); // out.append(c); // } // state = ColorizeState.TEXT; // } // else if (state == ColorizeState.COLOR_ESCAPE) { // out.append(decodeColor(c)); // state = ColorizeState.TEXT; // } // else // throw new AssertionError("Unknown ColorizeState"); // } // // // End of string // if (state == ColorizeState.COLOR_CLOSE) { // out.append('}'); // } // else if (state != ColorizeState.TEXT) { // // Was in the middle of color name // throw new IllegalArgumentException("Invalid color name"); // } // // cacheResult = out.toString(); // colorizeCache.putIfAbsent(text, cacheResult); // // return cacheResult; // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static void sendMessage(CommandSender sender, String format, Object... args) { // String message = String.format(format, args); // for (String line : message.split("\n")) { // sender.sendMessage(line); // } // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static String delimitedString(String delimiter, Collection<?> coll) { // StringBuilder sb = new StringBuilder(); // for (Iterator<?> i = coll.iterator(); i.hasNext();) { // sb.append(i.next()); // if (i.hasNext()) // sb.append(delimiter); // } // return sb.toString(); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // } // Path: src/main/java/org/tyrannyofheaven/bukkit/util/command/reader/CommandReader.java import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.colorize; import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.sendMessage; import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.delimitedString; import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.bukkit.Server; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginCommand; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; } // Break up into args String[] args = line.split(" "); // Strip leading slash if present String c = args[0].toLowerCase(); if (c.startsWith("/")) c = c.substring(1); Command command = getCommand(server, c, plugins); if (command == null) { throw new CommandReaderException(String.format("Unknown command at line %d", lineNo)); } calls.add(new CommandCall(command, c, Arrays.copyOfRange(args, 1, args.length))); } } finally { in.close(); } // Set up abort flag abortFlags.set(Boolean.FALSE); try { // Execute each call for (CommandCall call : calls) { try { if (echo) {
sendMessage(sender, colorize("{GRAY}%s%s%s%s"),
ZerothAngel/ToHPluginUtils
src/main/java/org/tyrannyofheaven/bukkit/util/command/reader/CommandReader.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static String colorize(String text) { // if (text == null) return null; // // // Works best with interned strings // String cacheResult = colorizeCache.get(text); // if (cacheResult != null) return cacheResult; // // StringBuilder out = new StringBuilder(); // // ColorizeState state = ColorizeState.TEXT; // StringBuilder color = null; // // for (int i = 0; i < text.length(); i++) { // char c = text.charAt(i); // // if (state == ColorizeState.TEXT) { // if (c == '{') { // state = ColorizeState.COLOR_OPEN; // } // else if (c == '}') { // state = ColorizeState.COLOR_CLOSE; // } // else if (c == '`') { // state = ColorizeState.COLOR_ESCAPE; // } // else { // out.append(c); // } // } // else if (state == ColorizeState.COLOR_OPEN) { // if (c == '{') { // Escaped bracket // out.append('{'); // state = ColorizeState.TEXT; // } // else if (Character.isUpperCase(c)) { // // First character of color name // color = new StringBuilder(); // color.append(c); // state = ColorizeState.COLOR_NAME; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_NAME) { // if (Character.isUpperCase(c) || c == '_') { // color.append(c); // } // else if (c == '}') { // ChatColor chatColor = ChatColor.valueOf(color.toString()); // out.append(chatColor); // state = ColorizeState.TEXT; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_CLOSE) { // // Optional, but for sanity's sake, to keep brackets matched // if (c == '}') { // out.append('}'); // Collapse to single bracket // } // else { // out.append('}'); // out.append(c); // } // state = ColorizeState.TEXT; // } // else if (state == ColorizeState.COLOR_ESCAPE) { // out.append(decodeColor(c)); // state = ColorizeState.TEXT; // } // else // throw new AssertionError("Unknown ColorizeState"); // } // // // End of string // if (state == ColorizeState.COLOR_CLOSE) { // out.append('}'); // } // else if (state != ColorizeState.TEXT) { // // Was in the middle of color name // throw new IllegalArgumentException("Invalid color name"); // } // // cacheResult = out.toString(); // colorizeCache.putIfAbsent(text, cacheResult); // // return cacheResult; // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static void sendMessage(CommandSender sender, String format, Object... args) { // String message = String.format(format, args); // for (String line : message.split("\n")) { // sender.sendMessage(line); // } // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static String delimitedString(String delimiter, Collection<?> coll) { // StringBuilder sb = new StringBuilder(); // for (Iterator<?> i = coll.iterator(); i.hasNext();) { // sb.append(i.next()); // if (i.hasNext()) // sb.append(delimiter); // } // return sb.toString(); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // }
import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.colorize; import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.sendMessage; import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.delimitedString; import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.bukkit.Server; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginCommand; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin;
// Strip leading slash if present String c = args[0].toLowerCase(); if (c.startsWith("/")) c = c.substring(1); Command command = getCommand(server, c, plugins); if (command == null) { throw new CommandReaderException(String.format("Unknown command at line %d", lineNo)); } calls.add(new CommandCall(command, c, Arrays.copyOfRange(args, 1, args.length))); } } finally { in.close(); } // Set up abort flag abortFlags.set(Boolean.FALSE); try { // Execute each call for (CommandCall call : calls) { try { if (echo) { sendMessage(sender, colorize("{GRAY}%s%s%s%s"), (sender instanceof Player ? "/" : ""), call.getAlias(), (call.getArgs().length > 0 ? " " : ""),
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static String colorize(String text) { // if (text == null) return null; // // // Works best with interned strings // String cacheResult = colorizeCache.get(text); // if (cacheResult != null) return cacheResult; // // StringBuilder out = new StringBuilder(); // // ColorizeState state = ColorizeState.TEXT; // StringBuilder color = null; // // for (int i = 0; i < text.length(); i++) { // char c = text.charAt(i); // // if (state == ColorizeState.TEXT) { // if (c == '{') { // state = ColorizeState.COLOR_OPEN; // } // else if (c == '}') { // state = ColorizeState.COLOR_CLOSE; // } // else if (c == '`') { // state = ColorizeState.COLOR_ESCAPE; // } // else { // out.append(c); // } // } // else if (state == ColorizeState.COLOR_OPEN) { // if (c == '{') { // Escaped bracket // out.append('{'); // state = ColorizeState.TEXT; // } // else if (Character.isUpperCase(c)) { // // First character of color name // color = new StringBuilder(); // color.append(c); // state = ColorizeState.COLOR_NAME; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_NAME) { // if (Character.isUpperCase(c) || c == '_') { // color.append(c); // } // else if (c == '}') { // ChatColor chatColor = ChatColor.valueOf(color.toString()); // out.append(chatColor); // state = ColorizeState.TEXT; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_CLOSE) { // // Optional, but for sanity's sake, to keep brackets matched // if (c == '}') { // out.append('}'); // Collapse to single bracket // } // else { // out.append('}'); // out.append(c); // } // state = ColorizeState.TEXT; // } // else if (state == ColorizeState.COLOR_ESCAPE) { // out.append(decodeColor(c)); // state = ColorizeState.TEXT; // } // else // throw new AssertionError("Unknown ColorizeState"); // } // // // End of string // if (state == ColorizeState.COLOR_CLOSE) { // out.append('}'); // } // else if (state != ColorizeState.TEXT) { // // Was in the middle of color name // throw new IllegalArgumentException("Invalid color name"); // } // // cacheResult = out.toString(); // colorizeCache.putIfAbsent(text, cacheResult); // // return cacheResult; // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static void sendMessage(CommandSender sender, String format, Object... args) { // String message = String.format(format, args); // for (String line : message.split("\n")) { // sender.sendMessage(line); // } // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static String delimitedString(String delimiter, Collection<?> coll) { // StringBuilder sb = new StringBuilder(); // for (Iterator<?> i = coll.iterator(); i.hasNext();) { // sb.append(i.next()); // if (i.hasNext()) // sb.append(delimiter); // } // return sb.toString(); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // } // Path: src/main/java/org/tyrannyofheaven/bukkit/util/command/reader/CommandReader.java import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.colorize; import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.sendMessage; import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.delimitedString; import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.bukkit.Server; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginCommand; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; // Strip leading slash if present String c = args[0].toLowerCase(); if (c.startsWith("/")) c = c.substring(1); Command command = getCommand(server, c, plugins); if (command == null) { throw new CommandReaderException(String.format("Unknown command at line %d", lineNo)); } calls.add(new CommandCall(command, c, Arrays.copyOfRange(args, 1, args.length))); } } finally { in.close(); } // Set up abort flag abortFlags.set(Boolean.FALSE); try { // Execute each call for (CommandCall call : calls) { try { if (echo) { sendMessage(sender, colorize("{GRAY}%s%s%s%s"), (sender instanceof Player ? "/" : ""), call.getAlias(), (call.getArgs().length > 0 ? " " : ""),
delimitedString(" ", (Object[])call.getArgs()));
ZerothAngel/ToHPluginUtils
src/main/java/org/tyrannyofheaven/bukkit/util/command/reader/CommandReader.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static String colorize(String text) { // if (text == null) return null; // // // Works best with interned strings // String cacheResult = colorizeCache.get(text); // if (cacheResult != null) return cacheResult; // // StringBuilder out = new StringBuilder(); // // ColorizeState state = ColorizeState.TEXT; // StringBuilder color = null; // // for (int i = 0; i < text.length(); i++) { // char c = text.charAt(i); // // if (state == ColorizeState.TEXT) { // if (c == '{') { // state = ColorizeState.COLOR_OPEN; // } // else if (c == '}') { // state = ColorizeState.COLOR_CLOSE; // } // else if (c == '`') { // state = ColorizeState.COLOR_ESCAPE; // } // else { // out.append(c); // } // } // else if (state == ColorizeState.COLOR_OPEN) { // if (c == '{') { // Escaped bracket // out.append('{'); // state = ColorizeState.TEXT; // } // else if (Character.isUpperCase(c)) { // // First character of color name // color = new StringBuilder(); // color.append(c); // state = ColorizeState.COLOR_NAME; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_NAME) { // if (Character.isUpperCase(c) || c == '_') { // color.append(c); // } // else if (c == '}') { // ChatColor chatColor = ChatColor.valueOf(color.toString()); // out.append(chatColor); // state = ColorizeState.TEXT; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_CLOSE) { // // Optional, but for sanity's sake, to keep brackets matched // if (c == '}') { // out.append('}'); // Collapse to single bracket // } // else { // out.append('}'); // out.append(c); // } // state = ColorizeState.TEXT; // } // else if (state == ColorizeState.COLOR_ESCAPE) { // out.append(decodeColor(c)); // state = ColorizeState.TEXT; // } // else // throw new AssertionError("Unknown ColorizeState"); // } // // // End of string // if (state == ColorizeState.COLOR_CLOSE) { // out.append('}'); // } // else if (state != ColorizeState.TEXT) { // // Was in the middle of color name // throw new IllegalArgumentException("Invalid color name"); // } // // cacheResult = out.toString(); // colorizeCache.putIfAbsent(text, cacheResult); // // return cacheResult; // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static void sendMessage(CommandSender sender, String format, Object... args) { // String message = String.format(format, args); // for (String line : message.split("\n")) { // sender.sendMessage(line); // } // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static String delimitedString(String delimiter, Collection<?> coll) { // StringBuilder sb = new StringBuilder(); // for (Iterator<?> i = coll.iterator(); i.hasNext();) { // sb.append(i.next()); // if (i.hasNext()) // sb.append(delimiter); // } // return sb.toString(); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // }
import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.colorize; import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.sendMessage; import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.delimitedString; import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.bukkit.Server; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginCommand; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin;
* May be called by command handlers to abort batch processing. Does nothing * if the handler was not called within {@link #read(Server, CommandSender, InputStream, boolean, Plugin...)}. */ public static void abortBatchProcessing() { if (isBatchProcessing()) abortFlags.set(Boolean.TRUE); } /** * Tests if current thread is currently running batch commands, e.g. * called within {@link #read(Server, CommandSender, InputStream, boolean, Plugin...)}. * * @return true if the current thread is running batch commands */ public static boolean isBatchProcessing() { return abortFlags.get() != null; } // Holder for command invocation private static class CommandCall { private final Command command; private final String alias; private final String[] args; public CommandCall(Command command, String alias, String[] args) { if (command == null) throw new IllegalArgumentException("command cannot be null");
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static String colorize(String text) { // if (text == null) return null; // // // Works best with interned strings // String cacheResult = colorizeCache.get(text); // if (cacheResult != null) return cacheResult; // // StringBuilder out = new StringBuilder(); // // ColorizeState state = ColorizeState.TEXT; // StringBuilder color = null; // // for (int i = 0; i < text.length(); i++) { // char c = text.charAt(i); // // if (state == ColorizeState.TEXT) { // if (c == '{') { // state = ColorizeState.COLOR_OPEN; // } // else if (c == '}') { // state = ColorizeState.COLOR_CLOSE; // } // else if (c == '`') { // state = ColorizeState.COLOR_ESCAPE; // } // else { // out.append(c); // } // } // else if (state == ColorizeState.COLOR_OPEN) { // if (c == '{') { // Escaped bracket // out.append('{'); // state = ColorizeState.TEXT; // } // else if (Character.isUpperCase(c)) { // // First character of color name // color = new StringBuilder(); // color.append(c); // state = ColorizeState.COLOR_NAME; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_NAME) { // if (Character.isUpperCase(c) || c == '_') { // color.append(c); // } // else if (c == '}') { // ChatColor chatColor = ChatColor.valueOf(color.toString()); // out.append(chatColor); // state = ColorizeState.TEXT; // } // else { // // Invalid // throw new IllegalArgumentException("Invalid color name"); // } // } // else if (state == ColorizeState.COLOR_CLOSE) { // // Optional, but for sanity's sake, to keep brackets matched // if (c == '}') { // out.append('}'); // Collapse to single bracket // } // else { // out.append('}'); // out.append(c); // } // state = ColorizeState.TEXT; // } // else if (state == ColorizeState.COLOR_ESCAPE) { // out.append(decodeColor(c)); // state = ColorizeState.TEXT; // } // else // throw new AssertionError("Unknown ColorizeState"); // } // // // End of string // if (state == ColorizeState.COLOR_CLOSE) { // out.append('}'); // } // else if (state != ColorizeState.TEXT) { // // Was in the middle of color name // throw new IllegalArgumentException("Invalid color name"); // } // // cacheResult = out.toString(); // colorizeCache.putIfAbsent(text, cacheResult); // // return cacheResult; // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHMessageUtils.java // public static void sendMessage(CommandSender sender, String format, Object... args) { // String message = String.format(format, args); // for (String line : message.split("\n")) { // sender.sendMessage(line); // } // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static String delimitedString(String delimiter, Collection<?> coll) { // StringBuilder sb = new StringBuilder(); // for (Iterator<?> i = coll.iterator(); i.hasNext();) { // sb.append(i.next()); // if (i.hasNext()) // sb.append(delimiter); // } // return sb.toString(); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/ToHStringUtils.java // public static boolean hasText(String text) { // return text != null && text.trim().length() > 0; // } // Path: src/main/java/org/tyrannyofheaven/bukkit/util/command/reader/CommandReader.java import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.colorize; import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.sendMessage; import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.delimitedString; import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.bukkit.Server; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginCommand; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; * May be called by command handlers to abort batch processing. Does nothing * if the handler was not called within {@link #read(Server, CommandSender, InputStream, boolean, Plugin...)}. */ public static void abortBatchProcessing() { if (isBatchProcessing()) abortFlags.set(Boolean.TRUE); } /** * Tests if current thread is currently running batch commands, e.g. * called within {@link #read(Server, CommandSender, InputStream, boolean, Plugin...)}. * * @return true if the current thread is running batch commands */ public static boolean isBatchProcessing() { return abortFlags.get() != null; } // Holder for command invocation private static class CommandCall { private final Command command; private final String alias; private final String[] args; public CommandCall(Command command, String alias, String[] args) { if (command == null) throw new IllegalArgumentException("command cannot be null");
if (!hasText(alias))
ZerothAngel/ToHPluginUtils
src/test/java/org/tyrannyofheaven/bukkit/util/uuid/UuidTest.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/UuidUtils.java // public static String longUuidToShort(String uuidString) { // if (uuidString.length() != 36) // throw new IllegalArgumentException("Wrong length"); // return uuidString.replaceAll("-", ""); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/UuidUtils.java // public static UuidDisplayName parseUuidDisplayName(String name) { // Matcher m = UUID_NAME_RE.matcher(name); // if (m.matches()) { // String uuidString = m.group(1); // String displayName = m.group(2); // // if (uuidString.length() == 32) // uuidString = shortUuidToLong(uuidString); // UUID uuid; // try { // uuid = UUID.fromString(uuidString); // } // catch (IllegalArgumentException e) { // return null; // } // return new UuidDisplayName(uuid, displayName); // } // return null; // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/UuidUtils.java // public static String shortUuidToLong(String uuidString) { // if (uuidString.length() != 32) // throw new IllegalArgumentException("Wrong length"); // return uuidString.substring(0, 8) + "-" + uuidString.substring(8, 12) + "-" + uuidString.substring(12, 16) + "-" + uuidString.substring(16, 20) + "-" + uuidString.substring(20, 32); // }
import static junit.framework.Assert.assertNotNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.longUuidToShort; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.parseUuidDisplayName; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.shortUuidToLong; import java.util.UUID; import org.junit.Test;
package org.tyrannyofheaven.bukkit.util.uuid; public class UuidTest { @Test public void testConversion() { UUID uuid = UUID.randomUUID();
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/UuidUtils.java // public static String longUuidToShort(String uuidString) { // if (uuidString.length() != 36) // throw new IllegalArgumentException("Wrong length"); // return uuidString.replaceAll("-", ""); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/UuidUtils.java // public static UuidDisplayName parseUuidDisplayName(String name) { // Matcher m = UUID_NAME_RE.matcher(name); // if (m.matches()) { // String uuidString = m.group(1); // String displayName = m.group(2); // // if (uuidString.length() == 32) // uuidString = shortUuidToLong(uuidString); // UUID uuid; // try { // uuid = UUID.fromString(uuidString); // } // catch (IllegalArgumentException e) { // return null; // } // return new UuidDisplayName(uuid, displayName); // } // return null; // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/UuidUtils.java // public static String shortUuidToLong(String uuidString) { // if (uuidString.length() != 32) // throw new IllegalArgumentException("Wrong length"); // return uuidString.substring(0, 8) + "-" + uuidString.substring(8, 12) + "-" + uuidString.substring(12, 16) + "-" + uuidString.substring(16, 20) + "-" + uuidString.substring(20, 32); // } // Path: src/test/java/org/tyrannyofheaven/bukkit/util/uuid/UuidTest.java import static junit.framework.Assert.assertNotNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.longUuidToShort; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.parseUuidDisplayName; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.shortUuidToLong; import java.util.UUID; import org.junit.Test; package org.tyrannyofheaven.bukkit.util.uuid; public class UuidTest { @Test public void testConversion() { UUID uuid = UUID.randomUUID();
assertEquals(uuid.toString(), shortUuidToLong(longUuidToShort(uuid.toString())));
ZerothAngel/ToHPluginUtils
src/test/java/org/tyrannyofheaven/bukkit/util/uuid/UuidTest.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/UuidUtils.java // public static String longUuidToShort(String uuidString) { // if (uuidString.length() != 36) // throw new IllegalArgumentException("Wrong length"); // return uuidString.replaceAll("-", ""); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/UuidUtils.java // public static UuidDisplayName parseUuidDisplayName(String name) { // Matcher m = UUID_NAME_RE.matcher(name); // if (m.matches()) { // String uuidString = m.group(1); // String displayName = m.group(2); // // if (uuidString.length() == 32) // uuidString = shortUuidToLong(uuidString); // UUID uuid; // try { // uuid = UUID.fromString(uuidString); // } // catch (IllegalArgumentException e) { // return null; // } // return new UuidDisplayName(uuid, displayName); // } // return null; // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/UuidUtils.java // public static String shortUuidToLong(String uuidString) { // if (uuidString.length() != 32) // throw new IllegalArgumentException("Wrong length"); // return uuidString.substring(0, 8) + "-" + uuidString.substring(8, 12) + "-" + uuidString.substring(12, 16) + "-" + uuidString.substring(16, 20) + "-" + uuidString.substring(20, 32); // }
import static junit.framework.Assert.assertNotNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.longUuidToShort; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.parseUuidDisplayName; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.shortUuidToLong; import java.util.UUID; import org.junit.Test;
package org.tyrannyofheaven.bukkit.util.uuid; public class UuidTest { @Test public void testConversion() { UUID uuid = UUID.randomUUID();
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/UuidUtils.java // public static String longUuidToShort(String uuidString) { // if (uuidString.length() != 36) // throw new IllegalArgumentException("Wrong length"); // return uuidString.replaceAll("-", ""); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/UuidUtils.java // public static UuidDisplayName parseUuidDisplayName(String name) { // Matcher m = UUID_NAME_RE.matcher(name); // if (m.matches()) { // String uuidString = m.group(1); // String displayName = m.group(2); // // if (uuidString.length() == 32) // uuidString = shortUuidToLong(uuidString); // UUID uuid; // try { // uuid = UUID.fromString(uuidString); // } // catch (IllegalArgumentException e) { // return null; // } // return new UuidDisplayName(uuid, displayName); // } // return null; // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/UuidUtils.java // public static String shortUuidToLong(String uuidString) { // if (uuidString.length() != 32) // throw new IllegalArgumentException("Wrong length"); // return uuidString.substring(0, 8) + "-" + uuidString.substring(8, 12) + "-" + uuidString.substring(12, 16) + "-" + uuidString.substring(16, 20) + "-" + uuidString.substring(20, 32); // } // Path: src/test/java/org/tyrannyofheaven/bukkit/util/uuid/UuidTest.java import static junit.framework.Assert.assertNotNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.longUuidToShort; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.parseUuidDisplayName; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.shortUuidToLong; import java.util.UUID; import org.junit.Test; package org.tyrannyofheaven.bukkit.util.uuid; public class UuidTest { @Test public void testConversion() { UUID uuid = UUID.randomUUID();
assertEquals(uuid.toString(), shortUuidToLong(longUuidToShort(uuid.toString())));
ZerothAngel/ToHPluginUtils
src/test/java/org/tyrannyofheaven/bukkit/util/uuid/UuidTest.java
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/UuidUtils.java // public static String longUuidToShort(String uuidString) { // if (uuidString.length() != 36) // throw new IllegalArgumentException("Wrong length"); // return uuidString.replaceAll("-", ""); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/UuidUtils.java // public static UuidDisplayName parseUuidDisplayName(String name) { // Matcher m = UUID_NAME_RE.matcher(name); // if (m.matches()) { // String uuidString = m.group(1); // String displayName = m.group(2); // // if (uuidString.length() == 32) // uuidString = shortUuidToLong(uuidString); // UUID uuid; // try { // uuid = UUID.fromString(uuidString); // } // catch (IllegalArgumentException e) { // return null; // } // return new UuidDisplayName(uuid, displayName); // } // return null; // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/UuidUtils.java // public static String shortUuidToLong(String uuidString) { // if (uuidString.length() != 32) // throw new IllegalArgumentException("Wrong length"); // return uuidString.substring(0, 8) + "-" + uuidString.substring(8, 12) + "-" + uuidString.substring(12, 16) + "-" + uuidString.substring(16, 20) + "-" + uuidString.substring(20, 32); // }
import static junit.framework.Assert.assertNotNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.longUuidToShort; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.parseUuidDisplayName; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.shortUuidToLong; import java.util.UUID; import org.junit.Test;
package org.tyrannyofheaven.bukkit.util.uuid; public class UuidTest { @Test public void testConversion() { UUID uuid = UUID.randomUUID(); assertEquals(uuid.toString(), shortUuidToLong(longUuidToShort(uuid.toString()))); } @Test public void testNoMatch() {
// Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/UuidUtils.java // public static String longUuidToShort(String uuidString) { // if (uuidString.length() != 36) // throw new IllegalArgumentException("Wrong length"); // return uuidString.replaceAll("-", ""); // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/UuidUtils.java // public static UuidDisplayName parseUuidDisplayName(String name) { // Matcher m = UUID_NAME_RE.matcher(name); // if (m.matches()) { // String uuidString = m.group(1); // String displayName = m.group(2); // // if (uuidString.length() == 32) // uuidString = shortUuidToLong(uuidString); // UUID uuid; // try { // uuid = UUID.fromString(uuidString); // } // catch (IllegalArgumentException e) { // return null; // } // return new UuidDisplayName(uuid, displayName); // } // return null; // } // // Path: src/main/java/org/tyrannyofheaven/bukkit/util/uuid/UuidUtils.java // public static String shortUuidToLong(String uuidString) { // if (uuidString.length() != 32) // throw new IllegalArgumentException("Wrong length"); // return uuidString.substring(0, 8) + "-" + uuidString.substring(8, 12) + "-" + uuidString.substring(12, 16) + "-" + uuidString.substring(16, 20) + "-" + uuidString.substring(20, 32); // } // Path: src/test/java/org/tyrannyofheaven/bukkit/util/uuid/UuidTest.java import static junit.framework.Assert.assertNotNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.longUuidToShort; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.parseUuidDisplayName; import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.shortUuidToLong; import java.util.UUID; import org.junit.Test; package org.tyrannyofheaven.bukkit.util.uuid; public class UuidTest { @Test public void testConversion() { UUID uuid = UUID.randomUUID(); assertEquals(uuid.toString(), shortUuidToLong(longUuidToShort(uuid.toString()))); } @Test public void testNoMatch() {
UuidDisplayName udn = parseUuidDisplayName("ZerothAngel");
IRIT-SMAC/agent-tooling
agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/AgentMsgBox.java
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IDirectory.java // public interface IDirectory<T> { // // /** // * Returns the agent ref from the given agent id. // * // * @param agentId the agent id // * @return the agent ref // */ // public Ref<T> getAgentRef(String agentId); // // /** // * Returns the group ref from the given agent id. // * // * @param groupId the group id // * @return the group ref // */ // public Ref<T> getGroupRef(String groupId); // // /** // * Returns all the agents inscribed in a group. // * // * @param groupRef the group ref // * @return the agents of group // */ // public Set<Ref<T>> getAgentsOfGroup(Ref<T> groupRef); // // /** // * Returns all the agents inscribed in a group. // * // * @param groupId the group id // * @return the agents of group // */ // public Set<Ref<T>> getAgentsOfGroup(String groupId); // // /** // * Returns all the agent refs inscribed in the directory. // * // * @return the groups ref // */ // public List<Ref<T>> getGroupsRef(); // // /** // * Returns all the groups refs inscribed in the directory. // * // * @return the agents ref // */ // public List<Ref<T>> getAgentsRef(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/messagecontainer/BlockingQueueMsgContainer.java // public class BlockingQueueMsgContainer<T> implements // IMsgContainer<T> { // // /** The msg queue. */ // private BlockingQueue<T> msgQueue; // // /** // * Instantiates a new blocking queue msg container. // */ // public BlockingQueueMsgContainer() { // this.msgQueue = new LinkedBlockingQueue<T>(); // } // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.IMsgSink#putMsg(java.lang.Object) // */ // @Override // public boolean putMsg(T msg) { // return this.msgQueue.offer(msg); // } // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.IMsgSource#getMsgs() // */ // @Override // public List<T> getMsgs() { // List<T> messages = new ArrayList<T>(this.msgQueue.size()); // this.msgQueue.drainTo(messages); // // return messages; // } // // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/messagecontainer/DummyMsgContainer.java // public class DummyMsgContainer implements IMsgContainer<Object> { // // /* // * (non-Javadoc) // * // * @see // * fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.IMsgSink#putMsg // * (java.lang.Object) // */ // @Override // public boolean putMsg(Object msg) { // return false; // } // // /* // * (non-Javadoc) // * // * @see // * fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.IMsgSource# // * getMsgs() // */ // @Override // public List<Object> getMsgs() { // throw new IllegalStateException( // ExceptionMessage.GET_MESSAGES_DISPOSED_MSG_BOX); // } // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/messagecontainer/IMsgContainer.java // public interface IMsgContainer<T> extends IMsgSink<T>, // IMsgSource<T> { // // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/messagecontainer/IMsgSink.java // public interface IMsgSink<T> { // // /** // * Put msg. // * // * @param msg the msg // * @return true, if successful // */ // public boolean putMsg(T msg); // }
import java.util.List; import fr.irit.smac.libs.tooling.messaging.IDirectory; import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.BlockingQueueMsgContainer; import fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.DummyMsgContainer; import fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.IMsgContainer; import fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.IMsgSink;
*/ @Override public boolean sendToGroup(T msg, Ref<T> groupRef) { return this.sender.sendToGroup(msg, groupRef); } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.messaging.ISender#broadcast(java.lang.Object) */ @Override public boolean broadcast(T msg) { return this.sender.broadcast(msg); } // ///////////////////////////////////////////////////////////////////////////// // MsgContainer Concerns // ///////////////////////////////////////////////////////////////////////////// /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.IMsgSource#getMsgs() */ @Override public List<T> getMsgs() { return this.msgContainer.getMsgs(); } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.messaging.impl.Ref#getMsgSink() */ @Override
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IDirectory.java // public interface IDirectory<T> { // // /** // * Returns the agent ref from the given agent id. // * // * @param agentId the agent id // * @return the agent ref // */ // public Ref<T> getAgentRef(String agentId); // // /** // * Returns the group ref from the given agent id. // * // * @param groupId the group id // * @return the group ref // */ // public Ref<T> getGroupRef(String groupId); // // /** // * Returns all the agents inscribed in a group. // * // * @param groupRef the group ref // * @return the agents of group // */ // public Set<Ref<T>> getAgentsOfGroup(Ref<T> groupRef); // // /** // * Returns all the agents inscribed in a group. // * // * @param groupId the group id // * @return the agents of group // */ // public Set<Ref<T>> getAgentsOfGroup(String groupId); // // /** // * Returns all the agent refs inscribed in the directory. // * // * @return the groups ref // */ // public List<Ref<T>> getGroupsRef(); // // /** // * Returns all the groups refs inscribed in the directory. // * // * @return the agents ref // */ // public List<Ref<T>> getAgentsRef(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/messagecontainer/BlockingQueueMsgContainer.java // public class BlockingQueueMsgContainer<T> implements // IMsgContainer<T> { // // /** The msg queue. */ // private BlockingQueue<T> msgQueue; // // /** // * Instantiates a new blocking queue msg container. // */ // public BlockingQueueMsgContainer() { // this.msgQueue = new LinkedBlockingQueue<T>(); // } // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.IMsgSink#putMsg(java.lang.Object) // */ // @Override // public boolean putMsg(T msg) { // return this.msgQueue.offer(msg); // } // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.IMsgSource#getMsgs() // */ // @Override // public List<T> getMsgs() { // List<T> messages = new ArrayList<T>(this.msgQueue.size()); // this.msgQueue.drainTo(messages); // // return messages; // } // // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/messagecontainer/DummyMsgContainer.java // public class DummyMsgContainer implements IMsgContainer<Object> { // // /* // * (non-Javadoc) // * // * @see // * fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.IMsgSink#putMsg // * (java.lang.Object) // */ // @Override // public boolean putMsg(Object msg) { // return false; // } // // /* // * (non-Javadoc) // * // * @see // * fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.IMsgSource# // * getMsgs() // */ // @Override // public List<Object> getMsgs() { // throw new IllegalStateException( // ExceptionMessage.GET_MESSAGES_DISPOSED_MSG_BOX); // } // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/messagecontainer/IMsgContainer.java // public interface IMsgContainer<T> extends IMsgSink<T>, // IMsgSource<T> { // // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/messagecontainer/IMsgSink.java // public interface IMsgSink<T> { // // /** // * Put msg. // * // * @param msg the msg // * @return true, if successful // */ // public boolean putMsg(T msg); // } // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/AgentMsgBox.java import java.util.List; import fr.irit.smac.libs.tooling.messaging.IDirectory; import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.BlockingQueueMsgContainer; import fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.DummyMsgContainer; import fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.IMsgContainer; import fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.IMsgSink; */ @Override public boolean sendToGroup(T msg, Ref<T> groupRef) { return this.sender.sendToGroup(msg, groupRef); } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.messaging.ISender#broadcast(java.lang.Object) */ @Override public boolean broadcast(T msg) { return this.sender.broadcast(msg); } // ///////////////////////////////////////////////////////////////////////////// // MsgContainer Concerns // ///////////////////////////////////////////////////////////////////////////// /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.IMsgSource#getMsgs() */ @Override public List<T> getMsgs() { return this.msgContainer.getMsgs(); } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.messaging.impl.Ref#getMsgSink() */ @Override
IMsgSink<T> getMsgSink() {
IRIT-SMAC/agent-tooling
avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAdvancedAVT.java
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/IDeltaManager.java // public interface IDeltaManager { // // /** // * Defines the direction given to the method <code>adjustDelta</code> in // * order to update the tunning step delta. // * // * @author Sylvain Lemouzy // */ // public enum EDirection { // // /** The direct. */ // DIRECT, // /** The indirect. */ // INDIRECT, // /** The none. */ // NONE // } // // /** // * Adjusts (tunes) the delta value from the succession of directions // * successively given to this method. // * <p> // * The way the adjustment is done depends on the implementation of the // * DeltaManager // * </p> // * // * @param direction // * the direction of the adjustment // */ // public void adjustDelta(EDirection direction); // // /** // * Returns the delta value. // * // * @return the delta value // */ // public double getDelta(); // // /** // * Returns an advanced interface to control the DeltaManager. // * <p> // * Pay caution, some of the methods of this interface doesn't guarantee the // * DeltaManager state consistency. Generally, you should only uses this // * interface if you have good reasons and you know what you are doing. // * </p> // * // * @return this AVT instance with an advanced interface // */ // public IAdvancedDM getAdvancedDM(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/range/IRange.java // public interface IRange { // // /** // * The lower bound of this range. // * // * @return the lower bound // */ // public double getLowerBound(); // // /** // * The upper bound of this range. // * // * @return the upper bound // */ // public double getUpperBound(); // // /** // * Checks if is inside range. // * // * @param value the value // * @return true if value is inside lower and upper bounds, including bounds // */ // public boolean isInsideRange(double value); // // /** // * Computes the size of the range. // * // * @return the big decimal // */ // public BigDecimal computeRangeSize(); // // /** // * Checks for infinite size. // * // * @return isInfinite // */ // public boolean hasInfiniteSize(); // }
import fr.irit.smac.libs.tooling.avt.range.IRange; import fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManager;
/* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt; /** * Advanced interface to control the AVT. * <p> * Pay caution, some of those methods don't guarantee the AVT state consistency. * Generally, you should only use this interface if you have good reasons and * you know what you are doing. * </p> * <p> * The state consistency guaranty depends on the implementation, so please refer * to the java doc of these implementations. The methods that doesn't guarantee * this consistency are tagged with a <strong>STATE CONSISTENCY WARNING</strong> * </p> * * @author Sylvain Lemouzy */ public interface IAdvancedAVT extends IAVT { /** * Returns the next value of the AVT if it'd receive the given feedback * * @param feedback * @return the next value of the AVT if it'd receive the given feedback */ public double getValueIf(EFeedback feedback); /** * @return The range that represents the AVT search space */
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/IDeltaManager.java // public interface IDeltaManager { // // /** // * Defines the direction given to the method <code>adjustDelta</code> in // * order to update the tunning step delta. // * // * @author Sylvain Lemouzy // */ // public enum EDirection { // // /** The direct. */ // DIRECT, // /** The indirect. */ // INDIRECT, // /** The none. */ // NONE // } // // /** // * Adjusts (tunes) the delta value from the succession of directions // * successively given to this method. // * <p> // * The way the adjustment is done depends on the implementation of the // * DeltaManager // * </p> // * // * @param direction // * the direction of the adjustment // */ // public void adjustDelta(EDirection direction); // // /** // * Returns the delta value. // * // * @return the delta value // */ // public double getDelta(); // // /** // * Returns an advanced interface to control the DeltaManager. // * <p> // * Pay caution, some of the methods of this interface doesn't guarantee the // * DeltaManager state consistency. Generally, you should only uses this // * interface if you have good reasons and you know what you are doing. // * </p> // * // * @return this AVT instance with an advanced interface // */ // public IAdvancedDM getAdvancedDM(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/range/IRange.java // public interface IRange { // // /** // * The lower bound of this range. // * // * @return the lower bound // */ // public double getLowerBound(); // // /** // * The upper bound of this range. // * // * @return the upper bound // */ // public double getUpperBound(); // // /** // * Checks if is inside range. // * // * @param value the value // * @return true if value is inside lower and upper bounds, including bounds // */ // public boolean isInsideRange(double value); // // /** // * Computes the size of the range. // * // * @return the big decimal // */ // public BigDecimal computeRangeSize(); // // /** // * Checks for infinite size. // * // * @return isInfinite // */ // public boolean hasInfiniteSize(); // } // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAdvancedAVT.java import fr.irit.smac.libs.tooling.avt.range.IRange; import fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManager; /* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt; /** * Advanced interface to control the AVT. * <p> * Pay caution, some of those methods don't guarantee the AVT state consistency. * Generally, you should only use this interface if you have good reasons and * you know what you are doing. * </p> * <p> * The state consistency guaranty depends on the implementation, so please refer * to the java doc of these implementations. The methods that doesn't guarantee * this consistency are tagged with a <strong>STATE CONSISTENCY WARNING</strong> * </p> * * @author Sylvain Lemouzy */ public interface IAdvancedAVT extends IAVT { /** * Returns the next value of the AVT if it'd receive the given feedback * * @param feedback * @return the next value of the AVT if it'd receive the given feedback */ public double getValueIf(EFeedback feedback); /** * @return The range that represents the AVT search space */
public IRange getRange();
IRIT-SMAC/agent-tooling
avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAVTFactory.java
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/IDeltaManagerFactory.java // public interface IDeltaManagerFactory<T extends IDeltaManager> { // // /** // * Instanciate a DeltaManager that will be used for the given AVT. // * // * @param range the range // * @return the t // */ // T createInstance(IRange range); // // }
import fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory;
/* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt; /** * A factory for creating IAVT objects. * * @param <T> the generic type */ public interface IAVTFactory<T extends IAVT> { /** * Creates a new IAVT object. * * @param lowerBound the lower bound * @param upperBound the upper bound * @param startValue the start value * @param deltaManagerFactory the delta manager factory * @return the t */ T createInstance(double lowerBound, double upperBound, double startValue,
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/IDeltaManagerFactory.java // public interface IDeltaManagerFactory<T extends IDeltaManager> { // // /** // * Instanciate a DeltaManager that will be used for the given AVT. // * // * @param range the range // * @return the t // */ // T createInstance(IRange range); // // } // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAVTFactory.java import fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory; /* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt; /** * A factory for creating IAVT objects. * * @param <T> the generic type */ public interface IAVTFactory<T extends IAVT> { /** * Creates a new IAVT object. * * @param lowerBound the lower bound * @param upperBound the upper bound * @param startValue the start value * @param deltaManagerFactory the delta manager factory * @return the t */ T createInstance(double lowerBound, double upperBound, double startValue,
IDeltaManagerFactory<?> deltaManagerFactory);
IRIT-SMAC/agent-tooling
agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/server/AgentPlotServer.java
// Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/commons/EChartType.java // public enum EChartType { // PLOT, LINE // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/interfaces/IAgentPlotChart.java // public interface IAgentPlotChart { // /** // * Add the point (xMax+1, y) to the first serie of the chart. // * // * @param y // */ // public void add(double y); // // /** // * Add the point (x,y) to the first serie of the chart. // * // * @param x // * @param y // */ // public void add(double x, double y); // // /** // * Add the point (xMax+1, y) to the serie of the chart. // * // * @param serieName // * @param y // */ // public void add(String serieName, double y); // // /** // * Add the point (x, y) to the serie of the chart. // * // * @param serieName // * @param x // * @param y // */ // public void add(String serieName, double x, double y); // // /** // * Close the chart on the server. // */ // public void close(); // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/interfaces/IAgentPlotServer.java // public interface IAgentPlotServer { // /** // * Get or create the chart which is called _name. // * // * @param name // * @return // */ // public IAgentPlotChart getChart(String name); // // /** // * Preconfigure the chart _name with a chart's type and a number of series // * that will be displayed. // * // * @param name // * @param chartType // */ // public void configChart(String name, EChartType chartType); // }
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.Map; import java.util.TreeMap; import fr.irit.smac.libs.tooling.plot.commons.EChartType; import fr.irit.smac.libs.tooling.plot.interfaces.IAgentPlotChart; import fr.irit.smac.libs.tooling.plot.interfaces.IAgentPlotServer;
/* * #%L * agent-plot * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.plot.server; /** * Server which is able to receive requests from local or distant client. * * @author Alexandre Perles * */ public class AgentPlotServer implements IAgentPlotServer, Runnable { private ServerSocket socket; private boolean running = false;
// Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/commons/EChartType.java // public enum EChartType { // PLOT, LINE // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/interfaces/IAgentPlotChart.java // public interface IAgentPlotChart { // /** // * Add the point (xMax+1, y) to the first serie of the chart. // * // * @param y // */ // public void add(double y); // // /** // * Add the point (x,y) to the first serie of the chart. // * // * @param x // * @param y // */ // public void add(double x, double y); // // /** // * Add the point (xMax+1, y) to the serie of the chart. // * // * @param serieName // * @param y // */ // public void add(String serieName, double y); // // /** // * Add the point (x, y) to the serie of the chart. // * // * @param serieName // * @param x // * @param y // */ // public void add(String serieName, double x, double y); // // /** // * Close the chart on the server. // */ // public void close(); // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/interfaces/IAgentPlotServer.java // public interface IAgentPlotServer { // /** // * Get or create the chart which is called _name. // * // * @param name // * @return // */ // public IAgentPlotChart getChart(String name); // // /** // * Preconfigure the chart _name with a chart's type and a number of series // * that will be displayed. // * // * @param name // * @param chartType // */ // public void configChart(String name, EChartType chartType); // } // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/server/AgentPlotServer.java import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.Map; import java.util.TreeMap; import fr.irit.smac.libs.tooling.plot.commons.EChartType; import fr.irit.smac.libs.tooling.plot.interfaces.IAgentPlotChart; import fr.irit.smac.libs.tooling.plot.interfaces.IAgentPlotServer; /* * #%L * agent-plot * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.plot.server; /** * Server which is able to receive requests from local or distant client. * * @author Alexandre Perles * */ public class AgentPlotServer implements IAgentPlotServer, Runnable { private ServerSocket socket; private boolean running = false;
private Map<String, IAgentPlotChart> charts = new TreeMap<String, IAgentPlotChart>();
IRIT-SMAC/agent-tooling
agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/server/AgentPlotServer.java
// Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/commons/EChartType.java // public enum EChartType { // PLOT, LINE // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/interfaces/IAgentPlotChart.java // public interface IAgentPlotChart { // /** // * Add the point (xMax+1, y) to the first serie of the chart. // * // * @param y // */ // public void add(double y); // // /** // * Add the point (x,y) to the first serie of the chart. // * // * @param x // * @param y // */ // public void add(double x, double y); // // /** // * Add the point (xMax+1, y) to the serie of the chart. // * // * @param serieName // * @param y // */ // public void add(String serieName, double y); // // /** // * Add the point (x, y) to the serie of the chart. // * // * @param serieName // * @param x // * @param y // */ // public void add(String serieName, double x, double y); // // /** // * Close the chart on the server. // */ // public void close(); // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/interfaces/IAgentPlotServer.java // public interface IAgentPlotServer { // /** // * Get or create the chart which is called _name. // * // * @param name // * @return // */ // public IAgentPlotChart getChart(String name); // // /** // * Preconfigure the chart _name with a chart's type and a number of series // * that will be displayed. // * // * @param name // * @param chartType // */ // public void configChart(String name, EChartType chartType); // }
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.Map; import java.util.TreeMap; import fr.irit.smac.libs.tooling.plot.commons.EChartType; import fr.irit.smac.libs.tooling.plot.interfaces.IAgentPlotChart; import fr.irit.smac.libs.tooling.plot.interfaces.IAgentPlotServer;
} catch (IOException e) { e.printStackTrace(); } } @Override public IAgentPlotChart getChart(String name) { if (!charts.containsKey(name)) { charts.put(name, new AgentPlotChart(name)); } return charts.get(name); } @Override public void run() { while (running) { try { Socket clientSocket = socket.accept(); new AgentPlotConnectedClient(clientSocket, this); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Override
// Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/commons/EChartType.java // public enum EChartType { // PLOT, LINE // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/interfaces/IAgentPlotChart.java // public interface IAgentPlotChart { // /** // * Add the point (xMax+1, y) to the first serie of the chart. // * // * @param y // */ // public void add(double y); // // /** // * Add the point (x,y) to the first serie of the chart. // * // * @param x // * @param y // */ // public void add(double x, double y); // // /** // * Add the point (xMax+1, y) to the serie of the chart. // * // * @param serieName // * @param y // */ // public void add(String serieName, double y); // // /** // * Add the point (x, y) to the serie of the chart. // * // * @param serieName // * @param x // * @param y // */ // public void add(String serieName, double x, double y); // // /** // * Close the chart on the server. // */ // public void close(); // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/interfaces/IAgentPlotServer.java // public interface IAgentPlotServer { // /** // * Get or create the chart which is called _name. // * // * @param name // * @return // */ // public IAgentPlotChart getChart(String name); // // /** // * Preconfigure the chart _name with a chart's type and a number of series // * that will be displayed. // * // * @param name // * @param chartType // */ // public void configChart(String name, EChartType chartType); // } // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/server/AgentPlotServer.java import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.Map; import java.util.TreeMap; import fr.irit.smac.libs.tooling.plot.commons.EChartType; import fr.irit.smac.libs.tooling.plot.interfaces.IAgentPlotChart; import fr.irit.smac.libs.tooling.plot.interfaces.IAgentPlotServer; } catch (IOException e) { e.printStackTrace(); } } @Override public IAgentPlotChart getChart(String name) { if (!charts.containsKey(name)) { charts.put(name, new AgentPlotChart(name)); } return charts.get(name); } @Override public void run() { while (running) { try { Socket clientSocket = socket.accept(); new AgentPlotConnectedClient(clientSocket, this); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Override
public void configChart(String name, EChartType chartType) {
IRIT-SMAC/agent-tooling
agent-logging/src/main/java/fr/irit/smac/libs/tooling/logging/AgentLog.java
// Path: agent-logging/src/main/java/fr/irit/smac/libs/tooling/logging/AgentLog.java // public enum ESide { // LEFT, RIGHT // } // // Path: agent-logging/src/main/java/fr/irit/smac/libs/tooling/logging/logback/LoggerNameDiscriminator.java // public class LoggerNameDiscriminator implements Discriminator<ILoggingEvent> { // // private boolean started = false; // // @Override // public boolean isStarted() { // return this.started; // } // // @Override // public void start() { // this.started = true; // } // // @Override // public void stop() { // this.started = false; // } // // @Override // public String getDiscriminatingValue(ILoggingEvent logEvent) { // return logEvent.getLoggerName().substring(AgentLog.ROOT_AGENT_LOGGER.length()+1); // } // // @Override // public String getKey() { // return "loggerName"; // } // // }
import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.Marker; import org.slf4j.MarkerFactory; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.encoder.PatternLayoutEncoder; import ch.qos.logback.classic.sift.SiftingAppender; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.Appender; import ch.qos.logback.core.Context; import ch.qos.logback.core.FileAppender; import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.sift.AppenderFactory; import fr.irit.smac.libs.tooling.logging.AgentLog.ILogItemDisplayData.ESide; import fr.irit.smac.libs.tooling.logging.logback.LoggerNameDiscriminator;
/* * #%L * agent-logging * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.logging; /** * Class designed to satisfy simple agent logging needs. Actually, it uses the * logback library. * * @author lemouzy, perles * */ public class AgentLog { public final static String ROOT_AGENT_LOGGER = "rootAgentLogger"; private AgentLog() { } /** * Interface that helps to configure the way elements of logs are displayed * (format, order, justification, size, etc.) * * @author lemouzy, perles */ public static interface ILogItemDisplayData {
// Path: agent-logging/src/main/java/fr/irit/smac/libs/tooling/logging/AgentLog.java // public enum ESide { // LEFT, RIGHT // } // // Path: agent-logging/src/main/java/fr/irit/smac/libs/tooling/logging/logback/LoggerNameDiscriminator.java // public class LoggerNameDiscriminator implements Discriminator<ILoggingEvent> { // // private boolean started = false; // // @Override // public boolean isStarted() { // return this.started; // } // // @Override // public void start() { // this.started = true; // } // // @Override // public void stop() { // this.started = false; // } // // @Override // public String getDiscriminatingValue(ILoggingEvent logEvent) { // return logEvent.getLoggerName().substring(AgentLog.ROOT_AGENT_LOGGER.length()+1); // } // // @Override // public String getKey() { // return "loggerName"; // } // // } // Path: agent-logging/src/main/java/fr/irit/smac/libs/tooling/logging/AgentLog.java import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.Marker; import org.slf4j.MarkerFactory; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.encoder.PatternLayoutEncoder; import ch.qos.logback.classic.sift.SiftingAppender; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.Appender; import ch.qos.logback.core.Context; import ch.qos.logback.core.FileAppender; import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.sift.AppenderFactory; import fr.irit.smac.libs.tooling.logging.AgentLog.ILogItemDisplayData.ESide; import fr.irit.smac.libs.tooling.logging.logback.LoggerNameDiscriminator; /* * #%L * agent-logging * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.logging; /** * Class designed to satisfy simple agent logging needs. Actually, it uses the * logback library. * * @author lemouzy, perles * */ public class AgentLog { public final static String ROOT_AGENT_LOGGER = "rootAgentLogger"; private AgentLog() { } /** * Interface that helps to configure the way elements of logs are displayed * (format, order, justification, size, etc.) * * @author lemouzy, perles */ public static interface ILogItemDisplayData {
public enum ESide {
IRIT-SMAC/agent-tooling
agent-logging/src/main/java/fr/irit/smac/libs/tooling/logging/AgentLog.java
// Path: agent-logging/src/main/java/fr/irit/smac/libs/tooling/logging/AgentLog.java // public enum ESide { // LEFT, RIGHT // } // // Path: agent-logging/src/main/java/fr/irit/smac/libs/tooling/logging/logback/LoggerNameDiscriminator.java // public class LoggerNameDiscriminator implements Discriminator<ILoggingEvent> { // // private boolean started = false; // // @Override // public boolean isStarted() { // return this.started; // } // // @Override // public void start() { // this.started = true; // } // // @Override // public void stop() { // this.started = false; // } // // @Override // public String getDiscriminatingValue(ILoggingEvent logEvent) { // return logEvent.getLoggerName().substring(AgentLog.ROOT_AGENT_LOGGER.length()+1); // } // // @Override // public String getKey() { // return "loggerName"; // } // // }
import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.Marker; import org.slf4j.MarkerFactory; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.encoder.PatternLayoutEncoder; import ch.qos.logback.classic.sift.SiftingAppender; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.Appender; import ch.qos.logback.core.Context; import ch.qos.logback.core.FileAppender; import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.sift.AppenderFactory; import fr.irit.smac.libs.tooling.logging.AgentLog.ILogItemDisplayData.ESide; import fr.irit.smac.libs.tooling.logging.logback.LoggerNameDiscriminator;
* properties can be used in this configuration file : - ${loggerName} - * ${logFolderName} * * @param customLogbackConfigurationFile */ private static void initialiseLogback(final String customLogbackConfigurationFile) { System.setProperty("logback.configurationFile", customLogbackConfigurationFile); } /** * the initialization method that configure the file appender * * @param logFolderName * @param clearFolderContent * @param customLogbackConfigurationFile * @param logLevel * @param logTemplate */ private static void initialiseLogback( final String logFolderName, final Level logLevel, final String logTemplate) { // get root logger and clear all existing appenders LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); ch.qos.logback.classic.Logger rootAgentLogger = (ch.qos.logback.classic.Logger) LoggerFactory .getLogger(AgentLog.ROOT_AGENT_LOGGER); rootAgentLogger.detachAndStopAllAppenders(); // Configure and create a sifting encoder
// Path: agent-logging/src/main/java/fr/irit/smac/libs/tooling/logging/AgentLog.java // public enum ESide { // LEFT, RIGHT // } // // Path: agent-logging/src/main/java/fr/irit/smac/libs/tooling/logging/logback/LoggerNameDiscriminator.java // public class LoggerNameDiscriminator implements Discriminator<ILoggingEvent> { // // private boolean started = false; // // @Override // public boolean isStarted() { // return this.started; // } // // @Override // public void start() { // this.started = true; // } // // @Override // public void stop() { // this.started = false; // } // // @Override // public String getDiscriminatingValue(ILoggingEvent logEvent) { // return logEvent.getLoggerName().substring(AgentLog.ROOT_AGENT_LOGGER.length()+1); // } // // @Override // public String getKey() { // return "loggerName"; // } // // } // Path: agent-logging/src/main/java/fr/irit/smac/libs/tooling/logging/AgentLog.java import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.Marker; import org.slf4j.MarkerFactory; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.encoder.PatternLayoutEncoder; import ch.qos.logback.classic.sift.SiftingAppender; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.Appender; import ch.qos.logback.core.Context; import ch.qos.logback.core.FileAppender; import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.sift.AppenderFactory; import fr.irit.smac.libs.tooling.logging.AgentLog.ILogItemDisplayData.ESide; import fr.irit.smac.libs.tooling.logging.logback.LoggerNameDiscriminator; * properties can be used in this configuration file : - ${loggerName} - * ${logFolderName} * * @param customLogbackConfigurationFile */ private static void initialiseLogback(final String customLogbackConfigurationFile) { System.setProperty("logback.configurationFile", customLogbackConfigurationFile); } /** * the initialization method that configure the file appender * * @param logFolderName * @param clearFolderContent * @param customLogbackConfigurationFile * @param logLevel * @param logTemplate */ private static void initialiseLogback( final String logFolderName, final Level logLevel, final String logTemplate) { // get root logger and clear all existing appenders LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); ch.qos.logback.classic.Logger rootAgentLogger = (ch.qos.logback.classic.Logger) LoggerFactory .getLogger(AgentLog.ROOT_AGENT_LOGGER); rootAgentLogger.detachAndStopAllAppenders(); // Configure and create a sifting encoder
LoggerNameDiscriminator loggerNameDiscriminator = new LoggerNameDiscriminator();
IRIT-SMAC/agent-tooling
agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/messagecontainer/DummyMsgContainer.java
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/ExceptionMessage.java // public class ExceptionMessage { // // /** The Constant UNKNOWN_GROUP_UNSUBSCRIBE. */ // public static final String UNKNOWN_GROUP_UNSUBSCRIBE = "Trying to unsubscribe an agent from an unknown group : {0}"; // // /** The Constant UNKNOWN_GROUP_SUBSCRIBE. */ // public static final String UNKNOWN_GROUP_SUBSCRIBE = "Trying to subscribe an agent from an unknown group : {0}"; // // /** The Constant UNKNOWN_RECEIVER_SEND. */ // public static final String UNKNOWN_RECEIVER_SEND = "Trying to send a message to an unknown receiver : {0}"; // // /** The Constant UNKNOWN_GROUP_SEND. */ // public static final String UNKNOWN_GROUP_SEND = "Trying to send a message to an unknown group : {0}"; // // /** The Constant GET_MESSAGES_DISPOSED_MSG_BOX. */ // public static final String GET_MESSAGES_DISPOSED_MSG_BOX = "Trying to receive messages from a disposed message box."; // // /** The Constant AGENT_ALREADY_ASSOCIATED_MSG_BOX. */ // public static final String AGENT_ALREADY_ASSOCIATED_MSG_BOX = "The agent {0} is already associated with a msgBox."; // // /** // * Instantiates a new exception message. // */ // private ExceptionMessage() { // // } // // /** // * Format message. // * // * @param messageString // * the message string // * @param arg0 // * the arg0 // * @return the string // */ // public static String formatMessage(String messageString, Object arg0) { // // MessageFormat mf = new MessageFormat(messageString); // Object[] args = new Object[1]; // args[0] = arg0; // return mf.format(args); // } // // }
import fr.irit.smac.libs.tooling.messaging.ExceptionMessage; import java.util.List;
/* * #%L * agent-messaging * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.messaging.impl.messagecontainer; /** * An implementation of a dummy msgContainer used when an AgentMsgBox is * disposed. * * @author lemouzy */ public class DummyMsgContainer implements IMsgContainer<Object> { /* * (non-Javadoc) * * @see * fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.IMsgSink#putMsg * (java.lang.Object) */ @Override public boolean putMsg(Object msg) { return false; } /* * (non-Javadoc) * * @see * fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.IMsgSource# * getMsgs() */ @Override public List<Object> getMsgs() { throw new IllegalStateException(
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/ExceptionMessage.java // public class ExceptionMessage { // // /** The Constant UNKNOWN_GROUP_UNSUBSCRIBE. */ // public static final String UNKNOWN_GROUP_UNSUBSCRIBE = "Trying to unsubscribe an agent from an unknown group : {0}"; // // /** The Constant UNKNOWN_GROUP_SUBSCRIBE. */ // public static final String UNKNOWN_GROUP_SUBSCRIBE = "Trying to subscribe an agent from an unknown group : {0}"; // // /** The Constant UNKNOWN_RECEIVER_SEND. */ // public static final String UNKNOWN_RECEIVER_SEND = "Trying to send a message to an unknown receiver : {0}"; // // /** The Constant UNKNOWN_GROUP_SEND. */ // public static final String UNKNOWN_GROUP_SEND = "Trying to send a message to an unknown group : {0}"; // // /** The Constant GET_MESSAGES_DISPOSED_MSG_BOX. */ // public static final String GET_MESSAGES_DISPOSED_MSG_BOX = "Trying to receive messages from a disposed message box."; // // /** The Constant AGENT_ALREADY_ASSOCIATED_MSG_BOX. */ // public static final String AGENT_ALREADY_ASSOCIATED_MSG_BOX = "The agent {0} is already associated with a msgBox."; // // /** // * Instantiates a new exception message. // */ // private ExceptionMessage() { // // } // // /** // * Format message. // * // * @param messageString // * the message string // * @param arg0 // * the arg0 // * @return the string // */ // public static String formatMessage(String messageString, Object arg0) { // // MessageFormat mf = new MessageFormat(messageString); // Object[] args = new Object[1]; // args[0] = arg0; // return mf.format(args); // } // // } // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/messagecontainer/DummyMsgContainer.java import fr.irit.smac.libs.tooling.messaging.ExceptionMessage; import java.util.List; /* * #%L * agent-messaging * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.messaging.impl.messagecontainer; /** * An implementation of a dummy msgContainer used when an AgentMsgBox is * disposed. * * @author lemouzy */ public class DummyMsgContainer implements IMsgContainer<Object> { /* * (non-Javadoc) * * @see * fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.IMsgSink#putMsg * (java.lang.Object) */ @Override public boolean putMsg(Object msg) { return false; } /* * (non-Javadoc) * * @see * fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.IMsgSource# * getMsgs() */ @Override public List<Object> getMsgs() { throw new IllegalStateException(
ExceptionMessage.GET_MESSAGES_DISPOSED_MSG_BOX);
IRIT-SMAC/agent-tooling
agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/ISender.java
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/Ref.java // public abstract class Ref<T> implements Comparable<Ref<T>> { // // /** The id. */ // private final String id; // // /** // * Instantiates a new ref. // * // * @param id the id // */ // public Ref(String id) { // this.id = id; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "@" + id; // } // // /** // * Gets the id. // * // * @return the id // */ // public String getId() { // return id; // } // // /* (non-Javadoc) // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(Ref<T> ref) { // return this.getId().compareTo(ref.getId()); // } // // /** // * Gets the msg sink. // * // * @return the external package hidden message sink // */ // abstract IMsgSink<T> getMsgSink(); // }
import fr.irit.smac.libs.tooling.messaging.impl.Ref;
/* * #%L * agent-messaging * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.messaging; /** * Interface of a service that permits to send messages. * * @author lemouzy * @param <T> * the generic type */ public interface ISender<T> { /** * Returns the directory used for sending messages. * * @return the directory */ public IDirectory<T> getDirectory(); /** * Sends a message to the given id Note : this method is slower than the * send(MsgType msg, Ref<MsgType> receiverRef) method we recommend to use * this other method for performance reasons. * * @param msg * the msg * @param receiverId * the receiver id * @return true if the message has been actually sent, false otherwise */ public boolean send(T msg, String receiverId); /** * Sends a message to the given ref Note : this method is faster than the * send(MsgType msg, String receiverId) method. * * @param msg * the msg * @param receiverRef * the receiver ref * @return true if the message has been actually sent, false otherwise */
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/Ref.java // public abstract class Ref<T> implements Comparable<Ref<T>> { // // /** The id. */ // private final String id; // // /** // * Instantiates a new ref. // * // * @param id the id // */ // public Ref(String id) { // this.id = id; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "@" + id; // } // // /** // * Gets the id. // * // * @return the id // */ // public String getId() { // return id; // } // // /* (non-Javadoc) // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(Ref<T> ref) { // return this.getId().compareTo(ref.getId()); // } // // /** // * Gets the msg sink. // * // * @return the external package hidden message sink // */ // abstract IMsgSink<T> getMsgSink(); // } // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/ISender.java import fr.irit.smac.libs.tooling.messaging.impl.Ref; /* * #%L * agent-messaging * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.messaging; /** * Interface of a service that permits to send messages. * * @author lemouzy * @param <T> * the generic type */ public interface ISender<T> { /** * Returns the directory used for sending messages. * * @return the directory */ public IDirectory<T> getDirectory(); /** * Sends a message to the given id Note : this method is slower than the * send(MsgType msg, Ref<MsgType> receiverRef) method we recommend to use * this other method for performance reasons. * * @param msg * the msg * @param receiverId * the receiver id * @return true if the message has been actually sent, false otherwise */ public boolean send(T msg, String receiverId); /** * Sends a message to the given ref Note : this method is faster than the * send(MsgType msg, String receiverId) method. * * @param msg * the msg * @param receiverRef * the receiver ref * @return true if the message has been actually sent, false otherwise */
public boolean send(T msg, Ref<T> receiverRef);
IRIT-SMAC/agent-tooling
agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/server/AgentPlotConnectedClient.java
// Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/commons/EChartType.java // public enum EChartType { // PLOT, LINE // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/interfaces/IAgentPlotChart.java // public interface IAgentPlotChart { // /** // * Add the point (xMax+1, y) to the first serie of the chart. // * // * @param y // */ // public void add(double y); // // /** // * Add the point (x,y) to the first serie of the chart. // * // * @param x // * @param y // */ // public void add(double x, double y); // // /** // * Add the point (xMax+1, y) to the serie of the chart. // * // * @param serieName // * @param y // */ // public void add(String serieName, double y); // // /** // * Add the point (x, y) to the serie of the chart. // * // * @param serieName // * @param x // * @param y // */ // public void add(String serieName, double x, double y); // // /** // * Close the chart on the server. // */ // public void close(); // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import fr.irit.smac.libs.tooling.plot.commons.EChartType; import fr.irit.smac.libs.tooling.plot.interfaces.IAgentPlotChart;
String line; try { while ((line = in.readLine()) != null) { String[] res = line.split(";"); switch (res[0]) { case "config": config(res); break; case "add": add(res); break; case "close": close(res); break; default: break; } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void close(String[] res) { agentPlotServer.getChart(res[1]).close(); } private void add(String[] res) {
// Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/commons/EChartType.java // public enum EChartType { // PLOT, LINE // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/interfaces/IAgentPlotChart.java // public interface IAgentPlotChart { // /** // * Add the point (xMax+1, y) to the first serie of the chart. // * // * @param y // */ // public void add(double y); // // /** // * Add the point (x,y) to the first serie of the chart. // * // * @param x // * @param y // */ // public void add(double x, double y); // // /** // * Add the point (xMax+1, y) to the serie of the chart. // * // * @param serieName // * @param y // */ // public void add(String serieName, double y); // // /** // * Add the point (x, y) to the serie of the chart. // * // * @param serieName // * @param x // * @param y // */ // public void add(String serieName, double x, double y); // // /** // * Close the chart on the server. // */ // public void close(); // } // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/server/AgentPlotConnectedClient.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import fr.irit.smac.libs.tooling.plot.commons.EChartType; import fr.irit.smac.libs.tooling.plot.interfaces.IAgentPlotChart; String line; try { while ((line = in.readLine()) != null) { String[] res = line.split(";"); switch (res[0]) { case "config": config(res); break; case "add": add(res); break; case "close": close(res); break; default: break; } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void close(String[] res) { agentPlotServer.getChart(res[1]).close(); } private void add(String[] res) {
IAgentPlotChart chart = agentPlotServer.getChart(res[1]);
IRIT-SMAC/agent-tooling
agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/server/AgentPlotConnectedClient.java
// Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/commons/EChartType.java // public enum EChartType { // PLOT, LINE // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/interfaces/IAgentPlotChart.java // public interface IAgentPlotChart { // /** // * Add the point (xMax+1, y) to the first serie of the chart. // * // * @param y // */ // public void add(double y); // // /** // * Add the point (x,y) to the first serie of the chart. // * // * @param x // * @param y // */ // public void add(double x, double y); // // /** // * Add the point (xMax+1, y) to the serie of the chart. // * // * @param serieName // * @param y // */ // public void add(String serieName, double y); // // /** // * Add the point (x, y) to the serie of the chart. // * // * @param serieName // * @param x // * @param y // */ // public void add(String serieName, double x, double y); // // /** // * Close the chart on the server. // */ // public void close(); // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import fr.irit.smac.libs.tooling.plot.commons.EChartType; import fr.irit.smac.libs.tooling.plot.interfaces.IAgentPlotChart;
} } private void close(String[] res) { agentPlotServer.getChart(res[1]).close(); } private void add(String[] res) { IAgentPlotChart chart = agentPlotServer.getChart(res[1]); double y = Double.parseDouble(res[4]); if (res[3].isEmpty()) { if (res[2].isEmpty()) { chart.add(y); } else { chart.add(res[2], y); } } else { double x = Double.parseDouble(res[3]); if (res[2].isEmpty()) { chart.add(x, y); } else { chart.add(res[2], x, y); } } } private void config(String[] res) {
// Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/commons/EChartType.java // public enum EChartType { // PLOT, LINE // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/interfaces/IAgentPlotChart.java // public interface IAgentPlotChart { // /** // * Add the point (xMax+1, y) to the first serie of the chart. // * // * @param y // */ // public void add(double y); // // /** // * Add the point (x,y) to the first serie of the chart. // * // * @param x // * @param y // */ // public void add(double x, double y); // // /** // * Add the point (xMax+1, y) to the serie of the chart. // * // * @param serieName // * @param y // */ // public void add(String serieName, double y); // // /** // * Add the point (x, y) to the serie of the chart. // * // * @param serieName // * @param x // * @param y // */ // public void add(String serieName, double x, double y); // // /** // * Close the chart on the server. // */ // public void close(); // } // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/server/AgentPlotConnectedClient.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import fr.irit.smac.libs.tooling.plot.commons.EChartType; import fr.irit.smac.libs.tooling.plot.interfaces.IAgentPlotChart; } } private void close(String[] res) { agentPlotServer.getChart(res[1]).close(); } private void add(String[] res) { IAgentPlotChart chart = agentPlotServer.getChart(res[1]); double y = Double.parseDouble(res[4]); if (res[3].isEmpty()) { if (res[2].isEmpty()) { chart.add(y); } else { chart.add(res[2], y); } } else { double x = Double.parseDouble(res[3]); if (res[2].isEmpty()) { chart.add(x, y); } else { chart.add(res[2], x, y); } } } private void config(String[] res) {
agentPlotServer.configChart(res[1], EChartType.valueOf(res[2]));
IRIT-SMAC/agent-tooling
agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/example/network/Server.java
// Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/AgentPlot.java // public class AgentPlot { // // /** // * If no name is given for the server, this one will be used // */ // private static IAgentPlotServer defaultServer; // // /** // * Server's map linking name and server // */ // private static Map<String, IAgentPlotServer> servers = new TreeMap<String, IAgentPlotServer>(); // // private AgentPlot() { // // } // // /** // * Create a new server which will be accessible through network with the // * port _port // * // * @param port // */ // public static void createServer(int port) { // defaultServer = new AgentPlotServer("default", port); // } // // /** // * Create a new server with the name _name and which will be accessible // * through network with the port _port. The name is only used in the // * server's side // * // * @param name // * @param port // */ // public static void createServer(String name, int port) { // servers.put(name, new AgentPlotServer(name, port)); // } // // /** // * Get default server if any. Otherwise create it. // * // * @return // */ // public static IAgentPlotServer getServer() { // if (defaultServer == null) // defaultServer = new AgentPlotServer("default"); // return defaultServer; // } // // /** // * Get server with the given name if it exists. Otherwise create a // * connection to it. // * // * @param name // * @return // */ // public static IAgentPlotServer getServer(String name) { // if (!servers.containsKey(name)) { // servers.put(name, new AgentPlotServer(name)); // } // return servers.get(name); // } // // /** // * Get the chart with the given name if any. Otherwise, create it. // * // * @param name // * @return // */ // public static IAgentPlotChart getChart(String name) { // return getServer().getChart(name); // } // // /** // * Get the chart _name located on the server _serverName if any. Otherwise, // * create it. // * // * @param name // * @param serverName // * @return // */ // public static IAgentPlotChart getChart(String name, String serverName) { // return getServer(serverName).getChart(name); // } // // /** // * Configure the connection to a server and set a local name. The name _name // * will be then used with the method getServer(String _name). // * // * @param name // * @param host // * @param port // */ // public static void configServer(String name, String host, int port) { // servers.put(name, new AgentPlotDistantServer(host, port)); // } // // /** // * Configure the connection with the default server. // * // * @param host // * @param port // */ // public static void configServer(String host, int port) { // defaultServer = new AgentPlotDistantServer(host, port); // } // }
import fr.irit.smac.libs.tooling.plot.AgentPlot;
/* * #%L * agent-plot * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.plot.example.network; /** * Example showing the creation of an instance of the server. * * @author Alexandre Perles * */ public class Server { private Server() { } public static void main(String[] args) {
// Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/AgentPlot.java // public class AgentPlot { // // /** // * If no name is given for the server, this one will be used // */ // private static IAgentPlotServer defaultServer; // // /** // * Server's map linking name and server // */ // private static Map<String, IAgentPlotServer> servers = new TreeMap<String, IAgentPlotServer>(); // // private AgentPlot() { // // } // // /** // * Create a new server which will be accessible through network with the // * port _port // * // * @param port // */ // public static void createServer(int port) { // defaultServer = new AgentPlotServer("default", port); // } // // /** // * Create a new server with the name _name and which will be accessible // * through network with the port _port. The name is only used in the // * server's side // * // * @param name // * @param port // */ // public static void createServer(String name, int port) { // servers.put(name, new AgentPlotServer(name, port)); // } // // /** // * Get default server if any. Otherwise create it. // * // * @return // */ // public static IAgentPlotServer getServer() { // if (defaultServer == null) // defaultServer = new AgentPlotServer("default"); // return defaultServer; // } // // /** // * Get server with the given name if it exists. Otherwise create a // * connection to it. // * // * @param name // * @return // */ // public static IAgentPlotServer getServer(String name) { // if (!servers.containsKey(name)) { // servers.put(name, new AgentPlotServer(name)); // } // return servers.get(name); // } // // /** // * Get the chart with the given name if any. Otherwise, create it. // * // * @param name // * @return // */ // public static IAgentPlotChart getChart(String name) { // return getServer().getChart(name); // } // // /** // * Get the chart _name located on the server _serverName if any. Otherwise, // * create it. // * // * @param name // * @param serverName // * @return // */ // public static IAgentPlotChart getChart(String name, String serverName) { // return getServer(serverName).getChart(name); // } // // /** // * Configure the connection to a server and set a local name. The name _name // * will be then used with the method getServer(String _name). // * // * @param name // * @param host // * @param port // */ // public static void configServer(String name, String host, int port) { // servers.put(name, new AgentPlotDistantServer(host, port)); // } // // /** // * Configure the connection with the default server. // * // * @param host // * @param port // */ // public static void configServer(String host, int port) { // defaultServer = new AgentPlotDistantServer(host, port); // } // } // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/example/network/Server.java import fr.irit.smac.libs.tooling.plot.AgentPlot; /* * #%L * agent-plot * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.plot.example.network; /** * Example showing the creation of an instance of the server. * * @author Alexandre Perles * */ public class Server { private Server() { } public static void main(String[] args) {
AgentPlot.createServer(6090);
IRIT-SMAC/agent-tooling
agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/server/AgentPlotChart.java
// Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/commons/EChartType.java // public enum EChartType { // PLOT, LINE // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/interfaces/IAgentPlotChart.java // public interface IAgentPlotChart { // /** // * Add the point (xMax+1, y) to the first serie of the chart. // * // * @param y // */ // public void add(double y); // // /** // * Add the point (x,y) to the first serie of the chart. // * // * @param x // * @param y // */ // public void add(double x, double y); // // /** // * Add the point (xMax+1, y) to the serie of the chart. // * // * @param serieName // * @param y // */ // public void add(String serieName, double y); // // /** // * Add the point (x, y) to the serie of the chart. // * // * @param serieName // * @param x // * @param y // */ // public void add(String serieName, double x, double y); // // /** // * Close the chart on the server. // */ // public void close(); // }
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.util.Map; import java.util.TreeMap; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.border.TitledBorder; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import fr.irit.smac.libs.tooling.plot.commons.EChartType; import fr.irit.smac.libs.tooling.plot.interfaces.IAgentPlotChart;
/* * #%L * agent-plot * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.plot.server; /** * Real chart displayed by a server. * * @author Alexandre Perles, Thomas Sontheimer * */ public class AgentPlotChart implements IAgentPlotChart { private static JFrame frame; private static JPanel chartContainer; private XYSeriesCollection dataset; private static int chartCount = 0; private JFreeChart chart; private Map<String, XYSeries> series = new TreeMap<String, XYSeries>(); private String name; private TitledBorder border;
// Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/commons/EChartType.java // public enum EChartType { // PLOT, LINE // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/interfaces/IAgentPlotChart.java // public interface IAgentPlotChart { // /** // * Add the point (xMax+1, y) to the first serie of the chart. // * // * @param y // */ // public void add(double y); // // /** // * Add the point (x,y) to the first serie of the chart. // * // * @param x // * @param y // */ // public void add(double x, double y); // // /** // * Add the point (xMax+1, y) to the serie of the chart. // * // * @param serieName // * @param y // */ // public void add(String serieName, double y); // // /** // * Add the point (x, y) to the serie of the chart. // * // * @param serieName // * @param x // * @param y // */ // public void add(String serieName, double x, double y); // // /** // * Close the chart on the server. // */ // public void close(); // } // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/server/AgentPlotChart.java import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.util.Map; import java.util.TreeMap; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.border.TitledBorder; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import fr.irit.smac.libs.tooling.plot.commons.EChartType; import fr.irit.smac.libs.tooling.plot.interfaces.IAgentPlotChart; /* * #%L * agent-plot * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.plot.server; /** * Real chart displayed by a server. * * @author Alexandre Perles, Thomas Sontheimer * */ public class AgentPlotChart implements IAgentPlotChart { private static JFrame frame; private static JPanel chartContainer; private XYSeriesCollection dataset; private static int chartCount = 0; private JFreeChart chart; private Map<String, XYSeries> series = new TreeMap<String, XYSeries>(); private String name; private TitledBorder border;
private EChartType chartType = EChartType.PLOT;
IRIT-SMAC/agent-tooling
avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/dmdecision/impl/StandardDMDFactory.java
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/dmdecision/IDMDecision.java // public interface IDMDecision { // // /** // * The Enum EDecision. // */ // public enum EDecision { // // /** The increase delta. */ // INCREASE_DELTA, // /** The decrease delta. */ // DECREASE_DELTA, // /** The same delta. */ // SAME_DELTA // } // // /** // * Gets the next decision. // * // * @param direction // * the direction // * @return the next decision // */ // public EDecision getNextDecision(EDirection direction); // // /** // * Gets the next decision if. // * // * @param direction // * the direction // * @return the next decision if // */ // public EDecision getNextDecisionIf(EDirection direction); // // /** // * Reset state. // */ // public void resetState(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/dmdecision/IDMDecisionFactory.java // public interface IDMDecisionFactory { // // /** // * Creates a new IDMDecision object. // * // * @return the IDM decision // */ // IDMDecision createInstance(); // }
import fr.irit.smac.libs.tooling.avt.deltamanager.dmdecision.IDMDecisionFactory; import fr.irit.smac.libs.tooling.avt.deltamanager.dmdecision.IDMDecision;
/* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.deltamanager.dmdecision.impl; /** * A factory for creating StandardDMD objects. */ public class StandardDMDFactory implements IDMDecisionFactory { /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.avt.deltamanager.dmdecision.IDMDecisionFactory#createInstance() */ @Override
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/dmdecision/IDMDecision.java // public interface IDMDecision { // // /** // * The Enum EDecision. // */ // public enum EDecision { // // /** The increase delta. */ // INCREASE_DELTA, // /** The decrease delta. */ // DECREASE_DELTA, // /** The same delta. */ // SAME_DELTA // } // // /** // * Gets the next decision. // * // * @param direction // * the direction // * @return the next decision // */ // public EDecision getNextDecision(EDirection direction); // // /** // * Gets the next decision if. // * // * @param direction // * the direction // * @return the next decision if // */ // public EDecision getNextDecisionIf(EDirection direction); // // /** // * Reset state. // */ // public void resetState(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/dmdecision/IDMDecisionFactory.java // public interface IDMDecisionFactory { // // /** // * Creates a new IDMDecision object. // * // * @return the IDM decision // */ // IDMDecision createInstance(); // } // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/dmdecision/impl/StandardDMDFactory.java import fr.irit.smac.libs.tooling.avt.deltamanager.dmdecision.IDMDecisionFactory; import fr.irit.smac.libs.tooling.avt.deltamanager.dmdecision.IDMDecision; /* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.deltamanager.dmdecision.impl; /** * A factory for creating StandardDMD objects. */ public class StandardDMDFactory implements IDMDecisionFactory { /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.avt.deltamanager.dmdecision.IDMDecisionFactory#createInstance() */ @Override
public IDMDecision createInstance() {
IRIT-SMAC/agent-tooling
agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/Ref.java
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/messagecontainer/IMsgSink.java // public interface IMsgSink<T> { // // /** // * Put msg. // * // * @param msg the msg // * @return true, if successful // */ // public boolean putMsg(T msg); // }
import fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.IMsgSink;
/* * #%L * agent-messaging * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.messaging.impl; /** * A representation of a kind of address used to point to message boxes. * * This implementation hides to external package a direct access to a message * sink. * * @author lemouzy * @param <T> the generic type */ public abstract class Ref<T> implements Comparable<Ref<T>> { /** The id. */ private final String id; /** * Instantiates a new ref. * * @param id the id */ public Ref(String id) { this.id = id; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "@" + id; } /** * Gets the id. * * @return the id */ public String getId() { return id; } /* (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(Ref<T> ref) { return this.getId().compareTo(ref.getId()); } /** * Gets the msg sink. * * @return the external package hidden message sink */
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/messagecontainer/IMsgSink.java // public interface IMsgSink<T> { // // /** // * Put msg. // * // * @param msg the msg // * @return true, if successful // */ // public boolean putMsg(T msg); // } // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/Ref.java import fr.irit.smac.libs.tooling.messaging.impl.messagecontainer.IMsgSink; /* * #%L * agent-messaging * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.messaging.impl; /** * A representation of a kind of address used to point to message boxes. * * This implementation hides to external package a direct access to a message * sink. * * @author lemouzy * @param <T> the generic type */ public abstract class Ref<T> implements Comparable<Ref<T>> { /** The id. */ private final String id; /** * Instantiates a new ref. * * @param id the id */ public Ref(String id) { this.id = id; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "@" + id; } /** * Gets the id. * * @return the id */ public String getId() { return id; } /* (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(Ref<T> ref) { return this.getId().compareTo(ref.getId()); } /** * Gets the msg sink. * * @return the external package hidden message sink */
abstract IMsgSink<T> getMsgSink();
IRIT-SMAC/agent-tooling
agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/server/AgentPlotDistantServer.java
// Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/commons/EChartType.java // public enum EChartType { // PLOT, LINE // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/interfaces/IAgentPlotChart.java // public interface IAgentPlotChart { // /** // * Add the point (xMax+1, y) to the first serie of the chart. // * // * @param y // */ // public void add(double y); // // /** // * Add the point (x,y) to the first serie of the chart. // * // * @param x // * @param y // */ // public void add(double x, double y); // // /** // * Add the point (xMax+1, y) to the serie of the chart. // * // * @param serieName // * @param y // */ // public void add(String serieName, double y); // // /** // * Add the point (x, y) to the serie of the chart. // * // * @param serieName // * @param x // * @param y // */ // public void add(String serieName, double x, double y); // // /** // * Close the chart on the server. // */ // public void close(); // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/interfaces/IAgentPlotServer.java // public interface IAgentPlotServer { // /** // * Get or create the chart which is called _name. // * // * @param name // * @return // */ // public IAgentPlotChart getChart(String name); // // /** // * Preconfigure the chart _name with a chart's type and a number of series // * that will be displayed. // * // * @param name // * @param chartType // */ // public void configChart(String name, EChartType chartType); // }
import fr.irit.smac.libs.tooling.plot.interfaces.IAgentPlotServer; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.Map; import java.util.TreeMap; import fr.irit.smac.libs.tooling.plot.commons.EChartType; import fr.irit.smac.libs.tooling.plot.interfaces.IAgentPlotChart;
/* * #%L * agent-plot * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.plot.server; /** * Representation of the server made by a client * * @author Alexandre Perles * */ public class AgentPlotDistantServer implements IAgentPlotServer { private Map<String, IAgentPlotChart> charts = new TreeMap<String, IAgentPlotChart>(); private Socket socket; private PrintWriter out; public AgentPlotDistantServer(String host, int port) { try { socket = new Socket(host, port); out = new PrintWriter(socket.getOutputStream()); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public IAgentPlotChart getChart(String name) { if (!charts.containsKey(name)) {
// Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/commons/EChartType.java // public enum EChartType { // PLOT, LINE // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/interfaces/IAgentPlotChart.java // public interface IAgentPlotChart { // /** // * Add the point (xMax+1, y) to the first serie of the chart. // * // * @param y // */ // public void add(double y); // // /** // * Add the point (x,y) to the first serie of the chart. // * // * @param x // * @param y // */ // public void add(double x, double y); // // /** // * Add the point (xMax+1, y) to the serie of the chart. // * // * @param serieName // * @param y // */ // public void add(String serieName, double y); // // /** // * Add the point (x, y) to the serie of the chart. // * // * @param serieName // * @param x // * @param y // */ // public void add(String serieName, double x, double y); // // /** // * Close the chart on the server. // */ // public void close(); // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/interfaces/IAgentPlotServer.java // public interface IAgentPlotServer { // /** // * Get or create the chart which is called _name. // * // * @param name // * @return // */ // public IAgentPlotChart getChart(String name); // // /** // * Preconfigure the chart _name with a chart's type and a number of series // * that will be displayed. // * // * @param name // * @param chartType // */ // public void configChart(String name, EChartType chartType); // } // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/server/AgentPlotDistantServer.java import fr.irit.smac.libs.tooling.plot.interfaces.IAgentPlotServer; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.Map; import java.util.TreeMap; import fr.irit.smac.libs.tooling.plot.commons.EChartType; import fr.irit.smac.libs.tooling.plot.interfaces.IAgentPlotChart; /* * #%L * agent-plot * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.plot.server; /** * Representation of the server made by a client * * @author Alexandre Perles * */ public class AgentPlotDistantServer implements IAgentPlotServer { private Map<String, IAgentPlotChart> charts = new TreeMap<String, IAgentPlotChart>(); private Socket socket; private PrintWriter out; public AgentPlotDistantServer(String host, int port) { try { socket = new Socket(host, port); out = new PrintWriter(socket.getOutputStream()); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public IAgentPlotChart getChart(String name) { if (!charts.containsKey(name)) {
charts.put(name, new AgentPlotDistantChart(name, EChartType.LINE, out));
IRIT-SMAC/agent-tooling
agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/server/AgentPlotDistantChart.java
// Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/commons/EChartType.java // public enum EChartType { // PLOT, LINE // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/interfaces/IAgentPlotChart.java // public interface IAgentPlotChart { // /** // * Add the point (xMax+1, y) to the first serie of the chart. // * // * @param y // */ // public void add(double y); // // /** // * Add the point (x,y) to the first serie of the chart. // * // * @param x // * @param y // */ // public void add(double x, double y); // // /** // * Add the point (xMax+1, y) to the serie of the chart. // * // * @param serieName // * @param y // */ // public void add(String serieName, double y); // // /** // * Add the point (x, y) to the serie of the chart. // * // * @param serieName // * @param x // * @param y // */ // public void add(String serieName, double x, double y); // // /** // * Close the chart on the server. // */ // public void close(); // }
import fr.irit.smac.libs.tooling.plot.commons.EChartType; import fr.irit.smac.libs.tooling.plot.interfaces.IAgentPlotChart; import java.io.PrintWriter;
/* * #%L * agent-plot * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.plot.server; /** * Representation of a distant chart made by a client. * * @author Alexandre Perles, Thomas Sontheimer * */ public class AgentPlotDistantChart implements IAgentPlotChart { private String name; private PrintWriter out;
// Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/commons/EChartType.java // public enum EChartType { // PLOT, LINE // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/interfaces/IAgentPlotChart.java // public interface IAgentPlotChart { // /** // * Add the point (xMax+1, y) to the first serie of the chart. // * // * @param y // */ // public void add(double y); // // /** // * Add the point (x,y) to the first serie of the chart. // * // * @param x // * @param y // */ // public void add(double x, double y); // // /** // * Add the point (xMax+1, y) to the serie of the chart. // * // * @param serieName // * @param y // */ // public void add(String serieName, double y); // // /** // * Add the point (x, y) to the serie of the chart. // * // * @param serieName // * @param x // * @param y // */ // public void add(String serieName, double x, double y); // // /** // * Close the chart on the server. // */ // public void close(); // } // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/server/AgentPlotDistantChart.java import fr.irit.smac.libs.tooling.plot.commons.EChartType; import fr.irit.smac.libs.tooling.plot.interfaces.IAgentPlotChart; import java.io.PrintWriter; /* * #%L * agent-plot * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.plot.server; /** * Representation of a distant chart made by a client. * * @author Alexandre Perles, Thomas Sontheimer * */ public class AgentPlotDistantChart implements IAgentPlotChart { private String name; private PrintWriter out;
public AgentPlotDistantChart(String name, EChartType chartType, PrintWriter out) {
IRIT-SMAC/agent-tooling
agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/interfaces/IAgentPlotServer.java
// Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/commons/EChartType.java // public enum EChartType { // PLOT, LINE // }
import fr.irit.smac.libs.tooling.plot.commons.EChartType;
/* * #%L * agent-plot * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.plot.interfaces; /** * Common server's interface between the server and the client. * * @author Alexandre Perles * */ public interface IAgentPlotServer { /** * Get or create the chart which is called _name. * * @param name * @return */ public IAgentPlotChart getChart(String name); /** * Preconfigure the chart _name with a chart's type and a number of series * that will be displayed. * * @param name * @param chartType */
// Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/commons/EChartType.java // public enum EChartType { // PLOT, LINE // } // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/interfaces/IAgentPlotServer.java import fr.irit.smac.libs.tooling.plot.commons.EChartType; /* * #%L * agent-plot * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.plot.interfaces; /** * Common server's interface between the server and the client. * * @author Alexandre Perles * */ public interface IAgentPlotServer { /** * Get or create the chart which is called _name. * * @param name * @return */ public IAgentPlotChart getChart(String name); /** * Preconfigure the chart _name with a chart's type and a number of series * that will be displayed. * * @param name * @param chartType */
public void configChart(String name, EChartType chartType);
IRIT-SMAC/agent-tooling
agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/example/AdvancedMessagingExample.java
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/AgentMessaging.java // public class AgentMessaging { // // // the storage of all message service instance, associated to the message // /** The instancied msg services. */ // // type class the handle // private static Map<Class<?>, IMsgService<?>> instanciedMsgServices = new HashMap<Class<?>, IMsgService<?>>(); // // /** // * Instantiates a new agent messaging. // */ // private AgentMessaging() { // // } // // /** // * Get or create a message box for the given agentId, associated to the // * given class message service type. // * // * @param <T> // * the generic type // * @param agentId // * the agent // * @param messageClassType // * the class type or the messages handled by the message box // * @return the msg box // */ // public static <T> IMsgBox<T> getMsgBox(String agentId, // Class<T> messageClassType) { // return AgentMessaging.<T> getMsgService(messageClassType) // .getMsgBox(agentId); // } // // /** // * Get or create a message service associated to the given class message // * service type. // * // * @param <T> // * the generic type // * @param messageClassType // * the message class type // * @return the msg service // */ // public static <T> IMsgService<T> getMsgService( // Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService == null) { // msgService = new DefaultMsgService<T>(); // instanciedMsgServices.put(messageClassType, msgService); // } // // return msgService; // } // // /** // * Shutdown the message service associated with the given class message // * @param messageClassType // */ // public static <T> void shutdownMsgService(Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService != null) { // instanciedMsgServices.remove(messageClassType); // } else { // throw new IllegalArgumentException( // "Trying to shutdown a non existing service : "+messageClassType // ); // } // } // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/Ref.java // public abstract class Ref<T> implements Comparable<Ref<T>> { // // /** The id. */ // private final String id; // // /** // * Instantiates a new ref. // * // * @param id the id // */ // public Ref(String id) { // this.id = id; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "@" + id; // } // // /** // * Gets the id. // * // * @return the id // */ // public String getId() { // return id; // } // // /* (non-Javadoc) // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(Ref<T> ref) { // return this.getId().compareTo(ref.getId()); // } // // /** // * Gets the msg sink. // * // * @return the external package hidden message sink // */ // abstract IMsgSink<T> getMsgSink(); // }
import java.util.ArrayList; import java.util.List; import java.util.Random; import fr.irit.smac.libs.tooling.messaging.AgentMessaging; import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.impl.Ref;
for (int i = 0; i < nbCycles; i++) { for (ChattingAgent agent : chattingAgents) { agent.readMessages(); } for (ChattingAgent agent : chattingAgents) { agent.sendMessages(); } } long toc = System.currentTimeMillis(); System.out.println("Stop system..."); int nbReceivedMsgs = 0; for (ChattingAgent agent : chattingAgents) { nbReceivedMsgs += agent.getNbReceivedMessages(); } long nbMillis = toc - tic; System.out.println("Total received messages : " + nbReceivedMsgs); System.out.println("Total time : " + nbMillis / 1000. + " s"); System.out.println("Speed : " + (nbMillis) / ((double) nbReceivedMsgs) * 1000 + " μs / message"); } /** * The Class ChattingAgent. */ private static abstract class ChattingAgent { /** The msg box. */
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/AgentMessaging.java // public class AgentMessaging { // // // the storage of all message service instance, associated to the message // /** The instancied msg services. */ // // type class the handle // private static Map<Class<?>, IMsgService<?>> instanciedMsgServices = new HashMap<Class<?>, IMsgService<?>>(); // // /** // * Instantiates a new agent messaging. // */ // private AgentMessaging() { // // } // // /** // * Get or create a message box for the given agentId, associated to the // * given class message service type. // * // * @param <T> // * the generic type // * @param agentId // * the agent // * @param messageClassType // * the class type or the messages handled by the message box // * @return the msg box // */ // public static <T> IMsgBox<T> getMsgBox(String agentId, // Class<T> messageClassType) { // return AgentMessaging.<T> getMsgService(messageClassType) // .getMsgBox(agentId); // } // // /** // * Get or create a message service associated to the given class message // * service type. // * // * @param <T> // * the generic type // * @param messageClassType // * the message class type // * @return the msg service // */ // public static <T> IMsgService<T> getMsgService( // Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService == null) { // msgService = new DefaultMsgService<T>(); // instanciedMsgServices.put(messageClassType, msgService); // } // // return msgService; // } // // /** // * Shutdown the message service associated with the given class message // * @param messageClassType // */ // public static <T> void shutdownMsgService(Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService != null) { // instanciedMsgServices.remove(messageClassType); // } else { // throw new IllegalArgumentException( // "Trying to shutdown a non existing service : "+messageClassType // ); // } // } // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/Ref.java // public abstract class Ref<T> implements Comparable<Ref<T>> { // // /** The id. */ // private final String id; // // /** // * Instantiates a new ref. // * // * @param id the id // */ // public Ref(String id) { // this.id = id; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "@" + id; // } // // /** // * Gets the id. // * // * @return the id // */ // public String getId() { // return id; // } // // /* (non-Javadoc) // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(Ref<T> ref) { // return this.getId().compareTo(ref.getId()); // } // // /** // * Gets the msg sink. // * // * @return the external package hidden message sink // */ // abstract IMsgSink<T> getMsgSink(); // } // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/example/AdvancedMessagingExample.java import java.util.ArrayList; import java.util.List; import java.util.Random; import fr.irit.smac.libs.tooling.messaging.AgentMessaging; import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.impl.Ref; for (int i = 0; i < nbCycles; i++) { for (ChattingAgent agent : chattingAgents) { agent.readMessages(); } for (ChattingAgent agent : chattingAgents) { agent.sendMessages(); } } long toc = System.currentTimeMillis(); System.out.println("Stop system..."); int nbReceivedMsgs = 0; for (ChattingAgent agent : chattingAgents) { nbReceivedMsgs += agent.getNbReceivedMessages(); } long nbMillis = toc - tic; System.out.println("Total received messages : " + nbReceivedMsgs); System.out.println("Total time : " + nbMillis / 1000. + " s"); System.out.println("Speed : " + (nbMillis) / ((double) nbReceivedMsgs) * 1000 + " μs / message"); } /** * The Class ChattingAgent. */ private static abstract class ChattingAgent { /** The msg box. */
protected IMsgBox<String> msgBox;
IRIT-SMAC/agent-tooling
agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/example/AdvancedMessagingExample.java
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/AgentMessaging.java // public class AgentMessaging { // // // the storage of all message service instance, associated to the message // /** The instancied msg services. */ // // type class the handle // private static Map<Class<?>, IMsgService<?>> instanciedMsgServices = new HashMap<Class<?>, IMsgService<?>>(); // // /** // * Instantiates a new agent messaging. // */ // private AgentMessaging() { // // } // // /** // * Get or create a message box for the given agentId, associated to the // * given class message service type. // * // * @param <T> // * the generic type // * @param agentId // * the agent // * @param messageClassType // * the class type or the messages handled by the message box // * @return the msg box // */ // public static <T> IMsgBox<T> getMsgBox(String agentId, // Class<T> messageClassType) { // return AgentMessaging.<T> getMsgService(messageClassType) // .getMsgBox(agentId); // } // // /** // * Get or create a message service associated to the given class message // * service type. // * // * @param <T> // * the generic type // * @param messageClassType // * the message class type // * @return the msg service // */ // public static <T> IMsgService<T> getMsgService( // Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService == null) { // msgService = new DefaultMsgService<T>(); // instanciedMsgServices.put(messageClassType, msgService); // } // // return msgService; // } // // /** // * Shutdown the message service associated with the given class message // * @param messageClassType // */ // public static <T> void shutdownMsgService(Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService != null) { // instanciedMsgServices.remove(messageClassType); // } else { // throw new IllegalArgumentException( // "Trying to shutdown a non existing service : "+messageClassType // ); // } // } // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/Ref.java // public abstract class Ref<T> implements Comparable<Ref<T>> { // // /** The id. */ // private final String id; // // /** // * Instantiates a new ref. // * // * @param id the id // */ // public Ref(String id) { // this.id = id; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "@" + id; // } // // /** // * Gets the id. // * // * @return the id // */ // public String getId() { // return id; // } // // /* (non-Javadoc) // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(Ref<T> ref) { // return this.getId().compareTo(ref.getId()); // } // // /** // * Gets the msg sink. // * // * @return the external package hidden message sink // */ // abstract IMsgSink<T> getMsgSink(); // }
import java.util.ArrayList; import java.util.List; import java.util.Random; import fr.irit.smac.libs.tooling.messaging.AgentMessaging; import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.impl.Ref;
System.out.println("Total received messages : " + nbReceivedMsgs); System.out.println("Total time : " + nbMillis / 1000. + " s"); System.out.println("Speed : " + (nbMillis) / ((double) nbReceivedMsgs) * 1000 + " μs / message"); } /** * The Class ChattingAgent. */ private static abstract class ChattingAgent { /** The msg box. */ protected IMsgBox<String> msgBox; /** The id. */ protected final String id; /** The nb received messages. */ protected int nbReceivedMessages; /** * Instantiates a new chatting agent. * * @param id the id */ public ChattingAgent(String id) { this.id = id; this.nbReceivedMessages = 0; // get the message box
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/AgentMessaging.java // public class AgentMessaging { // // // the storage of all message service instance, associated to the message // /** The instancied msg services. */ // // type class the handle // private static Map<Class<?>, IMsgService<?>> instanciedMsgServices = new HashMap<Class<?>, IMsgService<?>>(); // // /** // * Instantiates a new agent messaging. // */ // private AgentMessaging() { // // } // // /** // * Get or create a message box for the given agentId, associated to the // * given class message service type. // * // * @param <T> // * the generic type // * @param agentId // * the agent // * @param messageClassType // * the class type or the messages handled by the message box // * @return the msg box // */ // public static <T> IMsgBox<T> getMsgBox(String agentId, // Class<T> messageClassType) { // return AgentMessaging.<T> getMsgService(messageClassType) // .getMsgBox(agentId); // } // // /** // * Get or create a message service associated to the given class message // * service type. // * // * @param <T> // * the generic type // * @param messageClassType // * the message class type // * @return the msg service // */ // public static <T> IMsgService<T> getMsgService( // Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService == null) { // msgService = new DefaultMsgService<T>(); // instanciedMsgServices.put(messageClassType, msgService); // } // // return msgService; // } // // /** // * Shutdown the message service associated with the given class message // * @param messageClassType // */ // public static <T> void shutdownMsgService(Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService != null) { // instanciedMsgServices.remove(messageClassType); // } else { // throw new IllegalArgumentException( // "Trying to shutdown a non existing service : "+messageClassType // ); // } // } // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/Ref.java // public abstract class Ref<T> implements Comparable<Ref<T>> { // // /** The id. */ // private final String id; // // /** // * Instantiates a new ref. // * // * @param id the id // */ // public Ref(String id) { // this.id = id; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "@" + id; // } // // /** // * Gets the id. // * // * @return the id // */ // public String getId() { // return id; // } // // /* (non-Javadoc) // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(Ref<T> ref) { // return this.getId().compareTo(ref.getId()); // } // // /** // * Gets the msg sink. // * // * @return the external package hidden message sink // */ // abstract IMsgSink<T> getMsgSink(); // } // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/example/AdvancedMessagingExample.java import java.util.ArrayList; import java.util.List; import java.util.Random; import fr.irit.smac.libs.tooling.messaging.AgentMessaging; import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.impl.Ref; System.out.println("Total received messages : " + nbReceivedMsgs); System.out.println("Total time : " + nbMillis / 1000. + " s"); System.out.println("Speed : " + (nbMillis) / ((double) nbReceivedMsgs) * 1000 + " μs / message"); } /** * The Class ChattingAgent. */ private static abstract class ChattingAgent { /** The msg box. */ protected IMsgBox<String> msgBox; /** The id. */ protected final String id; /** The nb received messages. */ protected int nbReceivedMessages; /** * Instantiates a new chatting agent. * * @param id the id */ public ChattingAgent(String id) { this.id = id; this.nbReceivedMessages = 0; // get the message box
this.msgBox = AgentMessaging.getMsgBox(id, String.class);
IRIT-SMAC/agent-tooling
agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/example/AdvancedMessagingExample.java
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/AgentMessaging.java // public class AgentMessaging { // // // the storage of all message service instance, associated to the message // /** The instancied msg services. */ // // type class the handle // private static Map<Class<?>, IMsgService<?>> instanciedMsgServices = new HashMap<Class<?>, IMsgService<?>>(); // // /** // * Instantiates a new agent messaging. // */ // private AgentMessaging() { // // } // // /** // * Get or create a message box for the given agentId, associated to the // * given class message service type. // * // * @param <T> // * the generic type // * @param agentId // * the agent // * @param messageClassType // * the class type or the messages handled by the message box // * @return the msg box // */ // public static <T> IMsgBox<T> getMsgBox(String agentId, // Class<T> messageClassType) { // return AgentMessaging.<T> getMsgService(messageClassType) // .getMsgBox(agentId); // } // // /** // * Get or create a message service associated to the given class message // * service type. // * // * @param <T> // * the generic type // * @param messageClassType // * the message class type // * @return the msg service // */ // public static <T> IMsgService<T> getMsgService( // Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService == null) { // msgService = new DefaultMsgService<T>(); // instanciedMsgServices.put(messageClassType, msgService); // } // // return msgService; // } // // /** // * Shutdown the message service associated with the given class message // * @param messageClassType // */ // public static <T> void shutdownMsgService(Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService != null) { // instanciedMsgServices.remove(messageClassType); // } else { // throw new IllegalArgumentException( // "Trying to shutdown a non existing service : "+messageClassType // ); // } // } // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/Ref.java // public abstract class Ref<T> implements Comparable<Ref<T>> { // // /** The id. */ // private final String id; // // /** // * Instantiates a new ref. // * // * @param id the id // */ // public Ref(String id) { // this.id = id; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "@" + id; // } // // /** // * Gets the id. // * // * @return the id // */ // public String getId() { // return id; // } // // /* (non-Javadoc) // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(Ref<T> ref) { // return this.getId().compareTo(ref.getId()); // } // // /** // * Gets the msg sink. // * // * @return the external package hidden message sink // */ // abstract IMsgSink<T> getMsgSink(); // }
import java.util.ArrayList; import java.util.List; import java.util.Random; import fr.irit.smac.libs.tooling.messaging.AgentMessaging; import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.impl.Ref;
/** * Read messages. */ public void readMessages() { List<String> receivedMessages = this.msgBox.getMsgs(); this.nbReceivedMessages += receivedMessages.size(); } /** * Gets the nb received messages. * * @return the nb received messages */ public int getNbReceivedMessages() { return this.nbReceivedMessages; } /** * Send messages. */ public abstract void sendMessages(); } /** * The Class ChattingToAGroupAgent. */ private static class ChattingToAGroupAgent extends ChattingAgent { /** The my group. */
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/AgentMessaging.java // public class AgentMessaging { // // // the storage of all message service instance, associated to the message // /** The instancied msg services. */ // // type class the handle // private static Map<Class<?>, IMsgService<?>> instanciedMsgServices = new HashMap<Class<?>, IMsgService<?>>(); // // /** // * Instantiates a new agent messaging. // */ // private AgentMessaging() { // // } // // /** // * Get or create a message box for the given agentId, associated to the // * given class message service type. // * // * @param <T> // * the generic type // * @param agentId // * the agent // * @param messageClassType // * the class type or the messages handled by the message box // * @return the msg box // */ // public static <T> IMsgBox<T> getMsgBox(String agentId, // Class<T> messageClassType) { // return AgentMessaging.<T> getMsgService(messageClassType) // .getMsgBox(agentId); // } // // /** // * Get or create a message service associated to the given class message // * service type. // * // * @param <T> // * the generic type // * @param messageClassType // * the message class type // * @return the msg service // */ // public static <T> IMsgService<T> getMsgService( // Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService == null) { // msgService = new DefaultMsgService<T>(); // instanciedMsgServices.put(messageClassType, msgService); // } // // return msgService; // } // // /** // * Shutdown the message service associated with the given class message // * @param messageClassType // */ // public static <T> void shutdownMsgService(Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService != null) { // instanciedMsgServices.remove(messageClassType); // } else { // throw new IllegalArgumentException( // "Trying to shutdown a non existing service : "+messageClassType // ); // } // } // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/Ref.java // public abstract class Ref<T> implements Comparable<Ref<T>> { // // /** The id. */ // private final String id; // // /** // * Instantiates a new ref. // * // * @param id the id // */ // public Ref(String id) { // this.id = id; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "@" + id; // } // // /** // * Gets the id. // * // * @return the id // */ // public String getId() { // return id; // } // // /* (non-Javadoc) // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(Ref<T> ref) { // return this.getId().compareTo(ref.getId()); // } // // /** // * Gets the msg sink. // * // * @return the external package hidden message sink // */ // abstract IMsgSink<T> getMsgSink(); // } // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/example/AdvancedMessagingExample.java import java.util.ArrayList; import java.util.List; import java.util.Random; import fr.irit.smac.libs.tooling.messaging.AgentMessaging; import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.impl.Ref; /** * Read messages. */ public void readMessages() { List<String> receivedMessages = this.msgBox.getMsgs(); this.nbReceivedMessages += receivedMessages.size(); } /** * Gets the nb received messages. * * @return the nb received messages */ public int getNbReceivedMessages() { return this.nbReceivedMessages; } /** * Send messages. */ public abstract void sendMessages(); } /** * The Class ChattingToAGroupAgent. */ private static class ChattingToAGroupAgent extends ChattingAgent { /** The my group. */
private final Ref<String> myGroup;
IRIT-SMAC/agent-tooling
avt/src/main/java/fr/irit/smac/libs/tooling/avt/AVTBuilder.java
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/SoftBoundsAVTFactory.java // public class SoftBoundsAVTFactory implements IAVTFactory<IAVT> { // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) // */ // @Override // public IAVT createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory) { // return new SoftBoundsAVT(lowerBound, upperBound, startValue, deltaManagerFactory); // } // // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/SoftBoundsMemoryAVTFactory.java // public class SoftBoundsMemoryAVTFactory implements IAVTFactory<IAVT> { // // /** The soft bounds memory. */ // private final int softBoundsMemory; // // /** // * Instantiates a new soft bounds memory avt factory. // * // * @param softBoundsMemory the soft bounds memory // */ // public SoftBoundsMemoryAVTFactory(int softBoundsMemory) { // super(); // this.softBoundsMemory = softBoundsMemory; // } // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) // */ // @Override // public IAVT createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory) { // // return new SoftBoundsMemoryAVT(lowerBound, upperBound, startValue, deltaManagerFactory, this.softBoundsMemory); // } // // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/StandardAVTFactory.java // public class StandardAVTFactory implements IAVTFactory<IAVT> { // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) // */ // @Override // public IAVT createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory) { // return new StandardAVT(lowerBound, upperBound, startValue, deltaManagerFactory); // } // // }
import fr.irit.smac.libs.tooling.avt.impl.SoftBoundsMemoryAVTFactory; import fr.irit.smac.libs.tooling.avt.impl.StandardAVTFactory; import fr.irit.smac.libs.tooling.avt.impl.SoftBoundsAVTFactory;
/* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt; /** * The Class AVTBuilder. * * @author Sylvain Lemouzy */ public class AVTBuilder extends AbstractAVTBuilder<IAVT> { /* * (non-Javadoc) * * @see fr.irit.smac.util.avt.IAVTBuilder#build() */ @Override public IAVT build() { if (this.avtFactory == null) { if (!this.isHardBounds) { if (this.softBoundsMemory > 0) {
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/SoftBoundsAVTFactory.java // public class SoftBoundsAVTFactory implements IAVTFactory<IAVT> { // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) // */ // @Override // public IAVT createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory) { // return new SoftBoundsAVT(lowerBound, upperBound, startValue, deltaManagerFactory); // } // // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/SoftBoundsMemoryAVTFactory.java // public class SoftBoundsMemoryAVTFactory implements IAVTFactory<IAVT> { // // /** The soft bounds memory. */ // private final int softBoundsMemory; // // /** // * Instantiates a new soft bounds memory avt factory. // * // * @param softBoundsMemory the soft bounds memory // */ // public SoftBoundsMemoryAVTFactory(int softBoundsMemory) { // super(); // this.softBoundsMemory = softBoundsMemory; // } // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) // */ // @Override // public IAVT createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory) { // // return new SoftBoundsMemoryAVT(lowerBound, upperBound, startValue, deltaManagerFactory, this.softBoundsMemory); // } // // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/StandardAVTFactory.java // public class StandardAVTFactory implements IAVTFactory<IAVT> { // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) // */ // @Override // public IAVT createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory) { // return new StandardAVT(lowerBound, upperBound, startValue, deltaManagerFactory); // } // // } // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/AVTBuilder.java import fr.irit.smac.libs.tooling.avt.impl.SoftBoundsMemoryAVTFactory; import fr.irit.smac.libs.tooling.avt.impl.StandardAVTFactory; import fr.irit.smac.libs.tooling.avt.impl.SoftBoundsAVTFactory; /* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt; /** * The Class AVTBuilder. * * @author Sylvain Lemouzy */ public class AVTBuilder extends AbstractAVTBuilder<IAVT> { /* * (non-Javadoc) * * @see fr.irit.smac.util.avt.IAVTBuilder#build() */ @Override public IAVT build() { if (this.avtFactory == null) { if (!this.isHardBounds) { if (this.softBoundsMemory > 0) {
this.avtFactory = new SoftBoundsMemoryAVTFactory(this.softBoundsMemory);
IRIT-SMAC/agent-tooling
avt/src/main/java/fr/irit/smac/libs/tooling/avt/AVTBuilder.java
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/SoftBoundsAVTFactory.java // public class SoftBoundsAVTFactory implements IAVTFactory<IAVT> { // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) // */ // @Override // public IAVT createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory) { // return new SoftBoundsAVT(lowerBound, upperBound, startValue, deltaManagerFactory); // } // // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/SoftBoundsMemoryAVTFactory.java // public class SoftBoundsMemoryAVTFactory implements IAVTFactory<IAVT> { // // /** The soft bounds memory. */ // private final int softBoundsMemory; // // /** // * Instantiates a new soft bounds memory avt factory. // * // * @param softBoundsMemory the soft bounds memory // */ // public SoftBoundsMemoryAVTFactory(int softBoundsMemory) { // super(); // this.softBoundsMemory = softBoundsMemory; // } // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) // */ // @Override // public IAVT createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory) { // // return new SoftBoundsMemoryAVT(lowerBound, upperBound, startValue, deltaManagerFactory, this.softBoundsMemory); // } // // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/StandardAVTFactory.java // public class StandardAVTFactory implements IAVTFactory<IAVT> { // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) // */ // @Override // public IAVT createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory) { // return new StandardAVT(lowerBound, upperBound, startValue, deltaManagerFactory); // } // // }
import fr.irit.smac.libs.tooling.avt.impl.SoftBoundsMemoryAVTFactory; import fr.irit.smac.libs.tooling.avt.impl.StandardAVTFactory; import fr.irit.smac.libs.tooling.avt.impl.SoftBoundsAVTFactory;
/* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt; /** * The Class AVTBuilder. * * @author Sylvain Lemouzy */ public class AVTBuilder extends AbstractAVTBuilder<IAVT> { /* * (non-Javadoc) * * @see fr.irit.smac.util.avt.IAVTBuilder#build() */ @Override public IAVT build() { if (this.avtFactory == null) { if (!this.isHardBounds) { if (this.softBoundsMemory > 0) { this.avtFactory = new SoftBoundsMemoryAVTFactory(this.softBoundsMemory); } else {
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/SoftBoundsAVTFactory.java // public class SoftBoundsAVTFactory implements IAVTFactory<IAVT> { // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) // */ // @Override // public IAVT createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory) { // return new SoftBoundsAVT(lowerBound, upperBound, startValue, deltaManagerFactory); // } // // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/SoftBoundsMemoryAVTFactory.java // public class SoftBoundsMemoryAVTFactory implements IAVTFactory<IAVT> { // // /** The soft bounds memory. */ // private final int softBoundsMemory; // // /** // * Instantiates a new soft bounds memory avt factory. // * // * @param softBoundsMemory the soft bounds memory // */ // public SoftBoundsMemoryAVTFactory(int softBoundsMemory) { // super(); // this.softBoundsMemory = softBoundsMemory; // } // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) // */ // @Override // public IAVT createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory) { // // return new SoftBoundsMemoryAVT(lowerBound, upperBound, startValue, deltaManagerFactory, this.softBoundsMemory); // } // // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/StandardAVTFactory.java // public class StandardAVTFactory implements IAVTFactory<IAVT> { // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) // */ // @Override // public IAVT createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory) { // return new StandardAVT(lowerBound, upperBound, startValue, deltaManagerFactory); // } // // } // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/AVTBuilder.java import fr.irit.smac.libs.tooling.avt.impl.SoftBoundsMemoryAVTFactory; import fr.irit.smac.libs.tooling.avt.impl.StandardAVTFactory; import fr.irit.smac.libs.tooling.avt.impl.SoftBoundsAVTFactory; /* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt; /** * The Class AVTBuilder. * * @author Sylvain Lemouzy */ public class AVTBuilder extends AbstractAVTBuilder<IAVT> { /* * (non-Javadoc) * * @see fr.irit.smac.util.avt.IAVTBuilder#build() */ @Override public IAVT build() { if (this.avtFactory == null) { if (!this.isHardBounds) { if (this.softBoundsMemory > 0) { this.avtFactory = new SoftBoundsMemoryAVTFactory(this.softBoundsMemory); } else {
this.avtFactory = new SoftBoundsAVTFactory();
IRIT-SMAC/agent-tooling
avt/src/main/java/fr/irit/smac/libs/tooling/avt/AVTBuilder.java
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/SoftBoundsAVTFactory.java // public class SoftBoundsAVTFactory implements IAVTFactory<IAVT> { // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) // */ // @Override // public IAVT createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory) { // return new SoftBoundsAVT(lowerBound, upperBound, startValue, deltaManagerFactory); // } // // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/SoftBoundsMemoryAVTFactory.java // public class SoftBoundsMemoryAVTFactory implements IAVTFactory<IAVT> { // // /** The soft bounds memory. */ // private final int softBoundsMemory; // // /** // * Instantiates a new soft bounds memory avt factory. // * // * @param softBoundsMemory the soft bounds memory // */ // public SoftBoundsMemoryAVTFactory(int softBoundsMemory) { // super(); // this.softBoundsMemory = softBoundsMemory; // } // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) // */ // @Override // public IAVT createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory) { // // return new SoftBoundsMemoryAVT(lowerBound, upperBound, startValue, deltaManagerFactory, this.softBoundsMemory); // } // // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/StandardAVTFactory.java // public class StandardAVTFactory implements IAVTFactory<IAVT> { // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) // */ // @Override // public IAVT createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory) { // return new StandardAVT(lowerBound, upperBound, startValue, deltaManagerFactory); // } // // }
import fr.irit.smac.libs.tooling.avt.impl.SoftBoundsMemoryAVTFactory; import fr.irit.smac.libs.tooling.avt.impl.StandardAVTFactory; import fr.irit.smac.libs.tooling.avt.impl.SoftBoundsAVTFactory;
/* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt; /** * The Class AVTBuilder. * * @author Sylvain Lemouzy */ public class AVTBuilder extends AbstractAVTBuilder<IAVT> { /* * (non-Javadoc) * * @see fr.irit.smac.util.avt.IAVTBuilder#build() */ @Override public IAVT build() { if (this.avtFactory == null) { if (!this.isHardBounds) { if (this.softBoundsMemory > 0) { this.avtFactory = new SoftBoundsMemoryAVTFactory(this.softBoundsMemory); } else { this.avtFactory = new SoftBoundsAVTFactory(); } } else {
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/SoftBoundsAVTFactory.java // public class SoftBoundsAVTFactory implements IAVTFactory<IAVT> { // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) // */ // @Override // public IAVT createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory) { // return new SoftBoundsAVT(lowerBound, upperBound, startValue, deltaManagerFactory); // } // // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/SoftBoundsMemoryAVTFactory.java // public class SoftBoundsMemoryAVTFactory implements IAVTFactory<IAVT> { // // /** The soft bounds memory. */ // private final int softBoundsMemory; // // /** // * Instantiates a new soft bounds memory avt factory. // * // * @param softBoundsMemory the soft bounds memory // */ // public SoftBoundsMemoryAVTFactory(int softBoundsMemory) { // super(); // this.softBoundsMemory = softBoundsMemory; // } // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) // */ // @Override // public IAVT createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory) { // // return new SoftBoundsMemoryAVT(lowerBound, upperBound, startValue, deltaManagerFactory, this.softBoundsMemory); // } // // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/StandardAVTFactory.java // public class StandardAVTFactory implements IAVTFactory<IAVT> { // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) // */ // @Override // public IAVT createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory) { // return new StandardAVT(lowerBound, upperBound, startValue, deltaManagerFactory); // } // // } // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/AVTBuilder.java import fr.irit.smac.libs.tooling.avt.impl.SoftBoundsMemoryAVTFactory; import fr.irit.smac.libs.tooling.avt.impl.StandardAVTFactory; import fr.irit.smac.libs.tooling.avt.impl.SoftBoundsAVTFactory; /* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt; /** * The Class AVTBuilder. * * @author Sylvain Lemouzy */ public class AVTBuilder extends AbstractAVTBuilder<IAVT> { /* * (non-Javadoc) * * @see fr.irit.smac.util.avt.IAVTBuilder#build() */ @Override public IAVT build() { if (this.avtFactory == null) { if (!this.isHardBounds) { if (this.softBoundsMemory > 0) { this.avtFactory = new SoftBoundsMemoryAVTFactory(this.softBoundsMemory); } else { this.avtFactory = new SoftBoundsAVTFactory(); } } else {
this.avtFactory = new StandardAVTFactory();
IRIT-SMAC/agent-tooling
agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/IMutableDirectory.java
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IDirectory.java // public interface IDirectory<T> { // // /** // * Returns the agent ref from the given agent id. // * // * @param agentId the agent id // * @return the agent ref // */ // public Ref<T> getAgentRef(String agentId); // // /** // * Returns the group ref from the given agent id. // * // * @param groupId the group id // * @return the group ref // */ // public Ref<T> getGroupRef(String groupId); // // /** // * Returns all the agents inscribed in a group. // * // * @param groupRef the group ref // * @return the agents of group // */ // public Set<Ref<T>> getAgentsOfGroup(Ref<T> groupRef); // // /** // * Returns all the agents inscribed in a group. // * // * @param groupId the group id // * @return the agents of group // */ // public Set<Ref<T>> getAgentsOfGroup(String groupId); // // /** // * Returns all the agent refs inscribed in the directory. // * // * @return the groups ref // */ // public List<Ref<T>> getGroupsRef(); // // /** // * Returns all the groups refs inscribed in the directory. // * // * @return the agents ref // */ // public List<Ref<T>> getAgentsRef(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // }
import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.IDirectory;
/* * #%L * agent-messaging * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.messaging.impl; /** * Interface of a directory that can be modified, and allow add/remove of msgBox * and groups. * * @author lemouzy * @param <T> the generic type */ interface IMutableDirectory<T> extends IDirectory<T> { /** * Subscribe an agent to a group. * * The group is created if it does not exist * * @param agentRef the agent ref * @param groupId the group id * @return the ref */ public Ref<T> subscribeAgentToGroup(Ref<T> agentRef, String groupId); /** * Subscribe an agent to a group. * * @param agentRef the agent ref * @param groupRef the group ref */ public void subscribeAgentToGroup(Ref<T> agentRef, Ref<T> groupRef); /** * Unsubscribe an agent from a group. * * @param agentRef the agent ref * @param groupId the group id */ public void unsubscribeAgentFromGroup(Ref<T> agentRef, String groupId); /** * Unsubscribe an agent from a group. * * @param agentRef the agent ref * @param groupRef the group ref */ public void unsubscribeAgentFromGroup(Ref<T> agentRef, Ref<T> groupRef); /** * Creates the agent msg box. * * @param agentId the agent id * @return the i msg box */
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IDirectory.java // public interface IDirectory<T> { // // /** // * Returns the agent ref from the given agent id. // * // * @param agentId the agent id // * @return the agent ref // */ // public Ref<T> getAgentRef(String agentId); // // /** // * Returns the group ref from the given agent id. // * // * @param groupId the group id // * @return the group ref // */ // public Ref<T> getGroupRef(String groupId); // // /** // * Returns all the agents inscribed in a group. // * // * @param groupRef the group ref // * @return the agents of group // */ // public Set<Ref<T>> getAgentsOfGroup(Ref<T> groupRef); // // /** // * Returns all the agents inscribed in a group. // * // * @param groupId the group id // * @return the agents of group // */ // public Set<Ref<T>> getAgentsOfGroup(String groupId); // // /** // * Returns all the agent refs inscribed in the directory. // * // * @return the groups ref // */ // public List<Ref<T>> getGroupsRef(); // // /** // * Returns all the groups refs inscribed in the directory. // * // * @return the agents ref // */ // public List<Ref<T>> getAgentsRef(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/IMutableDirectory.java import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.IDirectory; /* * #%L * agent-messaging * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.messaging.impl; /** * Interface of a directory that can be modified, and allow add/remove of msgBox * and groups. * * @author lemouzy * @param <T> the generic type */ interface IMutableDirectory<T> extends IDirectory<T> { /** * Subscribe an agent to a group. * * The group is created if it does not exist * * @param agentRef the agent ref * @param groupId the group id * @return the ref */ public Ref<T> subscribeAgentToGroup(Ref<T> agentRef, String groupId); /** * Subscribe an agent to a group. * * @param agentRef the agent ref * @param groupRef the group ref */ public void subscribeAgentToGroup(Ref<T> agentRef, Ref<T> groupRef); /** * Unsubscribe an agent from a group. * * @param agentRef the agent ref * @param groupId the group id */ public void unsubscribeAgentFromGroup(Ref<T> agentRef, String groupId); /** * Unsubscribe an agent from a group. * * @param agentRef the agent ref * @param groupRef the group ref */ public void unsubscribeAgentFromGroup(Ref<T> agentRef, Ref<T> groupRef); /** * Creates the agent msg box. * * @param agentId the agent id * @return the i msg box */
public IMsgBox<T> createAgentMsgBox(String agentId);
IRIT-SMAC/agent-tooling
avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/deltaevolution/impl/UndeterministicGDEFactory.java
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/deltaevolution/IGeometricDE.java // public interface IGeometricDE extends IDeltaEvolution { // // /** // * Gets the increase factor. // * // * @return the increase factor // */ // public double getIncreaseFactor(); // // /** // * Gets the decrease factor. // * // * @return the decrease factor // */ // public double getDecreaseFactor(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/deltaevolution/IGeometricDEFactory.java // public interface IGeometricDEFactory extends IDeltaEvolutionFactory { // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.avt.deltamanager.deltaevolution.IDeltaEvolutionFactory#createInstance() // */ // @Override // IGeometricDE createInstance(); // }
import fr.irit.smac.libs.tooling.avt.deltamanager.deltaevolution.IGeometricDEFactory; import fr.irit.smac.libs.tooling.avt.deltamanager.deltaevolution.IGeometricDE;
/* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.deltamanager.deltaevolution.impl; /** * A factory for creating UndeterministicGDE objects. */ public class UndeterministicGDEFactory implements IGeometricDEFactory { /** The increase factor. */ private final double increaseFactor; /** The decrease factor. */ private final double decreaseFactor; /** The decrease noise. */ private final double decreaseNoise; /** The random seed. */ private final Long randomSeed; /** * Instantiates a new undeterministic gde factory. * * @param increaseFactor the increase factor * @param decreaseFactor the decrease factor * @param decreaseNoise the decrease noise */ public UndeterministicGDEFactory(double increaseFactor, double decreaseFactor, double decreaseNoise) { this(increaseFactor, decreaseFactor, decreaseNoise, null); } /** * Instantiates a new undeterministic gde factory. * * @param increaseFactor the increase factor * @param decreaseFactor the decrease factor * @param decreaseNoise the decrease noise * @param randomSeed the random seed */ public UndeterministicGDEFactory(double increaseFactor, double decreaseFactor, double decreaseNoise, Long randomSeed) { super(); this.increaseFactor = increaseFactor; this.decreaseFactor = decreaseFactor; this.decreaseNoise = decreaseNoise; this.randomSeed = randomSeed; } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.avt.deltamanager.deltaevolution.IGeometricDEFactory#createInstance() */ @Override
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/deltaevolution/IGeometricDE.java // public interface IGeometricDE extends IDeltaEvolution { // // /** // * Gets the increase factor. // * // * @return the increase factor // */ // public double getIncreaseFactor(); // // /** // * Gets the decrease factor. // * // * @return the decrease factor // */ // public double getDecreaseFactor(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/deltaevolution/IGeometricDEFactory.java // public interface IGeometricDEFactory extends IDeltaEvolutionFactory { // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.avt.deltamanager.deltaevolution.IDeltaEvolutionFactory#createInstance() // */ // @Override // IGeometricDE createInstance(); // } // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/deltaevolution/impl/UndeterministicGDEFactory.java import fr.irit.smac.libs.tooling.avt.deltamanager.deltaevolution.IGeometricDEFactory; import fr.irit.smac.libs.tooling.avt.deltamanager.deltaevolution.IGeometricDE; /* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.deltamanager.deltaevolution.impl; /** * A factory for creating UndeterministicGDE objects. */ public class UndeterministicGDEFactory implements IGeometricDEFactory { /** The increase factor. */ private final double increaseFactor; /** The decrease factor. */ private final double decreaseFactor; /** The decrease noise. */ private final double decreaseNoise; /** The random seed. */ private final Long randomSeed; /** * Instantiates a new undeterministic gde factory. * * @param increaseFactor the increase factor * @param decreaseFactor the decrease factor * @param decreaseNoise the decrease noise */ public UndeterministicGDEFactory(double increaseFactor, double decreaseFactor, double decreaseNoise) { this(increaseFactor, decreaseFactor, decreaseNoise, null); } /** * Instantiates a new undeterministic gde factory. * * @param increaseFactor the increase factor * @param decreaseFactor the decrease factor * @param decreaseNoise the decrease noise * @param randomSeed the random seed */ public UndeterministicGDEFactory(double increaseFactor, double decreaseFactor, double decreaseNoise, Long randomSeed) { super(); this.increaseFactor = increaseFactor; this.decreaseFactor = decreaseFactor; this.decreaseNoise = decreaseNoise; this.randomSeed = randomSeed; } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.avt.deltamanager.deltaevolution.IGeometricDEFactory#createInstance() */ @Override
public IGeometricDE createInstance() {
IRIT-SMAC/agent-tooling
agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/BasicMutableDirectory.java
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/ExceptionMessage.java // public class ExceptionMessage { // // /** The Constant UNKNOWN_GROUP_UNSUBSCRIBE. */ // public static final String UNKNOWN_GROUP_UNSUBSCRIBE = "Trying to unsubscribe an agent from an unknown group : {0}"; // // /** The Constant UNKNOWN_GROUP_SUBSCRIBE. */ // public static final String UNKNOWN_GROUP_SUBSCRIBE = "Trying to subscribe an agent from an unknown group : {0}"; // // /** The Constant UNKNOWN_RECEIVER_SEND. */ // public static final String UNKNOWN_RECEIVER_SEND = "Trying to send a message to an unknown receiver : {0}"; // // /** The Constant UNKNOWN_GROUP_SEND. */ // public static final String UNKNOWN_GROUP_SEND = "Trying to send a message to an unknown group : {0}"; // // /** The Constant GET_MESSAGES_DISPOSED_MSG_BOX. */ // public static final String GET_MESSAGES_DISPOSED_MSG_BOX = "Trying to receive messages from a disposed message box."; // // /** The Constant AGENT_ALREADY_ASSOCIATED_MSG_BOX. */ // public static final String AGENT_ALREADY_ASSOCIATED_MSG_BOX = "The agent {0} is already associated with a msgBox."; // // /** // * Instantiates a new exception message. // */ // private ExceptionMessage() { // // } // // /** // * Format message. // * // * @param messageString // * the message string // * @param arg0 // * the arg0 // * @return the string // */ // public static String formatMessage(String messageString, Object arg0) { // // MessageFormat mf = new MessageFormat(messageString); // Object[] args = new Object[1]; // args[0] = arg0; // return mf.format(args); // } // // }
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.ExceptionMessage;
/* * #%L * agent-messaging * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.messaging.impl; /** * Basic implementation of the msgBox directory. * * Manages msgBox and Groups. Theoretically this implementation is thread safe. * * @author lemouzy * @param <T> * the generic type */ public class BasicMutableDirectory<T> implements IMutableDirectory<T> { /** The agent directory. */ private final Map<String, AgentMsgBox<T>> agentDirectory; /** The group directory. */ private final Map<String, GroupMsgBox<T>> groupDirectory; /** The group modification lock. */ private final ReentrantLock groupModificationLock; /** The agent modification lock. */ private final ReentrantLock agentModificationLock; /** The broad cast msg box. */ private final GroupMsgBox<T> broadCastMsgBox; /** * Name of the group that will contain all the agents (used for broadcast). */ public static final String ALL = "all"; /** * Instantiates a new basic mutable directory. */ public BasicMutableDirectory() { super(); this.agentDirectory = new ConcurrentHashMap<String, AgentMsgBox<T>>(); this.groupDirectory = new ConcurrentHashMap<String, GroupMsgBox<T>>(); this.groupModificationLock = new ReentrantLock(); this.agentModificationLock = new ReentrantLock(); this.broadCastMsgBox = this.getOrCreateGroupMsgBox(ALL); } // /////////////////////////////////////////////////////////////////////////////// // Agent - Group Creation / Deletion // /////////////////////////////////////////////////////////////////////////////// /* * (non-Javadoc) * * @see * fr.irit.smac.libs.tooling.messaging.impl.IMutableDirectory#createAgentMsgBox * (java.lang.String) */ @Override
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/ExceptionMessage.java // public class ExceptionMessage { // // /** The Constant UNKNOWN_GROUP_UNSUBSCRIBE. */ // public static final String UNKNOWN_GROUP_UNSUBSCRIBE = "Trying to unsubscribe an agent from an unknown group : {0}"; // // /** The Constant UNKNOWN_GROUP_SUBSCRIBE. */ // public static final String UNKNOWN_GROUP_SUBSCRIBE = "Trying to subscribe an agent from an unknown group : {0}"; // // /** The Constant UNKNOWN_RECEIVER_SEND. */ // public static final String UNKNOWN_RECEIVER_SEND = "Trying to send a message to an unknown receiver : {0}"; // // /** The Constant UNKNOWN_GROUP_SEND. */ // public static final String UNKNOWN_GROUP_SEND = "Trying to send a message to an unknown group : {0}"; // // /** The Constant GET_MESSAGES_DISPOSED_MSG_BOX. */ // public static final String GET_MESSAGES_DISPOSED_MSG_BOX = "Trying to receive messages from a disposed message box."; // // /** The Constant AGENT_ALREADY_ASSOCIATED_MSG_BOX. */ // public static final String AGENT_ALREADY_ASSOCIATED_MSG_BOX = "The agent {0} is already associated with a msgBox."; // // /** // * Instantiates a new exception message. // */ // private ExceptionMessage() { // // } // // /** // * Format message. // * // * @param messageString // * the message string // * @param arg0 // * the arg0 // * @return the string // */ // public static String formatMessage(String messageString, Object arg0) { // // MessageFormat mf = new MessageFormat(messageString); // Object[] args = new Object[1]; // args[0] = arg0; // return mf.format(args); // } // // } // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/BasicMutableDirectory.java import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.ExceptionMessage; /* * #%L * agent-messaging * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.messaging.impl; /** * Basic implementation of the msgBox directory. * * Manages msgBox and Groups. Theoretically this implementation is thread safe. * * @author lemouzy * @param <T> * the generic type */ public class BasicMutableDirectory<T> implements IMutableDirectory<T> { /** The agent directory. */ private final Map<String, AgentMsgBox<T>> agentDirectory; /** The group directory. */ private final Map<String, GroupMsgBox<T>> groupDirectory; /** The group modification lock. */ private final ReentrantLock groupModificationLock; /** The agent modification lock. */ private final ReentrantLock agentModificationLock; /** The broad cast msg box. */ private final GroupMsgBox<T> broadCastMsgBox; /** * Name of the group that will contain all the agents (used for broadcast). */ public static final String ALL = "all"; /** * Instantiates a new basic mutable directory. */ public BasicMutableDirectory() { super(); this.agentDirectory = new ConcurrentHashMap<String, AgentMsgBox<T>>(); this.groupDirectory = new ConcurrentHashMap<String, GroupMsgBox<T>>(); this.groupModificationLock = new ReentrantLock(); this.agentModificationLock = new ReentrantLock(); this.broadCastMsgBox = this.getOrCreateGroupMsgBox(ALL); } // /////////////////////////////////////////////////////////////////////////////// // Agent - Group Creation / Deletion // /////////////////////////////////////////////////////////////////////////////// /* * (non-Javadoc) * * @see * fr.irit.smac.libs.tooling.messaging.impl.IMutableDirectory#createAgentMsgBox * (java.lang.String) */ @Override
public IMsgBox<T> createAgentMsgBox(String agentId) {
IRIT-SMAC/agent-tooling
agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/BasicMutableDirectory.java
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/ExceptionMessage.java // public class ExceptionMessage { // // /** The Constant UNKNOWN_GROUP_UNSUBSCRIBE. */ // public static final String UNKNOWN_GROUP_UNSUBSCRIBE = "Trying to unsubscribe an agent from an unknown group : {0}"; // // /** The Constant UNKNOWN_GROUP_SUBSCRIBE. */ // public static final String UNKNOWN_GROUP_SUBSCRIBE = "Trying to subscribe an agent from an unknown group : {0}"; // // /** The Constant UNKNOWN_RECEIVER_SEND. */ // public static final String UNKNOWN_RECEIVER_SEND = "Trying to send a message to an unknown receiver : {0}"; // // /** The Constant UNKNOWN_GROUP_SEND. */ // public static final String UNKNOWN_GROUP_SEND = "Trying to send a message to an unknown group : {0}"; // // /** The Constant GET_MESSAGES_DISPOSED_MSG_BOX. */ // public static final String GET_MESSAGES_DISPOSED_MSG_BOX = "Trying to receive messages from a disposed message box."; // // /** The Constant AGENT_ALREADY_ASSOCIATED_MSG_BOX. */ // public static final String AGENT_ALREADY_ASSOCIATED_MSG_BOX = "The agent {0} is already associated with a msgBox."; // // /** // * Instantiates a new exception message. // */ // private ExceptionMessage() { // // } // // /** // * Format message. // * // * @param messageString // * the message string // * @param arg0 // * the arg0 // * @return the string // */ // public static String formatMessage(String messageString, Object arg0) { // // MessageFormat mf = new MessageFormat(messageString); // Object[] args = new Object[1]; // args[0] = arg0; // return mf.format(args); // } // // }
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.ExceptionMessage;
/* * #%L * agent-messaging * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.messaging.impl; /** * Basic implementation of the msgBox directory. * * Manages msgBox and Groups. Theoretically this implementation is thread safe. * * @author lemouzy * @param <T> * the generic type */ public class BasicMutableDirectory<T> implements IMutableDirectory<T> { /** The agent directory. */ private final Map<String, AgentMsgBox<T>> agentDirectory; /** The group directory. */ private final Map<String, GroupMsgBox<T>> groupDirectory; /** The group modification lock. */ private final ReentrantLock groupModificationLock; /** The agent modification lock. */ private final ReentrantLock agentModificationLock; /** The broad cast msg box. */ private final GroupMsgBox<T> broadCastMsgBox; /** * Name of the group that will contain all the agents (used for broadcast). */ public static final String ALL = "all"; /** * Instantiates a new basic mutable directory. */ public BasicMutableDirectory() { super(); this.agentDirectory = new ConcurrentHashMap<String, AgentMsgBox<T>>(); this.groupDirectory = new ConcurrentHashMap<String, GroupMsgBox<T>>(); this.groupModificationLock = new ReentrantLock(); this.agentModificationLock = new ReentrantLock(); this.broadCastMsgBox = this.getOrCreateGroupMsgBox(ALL); } // /////////////////////////////////////////////////////////////////////////////// // Agent - Group Creation / Deletion // /////////////////////////////////////////////////////////////////////////////// /* * (non-Javadoc) * * @see * fr.irit.smac.libs.tooling.messaging.impl.IMutableDirectory#createAgentMsgBox * (java.lang.String) */ @Override public IMsgBox<T> createAgentMsgBox(String agentId) { AgentMsgBox<T> agentRef; this.agentModificationLock.lock(); if (!this.agentDirectory.containsKey(agentId)) { agentRef = new AgentMsgBox<T>(agentId, this); this.subscribeAgentToGroup(agentRef, broadCastMsgBox); this.agentDirectory.put(agentId, agentRef); } else { this.agentModificationLock.unlock();
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/ExceptionMessage.java // public class ExceptionMessage { // // /** The Constant UNKNOWN_GROUP_UNSUBSCRIBE. */ // public static final String UNKNOWN_GROUP_UNSUBSCRIBE = "Trying to unsubscribe an agent from an unknown group : {0}"; // // /** The Constant UNKNOWN_GROUP_SUBSCRIBE. */ // public static final String UNKNOWN_GROUP_SUBSCRIBE = "Trying to subscribe an agent from an unknown group : {0}"; // // /** The Constant UNKNOWN_RECEIVER_SEND. */ // public static final String UNKNOWN_RECEIVER_SEND = "Trying to send a message to an unknown receiver : {0}"; // // /** The Constant UNKNOWN_GROUP_SEND. */ // public static final String UNKNOWN_GROUP_SEND = "Trying to send a message to an unknown group : {0}"; // // /** The Constant GET_MESSAGES_DISPOSED_MSG_BOX. */ // public static final String GET_MESSAGES_DISPOSED_MSG_BOX = "Trying to receive messages from a disposed message box."; // // /** The Constant AGENT_ALREADY_ASSOCIATED_MSG_BOX. */ // public static final String AGENT_ALREADY_ASSOCIATED_MSG_BOX = "The agent {0} is already associated with a msgBox."; // // /** // * Instantiates a new exception message. // */ // private ExceptionMessage() { // // } // // /** // * Format message. // * // * @param messageString // * the message string // * @param arg0 // * the arg0 // * @return the string // */ // public static String formatMessage(String messageString, Object arg0) { // // MessageFormat mf = new MessageFormat(messageString); // Object[] args = new Object[1]; // args[0] = arg0; // return mf.format(args); // } // // } // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/BasicMutableDirectory.java import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.ExceptionMessage; /* * #%L * agent-messaging * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.messaging.impl; /** * Basic implementation of the msgBox directory. * * Manages msgBox and Groups. Theoretically this implementation is thread safe. * * @author lemouzy * @param <T> * the generic type */ public class BasicMutableDirectory<T> implements IMutableDirectory<T> { /** The agent directory. */ private final Map<String, AgentMsgBox<T>> agentDirectory; /** The group directory. */ private final Map<String, GroupMsgBox<T>> groupDirectory; /** The group modification lock. */ private final ReentrantLock groupModificationLock; /** The agent modification lock. */ private final ReentrantLock agentModificationLock; /** The broad cast msg box. */ private final GroupMsgBox<T> broadCastMsgBox; /** * Name of the group that will contain all the agents (used for broadcast). */ public static final String ALL = "all"; /** * Instantiates a new basic mutable directory. */ public BasicMutableDirectory() { super(); this.agentDirectory = new ConcurrentHashMap<String, AgentMsgBox<T>>(); this.groupDirectory = new ConcurrentHashMap<String, GroupMsgBox<T>>(); this.groupModificationLock = new ReentrantLock(); this.agentModificationLock = new ReentrantLock(); this.broadCastMsgBox = this.getOrCreateGroupMsgBox(ALL); } // /////////////////////////////////////////////////////////////////////////////// // Agent - Group Creation / Deletion // /////////////////////////////////////////////////////////////////////////////// /* * (non-Javadoc) * * @see * fr.irit.smac.libs.tooling.messaging.impl.IMutableDirectory#createAgentMsgBox * (java.lang.String) */ @Override public IMsgBox<T> createAgentMsgBox(String agentId) { AgentMsgBox<T> agentRef; this.agentModificationLock.lock(); if (!this.agentDirectory.containsKey(agentId)) { agentRef = new AgentMsgBox<T>(agentId, this); this.subscribeAgentToGroup(agentRef, broadCastMsgBox); this.agentDirectory.put(agentId, agentRef); } else { this.agentModificationLock.unlock();
throw new IllegalArgumentException(ExceptionMessage.formatMessage(
IRIT-SMAC/agent-tooling
agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/example/network/Client.java
// Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/AgentPlot.java // public class AgentPlot { // // /** // * If no name is given for the server, this one will be used // */ // private static IAgentPlotServer defaultServer; // // /** // * Server's map linking name and server // */ // private static Map<String, IAgentPlotServer> servers = new TreeMap<String, IAgentPlotServer>(); // // private AgentPlot() { // // } // // /** // * Create a new server which will be accessible through network with the // * port _port // * // * @param port // */ // public static void createServer(int port) { // defaultServer = new AgentPlotServer("default", port); // } // // /** // * Create a new server with the name _name and which will be accessible // * through network with the port _port. The name is only used in the // * server's side // * // * @param name // * @param port // */ // public static void createServer(String name, int port) { // servers.put(name, new AgentPlotServer(name, port)); // } // // /** // * Get default server if any. Otherwise create it. // * // * @return // */ // public static IAgentPlotServer getServer() { // if (defaultServer == null) // defaultServer = new AgentPlotServer("default"); // return defaultServer; // } // // /** // * Get server with the given name if it exists. Otherwise create a // * connection to it. // * // * @param name // * @return // */ // public static IAgentPlotServer getServer(String name) { // if (!servers.containsKey(name)) { // servers.put(name, new AgentPlotServer(name)); // } // return servers.get(name); // } // // /** // * Get the chart with the given name if any. Otherwise, create it. // * // * @param name // * @return // */ // public static IAgentPlotChart getChart(String name) { // return getServer().getChart(name); // } // // /** // * Get the chart _name located on the server _serverName if any. Otherwise, // * create it. // * // * @param name // * @param serverName // * @return // */ // public static IAgentPlotChart getChart(String name, String serverName) { // return getServer(serverName).getChart(name); // } // // /** // * Configure the connection to a server and set a local name. The name _name // * will be then used with the method getServer(String _name). // * // * @param name // * @param host // * @param port // */ // public static void configServer(String name, String host, int port) { // servers.put(name, new AgentPlotDistantServer(host, port)); // } // // /** // * Configure the connection with the default server. // * // * @param host // * @param port // */ // public static void configServer(String host, int port) { // defaultServer = new AgentPlotDistantServer(host, port); // } // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/commons/EChartType.java // public enum EChartType { // PLOT, LINE // }
import fr.irit.smac.libs.tooling.plot.commons.EChartType; import fr.irit.smac.libs.tooling.plot.AgentPlot;
/* * #%L * agent-plot * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.plot.example.network; /** * Example showing the distant connection to the server. * * @author Alexandre Perles * */ public class Client { private Client() { } public static void main(String[] args) { // Server's configuration
// Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/AgentPlot.java // public class AgentPlot { // // /** // * If no name is given for the server, this one will be used // */ // private static IAgentPlotServer defaultServer; // // /** // * Server's map linking name and server // */ // private static Map<String, IAgentPlotServer> servers = new TreeMap<String, IAgentPlotServer>(); // // private AgentPlot() { // // } // // /** // * Create a new server which will be accessible through network with the // * port _port // * // * @param port // */ // public static void createServer(int port) { // defaultServer = new AgentPlotServer("default", port); // } // // /** // * Create a new server with the name _name and which will be accessible // * through network with the port _port. The name is only used in the // * server's side // * // * @param name // * @param port // */ // public static void createServer(String name, int port) { // servers.put(name, new AgentPlotServer(name, port)); // } // // /** // * Get default server if any. Otherwise create it. // * // * @return // */ // public static IAgentPlotServer getServer() { // if (defaultServer == null) // defaultServer = new AgentPlotServer("default"); // return defaultServer; // } // // /** // * Get server with the given name if it exists. Otherwise create a // * connection to it. // * // * @param name // * @return // */ // public static IAgentPlotServer getServer(String name) { // if (!servers.containsKey(name)) { // servers.put(name, new AgentPlotServer(name)); // } // return servers.get(name); // } // // /** // * Get the chart with the given name if any. Otherwise, create it. // * // * @param name // * @return // */ // public static IAgentPlotChart getChart(String name) { // return getServer().getChart(name); // } // // /** // * Get the chart _name located on the server _serverName if any. Otherwise, // * create it. // * // * @param name // * @param serverName // * @return // */ // public static IAgentPlotChart getChart(String name, String serverName) { // return getServer(serverName).getChart(name); // } // // /** // * Configure the connection to a server and set a local name. The name _name // * will be then used with the method getServer(String _name). // * // * @param name // * @param host // * @param port // */ // public static void configServer(String name, String host, int port) { // servers.put(name, new AgentPlotDistantServer(host, port)); // } // // /** // * Configure the connection with the default server. // * // * @param host // * @param port // */ // public static void configServer(String host, int port) { // defaultServer = new AgentPlotDistantServer(host, port); // } // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/commons/EChartType.java // public enum EChartType { // PLOT, LINE // } // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/example/network/Client.java import fr.irit.smac.libs.tooling.plot.commons.EChartType; import fr.irit.smac.libs.tooling.plot.AgentPlot; /* * #%L * agent-plot * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.plot.example.network; /** * Example showing the distant connection to the server. * * @author Alexandre Perles * */ public class Client { private Client() { } public static void main(String[] args) { // Server's configuration
AgentPlot.configServer("My server", "localhost", 6090);
IRIT-SMAC/agent-tooling
agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/example/network/Client.java
// Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/AgentPlot.java // public class AgentPlot { // // /** // * If no name is given for the server, this one will be used // */ // private static IAgentPlotServer defaultServer; // // /** // * Server's map linking name and server // */ // private static Map<String, IAgentPlotServer> servers = new TreeMap<String, IAgentPlotServer>(); // // private AgentPlot() { // // } // // /** // * Create a new server which will be accessible through network with the // * port _port // * // * @param port // */ // public static void createServer(int port) { // defaultServer = new AgentPlotServer("default", port); // } // // /** // * Create a new server with the name _name and which will be accessible // * through network with the port _port. The name is only used in the // * server's side // * // * @param name // * @param port // */ // public static void createServer(String name, int port) { // servers.put(name, new AgentPlotServer(name, port)); // } // // /** // * Get default server if any. Otherwise create it. // * // * @return // */ // public static IAgentPlotServer getServer() { // if (defaultServer == null) // defaultServer = new AgentPlotServer("default"); // return defaultServer; // } // // /** // * Get server with the given name if it exists. Otherwise create a // * connection to it. // * // * @param name // * @return // */ // public static IAgentPlotServer getServer(String name) { // if (!servers.containsKey(name)) { // servers.put(name, new AgentPlotServer(name)); // } // return servers.get(name); // } // // /** // * Get the chart with the given name if any. Otherwise, create it. // * // * @param name // * @return // */ // public static IAgentPlotChart getChart(String name) { // return getServer().getChart(name); // } // // /** // * Get the chart _name located on the server _serverName if any. Otherwise, // * create it. // * // * @param name // * @param serverName // * @return // */ // public static IAgentPlotChart getChart(String name, String serverName) { // return getServer(serverName).getChart(name); // } // // /** // * Configure the connection to a server and set a local name. The name _name // * will be then used with the method getServer(String _name). // * // * @param name // * @param host // * @param port // */ // public static void configServer(String name, String host, int port) { // servers.put(name, new AgentPlotDistantServer(host, port)); // } // // /** // * Configure the connection with the default server. // * // * @param host // * @param port // */ // public static void configServer(String host, int port) { // defaultServer = new AgentPlotDistantServer(host, port); // } // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/commons/EChartType.java // public enum EChartType { // PLOT, LINE // }
import fr.irit.smac.libs.tooling.plot.commons.EChartType; import fr.irit.smac.libs.tooling.plot.AgentPlot;
/* * #%L * agent-plot * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.plot.example.network; /** * Example showing the distant connection to the server. * * @author Alexandre Perles * */ public class Client { private Client() { } public static void main(String[] args) { // Server's configuration AgentPlot.configServer("My server", "localhost", 6090); // Create "My chart" on "My server" and plot two points AgentPlot.getServer("My server").getChart("My chart").add(1, 2); AgentPlot.getServer("My server").getChart("My chart").add(2, 3); // Plot two points in serie "My serie" AgentPlot.getServer("My server").getChart("My chart").add("My serie", 3, 2.5); AgentPlot.getServer("My server").getChart("My chart").add("My serie", 5, 2); // Preconfigure chart by setting name and type AgentPlot.getServer("My server").configChart("My chart 2",
// Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/AgentPlot.java // public class AgentPlot { // // /** // * If no name is given for the server, this one will be used // */ // private static IAgentPlotServer defaultServer; // // /** // * Server's map linking name and server // */ // private static Map<String, IAgentPlotServer> servers = new TreeMap<String, IAgentPlotServer>(); // // private AgentPlot() { // // } // // /** // * Create a new server which will be accessible through network with the // * port _port // * // * @param port // */ // public static void createServer(int port) { // defaultServer = new AgentPlotServer("default", port); // } // // /** // * Create a new server with the name _name and which will be accessible // * through network with the port _port. The name is only used in the // * server's side // * // * @param name // * @param port // */ // public static void createServer(String name, int port) { // servers.put(name, new AgentPlotServer(name, port)); // } // // /** // * Get default server if any. Otherwise create it. // * // * @return // */ // public static IAgentPlotServer getServer() { // if (defaultServer == null) // defaultServer = new AgentPlotServer("default"); // return defaultServer; // } // // /** // * Get server with the given name if it exists. Otherwise create a // * connection to it. // * // * @param name // * @return // */ // public static IAgentPlotServer getServer(String name) { // if (!servers.containsKey(name)) { // servers.put(name, new AgentPlotServer(name)); // } // return servers.get(name); // } // // /** // * Get the chart with the given name if any. Otherwise, create it. // * // * @param name // * @return // */ // public static IAgentPlotChart getChart(String name) { // return getServer().getChart(name); // } // // /** // * Get the chart _name located on the server _serverName if any. Otherwise, // * create it. // * // * @param name // * @param serverName // * @return // */ // public static IAgentPlotChart getChart(String name, String serverName) { // return getServer(serverName).getChart(name); // } // // /** // * Configure the connection to a server and set a local name. The name _name // * will be then used with the method getServer(String _name). // * // * @param name // * @param host // * @param port // */ // public static void configServer(String name, String host, int port) { // servers.put(name, new AgentPlotDistantServer(host, port)); // } // // /** // * Configure the connection with the default server. // * // * @param host // * @param port // */ // public static void configServer(String host, int port) { // defaultServer = new AgentPlotDistantServer(host, port); // } // } // // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/commons/EChartType.java // public enum EChartType { // PLOT, LINE // } // Path: agent-plot/src/main/java/fr/irit/smac/libs/tooling/plot/example/network/Client.java import fr.irit.smac.libs.tooling.plot.commons.EChartType; import fr.irit.smac.libs.tooling.plot.AgentPlot; /* * #%L * agent-plot * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.plot.example.network; /** * Example showing the distant connection to the server. * * @author Alexandre Perles * */ public class Client { private Client() { } public static void main(String[] args) { // Server's configuration AgentPlot.configServer("My server", "localhost", 6090); // Create "My chart" on "My server" and plot two points AgentPlot.getServer("My server").getChart("My chart").add(1, 2); AgentPlot.getServer("My server").getChart("My chart").add(2, 3); // Plot two points in serie "My serie" AgentPlot.getServer("My server").getChart("My chart").add("My serie", 3, 2.5); AgentPlot.getServer("My server").getChart("My chart").add("My serie", 5, 2); // Preconfigure chart by setting name and type AgentPlot.getServer("My server").configChart("My chart 2",
EChartType.PLOT);
IRIT-SMAC/agent-tooling
avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/SoftBoundsAVTFactory.java
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAVT.java // public interface IAVT { // // /** // * Adjusts the value to the direction of the given feedback. // * <ul> // * <li><code>Feedback.GREATER</code>: increments the current value</li> // * <li><code>Feedback.LOWER<code>: decrements the current value</li> // * <li><code>Feedback.GOOD</code>: decreases the criticity of the AVT but // * doesn't change the value. This feedbacks express that the current value // * is good and should evolve more slowly at the next adjustment.</li> // * </ul> // * // * // * @param feedback // */ // public void adjustValue(EFeedback feedback); // // /** // * Current value determied by the AVT. // * // * @return the current value determied by the AVT // */ // public double getValue(); // // /** // * Returns the criticity of the AVT. // * <p> // * Criticity is a value that express the estimated inaccuracy of the current // * value. The criticity is a value between 0 and 1 where : // * </p> // * <ul> // * <li>0 stands for the best accuracy</li> // * <li>1 stands for the worst accuracy</lI> // * </ul> // * // * @return the criticity of this AVT // */ // public double getCriticity(); // // /** // * Returns an advanced interface to control the AVT. // * <p> // * Pay caution, some of the methods of this interface doesn't guarantee the // * AVT state consistency. Generally, you should only uses this interface if // * you have good reasons and you know what you are doing. // * </p> // * // * @return this AVT instance with an advanced interface // */ // public IAdvancedAVT getAdvancedAVT(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAVTFactory.java // public interface IAVTFactory<T extends IAVT> { // // /** // * Creates a new IAVT object. // * // * @param lowerBound the lower bound // * @param upperBound the upper bound // * @param startValue the start value // * @param deltaManagerFactory the delta manager factory // * @return the t // */ // T createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory); // // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/IDeltaManagerFactory.java // public interface IDeltaManagerFactory<T extends IDeltaManager> { // // /** // * Instanciate a DeltaManager that will be used for the given AVT. // * // * @param range the range // * @return the t // */ // T createInstance(IRange range); // // }
import fr.irit.smac.libs.tooling.avt.IAVTFactory; import fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory; import fr.irit.smac.libs.tooling.avt.IAVT;
/* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.impl; /** * A factory for creating SoftBoundsAVT objects. */ public class SoftBoundsAVTFactory implements IAVTFactory<IAVT> { /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) */ @Override public IAVT createInstance(double lowerBound, double upperBound, double startValue,
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAVT.java // public interface IAVT { // // /** // * Adjusts the value to the direction of the given feedback. // * <ul> // * <li><code>Feedback.GREATER</code>: increments the current value</li> // * <li><code>Feedback.LOWER<code>: decrements the current value</li> // * <li><code>Feedback.GOOD</code>: decreases the criticity of the AVT but // * doesn't change the value. This feedbacks express that the current value // * is good and should evolve more slowly at the next adjustment.</li> // * </ul> // * // * // * @param feedback // */ // public void adjustValue(EFeedback feedback); // // /** // * Current value determied by the AVT. // * // * @return the current value determied by the AVT // */ // public double getValue(); // // /** // * Returns the criticity of the AVT. // * <p> // * Criticity is a value that express the estimated inaccuracy of the current // * value. The criticity is a value between 0 and 1 where : // * </p> // * <ul> // * <li>0 stands for the best accuracy</li> // * <li>1 stands for the worst accuracy</lI> // * </ul> // * // * @return the criticity of this AVT // */ // public double getCriticity(); // // /** // * Returns an advanced interface to control the AVT. // * <p> // * Pay caution, some of the methods of this interface doesn't guarantee the // * AVT state consistency. Generally, you should only uses this interface if // * you have good reasons and you know what you are doing. // * </p> // * // * @return this AVT instance with an advanced interface // */ // public IAdvancedAVT getAdvancedAVT(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAVTFactory.java // public interface IAVTFactory<T extends IAVT> { // // /** // * Creates a new IAVT object. // * // * @param lowerBound the lower bound // * @param upperBound the upper bound // * @param startValue the start value // * @param deltaManagerFactory the delta manager factory // * @return the t // */ // T createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory); // // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/IDeltaManagerFactory.java // public interface IDeltaManagerFactory<T extends IDeltaManager> { // // /** // * Instanciate a DeltaManager that will be used for the given AVT. // * // * @param range the range // * @return the t // */ // T createInstance(IRange range); // // } // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/SoftBoundsAVTFactory.java import fr.irit.smac.libs.tooling.avt.IAVTFactory; import fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory; import fr.irit.smac.libs.tooling.avt.IAVT; /* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.impl; /** * A factory for creating SoftBoundsAVT objects. */ public class SoftBoundsAVTFactory implements IAVTFactory<IAVT> { /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) */ @Override public IAVT createInstance(double lowerBound, double upperBound, double startValue,
IDeltaManagerFactory<?> deltaManagerFactory) {
IRIT-SMAC/agent-tooling
avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/StandardAVTFactory.java
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAVT.java // public interface IAVT { // // /** // * Adjusts the value to the direction of the given feedback. // * <ul> // * <li><code>Feedback.GREATER</code>: increments the current value</li> // * <li><code>Feedback.LOWER<code>: decrements the current value</li> // * <li><code>Feedback.GOOD</code>: decreases the criticity of the AVT but // * doesn't change the value. This feedbacks express that the current value // * is good and should evolve more slowly at the next adjustment.</li> // * </ul> // * // * // * @param feedback // */ // public void adjustValue(EFeedback feedback); // // /** // * Current value determied by the AVT. // * // * @return the current value determied by the AVT // */ // public double getValue(); // // /** // * Returns the criticity of the AVT. // * <p> // * Criticity is a value that express the estimated inaccuracy of the current // * value. The criticity is a value between 0 and 1 where : // * </p> // * <ul> // * <li>0 stands for the best accuracy</li> // * <li>1 stands for the worst accuracy</lI> // * </ul> // * // * @return the criticity of this AVT // */ // public double getCriticity(); // // /** // * Returns an advanced interface to control the AVT. // * <p> // * Pay caution, some of the methods of this interface doesn't guarantee the // * AVT state consistency. Generally, you should only uses this interface if // * you have good reasons and you know what you are doing. // * </p> // * // * @return this AVT instance with an advanced interface // */ // public IAdvancedAVT getAdvancedAVT(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAVTFactory.java // public interface IAVTFactory<T extends IAVT> { // // /** // * Creates a new IAVT object. // * // * @param lowerBound the lower bound // * @param upperBound the upper bound // * @param startValue the start value // * @param deltaManagerFactory the delta manager factory // * @return the t // */ // T createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory); // // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/IDeltaManagerFactory.java // public interface IDeltaManagerFactory<T extends IDeltaManager> { // // /** // * Instanciate a DeltaManager that will be used for the given AVT. // * // * @param range the range // * @return the t // */ // T createInstance(IRange range); // // }
import fr.irit.smac.libs.tooling.avt.IAVTFactory; import fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory; import fr.irit.smac.libs.tooling.avt.IAVT;
/* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.impl; /** * A factory for creating StandardAVT objects. */ public class StandardAVTFactory implements IAVTFactory<IAVT> { /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) */ @Override public IAVT createInstance(double lowerBound, double upperBound, double startValue,
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAVT.java // public interface IAVT { // // /** // * Adjusts the value to the direction of the given feedback. // * <ul> // * <li><code>Feedback.GREATER</code>: increments the current value</li> // * <li><code>Feedback.LOWER<code>: decrements the current value</li> // * <li><code>Feedback.GOOD</code>: decreases the criticity of the AVT but // * doesn't change the value. This feedbacks express that the current value // * is good and should evolve more slowly at the next adjustment.</li> // * </ul> // * // * // * @param feedback // */ // public void adjustValue(EFeedback feedback); // // /** // * Current value determied by the AVT. // * // * @return the current value determied by the AVT // */ // public double getValue(); // // /** // * Returns the criticity of the AVT. // * <p> // * Criticity is a value that express the estimated inaccuracy of the current // * value. The criticity is a value between 0 and 1 where : // * </p> // * <ul> // * <li>0 stands for the best accuracy</li> // * <li>1 stands for the worst accuracy</lI> // * </ul> // * // * @return the criticity of this AVT // */ // public double getCriticity(); // // /** // * Returns an advanced interface to control the AVT. // * <p> // * Pay caution, some of the methods of this interface doesn't guarantee the // * AVT state consistency. Generally, you should only uses this interface if // * you have good reasons and you know what you are doing. // * </p> // * // * @return this AVT instance with an advanced interface // */ // public IAdvancedAVT getAdvancedAVT(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAVTFactory.java // public interface IAVTFactory<T extends IAVT> { // // /** // * Creates a new IAVT object. // * // * @param lowerBound the lower bound // * @param upperBound the upper bound // * @param startValue the start value // * @param deltaManagerFactory the delta manager factory // * @return the t // */ // T createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory); // // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/IDeltaManagerFactory.java // public interface IDeltaManagerFactory<T extends IDeltaManager> { // // /** // * Instanciate a DeltaManager that will be used for the given AVT. // * // * @param range the range // * @return the t // */ // T createInstance(IRange range); // // } // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/StandardAVTFactory.java import fr.irit.smac.libs.tooling.avt.IAVTFactory; import fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory; import fr.irit.smac.libs.tooling.avt.IAVT; /* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.impl; /** * A factory for creating StandardAVT objects. */ public class StandardAVTFactory implements IAVTFactory<IAVT> { /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) */ @Override public IAVT createInstance(double lowerBound, double upperBound, double startValue,
IDeltaManagerFactory<?> deltaManagerFactory) {
IRIT-SMAC/agent-tooling
avt/src/main/java/fr/irit/smac/libs/tooling/avt/example/SearchValueExample.java
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAVT.java // public interface IAVT { // // /** // * Adjusts the value to the direction of the given feedback. // * <ul> // * <li><code>Feedback.GREATER</code>: increments the current value</li> // * <li><code>Feedback.LOWER<code>: decrements the current value</li> // * <li><code>Feedback.GOOD</code>: decreases the criticity of the AVT but // * doesn't change the value. This feedbacks express that the current value // * is good and should evolve more slowly at the next adjustment.</li> // * </ul> // * // * // * @param feedback // */ // public void adjustValue(EFeedback feedback); // // /** // * Current value determied by the AVT. // * // * @return the current value determied by the AVT // */ // public double getValue(); // // /** // * Returns the criticity of the AVT. // * <p> // * Criticity is a value that express the estimated inaccuracy of the current // * value. The criticity is a value between 0 and 1 where : // * </p> // * <ul> // * <li>0 stands for the best accuracy</li> // * <li>1 stands for the worst accuracy</lI> // * </ul> // * // * @return the criticity of this AVT // */ // public double getCriticity(); // // /** // * Returns an advanced interface to control the AVT. // * <p> // * Pay caution, some of the methods of this interface doesn't guarantee the // * AVT state consistency. Generally, you should only uses this interface if // * you have good reasons and you know what you are doing. // * </p> // * // * @return this AVT instance with an advanced interface // */ // public IAdvancedAVT getAdvancedAVT(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/AVTBuilder.java // public class AVTBuilder extends AbstractAVTBuilder<IAVT> { // // /* // * (non-Javadoc) // * // * @see fr.irit.smac.util.avt.IAVTBuilder#build() // */ // @Override // public IAVT build() { // // if (this.avtFactory == null) { // // if (!this.isHardBounds) { // if (this.softBoundsMemory > 0) { // this.avtFactory = new SoftBoundsMemoryAVTFactory(this.softBoundsMemory); // } // else { // this.avtFactory = new SoftBoundsAVTFactory(); // } // } // else { // this.avtFactory = new StandardAVTFactory(); // } // } // // return super.build(); // } // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/EFeedback.java // public enum EFeedback { // GREATER { // @Override // public String toString() { // return "+"; // } // }, // LOWER { // @Override // public String toString() { // return "-"; // } // }, // GOOD { // @Override // public String toString() { // return "g"; // } // } // }
import fr.irit.smac.libs.tooling.avt.AVTBuilder; import fr.irit.smac.libs.tooling.avt.EFeedback; import fr.irit.smac.libs.tooling.avt.IAVT;
/* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.example; public class SearchValueExample { private SearchValueExample() { } public static void main(String[] args) { double searchedValue = 9.208; double minValue = 0; double maxValue = 10; double precision = .001; int nbCycles = 0;
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAVT.java // public interface IAVT { // // /** // * Adjusts the value to the direction of the given feedback. // * <ul> // * <li><code>Feedback.GREATER</code>: increments the current value</li> // * <li><code>Feedback.LOWER<code>: decrements the current value</li> // * <li><code>Feedback.GOOD</code>: decreases the criticity of the AVT but // * doesn't change the value. This feedbacks express that the current value // * is good and should evolve more slowly at the next adjustment.</li> // * </ul> // * // * // * @param feedback // */ // public void adjustValue(EFeedback feedback); // // /** // * Current value determied by the AVT. // * // * @return the current value determied by the AVT // */ // public double getValue(); // // /** // * Returns the criticity of the AVT. // * <p> // * Criticity is a value that express the estimated inaccuracy of the current // * value. The criticity is a value between 0 and 1 where : // * </p> // * <ul> // * <li>0 stands for the best accuracy</li> // * <li>1 stands for the worst accuracy</lI> // * </ul> // * // * @return the criticity of this AVT // */ // public double getCriticity(); // // /** // * Returns an advanced interface to control the AVT. // * <p> // * Pay caution, some of the methods of this interface doesn't guarantee the // * AVT state consistency. Generally, you should only uses this interface if // * you have good reasons and you know what you are doing. // * </p> // * // * @return this AVT instance with an advanced interface // */ // public IAdvancedAVT getAdvancedAVT(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/AVTBuilder.java // public class AVTBuilder extends AbstractAVTBuilder<IAVT> { // // /* // * (non-Javadoc) // * // * @see fr.irit.smac.util.avt.IAVTBuilder#build() // */ // @Override // public IAVT build() { // // if (this.avtFactory == null) { // // if (!this.isHardBounds) { // if (this.softBoundsMemory > 0) { // this.avtFactory = new SoftBoundsMemoryAVTFactory(this.softBoundsMemory); // } // else { // this.avtFactory = new SoftBoundsAVTFactory(); // } // } // else { // this.avtFactory = new StandardAVTFactory(); // } // } // // return super.build(); // } // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/EFeedback.java // public enum EFeedback { // GREATER { // @Override // public String toString() { // return "+"; // } // }, // LOWER { // @Override // public String toString() { // return "-"; // } // }, // GOOD { // @Override // public String toString() { // return "g"; // } // } // } // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/example/SearchValueExample.java import fr.irit.smac.libs.tooling.avt.AVTBuilder; import fr.irit.smac.libs.tooling.avt.EFeedback; import fr.irit.smac.libs.tooling.avt.IAVT; /* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.example; public class SearchValueExample { private SearchValueExample() { } public static void main(String[] args) { double searchedValue = 9.208; double minValue = 0; double maxValue = 10; double precision = .001; int nbCycles = 0;
IAVT avt = new AVTBuilder().lowerBound(minValue).upperBound(maxValue).deltaMin(precision).deltaDecreaseDelay(1)
IRIT-SMAC/agent-tooling
avt/src/main/java/fr/irit/smac/libs/tooling/avt/example/SearchValueExample.java
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAVT.java // public interface IAVT { // // /** // * Adjusts the value to the direction of the given feedback. // * <ul> // * <li><code>Feedback.GREATER</code>: increments the current value</li> // * <li><code>Feedback.LOWER<code>: decrements the current value</li> // * <li><code>Feedback.GOOD</code>: decreases the criticity of the AVT but // * doesn't change the value. This feedbacks express that the current value // * is good and should evolve more slowly at the next adjustment.</li> // * </ul> // * // * // * @param feedback // */ // public void adjustValue(EFeedback feedback); // // /** // * Current value determied by the AVT. // * // * @return the current value determied by the AVT // */ // public double getValue(); // // /** // * Returns the criticity of the AVT. // * <p> // * Criticity is a value that express the estimated inaccuracy of the current // * value. The criticity is a value between 0 and 1 where : // * </p> // * <ul> // * <li>0 stands for the best accuracy</li> // * <li>1 stands for the worst accuracy</lI> // * </ul> // * // * @return the criticity of this AVT // */ // public double getCriticity(); // // /** // * Returns an advanced interface to control the AVT. // * <p> // * Pay caution, some of the methods of this interface doesn't guarantee the // * AVT state consistency. Generally, you should only uses this interface if // * you have good reasons and you know what you are doing. // * </p> // * // * @return this AVT instance with an advanced interface // */ // public IAdvancedAVT getAdvancedAVT(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/AVTBuilder.java // public class AVTBuilder extends AbstractAVTBuilder<IAVT> { // // /* // * (non-Javadoc) // * // * @see fr.irit.smac.util.avt.IAVTBuilder#build() // */ // @Override // public IAVT build() { // // if (this.avtFactory == null) { // // if (!this.isHardBounds) { // if (this.softBoundsMemory > 0) { // this.avtFactory = new SoftBoundsMemoryAVTFactory(this.softBoundsMemory); // } // else { // this.avtFactory = new SoftBoundsAVTFactory(); // } // } // else { // this.avtFactory = new StandardAVTFactory(); // } // } // // return super.build(); // } // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/EFeedback.java // public enum EFeedback { // GREATER { // @Override // public String toString() { // return "+"; // } // }, // LOWER { // @Override // public String toString() { // return "-"; // } // }, // GOOD { // @Override // public String toString() { // return "g"; // } // } // }
import fr.irit.smac.libs.tooling.avt.AVTBuilder; import fr.irit.smac.libs.tooling.avt.EFeedback; import fr.irit.smac.libs.tooling.avt.IAVT;
/* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.example; public class SearchValueExample { private SearchValueExample() { } public static void main(String[] args) { double searchedValue = 9.208; double minValue = 0; double maxValue = 10; double precision = .001; int nbCycles = 0;
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAVT.java // public interface IAVT { // // /** // * Adjusts the value to the direction of the given feedback. // * <ul> // * <li><code>Feedback.GREATER</code>: increments the current value</li> // * <li><code>Feedback.LOWER<code>: decrements the current value</li> // * <li><code>Feedback.GOOD</code>: decreases the criticity of the AVT but // * doesn't change the value. This feedbacks express that the current value // * is good and should evolve more slowly at the next adjustment.</li> // * </ul> // * // * // * @param feedback // */ // public void adjustValue(EFeedback feedback); // // /** // * Current value determied by the AVT. // * // * @return the current value determied by the AVT // */ // public double getValue(); // // /** // * Returns the criticity of the AVT. // * <p> // * Criticity is a value that express the estimated inaccuracy of the current // * value. The criticity is a value between 0 and 1 where : // * </p> // * <ul> // * <li>0 stands for the best accuracy</li> // * <li>1 stands for the worst accuracy</lI> // * </ul> // * // * @return the criticity of this AVT // */ // public double getCriticity(); // // /** // * Returns an advanced interface to control the AVT. // * <p> // * Pay caution, some of the methods of this interface doesn't guarantee the // * AVT state consistency. Generally, you should only uses this interface if // * you have good reasons and you know what you are doing. // * </p> // * // * @return this AVT instance with an advanced interface // */ // public IAdvancedAVT getAdvancedAVT(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/AVTBuilder.java // public class AVTBuilder extends AbstractAVTBuilder<IAVT> { // // /* // * (non-Javadoc) // * // * @see fr.irit.smac.util.avt.IAVTBuilder#build() // */ // @Override // public IAVT build() { // // if (this.avtFactory == null) { // // if (!this.isHardBounds) { // if (this.softBoundsMemory > 0) { // this.avtFactory = new SoftBoundsMemoryAVTFactory(this.softBoundsMemory); // } // else { // this.avtFactory = new SoftBoundsAVTFactory(); // } // } // else { // this.avtFactory = new StandardAVTFactory(); // } // } // // return super.build(); // } // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/EFeedback.java // public enum EFeedback { // GREATER { // @Override // public String toString() { // return "+"; // } // }, // LOWER { // @Override // public String toString() { // return "-"; // } // }, // GOOD { // @Override // public String toString() { // return "g"; // } // } // } // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/example/SearchValueExample.java import fr.irit.smac.libs.tooling.avt.AVTBuilder; import fr.irit.smac.libs.tooling.avt.EFeedback; import fr.irit.smac.libs.tooling.avt.IAVT; /* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.example; public class SearchValueExample { private SearchValueExample() { } public static void main(String[] args) { double searchedValue = 9.208; double minValue = 0; double maxValue = 10; double precision = .001; int nbCycles = 0;
IAVT avt = new AVTBuilder().lowerBound(minValue).upperBound(maxValue).deltaMin(precision).deltaDecreaseDelay(1)
IRIT-SMAC/agent-tooling
avt/src/main/java/fr/irit/smac/libs/tooling/avt/example/SearchValueExample.java
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAVT.java // public interface IAVT { // // /** // * Adjusts the value to the direction of the given feedback. // * <ul> // * <li><code>Feedback.GREATER</code>: increments the current value</li> // * <li><code>Feedback.LOWER<code>: decrements the current value</li> // * <li><code>Feedback.GOOD</code>: decreases the criticity of the AVT but // * doesn't change the value. This feedbacks express that the current value // * is good and should evolve more slowly at the next adjustment.</li> // * </ul> // * // * // * @param feedback // */ // public void adjustValue(EFeedback feedback); // // /** // * Current value determied by the AVT. // * // * @return the current value determied by the AVT // */ // public double getValue(); // // /** // * Returns the criticity of the AVT. // * <p> // * Criticity is a value that express the estimated inaccuracy of the current // * value. The criticity is a value between 0 and 1 where : // * </p> // * <ul> // * <li>0 stands for the best accuracy</li> // * <li>1 stands for the worst accuracy</lI> // * </ul> // * // * @return the criticity of this AVT // */ // public double getCriticity(); // // /** // * Returns an advanced interface to control the AVT. // * <p> // * Pay caution, some of the methods of this interface doesn't guarantee the // * AVT state consistency. Generally, you should only uses this interface if // * you have good reasons and you know what you are doing. // * </p> // * // * @return this AVT instance with an advanced interface // */ // public IAdvancedAVT getAdvancedAVT(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/AVTBuilder.java // public class AVTBuilder extends AbstractAVTBuilder<IAVT> { // // /* // * (non-Javadoc) // * // * @see fr.irit.smac.util.avt.IAVTBuilder#build() // */ // @Override // public IAVT build() { // // if (this.avtFactory == null) { // // if (!this.isHardBounds) { // if (this.softBoundsMemory > 0) { // this.avtFactory = new SoftBoundsMemoryAVTFactory(this.softBoundsMemory); // } // else { // this.avtFactory = new SoftBoundsAVTFactory(); // } // } // else { // this.avtFactory = new StandardAVTFactory(); // } // } // // return super.build(); // } // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/EFeedback.java // public enum EFeedback { // GREATER { // @Override // public String toString() { // return "+"; // } // }, // LOWER { // @Override // public String toString() { // return "-"; // } // }, // GOOD { // @Override // public String toString() { // return "g"; // } // } // }
import fr.irit.smac.libs.tooling.avt.AVTBuilder; import fr.irit.smac.libs.tooling.avt.EFeedback; import fr.irit.smac.libs.tooling.avt.IAVT;
/* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.example; public class SearchValueExample { private SearchValueExample() { } public static void main(String[] args) { double searchedValue = 9.208; double minValue = 0; double maxValue = 10; double precision = .001; int nbCycles = 0; IAVT avt = new AVTBuilder().lowerBound(minValue).upperBound(maxValue).deltaMin(precision).deltaDecreaseDelay(1) .deltaIncreaseDelay(1).startValue(1.).build(); while (Math.abs(avt.getValue() - searchedValue) > precision) { System.out.println("============================"); System.out.println("Cycle number " + ++nbCycles); System.out.println("DeltaValue = " + avt.getAdvancedAVT().getDeltaManager().getDelta()); System.out.println("CurrentValue = " + avt.getValue()); if (avt.getValue() < searchedValue) {
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAVT.java // public interface IAVT { // // /** // * Adjusts the value to the direction of the given feedback. // * <ul> // * <li><code>Feedback.GREATER</code>: increments the current value</li> // * <li><code>Feedback.LOWER<code>: decrements the current value</li> // * <li><code>Feedback.GOOD</code>: decreases the criticity of the AVT but // * doesn't change the value. This feedbacks express that the current value // * is good and should evolve more slowly at the next adjustment.</li> // * </ul> // * // * // * @param feedback // */ // public void adjustValue(EFeedback feedback); // // /** // * Current value determied by the AVT. // * // * @return the current value determied by the AVT // */ // public double getValue(); // // /** // * Returns the criticity of the AVT. // * <p> // * Criticity is a value that express the estimated inaccuracy of the current // * value. The criticity is a value between 0 and 1 where : // * </p> // * <ul> // * <li>0 stands for the best accuracy</li> // * <li>1 stands for the worst accuracy</lI> // * </ul> // * // * @return the criticity of this AVT // */ // public double getCriticity(); // // /** // * Returns an advanced interface to control the AVT. // * <p> // * Pay caution, some of the methods of this interface doesn't guarantee the // * AVT state consistency. Generally, you should only uses this interface if // * you have good reasons and you know what you are doing. // * </p> // * // * @return this AVT instance with an advanced interface // */ // public IAdvancedAVT getAdvancedAVT(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/AVTBuilder.java // public class AVTBuilder extends AbstractAVTBuilder<IAVT> { // // /* // * (non-Javadoc) // * // * @see fr.irit.smac.util.avt.IAVTBuilder#build() // */ // @Override // public IAVT build() { // // if (this.avtFactory == null) { // // if (!this.isHardBounds) { // if (this.softBoundsMemory > 0) { // this.avtFactory = new SoftBoundsMemoryAVTFactory(this.softBoundsMemory); // } // else { // this.avtFactory = new SoftBoundsAVTFactory(); // } // } // else { // this.avtFactory = new StandardAVTFactory(); // } // } // // return super.build(); // } // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/EFeedback.java // public enum EFeedback { // GREATER { // @Override // public String toString() { // return "+"; // } // }, // LOWER { // @Override // public String toString() { // return "-"; // } // }, // GOOD { // @Override // public String toString() { // return "g"; // } // } // } // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/example/SearchValueExample.java import fr.irit.smac.libs.tooling.avt.AVTBuilder; import fr.irit.smac.libs.tooling.avt.EFeedback; import fr.irit.smac.libs.tooling.avt.IAVT; /* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.example; public class SearchValueExample { private SearchValueExample() { } public static void main(String[] args) { double searchedValue = 9.208; double minValue = 0; double maxValue = 10; double precision = .001; int nbCycles = 0; IAVT avt = new AVTBuilder().lowerBound(minValue).upperBound(maxValue).deltaMin(precision).deltaDecreaseDelay(1) .deltaIncreaseDelay(1).startValue(1.).build(); while (Math.abs(avt.getValue() - searchedValue) > precision) { System.out.println("============================"); System.out.println("Cycle number " + ++nbCycles); System.out.println("DeltaValue = " + avt.getAdvancedAVT().getDeltaManager().getDelta()); System.out.println("CurrentValue = " + avt.getValue()); if (avt.getValue() < searchedValue) {
avt.adjustValue(EFeedback.GREATER);
IRIT-SMAC/agent-tooling
avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/deltaevolution/impl/DeterministicGDEFactory.java
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/deltaevolution/IGeometricDE.java // public interface IGeometricDE extends IDeltaEvolution { // // /** // * Gets the increase factor. // * // * @return the increase factor // */ // public double getIncreaseFactor(); // // /** // * Gets the decrease factor. // * // * @return the decrease factor // */ // public double getDecreaseFactor(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/deltaevolution/IGeometricDEFactory.java // public interface IGeometricDEFactory extends IDeltaEvolutionFactory { // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.avt.deltamanager.deltaevolution.IDeltaEvolutionFactory#createInstance() // */ // @Override // IGeometricDE createInstance(); // }
import fr.irit.smac.libs.tooling.avt.deltamanager.deltaevolution.IGeometricDEFactory; import fr.irit.smac.libs.tooling.avt.deltamanager.deltaevolution.IGeometricDE;
/* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.deltamanager.deltaevolution.impl; /** * A factory for creating DeterministicGDE objects. */ public class DeterministicGDEFactory implements IGeometricDEFactory { /** The increase factor. */ private final double increaseFactor; /** The decrease factor. */ private final double decreaseFactor; /** * Instantiates a new deterministic gde factory. * * @param increaseFactor the increase factor * @param decreaseFactor the decrease factor */ public DeterministicGDEFactory(double increaseFactor, double decreaseFactor) { super(); this.increaseFactor = increaseFactor; this.decreaseFactor = decreaseFactor; } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.avt.deltamanager.deltaevolution.IGeometricDEFactory#createInstance() */ @Override
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/deltaevolution/IGeometricDE.java // public interface IGeometricDE extends IDeltaEvolution { // // /** // * Gets the increase factor. // * // * @return the increase factor // */ // public double getIncreaseFactor(); // // /** // * Gets the decrease factor. // * // * @return the decrease factor // */ // public double getDecreaseFactor(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/deltaevolution/IGeometricDEFactory.java // public interface IGeometricDEFactory extends IDeltaEvolutionFactory { // // /* (non-Javadoc) // * @see fr.irit.smac.libs.tooling.avt.deltamanager.deltaevolution.IDeltaEvolutionFactory#createInstance() // */ // @Override // IGeometricDE createInstance(); // } // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/deltaevolution/impl/DeterministicGDEFactory.java import fr.irit.smac.libs.tooling.avt.deltamanager.deltaevolution.IGeometricDEFactory; import fr.irit.smac.libs.tooling.avt.deltamanager.deltaevolution.IGeometricDE; /* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.deltamanager.deltaevolution.impl; /** * A factory for creating DeterministicGDE objects. */ public class DeterministicGDEFactory implements IGeometricDEFactory { /** The increase factor. */ private final double increaseFactor; /** The decrease factor. */ private final double decreaseFactor; /** * Instantiates a new deterministic gde factory. * * @param increaseFactor the increase factor * @param decreaseFactor the decrease factor */ public DeterministicGDEFactory(double increaseFactor, double decreaseFactor) { super(); this.increaseFactor = increaseFactor; this.decreaseFactor = decreaseFactor; } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.avt.deltamanager.deltaevolution.IGeometricDEFactory#createInstance() */ @Override
public IGeometricDE createInstance() {
IRIT-SMAC/agent-tooling
avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAVTBuilder.java
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/IDeltaManagerFactory.java // public interface IDeltaManagerFactory<T extends IDeltaManager> { // // /** // * Instanciate a DeltaManager that will be used for the given AVT. // * // * @param range the range // * @return the t // */ // T createInstance(IRange range); // // }
import fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory;
/* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt; /** * The Interface IAVTBuilder. * * @param <T> the generic type */ public interface IAVTBuilder<T extends IAVT> { /** * Checks if is hard bounds. * * @param isHardBounds the is hard bounds * @return the IAVT builder */ public IAVTBuilder<T> isHardBounds(boolean isHardBounds); /** * Avt factory. * * @param avtFactory the avt factory * @return the IAVT builder */ public IAVTBuilder<T> avtFactory(IAVTFactory<T> avtFactory); /** * Soft bounds memory. * * @param softBoundsMemory the soft bounds memory * @return the IAVT builder * @throws IllegalArgumentException if softBoundsMemory < 0 * @throws IllegalStateException hardBounds are set to true */ public IAVTBuilder<T> softBoundsMemory(int softBoundsMemory); /** * Checks if is delayed delta. * * @param isDelayed the is delayed * @return the IAVT builder */ public IAVTBuilder<T> isDelayedDelta(boolean isDelayed); /** * Checks if is bounded delta. * * @param isBounded the is bounded * @return the IAVT builder */ public IAVTBuilder<T> isBoundedDelta(boolean isBounded); /** * Checks if is deterministic delta. * * @param isDeterministic the is deterministic * @return the IAVT builder */ public IAVTBuilder<T> isDeterministicDelta(boolean isDeterministic); /** * Delta increase factor. * * @param increaseFactor the increase factor * @return the IAVT builder * @throws IllegalArgumentException if increaseFactor < 1. */ public IAVTBuilder<T> deltaIncreaseFactor(double increaseFactor); /** * Delta decrease factor. * * @param decreaseFactor the decrease factor * @return the IAVT builder * @throws IllegalArgumentException if decreaseFactor < 1. */ public IAVTBuilder<T> deltaDecreaseFactor(double decreaseFactor); /** * Delta decrease noise. * * @param decreaseNoise the decrease noise * @return the IAVT builder * @throws IllegalStateException if delta has been set to deterministic thanks to * this.setDeterministic(true) * @throws IllegalArgumentException if decreaseNoise <= 0 */ public IAVTBuilder<T> deltaDecreaseNoise(double decreaseNoise); /** * Sets the random seed that defines the non deterministic evolution of * delta decrease. * * @param seed the seed * @return the IAVT builder */ public IAVTBuilder<T> deltaRandomSeed(long seed); /** * Delta increase delay. * * @param increaseDelay the increase delay * @return the IAVT builder * @throws IllegalStateException if delta has not been set to delayed thanks to a call to * this.setDelayedDelat(true) * @throws IllegalArgumentException if increaseDelay < 0 */ public IAVTBuilder<T> deltaIncreaseDelay(int increaseDelay); /** * Delta decrease delay. * * @param decreaseDelay the decrease delay * @return the IAVT builder */ public IAVTBuilder<T> deltaDecreaseDelay(int decreaseDelay); /** * Delta min. * * @param deltaMin the delta min * @return the IAVT builder */ public IAVTBuilder<T> deltaMin(double deltaMin); /** * Delta max. * * @param deltaMax the delta max * @return the IAVT builder */ public IAVTBuilder<T> deltaMax(double deltaMax); /** * Lower bound. * * @param lowerBound the lower bound * @return the IAVT builder */ public IAVTBuilder<T> lowerBound(double lowerBound); /** * Upper bound. * * @param upperBound the upper bound * @return the IAVT builder */ public IAVTBuilder<T> upperBound(double upperBound); /** * Start value. * * @param startValue the start value * @return the IAVT builder */ public IAVTBuilder<T> startValue(double startValue); /** * Delta manager factory. * * @param deltaManagerFactory the delta manager factory * @return the IAVT builder * @throw new IllegalArgumentException if deltaManager == null */
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/IDeltaManagerFactory.java // public interface IDeltaManagerFactory<T extends IDeltaManager> { // // /** // * Instanciate a DeltaManager that will be used for the given AVT. // * // * @param range the range // * @return the t // */ // T createInstance(IRange range); // // } // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAVTBuilder.java import fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory; /* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt; /** * The Interface IAVTBuilder. * * @param <T> the generic type */ public interface IAVTBuilder<T extends IAVT> { /** * Checks if is hard bounds. * * @param isHardBounds the is hard bounds * @return the IAVT builder */ public IAVTBuilder<T> isHardBounds(boolean isHardBounds); /** * Avt factory. * * @param avtFactory the avt factory * @return the IAVT builder */ public IAVTBuilder<T> avtFactory(IAVTFactory<T> avtFactory); /** * Soft bounds memory. * * @param softBoundsMemory the soft bounds memory * @return the IAVT builder * @throws IllegalArgumentException if softBoundsMemory < 0 * @throws IllegalStateException hardBounds are set to true */ public IAVTBuilder<T> softBoundsMemory(int softBoundsMemory); /** * Checks if is delayed delta. * * @param isDelayed the is delayed * @return the IAVT builder */ public IAVTBuilder<T> isDelayedDelta(boolean isDelayed); /** * Checks if is bounded delta. * * @param isBounded the is bounded * @return the IAVT builder */ public IAVTBuilder<T> isBoundedDelta(boolean isBounded); /** * Checks if is deterministic delta. * * @param isDeterministic the is deterministic * @return the IAVT builder */ public IAVTBuilder<T> isDeterministicDelta(boolean isDeterministic); /** * Delta increase factor. * * @param increaseFactor the increase factor * @return the IAVT builder * @throws IllegalArgumentException if increaseFactor < 1. */ public IAVTBuilder<T> deltaIncreaseFactor(double increaseFactor); /** * Delta decrease factor. * * @param decreaseFactor the decrease factor * @return the IAVT builder * @throws IllegalArgumentException if decreaseFactor < 1. */ public IAVTBuilder<T> deltaDecreaseFactor(double decreaseFactor); /** * Delta decrease noise. * * @param decreaseNoise the decrease noise * @return the IAVT builder * @throws IllegalStateException if delta has been set to deterministic thanks to * this.setDeterministic(true) * @throws IllegalArgumentException if decreaseNoise <= 0 */ public IAVTBuilder<T> deltaDecreaseNoise(double decreaseNoise); /** * Sets the random seed that defines the non deterministic evolution of * delta decrease. * * @param seed the seed * @return the IAVT builder */ public IAVTBuilder<T> deltaRandomSeed(long seed); /** * Delta increase delay. * * @param increaseDelay the increase delay * @return the IAVT builder * @throws IllegalStateException if delta has not been set to delayed thanks to a call to * this.setDelayedDelat(true) * @throws IllegalArgumentException if increaseDelay < 0 */ public IAVTBuilder<T> deltaIncreaseDelay(int increaseDelay); /** * Delta decrease delay. * * @param decreaseDelay the decrease delay * @return the IAVT builder */ public IAVTBuilder<T> deltaDecreaseDelay(int decreaseDelay); /** * Delta min. * * @param deltaMin the delta min * @return the IAVT builder */ public IAVTBuilder<T> deltaMin(double deltaMin); /** * Delta max. * * @param deltaMax the delta max * @return the IAVT builder */ public IAVTBuilder<T> deltaMax(double deltaMax); /** * Lower bound. * * @param lowerBound the lower bound * @return the IAVT builder */ public IAVTBuilder<T> lowerBound(double lowerBound); /** * Upper bound. * * @param upperBound the upper bound * @return the IAVT builder */ public IAVTBuilder<T> upperBound(double upperBound); /** * Start value. * * @param startValue the start value * @return the IAVT builder */ public IAVTBuilder<T> startValue(double startValue); /** * Delta manager factory. * * @param deltaManagerFactory the delta manager factory * @return the IAVT builder * @throw new IllegalArgumentException if deltaManager == null */
public IAVTBuilder<T> deltaManagerFactory(IDeltaManagerFactory<?> deltaManagerFactory);
IRIT-SMAC/agent-tooling
avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/dmdecision/IDMDecision.java
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/IDeltaManager.java // public enum EDirection { // // /** The direct. */ // DIRECT, // /** The indirect. */ // INDIRECT, // /** The none. */ // NONE // }
import fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManager.EDirection;
/* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.deltamanager.dmdecision; /** * The Interface IDMDecision. * * <p> * A DMDecision decides on the direction of the evolution of the delta. * </p> */ public interface IDMDecision { /** * The Enum EDecision. */ public enum EDecision { /** The increase delta. */ INCREASE_DELTA, /** The decrease delta. */ DECREASE_DELTA, /** The same delta. */ SAME_DELTA } /** * Gets the next decision. * * @param direction * the direction * @return the next decision */
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/IDeltaManager.java // public enum EDirection { // // /** The direct. */ // DIRECT, // /** The indirect. */ // INDIRECT, // /** The none. */ // NONE // } // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/dmdecision/IDMDecision.java import fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManager.EDirection; /* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.deltamanager.dmdecision; /** * The Interface IDMDecision. * * <p> * A DMDecision decides on the direction of the evolution of the delta. * </p> */ public interface IDMDecision { /** * The Enum EDecision. */ public enum EDecision { /** The increase delta. */ INCREASE_DELTA, /** The decrease delta. */ DECREASE_DELTA, /** The same delta. */ SAME_DELTA } /** * Gets the next decision. * * @param direction * the direction * @return the next decision */
public EDecision getNextDecision(EDirection direction);
IRIT-SMAC/agent-tooling
agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/DefaultMsgService.java
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IDirectory.java // public interface IDirectory<T> { // // /** // * Returns the agent ref from the given agent id. // * // * @param agentId the agent id // * @return the agent ref // */ // public Ref<T> getAgentRef(String agentId); // // /** // * Returns the group ref from the given agent id. // * // * @param groupId the group id // * @return the group ref // */ // public Ref<T> getGroupRef(String groupId); // // /** // * Returns all the agents inscribed in a group. // * // * @param groupRef the group ref // * @return the agents of group // */ // public Set<Ref<T>> getAgentsOfGroup(Ref<T> groupRef); // // /** // * Returns all the agents inscribed in a group. // * // * @param groupId the group id // * @return the agents of group // */ // public Set<Ref<T>> getAgentsOfGroup(String groupId); // // /** // * Returns all the agent refs inscribed in the directory. // * // * @return the groups ref // */ // public List<Ref<T>> getGroupsRef(); // // /** // * Returns all the groups refs inscribed in the directory. // * // * @return the agents ref // */ // public List<Ref<T>> getAgentsRef(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgService.java // public interface IMsgService<T> extends ISender<T> { // // /** // * Gets or create a message box associated with the given agent id. // * // * @param agentId the agent id // * @return the msg box // */ // public IMsgBox<T> getMsgBox(String agentId); // // }
import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.IMsgService; import fr.irit.smac.libs.tooling.messaging.IDirectory;
/* * #%L * agent-messaging * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.messaging.impl; /** * A basic implementation of the message service. * * @author lemouzy * @param <T> the generic type */ public class DefaultMsgService<T> implements IMsgService<T> { /** The directory. */ private final BasicMutableDirectory<T> directory; /** The sender. */ private final BasicSender<T> sender; /** * Instantiates a new default msg service. */ public DefaultMsgService() { super(); this.directory = new BasicMutableDirectory<T>(); this.sender = new BasicSender<T>(this.directory); } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.messaging.ISender#getDirectory() */ @Override
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IDirectory.java // public interface IDirectory<T> { // // /** // * Returns the agent ref from the given agent id. // * // * @param agentId the agent id // * @return the agent ref // */ // public Ref<T> getAgentRef(String agentId); // // /** // * Returns the group ref from the given agent id. // * // * @param groupId the group id // * @return the group ref // */ // public Ref<T> getGroupRef(String groupId); // // /** // * Returns all the agents inscribed in a group. // * // * @param groupRef the group ref // * @return the agents of group // */ // public Set<Ref<T>> getAgentsOfGroup(Ref<T> groupRef); // // /** // * Returns all the agents inscribed in a group. // * // * @param groupId the group id // * @return the agents of group // */ // public Set<Ref<T>> getAgentsOfGroup(String groupId); // // /** // * Returns all the agent refs inscribed in the directory. // * // * @return the groups ref // */ // public List<Ref<T>> getGroupsRef(); // // /** // * Returns all the groups refs inscribed in the directory. // * // * @return the agents ref // */ // public List<Ref<T>> getAgentsRef(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgService.java // public interface IMsgService<T> extends ISender<T> { // // /** // * Gets or create a message box associated with the given agent id. // * // * @param agentId the agent id // * @return the msg box // */ // public IMsgBox<T> getMsgBox(String agentId); // // } // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/DefaultMsgService.java import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.IMsgService; import fr.irit.smac.libs.tooling.messaging.IDirectory; /* * #%L * agent-messaging * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.messaging.impl; /** * A basic implementation of the message service. * * @author lemouzy * @param <T> the generic type */ public class DefaultMsgService<T> implements IMsgService<T> { /** The directory. */ private final BasicMutableDirectory<T> directory; /** The sender. */ private final BasicSender<T> sender; /** * Instantiates a new default msg service. */ public DefaultMsgService() { super(); this.directory = new BasicMutableDirectory<T>(); this.sender = new BasicSender<T>(this.directory); } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.messaging.ISender#getDirectory() */ @Override
public IDirectory<T> getDirectory() {
IRIT-SMAC/agent-tooling
agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/DefaultMsgService.java
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IDirectory.java // public interface IDirectory<T> { // // /** // * Returns the agent ref from the given agent id. // * // * @param agentId the agent id // * @return the agent ref // */ // public Ref<T> getAgentRef(String agentId); // // /** // * Returns the group ref from the given agent id. // * // * @param groupId the group id // * @return the group ref // */ // public Ref<T> getGroupRef(String groupId); // // /** // * Returns all the agents inscribed in a group. // * // * @param groupRef the group ref // * @return the agents of group // */ // public Set<Ref<T>> getAgentsOfGroup(Ref<T> groupRef); // // /** // * Returns all the agents inscribed in a group. // * // * @param groupId the group id // * @return the agents of group // */ // public Set<Ref<T>> getAgentsOfGroup(String groupId); // // /** // * Returns all the agent refs inscribed in the directory. // * // * @return the groups ref // */ // public List<Ref<T>> getGroupsRef(); // // /** // * Returns all the groups refs inscribed in the directory. // * // * @return the agents ref // */ // public List<Ref<T>> getAgentsRef(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgService.java // public interface IMsgService<T> extends ISender<T> { // // /** // * Gets or create a message box associated with the given agent id. // * // * @param agentId the agent id // * @return the msg box // */ // public IMsgBox<T> getMsgBox(String agentId); // // }
import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.IMsgService; import fr.irit.smac.libs.tooling.messaging.IDirectory;
} /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.messaging.ISender#sendToGroup(java.lang.Object, java.lang.String) */ @Override public boolean sendToGroup(T msg, String groupId) { return this.sender.sendToGroup(msg, groupId); } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.messaging.ISender#sendToGroup(java.lang.Object, fr.irit.smac.libs.tooling.messaging.impl.Ref) */ @Override public boolean sendToGroup(T msg, Ref<T> groupRef) { return this.sender.sendToGroup(msg, groupRef); } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.messaging.ISender#broadcast(java.lang.Object) */ @Override public boolean broadcast(T msg) { return this.sender.broadcast(msg); } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.messaging.IMsgService#getMsgBox(java.lang.String) */ @Override
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IDirectory.java // public interface IDirectory<T> { // // /** // * Returns the agent ref from the given agent id. // * // * @param agentId the agent id // * @return the agent ref // */ // public Ref<T> getAgentRef(String agentId); // // /** // * Returns the group ref from the given agent id. // * // * @param groupId the group id // * @return the group ref // */ // public Ref<T> getGroupRef(String groupId); // // /** // * Returns all the agents inscribed in a group. // * // * @param groupRef the group ref // * @return the agents of group // */ // public Set<Ref<T>> getAgentsOfGroup(Ref<T> groupRef); // // /** // * Returns all the agents inscribed in a group. // * // * @param groupId the group id // * @return the agents of group // */ // public Set<Ref<T>> getAgentsOfGroup(String groupId); // // /** // * Returns all the agent refs inscribed in the directory. // * // * @return the groups ref // */ // public List<Ref<T>> getGroupsRef(); // // /** // * Returns all the groups refs inscribed in the directory. // * // * @return the agents ref // */ // public List<Ref<T>> getAgentsRef(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgService.java // public interface IMsgService<T> extends ISender<T> { // // /** // * Gets or create a message box associated with the given agent id. // * // * @param agentId the agent id // * @return the msg box // */ // public IMsgBox<T> getMsgBox(String agentId); // // } // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/DefaultMsgService.java import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.IMsgService; import fr.irit.smac.libs.tooling.messaging.IDirectory; } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.messaging.ISender#sendToGroup(java.lang.Object, java.lang.String) */ @Override public boolean sendToGroup(T msg, String groupId) { return this.sender.sendToGroup(msg, groupId); } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.messaging.ISender#sendToGroup(java.lang.Object, fr.irit.smac.libs.tooling.messaging.impl.Ref) */ @Override public boolean sendToGroup(T msg, Ref<T> groupRef) { return this.sender.sendToGroup(msg, groupRef); } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.messaging.ISender#broadcast(java.lang.Object) */ @Override public boolean broadcast(T msg) { return this.sender.broadcast(msg); } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.messaging.IMsgService#getMsgBox(java.lang.String) */ @Override
public IMsgBox<T> getMsgBox(String agentId) {
IRIT-SMAC/agent-tooling
avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/impl/BoundedDMFactory.java
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/IDeltaManager.java // public interface IDeltaManager { // // /** // * Defines the direction given to the method <code>adjustDelta</code> in // * order to update the tunning step delta. // * // * @author Sylvain Lemouzy // */ // public enum EDirection { // // /** The direct. */ // DIRECT, // /** The indirect. */ // INDIRECT, // /** The none. */ // NONE // } // // /** // * Adjusts (tunes) the delta value from the succession of directions // * successively given to this method. // * <p> // * The way the adjustment is done depends on the implementation of the // * DeltaManager // * </p> // * // * @param direction // * the direction of the adjustment // */ // public void adjustDelta(EDirection direction); // // /** // * Returns the delta value. // * // * @return the delta value // */ // public double getDelta(); // // /** // * Returns an advanced interface to control the DeltaManager. // * <p> // * Pay caution, some of the methods of this interface doesn't guarantee the // * DeltaManager state consistency. Generally, you should only uses this // * interface if you have good reasons and you know what you are doing. // * </p> // * // * @return this AVT instance with an advanced interface // */ // public IAdvancedDM getAdvancedDM(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/IDeltaManagerFactory.java // public interface IDeltaManagerFactory<T extends IDeltaManager> { // // /** // * Instanciate a DeltaManager that will be used for the given AVT. // * // * @param range the range // * @return the t // */ // T createInstance(IRange range); // // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/range/IRange.java // public interface IRange { // // /** // * The lower bound of this range. // * // * @return the lower bound // */ // public double getLowerBound(); // // /** // * The upper bound of this range. // * // * @return the upper bound // */ // public double getUpperBound(); // // /** // * Checks if is inside range. // * // * @param value the value // * @return true if value is inside lower and upper bounds, including bounds // */ // public boolean isInsideRange(double value); // // /** // * Computes the size of the range. // * // * @return the big decimal // */ // public BigDecimal computeRangeSize(); // // /** // * Checks for infinite size. // * // * @return isInfinite // */ // public boolean hasInfiniteSize(); // }
import fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory; import fr.irit.smac.libs.tooling.avt.range.IRange; import fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManager;
/* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.deltamanager.impl; /** * A factory for creating BoundedDM objects. */ public class BoundedDMFactory implements IDeltaManagerFactory<IDeltaManager> { /** The nested delta manager factory. */ private final IDeltaManagerFactory<?> nestedDeltaManagerFactory; /** * Instantiates a new bounded dm factory. * * @param nestedDeltaManagerFactory the nested delta manager factory */ public BoundedDMFactory(IDeltaManagerFactory<?> nestedDeltaManagerFactory) { this.nestedDeltaManagerFactory = nestedDeltaManagerFactory; } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory#createInstance(fr.irit.smac.libs.tooling.avt.range.IRange) */ @Override
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/IDeltaManager.java // public interface IDeltaManager { // // /** // * Defines the direction given to the method <code>adjustDelta</code> in // * order to update the tunning step delta. // * // * @author Sylvain Lemouzy // */ // public enum EDirection { // // /** The direct. */ // DIRECT, // /** The indirect. */ // INDIRECT, // /** The none. */ // NONE // } // // /** // * Adjusts (tunes) the delta value from the succession of directions // * successively given to this method. // * <p> // * The way the adjustment is done depends on the implementation of the // * DeltaManager // * </p> // * // * @param direction // * the direction of the adjustment // */ // public void adjustDelta(EDirection direction); // // /** // * Returns the delta value. // * // * @return the delta value // */ // public double getDelta(); // // /** // * Returns an advanced interface to control the DeltaManager. // * <p> // * Pay caution, some of the methods of this interface doesn't guarantee the // * DeltaManager state consistency. Generally, you should only uses this // * interface if you have good reasons and you know what you are doing. // * </p> // * // * @return this AVT instance with an advanced interface // */ // public IAdvancedDM getAdvancedDM(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/IDeltaManagerFactory.java // public interface IDeltaManagerFactory<T extends IDeltaManager> { // // /** // * Instanciate a DeltaManager that will be used for the given AVT. // * // * @param range the range // * @return the t // */ // T createInstance(IRange range); // // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/range/IRange.java // public interface IRange { // // /** // * The lower bound of this range. // * // * @return the lower bound // */ // public double getLowerBound(); // // /** // * The upper bound of this range. // * // * @return the upper bound // */ // public double getUpperBound(); // // /** // * Checks if is inside range. // * // * @param value the value // * @return true if value is inside lower and upper bounds, including bounds // */ // public boolean isInsideRange(double value); // // /** // * Computes the size of the range. // * // * @return the big decimal // */ // public BigDecimal computeRangeSize(); // // /** // * Checks for infinite size. // * // * @return isInfinite // */ // public boolean hasInfiniteSize(); // } // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/impl/BoundedDMFactory.java import fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory; import fr.irit.smac.libs.tooling.avt.range.IRange; import fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManager; /* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.deltamanager.impl; /** * A factory for creating BoundedDM objects. */ public class BoundedDMFactory implements IDeltaManagerFactory<IDeltaManager> { /** The nested delta manager factory. */ private final IDeltaManagerFactory<?> nestedDeltaManagerFactory; /** * Instantiates a new bounded dm factory. * * @param nestedDeltaManagerFactory the nested delta manager factory */ public BoundedDMFactory(IDeltaManagerFactory<?> nestedDeltaManagerFactory) { this.nestedDeltaManagerFactory = nestedDeltaManagerFactory; } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory#createInstance(fr.irit.smac.libs.tooling.avt.range.IRange) */ @Override
public IDeltaManager createInstance(IRange range) {
IRIT-SMAC/agent-tooling
avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/SoftBoundsMemoryAVTFactory.java
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAVT.java // public interface IAVT { // // /** // * Adjusts the value to the direction of the given feedback. // * <ul> // * <li><code>Feedback.GREATER</code>: increments the current value</li> // * <li><code>Feedback.LOWER<code>: decrements the current value</li> // * <li><code>Feedback.GOOD</code>: decreases the criticity of the AVT but // * doesn't change the value. This feedbacks express that the current value // * is good and should evolve more slowly at the next adjustment.</li> // * </ul> // * // * // * @param feedback // */ // public void adjustValue(EFeedback feedback); // // /** // * Current value determied by the AVT. // * // * @return the current value determied by the AVT // */ // public double getValue(); // // /** // * Returns the criticity of the AVT. // * <p> // * Criticity is a value that express the estimated inaccuracy of the current // * value. The criticity is a value between 0 and 1 where : // * </p> // * <ul> // * <li>0 stands for the best accuracy</li> // * <li>1 stands for the worst accuracy</lI> // * </ul> // * // * @return the criticity of this AVT // */ // public double getCriticity(); // // /** // * Returns an advanced interface to control the AVT. // * <p> // * Pay caution, some of the methods of this interface doesn't guarantee the // * AVT state consistency. Generally, you should only uses this interface if // * you have good reasons and you know what you are doing. // * </p> // * // * @return this AVT instance with an advanced interface // */ // public IAdvancedAVT getAdvancedAVT(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAVTFactory.java // public interface IAVTFactory<T extends IAVT> { // // /** // * Creates a new IAVT object. // * // * @param lowerBound the lower bound // * @param upperBound the upper bound // * @param startValue the start value // * @param deltaManagerFactory the delta manager factory // * @return the t // */ // T createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory); // // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/IDeltaManagerFactory.java // public interface IDeltaManagerFactory<T extends IDeltaManager> { // // /** // * Instanciate a DeltaManager that will be used for the given AVT. // * // * @param range the range // * @return the t // */ // T createInstance(IRange range); // // }
import fr.irit.smac.libs.tooling.avt.IAVTFactory; import fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory; import fr.irit.smac.libs.tooling.avt.IAVT;
/* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.impl; /** * A factory for creating SoftBoundsMemoryAVT objects. */ public class SoftBoundsMemoryAVTFactory implements IAVTFactory<IAVT> { /** The soft bounds memory. */ private final int softBoundsMemory; /** * Instantiates a new soft bounds memory avt factory. * * @param softBoundsMemory the soft bounds memory */ public SoftBoundsMemoryAVTFactory(int softBoundsMemory) { super(); this.softBoundsMemory = softBoundsMemory; } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) */ @Override public IAVT createInstance(double lowerBound, double upperBound, double startValue,
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAVT.java // public interface IAVT { // // /** // * Adjusts the value to the direction of the given feedback. // * <ul> // * <li><code>Feedback.GREATER</code>: increments the current value</li> // * <li><code>Feedback.LOWER<code>: decrements the current value</li> // * <li><code>Feedback.GOOD</code>: decreases the criticity of the AVT but // * doesn't change the value. This feedbacks express that the current value // * is good and should evolve more slowly at the next adjustment.</li> // * </ul> // * // * // * @param feedback // */ // public void adjustValue(EFeedback feedback); // // /** // * Current value determied by the AVT. // * // * @return the current value determied by the AVT // */ // public double getValue(); // // /** // * Returns the criticity of the AVT. // * <p> // * Criticity is a value that express the estimated inaccuracy of the current // * value. The criticity is a value between 0 and 1 where : // * </p> // * <ul> // * <li>0 stands for the best accuracy</li> // * <li>1 stands for the worst accuracy</lI> // * </ul> // * // * @return the criticity of this AVT // */ // public double getCriticity(); // // /** // * Returns an advanced interface to control the AVT. // * <p> // * Pay caution, some of the methods of this interface doesn't guarantee the // * AVT state consistency. Generally, you should only uses this interface if // * you have good reasons and you know what you are doing. // * </p> // * // * @return this AVT instance with an advanced interface // */ // public IAdvancedAVT getAdvancedAVT(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/IAVTFactory.java // public interface IAVTFactory<T extends IAVT> { // // /** // * Creates a new IAVT object. // * // * @param lowerBound the lower bound // * @param upperBound the upper bound // * @param startValue the start value // * @param deltaManagerFactory the delta manager factory // * @return the t // */ // T createInstance(double lowerBound, double upperBound, double startValue, // IDeltaManagerFactory<?> deltaManagerFactory); // // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/IDeltaManagerFactory.java // public interface IDeltaManagerFactory<T extends IDeltaManager> { // // /** // * Instanciate a DeltaManager that will be used for the given AVT. // * // * @param range the range // * @return the t // */ // T createInstance(IRange range); // // } // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/impl/SoftBoundsMemoryAVTFactory.java import fr.irit.smac.libs.tooling.avt.IAVTFactory; import fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory; import fr.irit.smac.libs.tooling.avt.IAVT; /* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.impl; /** * A factory for creating SoftBoundsMemoryAVT objects. */ public class SoftBoundsMemoryAVTFactory implements IAVTFactory<IAVT> { /** The soft bounds memory. */ private final int softBoundsMemory; /** * Instantiates a new soft bounds memory avt factory. * * @param softBoundsMemory the soft bounds memory */ public SoftBoundsMemoryAVTFactory(int softBoundsMemory) { super(); this.softBoundsMemory = softBoundsMemory; } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.avt.IAVTFactory#createInstance(double, double, double, fr.irit.smac.libs.tooling.avt.deltamanager.IDeltaManagerFactory) */ @Override public IAVT createInstance(double lowerBound, double upperBound, double startValue,
IDeltaManagerFactory<?> deltaManagerFactory) {
IRIT-SMAC/agent-tooling
avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/dmdecision/impl/DelayedDMDFactory.java
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/dmdecision/IDMDecision.java // public interface IDMDecision { // // /** // * The Enum EDecision. // */ // public enum EDecision { // // /** The increase delta. */ // INCREASE_DELTA, // /** The decrease delta. */ // DECREASE_DELTA, // /** The same delta. */ // SAME_DELTA // } // // /** // * Gets the next decision. // * // * @param direction // * the direction // * @return the next decision // */ // public EDecision getNextDecision(EDirection direction); // // /** // * Gets the next decision if. // * // * @param direction // * the direction // * @return the next decision if // */ // public EDecision getNextDecisionIf(EDirection direction); // // /** // * Reset state. // */ // public void resetState(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/dmdecision/IDMDecisionFactory.java // public interface IDMDecisionFactory { // // /** // * Creates a new IDMDecision object. // * // * @return the IDM decision // */ // IDMDecision createInstance(); // }
import fr.irit.smac.libs.tooling.avt.deltamanager.dmdecision.IDMDecisionFactory; import fr.irit.smac.libs.tooling.avt.deltamanager.dmdecision.IDMDecision;
/* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.deltamanager.dmdecision.impl; /** * A factory for creating DelayedDMD objects. */ public class DelayedDMDFactory implements IDMDecisionFactory { /** The nested dm decison factory. */ private final IDMDecisionFactory nestedDMDecisonFactory; /** The increase delay. */ private final int increaseDelay; /** The decrease delay. */ private final int decreaseDelay; /** * Instantiates a new delayed dmd factory. * * @param nestedDMDecisonFactory the nested dm decison factory * @param increaseDelay the increase delay * @param decreaseDelay the decrease delay */ public DelayedDMDFactory(IDMDecisionFactory nestedDMDecisonFactory, int increaseDelay, int decreaseDelay) { super(); this.nestedDMDecisonFactory = nestedDMDecisonFactory; this.increaseDelay = increaseDelay; this.decreaseDelay = decreaseDelay; } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.avt.deltamanager.dmdecision.IDMDecisionFactory#createInstance() */ @Override
// Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/dmdecision/IDMDecision.java // public interface IDMDecision { // // /** // * The Enum EDecision. // */ // public enum EDecision { // // /** The increase delta. */ // INCREASE_DELTA, // /** The decrease delta. */ // DECREASE_DELTA, // /** The same delta. */ // SAME_DELTA // } // // /** // * Gets the next decision. // * // * @param direction // * the direction // * @return the next decision // */ // public EDecision getNextDecision(EDirection direction); // // /** // * Gets the next decision if. // * // * @param direction // * the direction // * @return the next decision if // */ // public EDecision getNextDecisionIf(EDirection direction); // // /** // * Reset state. // */ // public void resetState(); // } // // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/dmdecision/IDMDecisionFactory.java // public interface IDMDecisionFactory { // // /** // * Creates a new IDMDecision object. // * // * @return the IDM decision // */ // IDMDecision createInstance(); // } // Path: avt/src/main/java/fr/irit/smac/libs/tooling/avt/deltamanager/dmdecision/impl/DelayedDMDFactory.java import fr.irit.smac.libs.tooling.avt.deltamanager.dmdecision.IDMDecisionFactory; import fr.irit.smac.libs.tooling.avt.deltamanager.dmdecision.IDMDecision; /* * #%L * avt * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.avt.deltamanager.dmdecision.impl; /** * A factory for creating DelayedDMD objects. */ public class DelayedDMDFactory implements IDMDecisionFactory { /** The nested dm decison factory. */ private final IDMDecisionFactory nestedDMDecisonFactory; /** The increase delay. */ private final int increaseDelay; /** The decrease delay. */ private final int decreaseDelay; /** * Instantiates a new delayed dmd factory. * * @param nestedDMDecisonFactory the nested dm decison factory * @param increaseDelay the increase delay * @param decreaseDelay the decrease delay */ public DelayedDMDFactory(IDMDecisionFactory nestedDMDecisonFactory, int increaseDelay, int decreaseDelay) { super(); this.nestedDMDecisonFactory = nestedDMDecisonFactory; this.increaseDelay = increaseDelay; this.decreaseDelay = decreaseDelay; } /* (non-Javadoc) * @see fr.irit.smac.libs.tooling.avt.deltamanager.dmdecision.IDMDecisionFactory#createInstance() */ @Override
public IDMDecision createInstance() {
IRIT-SMAC/agent-tooling
agent-scheduling/src/main/java/fr/irit/smac/libs/tooling/scheduling/example/Demo.java
// Path: agent-scheduling/src/main/java/fr/irit/smac/libs/tooling/scheduling/IAgentStrategy.java // public interface IAgentStrategy { // // /** // * The next step to be executed according to the execution strategy of the // * agent. // */ // public void nextStep(); // // }
import fr.irit.smac.libs.tooling.scheduling.IAgentStrategy;
/* * #%L * agent-scheduling * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.scheduling.example; public class Demo { private Demo() { }
// Path: agent-scheduling/src/main/java/fr/irit/smac/libs/tooling/scheduling/IAgentStrategy.java // public interface IAgentStrategy { // // /** // * The next step to be executed according to the execution strategy of the // * agent. // */ // public void nextStep(); // // } // Path: agent-scheduling/src/main/java/fr/irit/smac/libs/tooling/scheduling/example/Demo.java import fr.irit.smac.libs.tooling.scheduling.IAgentStrategy; /* * #%L * agent-scheduling * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.scheduling.example; public class Demo { private Demo() { }
static class MyAgent implements IAgentStrategy {
IRIT-SMAC/agent-tooling
agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/example/SimpleMessagingExample.java
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/AgentMessaging.java // public class AgentMessaging { // // // the storage of all message service instance, associated to the message // /** The instancied msg services. */ // // type class the handle // private static Map<Class<?>, IMsgService<?>> instanciedMsgServices = new HashMap<Class<?>, IMsgService<?>>(); // // /** // * Instantiates a new agent messaging. // */ // private AgentMessaging() { // // } // // /** // * Get or create a message box for the given agentId, associated to the // * given class message service type. // * // * @param <T> // * the generic type // * @param agentId // * the agent // * @param messageClassType // * the class type or the messages handled by the message box // * @return the msg box // */ // public static <T> IMsgBox<T> getMsgBox(String agentId, // Class<T> messageClassType) { // return AgentMessaging.<T> getMsgService(messageClassType) // .getMsgBox(agentId); // } // // /** // * Get or create a message service associated to the given class message // * service type. // * // * @param <T> // * the generic type // * @param messageClassType // * the message class type // * @return the msg service // */ // public static <T> IMsgService<T> getMsgService( // Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService == null) { // msgService = new DefaultMsgService<T>(); // instanciedMsgServices.put(messageClassType, msgService); // } // // return msgService; // } // // /** // * Shutdown the message service associated with the given class message // * @param messageClassType // */ // public static <T> void shutdownMsgService(Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService != null) { // instanciedMsgServices.remove(messageClassType); // } else { // throw new IllegalArgumentException( // "Trying to shutdown a non existing service : "+messageClassType // ); // } // } // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/Ref.java // public abstract class Ref<T> implements Comparable<Ref<T>> { // // /** The id. */ // private final String id; // // /** // * Instantiates a new ref. // * // * @param id the id // */ // public Ref(String id) { // this.id = id; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "@" + id; // } // // /** // * Gets the id. // * // * @return the id // */ // public String getId() { // return id; // } // // /* (non-Javadoc) // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(Ref<T> ref) { // return this.getId().compareTo(ref.getId()); // } // // /** // * Gets the msg sink. // * // * @return the external package hidden message sink // */ // abstract IMsgSink<T> getMsgSink(); // }
import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.impl.Ref; import fr.irit.smac.libs.tooling.messaging.AgentMessaging;
/* * #%L * agent-messaging * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.messaging.example; /** * The Class SimpleMessagingExample. */ public class SimpleMessagingExample { /** * The main method. * * @param args the arguments */ public static void main(String[] args) { // creation for message boxes able to handle String message type
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/AgentMessaging.java // public class AgentMessaging { // // // the storage of all message service instance, associated to the message // /** The instancied msg services. */ // // type class the handle // private static Map<Class<?>, IMsgService<?>> instanciedMsgServices = new HashMap<Class<?>, IMsgService<?>>(); // // /** // * Instantiates a new agent messaging. // */ // private AgentMessaging() { // // } // // /** // * Get or create a message box for the given agentId, associated to the // * given class message service type. // * // * @param <T> // * the generic type // * @param agentId // * the agent // * @param messageClassType // * the class type or the messages handled by the message box // * @return the msg box // */ // public static <T> IMsgBox<T> getMsgBox(String agentId, // Class<T> messageClassType) { // return AgentMessaging.<T> getMsgService(messageClassType) // .getMsgBox(agentId); // } // // /** // * Get or create a message service associated to the given class message // * service type. // * // * @param <T> // * the generic type // * @param messageClassType // * the message class type // * @return the msg service // */ // public static <T> IMsgService<T> getMsgService( // Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService == null) { // msgService = new DefaultMsgService<T>(); // instanciedMsgServices.put(messageClassType, msgService); // } // // return msgService; // } // // /** // * Shutdown the message service associated with the given class message // * @param messageClassType // */ // public static <T> void shutdownMsgService(Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService != null) { // instanciedMsgServices.remove(messageClassType); // } else { // throw new IllegalArgumentException( // "Trying to shutdown a non existing service : "+messageClassType // ); // } // } // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/Ref.java // public abstract class Ref<T> implements Comparable<Ref<T>> { // // /** The id. */ // private final String id; // // /** // * Instantiates a new ref. // * // * @param id the id // */ // public Ref(String id) { // this.id = id; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "@" + id; // } // // /** // * Gets the id. // * // * @return the id // */ // public String getId() { // return id; // } // // /* (non-Javadoc) // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(Ref<T> ref) { // return this.getId().compareTo(ref.getId()); // } // // /** // * Gets the msg sink. // * // * @return the external package hidden message sink // */ // abstract IMsgSink<T> getMsgSink(); // } // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/example/SimpleMessagingExample.java import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.impl.Ref; import fr.irit.smac.libs.tooling.messaging.AgentMessaging; /* * #%L * agent-messaging * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.messaging.example; /** * The Class SimpleMessagingExample. */ public class SimpleMessagingExample { /** * The main method. * * @param args the arguments */ public static void main(String[] args) { // creation for message boxes able to handle String message type
IMsgBox<String> msgBox1 = AgentMessaging.getMsgBox("agent1", String.class);
IRIT-SMAC/agent-tooling
agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/example/SimpleMessagingExample.java
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/AgentMessaging.java // public class AgentMessaging { // // // the storage of all message service instance, associated to the message // /** The instancied msg services. */ // // type class the handle // private static Map<Class<?>, IMsgService<?>> instanciedMsgServices = new HashMap<Class<?>, IMsgService<?>>(); // // /** // * Instantiates a new agent messaging. // */ // private AgentMessaging() { // // } // // /** // * Get or create a message box for the given agentId, associated to the // * given class message service type. // * // * @param <T> // * the generic type // * @param agentId // * the agent // * @param messageClassType // * the class type or the messages handled by the message box // * @return the msg box // */ // public static <T> IMsgBox<T> getMsgBox(String agentId, // Class<T> messageClassType) { // return AgentMessaging.<T> getMsgService(messageClassType) // .getMsgBox(agentId); // } // // /** // * Get or create a message service associated to the given class message // * service type. // * // * @param <T> // * the generic type // * @param messageClassType // * the message class type // * @return the msg service // */ // public static <T> IMsgService<T> getMsgService( // Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService == null) { // msgService = new DefaultMsgService<T>(); // instanciedMsgServices.put(messageClassType, msgService); // } // // return msgService; // } // // /** // * Shutdown the message service associated with the given class message // * @param messageClassType // */ // public static <T> void shutdownMsgService(Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService != null) { // instanciedMsgServices.remove(messageClassType); // } else { // throw new IllegalArgumentException( // "Trying to shutdown a non existing service : "+messageClassType // ); // } // } // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/Ref.java // public abstract class Ref<T> implements Comparable<Ref<T>> { // // /** The id. */ // private final String id; // // /** // * Instantiates a new ref. // * // * @param id the id // */ // public Ref(String id) { // this.id = id; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "@" + id; // } // // /** // * Gets the id. // * // * @return the id // */ // public String getId() { // return id; // } // // /* (non-Javadoc) // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(Ref<T> ref) { // return this.getId().compareTo(ref.getId()); // } // // /** // * Gets the msg sink. // * // * @return the external package hidden message sink // */ // abstract IMsgSink<T> getMsgSink(); // }
import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.impl.Ref; import fr.irit.smac.libs.tooling.messaging.AgentMessaging;
/* * #%L * agent-messaging * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.messaging.example; /** * The Class SimpleMessagingExample. */ public class SimpleMessagingExample { /** * The main method. * * @param args the arguments */ public static void main(String[] args) { // creation for message boxes able to handle String message type
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/AgentMessaging.java // public class AgentMessaging { // // // the storage of all message service instance, associated to the message // /** The instancied msg services. */ // // type class the handle // private static Map<Class<?>, IMsgService<?>> instanciedMsgServices = new HashMap<Class<?>, IMsgService<?>>(); // // /** // * Instantiates a new agent messaging. // */ // private AgentMessaging() { // // } // // /** // * Get or create a message box for the given agentId, associated to the // * given class message service type. // * // * @param <T> // * the generic type // * @param agentId // * the agent // * @param messageClassType // * the class type or the messages handled by the message box // * @return the msg box // */ // public static <T> IMsgBox<T> getMsgBox(String agentId, // Class<T> messageClassType) { // return AgentMessaging.<T> getMsgService(messageClassType) // .getMsgBox(agentId); // } // // /** // * Get or create a message service associated to the given class message // * service type. // * // * @param <T> // * the generic type // * @param messageClassType // * the message class type // * @return the msg service // */ // public static <T> IMsgService<T> getMsgService( // Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService == null) { // msgService = new DefaultMsgService<T>(); // instanciedMsgServices.put(messageClassType, msgService); // } // // return msgService; // } // // /** // * Shutdown the message service associated with the given class message // * @param messageClassType // */ // public static <T> void shutdownMsgService(Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService != null) { // instanciedMsgServices.remove(messageClassType); // } else { // throw new IllegalArgumentException( // "Trying to shutdown a non existing service : "+messageClassType // ); // } // } // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/Ref.java // public abstract class Ref<T> implements Comparable<Ref<T>> { // // /** The id. */ // private final String id; // // /** // * Instantiates a new ref. // * // * @param id the id // */ // public Ref(String id) { // this.id = id; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "@" + id; // } // // /** // * Gets the id. // * // * @return the id // */ // public String getId() { // return id; // } // // /* (non-Javadoc) // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(Ref<T> ref) { // return this.getId().compareTo(ref.getId()); // } // // /** // * Gets the msg sink. // * // * @return the external package hidden message sink // */ // abstract IMsgSink<T> getMsgSink(); // } // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/example/SimpleMessagingExample.java import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.impl.Ref; import fr.irit.smac.libs.tooling.messaging.AgentMessaging; /* * #%L * agent-messaging * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.messaging.example; /** * The Class SimpleMessagingExample. */ public class SimpleMessagingExample { /** * The main method. * * @param args the arguments */ public static void main(String[] args) { // creation for message boxes able to handle String message type
IMsgBox<String> msgBox1 = AgentMessaging.getMsgBox("agent1", String.class);
IRIT-SMAC/agent-tooling
agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/example/SimpleMessagingExample.java
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/AgentMessaging.java // public class AgentMessaging { // // // the storage of all message service instance, associated to the message // /** The instancied msg services. */ // // type class the handle // private static Map<Class<?>, IMsgService<?>> instanciedMsgServices = new HashMap<Class<?>, IMsgService<?>>(); // // /** // * Instantiates a new agent messaging. // */ // private AgentMessaging() { // // } // // /** // * Get or create a message box for the given agentId, associated to the // * given class message service type. // * // * @param <T> // * the generic type // * @param agentId // * the agent // * @param messageClassType // * the class type or the messages handled by the message box // * @return the msg box // */ // public static <T> IMsgBox<T> getMsgBox(String agentId, // Class<T> messageClassType) { // return AgentMessaging.<T> getMsgService(messageClassType) // .getMsgBox(agentId); // } // // /** // * Get or create a message service associated to the given class message // * service type. // * // * @param <T> // * the generic type // * @param messageClassType // * the message class type // * @return the msg service // */ // public static <T> IMsgService<T> getMsgService( // Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService == null) { // msgService = new DefaultMsgService<T>(); // instanciedMsgServices.put(messageClassType, msgService); // } // // return msgService; // } // // /** // * Shutdown the message service associated with the given class message // * @param messageClassType // */ // public static <T> void shutdownMsgService(Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService != null) { // instanciedMsgServices.remove(messageClassType); // } else { // throw new IllegalArgumentException( // "Trying to shutdown a non existing service : "+messageClassType // ); // } // } // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/Ref.java // public abstract class Ref<T> implements Comparable<Ref<T>> { // // /** The id. */ // private final String id; // // /** // * Instantiates a new ref. // * // * @param id the id // */ // public Ref(String id) { // this.id = id; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "@" + id; // } // // /** // * Gets the id. // * // * @return the id // */ // public String getId() { // return id; // } // // /* (non-Javadoc) // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(Ref<T> ref) { // return this.getId().compareTo(ref.getId()); // } // // /** // * Gets the msg sink. // * // * @return the external package hidden message sink // */ // abstract IMsgSink<T> getMsgSink(); // }
import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.impl.Ref; import fr.irit.smac.libs.tooling.messaging.AgentMessaging;
/* * #%L * agent-messaging * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.messaging.example; /** * The Class SimpleMessagingExample. */ public class SimpleMessagingExample { /** * The main method. * * @param args the arguments */ public static void main(String[] args) { // creation for message boxes able to handle String message type IMsgBox<String> msgBox1 = AgentMessaging.getMsgBox("agent1", String.class); IMsgBox<String> msgBox2 = AgentMessaging.getMsgBox("agent2", String.class); // Getting the ref of the agent2
// Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/AgentMessaging.java // public class AgentMessaging { // // // the storage of all message service instance, associated to the message // /** The instancied msg services. */ // // type class the handle // private static Map<Class<?>, IMsgService<?>> instanciedMsgServices = new HashMap<Class<?>, IMsgService<?>>(); // // /** // * Instantiates a new agent messaging. // */ // private AgentMessaging() { // // } // // /** // * Get or create a message box for the given agentId, associated to the // * given class message service type. // * // * @param <T> // * the generic type // * @param agentId // * the agent // * @param messageClassType // * the class type or the messages handled by the message box // * @return the msg box // */ // public static <T> IMsgBox<T> getMsgBox(String agentId, // Class<T> messageClassType) { // return AgentMessaging.<T> getMsgService(messageClassType) // .getMsgBox(agentId); // } // // /** // * Get or create a message service associated to the given class message // * service type. // * // * @param <T> // * the generic type // * @param messageClassType // * the message class type // * @return the msg service // */ // public static <T> IMsgService<T> getMsgService( // Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService == null) { // msgService = new DefaultMsgService<T>(); // instanciedMsgServices.put(messageClassType, msgService); // } // // return msgService; // } // // /** // * Shutdown the message service associated with the given class message // * @param messageClassType // */ // public static <T> void shutdownMsgService(Class<T> messageClassType) { // @SuppressWarnings("unchecked") // IMsgService<T> msgService = (IMsgService<T>) instanciedMsgServices // .get(messageClassType); // if (msgService != null) { // instanciedMsgServices.remove(messageClassType); // } else { // throw new IllegalArgumentException( // "Trying to shutdown a non existing service : "+messageClassType // ); // } // } // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/IMsgBox.java // public interface IMsgBox<T> extends ISender<T>, IReceiver<T> { // // /** // * The ref of the agent using the message box. // * // * @return the ref // */ // public Ref<T> getRef(); // // /** // * Disable the message box and uninscrible it to all the previously // * subscribed groups. // */ // public void dispose(); // } // // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/impl/Ref.java // public abstract class Ref<T> implements Comparable<Ref<T>> { // // /** The id. */ // private final String id; // // /** // * Instantiates a new ref. // * // * @param id the id // */ // public Ref(String id) { // this.id = id; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "@" + id; // } // // /** // * Gets the id. // * // * @return the id // */ // public String getId() { // return id; // } // // /* (non-Javadoc) // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(Ref<T> ref) { // return this.getId().compareTo(ref.getId()); // } // // /** // * Gets the msg sink. // * // * @return the external package hidden message sink // */ // abstract IMsgSink<T> getMsgSink(); // } // Path: agent-messaging/src/main/java/fr/irit/smac/libs/tooling/messaging/example/SimpleMessagingExample.java import fr.irit.smac.libs.tooling.messaging.IMsgBox; import fr.irit.smac.libs.tooling.messaging.impl.Ref; import fr.irit.smac.libs.tooling.messaging.AgentMessaging; /* * #%L * agent-messaging * %% * Copyright (C) 2014 - 2015 IRIT - SMAC Team * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package fr.irit.smac.libs.tooling.messaging.example; /** * The Class SimpleMessagingExample. */ public class SimpleMessagingExample { /** * The main method. * * @param args the arguments */ public static void main(String[] args) { // creation for message boxes able to handle String message type IMsgBox<String> msgBox1 = AgentMessaging.getMsgBox("agent1", String.class); IMsgBox<String> msgBox2 = AgentMessaging.getMsgBox("agent2", String.class); // Getting the ref of the agent2
Ref<String> refAgent2 = msgBox1.getDirectory().getAgentRef("agent2");
Logimethods/nats-connector-spark
src/test/java/com/logimethods/connector/spark/to_nats/SparkToNatsConnectorTest.java
// Path: src/main/java/com/logimethods/connector/spark/to_nats/SparkToNatsConnector.java // protected static String combineSubjects(String preSubject, String postSubject) { // if (preSubject.contains(SUBJECT_PATTERN_SEPARATOR)) { // Pattern pattern; // String replacement; // if (subjectPatternMap.containsKey(preSubject)) { // final Tuple2<Pattern, String> tuple = subjectPatternMap.get(preSubject); // pattern = tuple._1; // replacement = tuple._2; // } else { // // http://www.vogella.com/tutorials/JavaRegularExpressions/article.html // final int pos = preSubject.indexOf(SUBJECT_PATTERN_SEPARATOR); // // final String patternStr = preSubject.substring(0, pos).trim().replace(".", "\\.").replace("*", "[^\\.]*"); // logger.trace(patternStr); // pattern = Pattern.compile(patternStr); // // replacement = preSubject.substring(pos+SUBJECT_PATTERN_SEPARATOR.length()).trim(); // logger.trace(replacement); // // subjectPatternMap.put(preSubject, new Tuple2<Pattern, String>(pattern, replacement)); // } // return pattern.matcher(postSubject).replaceFirst(replacement); // } else { // return preSubject + postSubject; // } // }
import static com.logimethods.connector.spark.to_nats.SparkToNatsConnector.combineSubjects; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Properties; import org.apache.commons.lang3.SerializationUtils; import org.junit.Test;
package com.logimethods.connector.spark.to_nats; public class SparkToNatsConnectorTest { private static final String natsURL = "nats://123.123.123.123:4444"; private static final Properties properties = new Properties(); private static final Collection<String> subjects = Arrays.asList("Hello", "World!"); private static final boolean isStoredAsKeyValue = true; @Test public void testCombineSubjectsNoSubstitution() { final String subA = "subA"; final String subB = "subB";
// Path: src/main/java/com/logimethods/connector/spark/to_nats/SparkToNatsConnector.java // protected static String combineSubjects(String preSubject, String postSubject) { // if (preSubject.contains(SUBJECT_PATTERN_SEPARATOR)) { // Pattern pattern; // String replacement; // if (subjectPatternMap.containsKey(preSubject)) { // final Tuple2<Pattern, String> tuple = subjectPatternMap.get(preSubject); // pattern = tuple._1; // replacement = tuple._2; // } else { // // http://www.vogella.com/tutorials/JavaRegularExpressions/article.html // final int pos = preSubject.indexOf(SUBJECT_PATTERN_SEPARATOR); // // final String patternStr = preSubject.substring(0, pos).trim().replace(".", "\\.").replace("*", "[^\\.]*"); // logger.trace(patternStr); // pattern = Pattern.compile(patternStr); // // replacement = preSubject.substring(pos+SUBJECT_PATTERN_SEPARATOR.length()).trim(); // logger.trace(replacement); // // subjectPatternMap.put(preSubject, new Tuple2<Pattern, String>(pattern, replacement)); // } // return pattern.matcher(postSubject).replaceFirst(replacement); // } else { // return preSubject + postSubject; // } // } // Path: src/test/java/com/logimethods/connector/spark/to_nats/SparkToNatsConnectorTest.java import static com.logimethods.connector.spark.to_nats.SparkToNatsConnector.combineSubjects; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Properties; import org.apache.commons.lang3.SerializationUtils; import org.junit.Test; package com.logimethods.connector.spark.to_nats; public class SparkToNatsConnectorTest { private static final String natsURL = "nats://123.123.123.123:4444"; private static final Properties properties = new Properties(); private static final Collection<String> subjects = Arrays.asList("Hello", "World!"); private static final boolean isStoredAsKeyValue = true; @Test public void testCombineSubjectsNoSubstitution() { final String subA = "subA"; final String subB = "subB";
assertEquals(subA, combineSubjects("", subA));
Logimethods/nats-connector-spark
src/main/java/com/logimethods/connector/nats/to_spark/OmnipotentStandardNatsToSparkConnector.java
// Path: src/main/java/com/logimethods/connector/nats_spark/IncompleteException.java // public class IncompleteException extends Exception { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public IncompleteException() { // } // // public IncompleteException(String message) { // super(message); // } // // public IncompleteException(Throwable cause) { // super(cause); // } // // public IncompleteException(String message, Throwable cause) { // super(message, cause); // } // // public IncompleteException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // }
import static io.nats.client.Options.PROP_URL; import java.io.IOException; import java.util.Collection; import java.util.Properties; import java.util.concurrent.TimeoutException; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.spark.storage.StorageLevel; import com.logimethods.connector.nats_spark.IncompleteException; import io.nats.client.Connection; import io.nats.client.Dispatcher; import io.nats.client.MessageHandler; import io.nats.client.Nats; import io.nats.client.Options;
/******************************************************************************* * Copyright (c) 2016 Logimethods * All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License (MIT) * which accompanies this distribution, and is available at * http://opensource.org/licenses/MIT *******************************************************************************/ package com.logimethods.connector.nats.to_spark; /** * A NATS to Spark Connector. * <p> * It will transfer messages received from NATS into Spark data. * <p> * That class extends {@link com.logimethods.connector.nats.to_spark.NatsToSparkConnector}&lt;T,R,V&gt;. */ @SuppressWarnings("serial") public abstract class OmnipotentStandardNatsToSparkConnector<T,R,V> extends NatsToSparkConnector<T,R,V> { protected OmnipotentStandardNatsToSparkConnector(Class<V> type, Properties properties, StorageLevel storageLevel, String... subjects) { super(type, storageLevel, subjects); this.properties = properties; setNatsQueue(); } protected OmnipotentStandardNatsToSparkConnector(Class<V> type, StorageLevel storageLevel, String... subjects) { super(type, storageLevel, subjects); setNatsQueue(); } protected OmnipotentStandardNatsToSparkConnector(Class<V> type, Properties properties, StorageLevel storageLevel) { super(type, storageLevel); this.properties = properties; setNatsQueue(); } protected OmnipotentStandardNatsToSparkConnector(Class<V> type, StorageLevel storageLevel) { super(type, storageLevel); setNatsQueue(); } protected OmnipotentStandardNatsToSparkConnector(Class<V> type, StorageLevel storageLevel, Collection<String> subjects, Properties properties, String queue, String natsUrl) { super(type, storageLevel, subjects, properties, queue, natsUrl); } /** */ protected StandardNatsToKeyValueSparkConnectorImpl<V> storedAsKeyValue() { return new StandardNatsToKeyValueSparkConnectorImpl<V>(type, storageLevel(), subjects, properties, natsQueue, natsUrl, dataDecoder, scalaDataDecoder); } protected Properties enrichedProperties; /** Create a socket connection and receive data until receiver is stopped * @throws IncompleteException * @throws TimeoutException * @throws IOException * @throws InterruptedException * @throws IllegalArgumentException * @throws IllegalStateException **/
// Path: src/main/java/com/logimethods/connector/nats_spark/IncompleteException.java // public class IncompleteException extends Exception { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public IncompleteException() { // } // // public IncompleteException(String message) { // super(message); // } // // public IncompleteException(Throwable cause) { // super(cause); // } // // public IncompleteException(String message, Throwable cause) { // super(message, cause); // } // // public IncompleteException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // Path: src/main/java/com/logimethods/connector/nats/to_spark/OmnipotentStandardNatsToSparkConnector.java import static io.nats.client.Options.PROP_URL; import java.io.IOException; import java.util.Collection; import java.util.Properties; import java.util.concurrent.TimeoutException; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.spark.storage.StorageLevel; import com.logimethods.connector.nats_spark.IncompleteException; import io.nats.client.Connection; import io.nats.client.Dispatcher; import io.nats.client.MessageHandler; import io.nats.client.Nats; import io.nats.client.Options; /******************************************************************************* * Copyright (c) 2016 Logimethods * All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License (MIT) * which accompanies this distribution, and is available at * http://opensource.org/licenses/MIT *******************************************************************************/ package com.logimethods.connector.nats.to_spark; /** * A NATS to Spark Connector. * <p> * It will transfer messages received from NATS into Spark data. * <p> * That class extends {@link com.logimethods.connector.nats.to_spark.NatsToSparkConnector}&lt;T,R,V&gt;. */ @SuppressWarnings("serial") public abstract class OmnipotentStandardNatsToSparkConnector<T,R,V> extends NatsToSparkConnector<T,R,V> { protected OmnipotentStandardNatsToSparkConnector(Class<V> type, Properties properties, StorageLevel storageLevel, String... subjects) { super(type, storageLevel, subjects); this.properties = properties; setNatsQueue(); } protected OmnipotentStandardNatsToSparkConnector(Class<V> type, StorageLevel storageLevel, String... subjects) { super(type, storageLevel, subjects); setNatsQueue(); } protected OmnipotentStandardNatsToSparkConnector(Class<V> type, Properties properties, StorageLevel storageLevel) { super(type, storageLevel); this.properties = properties; setNatsQueue(); } protected OmnipotentStandardNatsToSparkConnector(Class<V> type, StorageLevel storageLevel) { super(type, storageLevel); setNatsQueue(); } protected OmnipotentStandardNatsToSparkConnector(Class<V> type, StorageLevel storageLevel, Collection<String> subjects, Properties properties, String queue, String natsUrl) { super(type, storageLevel, subjects, properties, queue, natsUrl); } /** */ protected StandardNatsToKeyValueSparkConnectorImpl<V> storedAsKeyValue() { return new StandardNatsToKeyValueSparkConnectorImpl<V>(type, storageLevel(), subjects, properties, natsQueue, natsUrl, dataDecoder, scalaDataDecoder); } protected Properties enrichedProperties; /** Create a socket connection and receive data until receiver is stopped * @throws IncompleteException * @throws TimeoutException * @throws IOException * @throws InterruptedException * @throws IllegalArgumentException * @throws IllegalStateException **/
protected void receive() throws IncompleteException, IOException, TimeoutException, IllegalStateException, IllegalArgumentException, InterruptedException {
Logimethods/nats-connector-spark
src/main/java/com/logimethods/connector/nats/to_spark/OmnipotentNatsStreamingToSparkConnector.java
// Path: src/main/java/com/logimethods/connector/nats_spark/IncompleteException.java // public class IncompleteException extends Exception { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public IncompleteException() { // } // // public IncompleteException(String message) { // super(message); // } // // public IncompleteException(Throwable cause) { // super(cause); // } // // public IncompleteException(String message, Throwable cause) { // super(message, cause); // } // // public IncompleteException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // }
import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.spark.storage.StorageLevel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.logimethods.connector.nats_spark.IncompleteException; import io.nats.streaming.Message; import io.nats.streaming.MessageHandler; import io.nats.streaming.NatsStreaming; import io.nats.streaming.Options; import io.nats.streaming.Subscription; import io.nats.streaming.SubscriptionOptions;
/** * @return the opts */ protected SubscriptionOptions getSubscriptionOptions() { if (subscriptionOpts == null){ subscriptionOpts = getSubscriptionOptsBuilder().dispatcher(DISPATCHER_NAME).build(); } return subscriptionOpts; } /** * @return the optsBuilder */ protected SubscriptionOptions.Builder getSubscriptionOptsBuilder() { if (subscriptionOptsBuilder == null) { subscriptionOptsBuilder = new SubscriptionOptions.Builder(); } return subscriptionOptsBuilder; } /** * @return a NATS Streaming to Spark Connector where the NATS Messages are stored in Spark as Key (the NATS Subject) / Value (the NATS Payload) */ public NatsStreamingToKeyValueSparkConnectorImpl<V> storedAsKeyValue() { return new NatsStreamingToKeyValueSparkConnectorImpl<V>(type, storageLevel(), subjects, properties, natsQueue, natsUrl, clusterID, clientID, subscriptionOpts, subscriptionOptsBuilder, dataDecoder, scalaDataDecoder); } /** Create a socket connection and receive data until receiver is stopped * @throws Exception **/
// Path: src/main/java/com/logimethods/connector/nats_spark/IncompleteException.java // public class IncompleteException extends Exception { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public IncompleteException() { // } // // public IncompleteException(String message) { // super(message); // } // // public IncompleteException(Throwable cause) { // super(cause); // } // // public IncompleteException(String message, Throwable cause) { // super(message, cause); // } // // public IncompleteException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // Path: src/main/java/com/logimethods/connector/nats/to_spark/OmnipotentNatsStreamingToSparkConnector.java import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.spark.storage.StorageLevel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.logimethods.connector.nats_spark.IncompleteException; import io.nats.streaming.Message; import io.nats.streaming.MessageHandler; import io.nats.streaming.NatsStreaming; import io.nats.streaming.Options; import io.nats.streaming.Subscription; import io.nats.streaming.SubscriptionOptions; /** * @return the opts */ protected SubscriptionOptions getSubscriptionOptions() { if (subscriptionOpts == null){ subscriptionOpts = getSubscriptionOptsBuilder().dispatcher(DISPATCHER_NAME).build(); } return subscriptionOpts; } /** * @return the optsBuilder */ protected SubscriptionOptions.Builder getSubscriptionOptsBuilder() { if (subscriptionOptsBuilder == null) { subscriptionOptsBuilder = new SubscriptionOptions.Builder(); } return subscriptionOptsBuilder; } /** * @return a NATS Streaming to Spark Connector where the NATS Messages are stored in Spark as Key (the NATS Subject) / Value (the NATS Payload) */ public NatsStreamingToKeyValueSparkConnectorImpl<V> storedAsKeyValue() { return new NatsStreamingToKeyValueSparkConnectorImpl<V>(type, storageLevel(), subjects, properties, natsQueue, natsUrl, clusterID, clientID, subscriptionOpts, subscriptionOptsBuilder, dataDecoder, scalaDataDecoder); } /** Create a socket connection and receive data until receiver is stopped * @throws Exception **/
protected void receive() throws IOException, InterruptedException, IncompleteException, TimeoutException {
Logimethods/nats-connector-spark
src/test/java/com/logimethods/connector/spark/to_nats/SparkToNatsStreamingConnectorTest.java
// Path: src/main/java/io/nats/streaming/OptionsHelper.java // public class OptionsHelper { // // public static String extractNatsUrl(Options options) { // return options.getNatsUrl(); // } // // }
import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.Collection; import java.util.Properties; import org.apache.commons.lang3.SerializationUtils; import org.junit.Test; import io.nats.streaming.Options; import io.nats.streaming.Options.Builder; import io.nats.streaming.OptionsHelper;
package com.logimethods.connector.spark.to_nats; public class SparkToNatsStreamingConnectorTest { private static final String natsURL = "nats://123.123.123.123:4444"; private static final Properties properties = new Properties(); private static final Collection<String> subjects = Arrays.asList("Hello", "World!"); private static final boolean isStoredAsKeyValue = true; private static final String clusterID = "ClusterID"; private static final Long connectionTimeout = 111l; @Test // @See https://github.com/Logimethods/nats-connector-spark/pull/3 // @See https://github.com/nats-io/java-nats-streaming/issues/51 public void testSparkToStandardNatsConnectorImpl_Serialization() throws Exception { final Builder optionsBuilder = new Options.Builder().natsUrl(natsURL); final SparkToNatsStreamingConnectorImpl source = new SparkToNatsStreamingConnectorImpl(clusterID, natsURL, properties, connectionTimeout, optionsBuilder, subjects, isStoredAsKeyValue); final SparkToNatsStreamingConnectorImpl target = SerializationUtils.clone(source); assertEquals(clusterID, target.clusterID); assertEquals(source.getNatsURL(), target.getNatsURL()); assertEquals(source.getProperties(), target.getProperties()); assertEquals(source.getSubjects(), target.getSubjects()); assertEquals(connectionTimeout, target.connectionTimeout); assertEquals(isStoredAsKeyValue, target.isStoredAsKeyValue());
// Path: src/main/java/io/nats/streaming/OptionsHelper.java // public class OptionsHelper { // // public static String extractNatsUrl(Options options) { // return options.getNatsUrl(); // } // // } // Path: src/test/java/com/logimethods/connector/spark/to_nats/SparkToNatsStreamingConnectorTest.java import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.Collection; import java.util.Properties; import org.apache.commons.lang3.SerializationUtils; import org.junit.Test; import io.nats.streaming.Options; import io.nats.streaming.Options.Builder; import io.nats.streaming.OptionsHelper; package com.logimethods.connector.spark.to_nats; public class SparkToNatsStreamingConnectorTest { private static final String natsURL = "nats://123.123.123.123:4444"; private static final Properties properties = new Properties(); private static final Collection<String> subjects = Arrays.asList("Hello", "World!"); private static final boolean isStoredAsKeyValue = true; private static final String clusterID = "ClusterID"; private static final Long connectionTimeout = 111l; @Test // @See https://github.com/Logimethods/nats-connector-spark/pull/3 // @See https://github.com/nats-io/java-nats-streaming/issues/51 public void testSparkToStandardNatsConnectorImpl_Serialization() throws Exception { final Builder optionsBuilder = new Options.Builder().natsUrl(natsURL); final SparkToNatsStreamingConnectorImpl source = new SparkToNatsStreamingConnectorImpl(clusterID, natsURL, properties, connectionTimeout, optionsBuilder, subjects, isStoredAsKeyValue); final SparkToNatsStreamingConnectorImpl target = SerializationUtils.clone(source); assertEquals(clusterID, target.clusterID); assertEquals(source.getNatsURL(), target.getNatsURL()); assertEquals(source.getProperties(), target.getProperties()); assertEquals(source.getSubjects(), target.getSubjects()); assertEquals(connectionTimeout, target.connectionTimeout); assertEquals(isStoredAsKeyValue, target.isStoredAsKeyValue());
assertEquals(OptionsHelper.extractNatsUrl(source.getOptionsBuilder().build()),
Logimethods/nats-connector-spark
src/test/java/com/logimethods/connector/spark/to_nats/KeyValueSparkToStandardNatsConnectorLifecycleTest.java
// Path: src/main/java/com/logimethods/connector/nats/spark/test/UnitTestUtilities.java // public static final String NATS_URL = "nats://"+NATS_SERVER+":"+NATS_PORT;
import static com.logimethods.connector.nats.spark.test.UnitTestUtilities.NATS_URL; import java.time.Duration; import org.apache.spark.api.java.function.PairFunction; import org.apache.spark.streaming.api.java.JavaDStream; import org.apache.spark.streaming.api.java.JavaPairDStream; import scala.Tuple2;
/******************************************************************************* * Copyright (c) 2016 Logimethods * All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License (MIT) * which accompanies this distribution, and is available at * http://opensource.org/licenses/MIT *******************************************************************************/ package com.logimethods.connector.spark.to_nats; //@Ignore @SuppressWarnings("serial") public class KeyValueSparkToStandardNatsConnectorLifecycleTest extends AbstractSparkToStandardNatsConnectorLifecycleTest { protected void publishToNats(final String subject1, final String subject2, final int partitionsNb) { final JavaDStream<String> lines = dataSource.dataStream(ssc).repartition(partitionsNb); //- ssc.textFileStream(tempDir.getAbsolutePath()).repartition(partitionsNb); JavaPairDStream<String, String> stream1 = lines.mapToPair((PairFunction<String, String, String>) str -> { return new Tuple2<String, String>(subject1, str); }); JavaPairDStream<String, String> stream2 = lines.mapToPair((PairFunction<String, String, String>) str -> { return new Tuple2<String, String>(subject2, str); }); final JavaPairDStream<String, String> stream = stream1.union(stream2); if (logger.isDebugEnabled()) { stream.print(); } SparkToNatsConnectorPool .newPool()
// Path: src/main/java/com/logimethods/connector/nats/spark/test/UnitTestUtilities.java // public static final String NATS_URL = "nats://"+NATS_SERVER+":"+NATS_PORT; // Path: src/test/java/com/logimethods/connector/spark/to_nats/KeyValueSparkToStandardNatsConnectorLifecycleTest.java import static com.logimethods.connector.nats.spark.test.UnitTestUtilities.NATS_URL; import java.time.Duration; import org.apache.spark.api.java.function.PairFunction; import org.apache.spark.streaming.api.java.JavaDStream; import org.apache.spark.streaming.api.java.JavaPairDStream; import scala.Tuple2; /******************************************************************************* * Copyright (c) 2016 Logimethods * All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License (MIT) * which accompanies this distribution, and is available at * http://opensource.org/licenses/MIT *******************************************************************************/ package com.logimethods.connector.spark.to_nats; //@Ignore @SuppressWarnings("serial") public class KeyValueSparkToStandardNatsConnectorLifecycleTest extends AbstractSparkToStandardNatsConnectorLifecycleTest { protected void publishToNats(final String subject1, final String subject2, final int partitionsNb) { final JavaDStream<String> lines = dataSource.dataStream(ssc).repartition(partitionsNb); //- ssc.textFileStream(tempDir.getAbsolutePath()).repartition(partitionsNb); JavaPairDStream<String, String> stream1 = lines.mapToPair((PairFunction<String, String, String>) str -> { return new Tuple2<String, String>(subject1, str); }); JavaPairDStream<String, String> stream2 = lines.mapToPair((PairFunction<String, String, String>) str -> { return new Tuple2<String, String>(subject2, str); }); final JavaPairDStream<String, String> stream = stream1.union(stream2); if (logger.isDebugEnabled()) { stream.print(); } SparkToNatsConnectorPool .newPool()
.withNatsURL(NATS_URL)
ibm-ecm/ibm-navigator-aspera-sample
src/main/java/com/ibm/ecm/extension/aspera/SendService.java
// Path: src/main/java/com/ibm/ecm/extension/aspera/faspex/MaxRequestsReachedException.java // public class MaxRequestsReachedException extends RuntimeException { // MaxRequestsReachedException(final String message) { // super(message); // } // }
import com.ibm.ecm.configuration.Config; import com.ibm.ecm.extension.PluginLogger; import com.ibm.ecm.extension.PluginResponseUtil; import com.ibm.ecm.extension.PluginService; import com.ibm.ecm.extension.PluginServiceCallbacks; import com.ibm.ecm.extension.aspera.faspex.MaxRequestsReachedException; import com.ibm.ecm.json.JSONMessage; import com.ibm.ecm.json.JSONResponse; import com.ibm.json.java.JSONObject; import org.apache.struts.util.MessageResources; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Locale;
/* * Licensed Materials - Property of IBM * (C) Copyright IBM Corp. 2010, 2017 * US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp. */ package com.ibm.ecm.extension.aspera; /** * The service to send packages. */ public class SendService extends PluginService { private static final String ID = "send"; private static final String POST = "POST"; private static final String execute = "execute"; /** * Returns the Id of the service. * * @return The Id of the service */ @Override public String getId() { return ID; } /** * Validates and sends the package requested by the client. An error is returned if any of the parameters are invalid * or the maximum number of concurrent requests configured in the plug-in configuration page has been reached. * * @param callbacks The PluginServiceCallbacks object provided by the ICN API * @param request The HttpServletRequest object provided by the ICN API * @param response The HttpServletResponse object provided by the ICN API */ @Override public void execute(final PluginServiceCallbacks callbacks, final HttpServletRequest request, final HttpServletResponse response) { final PluginLogger logger = callbacks.getLogger(); logger.logEntry(this, execute); final JSONResponse responseJson = new JSONResponse(); final MessageResources resources = callbacks.getPluginResources(); final Locale locale = request.getLocale(); try { validateRequest(request); final PackageSender sender = new PackageSender(Config.getDesktopConfig(Config.APPLICATION_NAME, request.getParameter("desktop")), callbacks); final JSONObject pkg = sender.sendPackage(request, response, callbacks); responseJson.put("pkg", pkg); responseJson.addInfoMessage(createMessage(resources, locale, "sendAction.started", pkg.get("title")));
// Path: src/main/java/com/ibm/ecm/extension/aspera/faspex/MaxRequestsReachedException.java // public class MaxRequestsReachedException extends RuntimeException { // MaxRequestsReachedException(final String message) { // super(message); // } // } // Path: src/main/java/com/ibm/ecm/extension/aspera/SendService.java import com.ibm.ecm.configuration.Config; import com.ibm.ecm.extension.PluginLogger; import com.ibm.ecm.extension.PluginResponseUtil; import com.ibm.ecm.extension.PluginService; import com.ibm.ecm.extension.PluginServiceCallbacks; import com.ibm.ecm.extension.aspera.faspex.MaxRequestsReachedException; import com.ibm.ecm.json.JSONMessage; import com.ibm.ecm.json.JSONResponse; import com.ibm.json.java.JSONObject; import org.apache.struts.util.MessageResources; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Locale; /* * Licensed Materials - Property of IBM * (C) Copyright IBM Corp. 2010, 2017 * US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp. */ package com.ibm.ecm.extension.aspera; /** * The service to send packages. */ public class SendService extends PluginService { private static final String ID = "send"; private static final String POST = "POST"; private static final String execute = "execute"; /** * Returns the Id of the service. * * @return The Id of the service */ @Override public String getId() { return ID; } /** * Validates and sends the package requested by the client. An error is returned if any of the parameters are invalid * or the maximum number of concurrent requests configured in the plug-in configuration page has been reached. * * @param callbacks The PluginServiceCallbacks object provided by the ICN API * @param request The HttpServletRequest object provided by the ICN API * @param response The HttpServletResponse object provided by the ICN API */ @Override public void execute(final PluginServiceCallbacks callbacks, final HttpServletRequest request, final HttpServletResponse response) { final PluginLogger logger = callbacks.getLogger(); logger.logEntry(this, execute); final JSONResponse responseJson = new JSONResponse(); final MessageResources resources = callbacks.getPluginResources(); final Locale locale = request.getLocale(); try { validateRequest(request); final PackageSender sender = new PackageSender(Config.getDesktopConfig(Config.APPLICATION_NAME, request.getParameter("desktop")), callbacks); final JSONObject pkg = sender.sendPackage(request, response, callbacks); responseJson.put("pkg", pkg); responseJson.addInfoMessage(createMessage(resources, locale, "sendAction.started", pkg.get("title")));
} catch (final MaxRequestsReachedException e) {
ibm-ecm/ibm-navigator-aspera-sample
src/test/java/com/ibm/ecm/extension/aspera/faspex/FaspexClientTest.java
// Path: src/main/java/com/ibm/ecm/extension/aspera/AsperaPluginException.java // public class AsperaPluginException extends Exception { // AsperaPluginException(final String message, final Throwable cause) { // super(message, cause); // } // // AsperaPluginException(final String message) { // super(message); // } // // AsperaPluginException(final Throwable cause) { // super(cause); // } // }
import com.ibm.ecm.extension.PluginLogger; import com.ibm.ecm.extension.aspera.AsperaPluginException; import com.ibm.json.java.JSONObject; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*;
package com.ibm.ecm.extension.aspera.faspex; public class FaspexClientTest { private FaspexClient client; private JSONObject pluginConfig; @Before public void setUp() throws Exception { // given final PluginLogger logger = new PluginLogger("aspera"); pluginConfig = new JSONObject(); pluginConfig.put("maxNumberOfRequests", 2); client = new FaspexClient(pluginConfig, logger); } @Test public void shouldGetIntegerConfigValue() { // when final int max = client.getIntegerConfigValue(pluginConfig, "maxNumberOfRequests", 1); // then assertEquals(2, max); // or when final int undefined = client.getIntegerConfigValue(pluginConfig, "undefined", 1); // then assertEquals(1, undefined); } @Test
// Path: src/main/java/com/ibm/ecm/extension/aspera/AsperaPluginException.java // public class AsperaPluginException extends Exception { // AsperaPluginException(final String message, final Throwable cause) { // super(message, cause); // } // // AsperaPluginException(final String message) { // super(message); // } // // AsperaPluginException(final Throwable cause) { // super(cause); // } // } // Path: src/test/java/com/ibm/ecm/extension/aspera/faspex/FaspexClientTest.java import com.ibm.ecm.extension.PluginLogger; import com.ibm.ecm.extension.aspera.AsperaPluginException; import com.ibm.json.java.JSONObject; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; package com.ibm.ecm.extension.aspera.faspex; public class FaspexClientTest { private FaspexClient client; private JSONObject pluginConfig; @Before public void setUp() throws Exception { // given final PluginLogger logger = new PluginLogger("aspera"); pluginConfig = new JSONObject(); pluginConfig.put("maxNumberOfRequests", 2); client = new FaspexClient(pluginConfig, logger); } @Test public void shouldGetIntegerConfigValue() { // when final int max = client.getIntegerConfigValue(pluginConfig, "maxNumberOfRequests", 1); // then assertEquals(2, max); // or when final int undefined = client.getIntegerConfigValue(pluginConfig, "undefined", 1); // then assertEquals(1, undefined); } @Test
public void shouldReachMaxNumberOfTransfers() throws AsperaPluginException {
lizardoluis/omtg-designer
src/com/omtgdesigner/servlets/XMLImporter.java
// Path: src/com/omtgdesigner/xml/XMLValidator.java // public class XMLValidator { // // private static final XMLValidator xmlValidator = new XMLValidator(); // // private SchemaFactory factory; // // /** // * Constructor // */ // private XMLValidator() { // factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // } // // /** // * @return the instance of this singleton class. // */ // public static XMLValidator getInstance() { // return xmlValidator; // } // // /** // * @param xml // * @param schema // * @return // */ // public boolean validateXML(String xsdPath, String xml){ // try { // Schema schema = factory.newSchema(new StreamSource(getClass().getResourceAsStream(xsdPath))); // Validator validator = schema.newValidator(); // validator.validate(new StreamSource(new StringReader(xml))); // } catch (SAXException e) { // return false; // } catch (IOException e) { // return false; // } // return true; // } // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.omtgdesigner.xml.XMLValidator;
package com.omtgdesigner.servlets; /** * Servlet implementation class XMLImporter */ public class XMLImporter extends HttpServlet { private static final long serialVersionUID = 1L; /** * Validates the XML document; */
// Path: src/com/omtgdesigner/xml/XMLValidator.java // public class XMLValidator { // // private static final XMLValidator xmlValidator = new XMLValidator(); // // private SchemaFactory factory; // // /** // * Constructor // */ // private XMLValidator() { // factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // } // // /** // * @return the instance of this singleton class. // */ // public static XMLValidator getInstance() { // return xmlValidator; // } // // /** // * @param xml // * @param schema // * @return // */ // public boolean validateXML(String xsdPath, String xml){ // try { // Schema schema = factory.newSchema(new StreamSource(getClass().getResourceAsStream(xsdPath))); // Validator validator = schema.newValidator(); // validator.validate(new StreamSource(new StringReader(xml))); // } catch (SAXException e) { // return false; // } catch (IOException e) { // return false; // } // return true; // } // } // Path: src/com/omtgdesigner/servlets/XMLImporter.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.omtgdesigner.xml.XMLValidator; package com.omtgdesigner.servlets; /** * Servlet implementation class XMLImporter */ public class XMLImporter extends HttpServlet { private static final long serialVersionUID = 1L; /** * Validates the XML document; */
private XMLValidator xmlValidator;
lizardoluis/omtg-designer
src/com/omtg2sql/omtg/classes/OMTGClass.java
// Path: src/com/omtg2sql/omtg/relationships/OMTGGeneralization.java // public class OMTGGeneralization extends OMTGRelationship { // // private static final String TOTAL = "total"; // private static final String PARTIAL = "partial"; // private static final String DISJOINT = "disjoint"; // // /* // * completeness = (t)/(p) total, partial // * disjointness = (d)/(o) disjoint, overlapping // */ // private String superClass, disjointness; // private List<String> subclasses; // // public OMTGGeneralization(String disjointness, String type, String superClass, List<String> subclasses) { // super("generalization-" + superClass, type, superClass, null); // this.superClass = superClass; // this.disjointness = disjointness; // this.subclasses = subclasses; // } // // public String getSuperClass() { // return superClass; // } // // public void setSuperClass(String superClass) { // this.superClass = superClass; // } // // public String getDisjointness() { // return disjointness; // } // // public void setDisjointness(String disjointness) { // this.disjointness = disjointness; // } // // public List<String> getSubclasses() { // return subclasses; // } // // public void setSubclasses(List<String> subclasses) { // this.subclasses = subclasses; // } // // public static String getTotal() { // return TOTAL; // } // // public static String getPartial() { // return PARTIAL; // } // // public static String getDisjoint() { // return DISJOINT; // } // // public boolean isDisjoint() { // return disjointness.equalsIgnoreCase(DISJOINT); // } // } // // Path: src/com/omtg2sql/omtg/relationships/OMTGRelationship.java // public abstract class OMTGRelationship implements Cloneable { // // private String name; // private String type; // private String class1, class2; // // public OMTGRelationship(String name, String type, String class1, String class2) { // this.name = name; // this.type = type; // this.class1 = class1; // this.class2 = class2; // } // // public String getName() { // return name; // } // // public String getType() { // return type; // } // // public boolean typeEquals(String type) { // return this.type.equalsIgnoreCase(type); // } // // public String getClass1() { // return class1; // } // // public void setClass1(String class1) { // this.class1 = class1; // } // // public String getClass2() { // return class2; // } // // public void setClass2(String class2) { // this.class2 = class2; // } // // public Object clone() throws CloneNotSupportedException { // return super.clone(); // } // }
import java.util.ArrayList; import java.util.List; import com.omtg2sql.omtg.relationships.OMTGGeneralization; import com.omtg2sql.omtg.relationships.OMTGRelationship;
package com.omtg2sql.omtg.classes; public class OMTGClass implements Cloneable { public static final String PLANAR_SUBDIVISION = "planar-subdivision"; public static final String ISOLINES = "isolines"; public static final String TESSELATION = "tesselation"; public static final String TIN = "TIN"; private String name, type;
// Path: src/com/omtg2sql/omtg/relationships/OMTGGeneralization.java // public class OMTGGeneralization extends OMTGRelationship { // // private static final String TOTAL = "total"; // private static final String PARTIAL = "partial"; // private static final String DISJOINT = "disjoint"; // // /* // * completeness = (t)/(p) total, partial // * disjointness = (d)/(o) disjoint, overlapping // */ // private String superClass, disjointness; // private List<String> subclasses; // // public OMTGGeneralization(String disjointness, String type, String superClass, List<String> subclasses) { // super("generalization-" + superClass, type, superClass, null); // this.superClass = superClass; // this.disjointness = disjointness; // this.subclasses = subclasses; // } // // public String getSuperClass() { // return superClass; // } // // public void setSuperClass(String superClass) { // this.superClass = superClass; // } // // public String getDisjointness() { // return disjointness; // } // // public void setDisjointness(String disjointness) { // this.disjointness = disjointness; // } // // public List<String> getSubclasses() { // return subclasses; // } // // public void setSubclasses(List<String> subclasses) { // this.subclasses = subclasses; // } // // public static String getTotal() { // return TOTAL; // } // // public static String getPartial() { // return PARTIAL; // } // // public static String getDisjoint() { // return DISJOINT; // } // // public boolean isDisjoint() { // return disjointness.equalsIgnoreCase(DISJOINT); // } // } // // Path: src/com/omtg2sql/omtg/relationships/OMTGRelationship.java // public abstract class OMTGRelationship implements Cloneable { // // private String name; // private String type; // private String class1, class2; // // public OMTGRelationship(String name, String type, String class1, String class2) { // this.name = name; // this.type = type; // this.class1 = class1; // this.class2 = class2; // } // // public String getName() { // return name; // } // // public String getType() { // return type; // } // // public boolean typeEquals(String type) { // return this.type.equalsIgnoreCase(type); // } // // public String getClass1() { // return class1; // } // // public void setClass1(String class1) { // this.class1 = class1; // } // // public String getClass2() { // return class2; // } // // public void setClass2(String class2) { // this.class2 = class2; // } // // public Object clone() throws CloneNotSupportedException { // return super.clone(); // } // } // Path: src/com/omtg2sql/omtg/classes/OMTGClass.java import java.util.ArrayList; import java.util.List; import com.omtg2sql.omtg.relationships.OMTGGeneralization; import com.omtg2sql.omtg.relationships.OMTGRelationship; package com.omtg2sql.omtg.classes; public class OMTGClass implements Cloneable { public static final String PLANAR_SUBDIVISION = "planar-subdivision"; public static final String ISOLINES = "isolines"; public static final String TESSELATION = "tesselation"; public static final String TIN = "TIN"; private String name, type;
private List<OMTGRelationship> relationships;
lizardoluis/omtg-designer
src/com/omtg2sql/omtg/classes/OMTGClass.java
// Path: src/com/omtg2sql/omtg/relationships/OMTGGeneralization.java // public class OMTGGeneralization extends OMTGRelationship { // // private static final String TOTAL = "total"; // private static final String PARTIAL = "partial"; // private static final String DISJOINT = "disjoint"; // // /* // * completeness = (t)/(p) total, partial // * disjointness = (d)/(o) disjoint, overlapping // */ // private String superClass, disjointness; // private List<String> subclasses; // // public OMTGGeneralization(String disjointness, String type, String superClass, List<String> subclasses) { // super("generalization-" + superClass, type, superClass, null); // this.superClass = superClass; // this.disjointness = disjointness; // this.subclasses = subclasses; // } // // public String getSuperClass() { // return superClass; // } // // public void setSuperClass(String superClass) { // this.superClass = superClass; // } // // public String getDisjointness() { // return disjointness; // } // // public void setDisjointness(String disjointness) { // this.disjointness = disjointness; // } // // public List<String> getSubclasses() { // return subclasses; // } // // public void setSubclasses(List<String> subclasses) { // this.subclasses = subclasses; // } // // public static String getTotal() { // return TOTAL; // } // // public static String getPartial() { // return PARTIAL; // } // // public static String getDisjoint() { // return DISJOINT; // } // // public boolean isDisjoint() { // return disjointness.equalsIgnoreCase(DISJOINT); // } // } // // Path: src/com/omtg2sql/omtg/relationships/OMTGRelationship.java // public abstract class OMTGRelationship implements Cloneable { // // private String name; // private String type; // private String class1, class2; // // public OMTGRelationship(String name, String type, String class1, String class2) { // this.name = name; // this.type = type; // this.class1 = class1; // this.class2 = class2; // } // // public String getName() { // return name; // } // // public String getType() { // return type; // } // // public boolean typeEquals(String type) { // return this.type.equalsIgnoreCase(type); // } // // public String getClass1() { // return class1; // } // // public void setClass1(String class1) { // this.class1 = class1; // } // // public String getClass2() { // return class2; // } // // public void setClass2(String class2) { // this.class2 = class2; // } // // public Object clone() throws CloneNotSupportedException { // return super.clone(); // } // }
import java.util.ArrayList; import java.util.List; import com.omtg2sql.omtg.relationships.OMTGGeneralization; import com.omtg2sql.omtg.relationships.OMTGRelationship;
package com.omtg2sql.omtg.classes; public class OMTGClass implements Cloneable { public static final String PLANAR_SUBDIVISION = "planar-subdivision"; public static final String ISOLINES = "isolines"; public static final String TESSELATION = "tesselation"; public static final String TIN = "TIN"; private String name, type; private List<OMTGRelationship> relationships; private List<OMTGAttribute> attributes;
// Path: src/com/omtg2sql/omtg/relationships/OMTGGeneralization.java // public class OMTGGeneralization extends OMTGRelationship { // // private static final String TOTAL = "total"; // private static final String PARTIAL = "partial"; // private static final String DISJOINT = "disjoint"; // // /* // * completeness = (t)/(p) total, partial // * disjointness = (d)/(o) disjoint, overlapping // */ // private String superClass, disjointness; // private List<String> subclasses; // // public OMTGGeneralization(String disjointness, String type, String superClass, List<String> subclasses) { // super("generalization-" + superClass, type, superClass, null); // this.superClass = superClass; // this.disjointness = disjointness; // this.subclasses = subclasses; // } // // public String getSuperClass() { // return superClass; // } // // public void setSuperClass(String superClass) { // this.superClass = superClass; // } // // public String getDisjointness() { // return disjointness; // } // // public void setDisjointness(String disjointness) { // this.disjointness = disjointness; // } // // public List<String> getSubclasses() { // return subclasses; // } // // public void setSubclasses(List<String> subclasses) { // this.subclasses = subclasses; // } // // public static String getTotal() { // return TOTAL; // } // // public static String getPartial() { // return PARTIAL; // } // // public static String getDisjoint() { // return DISJOINT; // } // // public boolean isDisjoint() { // return disjointness.equalsIgnoreCase(DISJOINT); // } // } // // Path: src/com/omtg2sql/omtg/relationships/OMTGRelationship.java // public abstract class OMTGRelationship implements Cloneable { // // private String name; // private String type; // private String class1, class2; // // public OMTGRelationship(String name, String type, String class1, String class2) { // this.name = name; // this.type = type; // this.class1 = class1; // this.class2 = class2; // } // // public String getName() { // return name; // } // // public String getType() { // return type; // } // // public boolean typeEquals(String type) { // return this.type.equalsIgnoreCase(type); // } // // public String getClass1() { // return class1; // } // // public void setClass1(String class1) { // this.class1 = class1; // } // // public String getClass2() { // return class2; // } // // public void setClass2(String class2) { // this.class2 = class2; // } // // public Object clone() throws CloneNotSupportedException { // return super.clone(); // } // } // Path: src/com/omtg2sql/omtg/classes/OMTGClass.java import java.util.ArrayList; import java.util.List; import com.omtg2sql.omtg.relationships.OMTGGeneralization; import com.omtg2sql.omtg.relationships.OMTGRelationship; package com.omtg2sql.omtg.classes; public class OMTGClass implements Cloneable { public static final String PLANAR_SUBDIVISION = "planar-subdivision"; public static final String ISOLINES = "isolines"; public static final String TESSELATION = "tesselation"; public static final String TIN = "TIN"; private String name, type; private List<OMTGRelationship> relationships; private List<OMTGAttribute> attributes;
private OMTGGeneralization generalization;
lizardoluis/omtg-designer
src/com/omtg2sql/omtg/relationships/OMTGTopologicalRelationship.java
// Path: src/com/omtg2sql/omtg/classes/OMTGCardinality.java // public class OMTGCardinality { // // public static final String ONE_TO_ONE = "(1,1)"; // public static final String ONE_TO_MANY = "(1,*)"; // public static final String MANY_TO_ONE = "(*,1)"; // public static final String MANY_TO_MANY = "(*,*)"; // public static final int PARTIAL = 0; // public static final int TOTAL = 1; // // private String min; // private String max; // private int participation; // // public OMTGCardinality(String cardString) { // Scanner in = new Scanner(cardString); // in.useDelimiter(","); // this.min = in.next(); // this.max = in.next(); // if (min.equals("0")) // this.participation = 0; //partial // else this.participation = 1; //total // // in.close(); // } // // public OMTGCardinality(String min, String max) { // this.min = min; // this.max = max; // if (min.equals("0")) // this.participation = 0; //partial // else this.participation = 1; //total // } // // public int getParticipation() { // return participation; // } // // public String getMin() { // return min; // } // // public String getMax() { // return max; // } // // public boolean isEqual(OMTGCardinality card) { // if ((min.equals(card.getMin()) && max.equals(card.getMax())) || // (min.equals(card.getMax()) && max.equals(card.getMin()))) { // return true; // } // return false; // } // // public String toString() { // return "(" + min + "," + max + ")"; // } // }
import java.util.List; import com.omtg2sql.omtg.classes.OMTGCardinality;
package com.omtg2sql.omtg.relationships; public class OMTGTopologicalRelationship extends OMTGRelationship { private List<String> spatialRelation; private String distance, unit;
// Path: src/com/omtg2sql/omtg/classes/OMTGCardinality.java // public class OMTGCardinality { // // public static final String ONE_TO_ONE = "(1,1)"; // public static final String ONE_TO_MANY = "(1,*)"; // public static final String MANY_TO_ONE = "(*,1)"; // public static final String MANY_TO_MANY = "(*,*)"; // public static final int PARTIAL = 0; // public static final int TOTAL = 1; // // private String min; // private String max; // private int participation; // // public OMTGCardinality(String cardString) { // Scanner in = new Scanner(cardString); // in.useDelimiter(","); // this.min = in.next(); // this.max = in.next(); // if (min.equals("0")) // this.participation = 0; //partial // else this.participation = 1; //total // // in.close(); // } // // public OMTGCardinality(String min, String max) { // this.min = min; // this.max = max; // if (min.equals("0")) // this.participation = 0; //partial // else this.participation = 1; //total // } // // public int getParticipation() { // return participation; // } // // public String getMin() { // return min; // } // // public String getMax() { // return max; // } // // public boolean isEqual(OMTGCardinality card) { // if ((min.equals(card.getMin()) && max.equals(card.getMax())) || // (min.equals(card.getMax()) && max.equals(card.getMin()))) { // return true; // } // return false; // } // // public String toString() { // return "(" + min + "," + max + ")"; // } // } // Path: src/com/omtg2sql/omtg/relationships/OMTGTopologicalRelationship.java import java.util.List; import com.omtg2sql.omtg.classes.OMTGCardinality; package com.omtg2sql.omtg.relationships; public class OMTGTopologicalRelationship extends OMTGRelationship { private List<String> spatialRelation; private String distance, unit;
private OMTGCardinality cardinality1, cardinality2;
x6uderek/rubik
app/src/main/java/com/derek/android/rubik/robot/IRobot.java
// Path: app/src/main/java/com/derek/android/rubik/Action.java // public abstract class Action { // protected ActionCallback sender; // // public Action(ActionCallback sender) { // this.sender = sender; // } // public abstract void update(Cube3 c); // // public interface ActionCallback { // public void setEnableAnimation(boolean enable); // public boolean getEnableAnimation(); // public void onActionStart(); // public void onActionFinish(); // } // }
import com.derek.android.rubik.Action;
package com.derek.android.rubik.robot; public interface IRobot { public void enableAI();
// Path: app/src/main/java/com/derek/android/rubik/Action.java // public abstract class Action { // protected ActionCallback sender; // // public Action(ActionCallback sender) { // this.sender = sender; // } // public abstract void update(Cube3 c); // // public interface ActionCallback { // public void setEnableAnimation(boolean enable); // public boolean getEnableAnimation(); // public void onActionStart(); // public void onActionFinish(); // } // } // Path: app/src/main/java/com/derek/android/rubik/robot/IRobot.java import com.derek.android.rubik.Action; package com.derek.android.rubik.robot; public interface IRobot { public void enableAI();
public Action next();