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
woodberry/ta-toolbox
src/main/java/au/net/woodberry/ta/toolbox/object/TrendVolatilityLine.java
// Path: src/main/java/au/net/woodberry/ta/toolbox/enums/Sustainability.java // public enum Sustainability { // // UNKNOWN, // Used under some conditions where the indicator cannot determine one of the other values // HOPE, // CONFIDENT, // CERTAINTY // // }
import au.net.woodberry.ta.toolbox.enums.Sustainability; import eu.verdelhan.ta4j.TADecimal;
package au.net.woodberry.ta.toolbox.object; public class TrendVolatilityLine { private final TADecimal value;
// Path: src/main/java/au/net/woodberry/ta/toolbox/enums/Sustainability.java // public enum Sustainability { // // UNKNOWN, // Used under some conditions where the indicator cannot determine one of the other values // HOPE, // CONFIDENT, // CERTAINTY // // } // Path: src/main/java/au/net/woodberry/ta/toolbox/object/TrendVolatilityLine.java import au.net.woodberry.ta.toolbox.enums.Sustainability; import eu.verdelhan.ta4j.TADecimal; package au.net.woodberry.ta.toolbox.object; public class TrendVolatilityLine { private final TADecimal value;
private final Sustainability sustainability;
woodberry/ta-toolbox
src/test/java/au/net/woodberry/ta/toolbox/indicators/volatility/CountBackStopLossIndicatorTest.java
// Path: src/test/java/au/net/woodberry/ta/toolbox/indicators/StubDataTestUtils.java // public class StubDataTestUtils { // // private static final String SEPARATOR = ","; // private static final String COMMENT_LINE = "#"; // private static final int TIMESTAMP = 0; // private static final int OPEN = 1; // private static final int HIGH = 2; // private static final int LOW = 3; // private static final int CLOSE = 4; // private static final int VOLUME = 5; // // private StubDataTestUtils() {} // // public static List<Tick> createTickData(String stubData) { // return createTickData(stubData, SEPARATOR, null, null); // } // // public static List<Tick> createTickData(String stubData, DateTimeFormatter dtf) { // return createTickData(stubData, SEPARATOR, null, dtf); // } // // public static List<Tick> createTickData(String stubData, String separator, Pattern header, DateTimeFormatter dtf) { // List<Tick> ticks = new ArrayList<>(); // BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(StubDataTestUtils.class.getResourceAsStream(stubData))); // String line; // try { // while ((line = bufferedReader.readLine()) != null) { // String[] data = line.split(separator); // if (data == null || (header != null && header.matcher(line).matches()) || line.startsWith(COMMENT_LINE)) { // Headers, comments, no data // continue; // } // DateTime dt = dtf != null ? DateTime.parse(data[TIMESTAMP], dtf) : DateTime.parse(data[TIMESTAMP]); // Tick tick = new Tick(dt, Double.parseDouble(data[OPEN]), Double.parseDouble(data[HIGH]), Double.parseDouble(data[LOW]), // Double.parseDouble(data[CLOSE]), Double.parseDouble(data[VOLUME])); // ticks.add(tick); // } // bufferedReader.close(); // } catch (IOException e) { // throw new RuntimeException(e); // } // return ticks; // } // }
import au.net.woodberry.ta.toolbox.indicators.StubDataTestUtils; import eu.verdelhan.ta4j.TimeSeries; import eu.verdelhan.ta4j.Tick; import org.joda.time.format.DateTimeFormat; import org.joda.time.DateTime; import org.junit.Test; import java.util.Arrays; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull;
package au.net.woodberry.ta.toolbox.indicators.volatility; public class CountBackStopLossIndicatorTest { @Test(expected = IllegalArgumentException.class) public void testNullData() { new CountBackStopLossIndicator(null, new Tick(DateTime.now(), DateTime.now()), 0); } @Test(expected = IllegalArgumentException.class) public void testInvalidCountBackSteps() { new CountBackStopLossIndicator(new TimeSeries(Arrays.asList(new Tick(DateTime.now(), DateTime.now()))), 0, new Tick(DateTime.now(), DateTime.now()), 0); } @Test(expected = IllegalArgumentException.class) public void testNullTick() { new CountBackStopLossIndicator(new TimeSeries(Arrays.asList(new Tick(DateTime.now(), DateTime.now()))), null, 0); } @Test public void testGetValue() {
// Path: src/test/java/au/net/woodberry/ta/toolbox/indicators/StubDataTestUtils.java // public class StubDataTestUtils { // // private static final String SEPARATOR = ","; // private static final String COMMENT_LINE = "#"; // private static final int TIMESTAMP = 0; // private static final int OPEN = 1; // private static final int HIGH = 2; // private static final int LOW = 3; // private static final int CLOSE = 4; // private static final int VOLUME = 5; // // private StubDataTestUtils() {} // // public static List<Tick> createTickData(String stubData) { // return createTickData(stubData, SEPARATOR, null, null); // } // // public static List<Tick> createTickData(String stubData, DateTimeFormatter dtf) { // return createTickData(stubData, SEPARATOR, null, dtf); // } // // public static List<Tick> createTickData(String stubData, String separator, Pattern header, DateTimeFormatter dtf) { // List<Tick> ticks = new ArrayList<>(); // BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(StubDataTestUtils.class.getResourceAsStream(stubData))); // String line; // try { // while ((line = bufferedReader.readLine()) != null) { // String[] data = line.split(separator); // if (data == null || (header != null && header.matcher(line).matches()) || line.startsWith(COMMENT_LINE)) { // Headers, comments, no data // continue; // } // DateTime dt = dtf != null ? DateTime.parse(data[TIMESTAMP], dtf) : DateTime.parse(data[TIMESTAMP]); // Tick tick = new Tick(dt, Double.parseDouble(data[OPEN]), Double.parseDouble(data[HIGH]), Double.parseDouble(data[LOW]), // Double.parseDouble(data[CLOSE]), Double.parseDouble(data[VOLUME])); // ticks.add(tick); // } // bufferedReader.close(); // } catch (IOException e) { // throw new RuntimeException(e); // } // return ticks; // } // } // Path: src/test/java/au/net/woodberry/ta/toolbox/indicators/volatility/CountBackStopLossIndicatorTest.java import au.net.woodberry.ta.toolbox.indicators.StubDataTestUtils; import eu.verdelhan.ta4j.TimeSeries; import eu.verdelhan.ta4j.Tick; import org.joda.time.format.DateTimeFormat; import org.joda.time.DateTime; import org.junit.Test; import java.util.Arrays; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; package au.net.woodberry.ta.toolbox.indicators.volatility; public class CountBackStopLossIndicatorTest { @Test(expected = IllegalArgumentException.class) public void testNullData() { new CountBackStopLossIndicator(null, new Tick(DateTime.now(), DateTime.now()), 0); } @Test(expected = IllegalArgumentException.class) public void testInvalidCountBackSteps() { new CountBackStopLossIndicator(new TimeSeries(Arrays.asList(new Tick(DateTime.now(), DateTime.now()))), 0, new Tick(DateTime.now(), DateTime.now()), 0); } @Test(expected = IllegalArgumentException.class) public void testNullTick() { new CountBackStopLossIndicator(new TimeSeries(Arrays.asList(new Tick(DateTime.now(), DateTime.now()))), null, 0); } @Test public void testGetValue() {
TimeSeries data = new TimeSeries(StubDataTestUtils.createTickData("/TEST_COUNT_BACK_LINE_TC3.stub", DateTimeFormat.forPattern("dd-MM-YYYY")));
woodberry/ta-toolbox
src/test/java/au/net/woodberry/ta/toolbox/indicators/volatility/TradersATRStopLossIndicatorTest.java
// Path: src/test/java/au/net/woodberry/ta/toolbox/indicators/StubDataTestUtils.java // public class StubDataTestUtils { // // private static final String SEPARATOR = ","; // private static final String COMMENT_LINE = "#"; // private static final int TIMESTAMP = 0; // private static final int OPEN = 1; // private static final int HIGH = 2; // private static final int LOW = 3; // private static final int CLOSE = 4; // private static final int VOLUME = 5; // // private StubDataTestUtils() {} // // public static List<Tick> createTickData(String stubData) { // return createTickData(stubData, SEPARATOR, null, null); // } // // public static List<Tick> createTickData(String stubData, DateTimeFormatter dtf) { // return createTickData(stubData, SEPARATOR, null, dtf); // } // // public static List<Tick> createTickData(String stubData, String separator, Pattern header, DateTimeFormatter dtf) { // List<Tick> ticks = new ArrayList<>(); // BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(StubDataTestUtils.class.getResourceAsStream(stubData))); // String line; // try { // while ((line = bufferedReader.readLine()) != null) { // String[] data = line.split(separator); // if (data == null || (header != null && header.matcher(line).matches()) || line.startsWith(COMMENT_LINE)) { // Headers, comments, no data // continue; // } // DateTime dt = dtf != null ? DateTime.parse(data[TIMESTAMP], dtf) : DateTime.parse(data[TIMESTAMP]); // Tick tick = new Tick(dt, Double.parseDouble(data[OPEN]), Double.parseDouble(data[HIGH]), Double.parseDouble(data[LOW]), // Double.parseDouble(data[CLOSE]), Double.parseDouble(data[VOLUME])); // ticks.add(tick); // } // bufferedReader.close(); // } catch (IOException e) { // throw new RuntimeException(e); // } // return ticks; // } // } // // Path: src/test/java/au/net/woodberry/ta/toolbox/indicators/Assertions.java // public static void assertDecimalEquals(TADecimal actual, String expected) { // if (expected != null) { // assertNotNull(actual); // assertThat(actual).isEqualTo(TADecimal.valueOf(expected)); // } else { // assertNull(actual); // } // }
import au.net.woodberry.ta.toolbox.indicators.StubDataTestUtils; import eu.verdelhan.ta4j.TADecimal; import eu.verdelhan.ta4j.TimeSeries; import eu.verdelhan.ta4j.indicators.simple.ClosePriceIndicator; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.junit.Test; import static au.net.woodberry.ta.toolbox.indicators.Assertions.assertDecimalEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull;
package au.net.woodberry.ta.toolbox.indicators.volatility; public class TradersATRStopLossIndicatorTest { private static final DateTimeFormatter DTF = DateTimeFormat.forPattern("dd-MM-YYYY"); private static final int LOOKBACK_PERIODS = 14; private static final int DISPLACEMENT_FACTOR = 2; //2xATR @Test(expected = IllegalArgumentException.class) public void testNullAtrIndicatorThrowsException() {
// Path: src/test/java/au/net/woodberry/ta/toolbox/indicators/StubDataTestUtils.java // public class StubDataTestUtils { // // private static final String SEPARATOR = ","; // private static final String COMMENT_LINE = "#"; // private static final int TIMESTAMP = 0; // private static final int OPEN = 1; // private static final int HIGH = 2; // private static final int LOW = 3; // private static final int CLOSE = 4; // private static final int VOLUME = 5; // // private StubDataTestUtils() {} // // public static List<Tick> createTickData(String stubData) { // return createTickData(stubData, SEPARATOR, null, null); // } // // public static List<Tick> createTickData(String stubData, DateTimeFormatter dtf) { // return createTickData(stubData, SEPARATOR, null, dtf); // } // // public static List<Tick> createTickData(String stubData, String separator, Pattern header, DateTimeFormatter dtf) { // List<Tick> ticks = new ArrayList<>(); // BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(StubDataTestUtils.class.getResourceAsStream(stubData))); // String line; // try { // while ((line = bufferedReader.readLine()) != null) { // String[] data = line.split(separator); // if (data == null || (header != null && header.matcher(line).matches()) || line.startsWith(COMMENT_LINE)) { // Headers, comments, no data // continue; // } // DateTime dt = dtf != null ? DateTime.parse(data[TIMESTAMP], dtf) : DateTime.parse(data[TIMESTAMP]); // Tick tick = new Tick(dt, Double.parseDouble(data[OPEN]), Double.parseDouble(data[HIGH]), Double.parseDouble(data[LOW]), // Double.parseDouble(data[CLOSE]), Double.parseDouble(data[VOLUME])); // ticks.add(tick); // } // bufferedReader.close(); // } catch (IOException e) { // throw new RuntimeException(e); // } // return ticks; // } // } // // Path: src/test/java/au/net/woodberry/ta/toolbox/indicators/Assertions.java // public static void assertDecimalEquals(TADecimal actual, String expected) { // if (expected != null) { // assertNotNull(actual); // assertThat(actual).isEqualTo(TADecimal.valueOf(expected)); // } else { // assertNull(actual); // } // } // Path: src/test/java/au/net/woodberry/ta/toolbox/indicators/volatility/TradersATRStopLossIndicatorTest.java import au.net.woodberry.ta.toolbox.indicators.StubDataTestUtils; import eu.verdelhan.ta4j.TADecimal; import eu.verdelhan.ta4j.TimeSeries; import eu.verdelhan.ta4j.indicators.simple.ClosePriceIndicator; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.junit.Test; import static au.net.woodberry.ta.toolbox.indicators.Assertions.assertDecimalEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; package au.net.woodberry.ta.toolbox.indicators.volatility; public class TradersATRStopLossIndicatorTest { private static final DateTimeFormatter DTF = DateTimeFormat.forPattern("dd-MM-YYYY"); private static final int LOOKBACK_PERIODS = 14; private static final int DISPLACEMENT_FACTOR = 2; //2xATR @Test(expected = IllegalArgumentException.class) public void testNullAtrIndicatorThrowsException() {
TimeSeries data = new TimeSeries(StubDataTestUtils.createTickData("/TEST_TRADERS_ATR_STOP_LOSS_TC1.stub", DTF));
woodberry/ta-toolbox
src/test/java/au/net/woodberry/ta/toolbox/indicators/volatility/TradersATRStopLossIndicatorTest.java
// Path: src/test/java/au/net/woodberry/ta/toolbox/indicators/StubDataTestUtils.java // public class StubDataTestUtils { // // private static final String SEPARATOR = ","; // private static final String COMMENT_LINE = "#"; // private static final int TIMESTAMP = 0; // private static final int OPEN = 1; // private static final int HIGH = 2; // private static final int LOW = 3; // private static final int CLOSE = 4; // private static final int VOLUME = 5; // // private StubDataTestUtils() {} // // public static List<Tick> createTickData(String stubData) { // return createTickData(stubData, SEPARATOR, null, null); // } // // public static List<Tick> createTickData(String stubData, DateTimeFormatter dtf) { // return createTickData(stubData, SEPARATOR, null, dtf); // } // // public static List<Tick> createTickData(String stubData, String separator, Pattern header, DateTimeFormatter dtf) { // List<Tick> ticks = new ArrayList<>(); // BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(StubDataTestUtils.class.getResourceAsStream(stubData))); // String line; // try { // while ((line = bufferedReader.readLine()) != null) { // String[] data = line.split(separator); // if (data == null || (header != null && header.matcher(line).matches()) || line.startsWith(COMMENT_LINE)) { // Headers, comments, no data // continue; // } // DateTime dt = dtf != null ? DateTime.parse(data[TIMESTAMP], dtf) : DateTime.parse(data[TIMESTAMP]); // Tick tick = new Tick(dt, Double.parseDouble(data[OPEN]), Double.parseDouble(data[HIGH]), Double.parseDouble(data[LOW]), // Double.parseDouble(data[CLOSE]), Double.parseDouble(data[VOLUME])); // ticks.add(tick); // } // bufferedReader.close(); // } catch (IOException e) { // throw new RuntimeException(e); // } // return ticks; // } // } // // Path: src/test/java/au/net/woodberry/ta/toolbox/indicators/Assertions.java // public static void assertDecimalEquals(TADecimal actual, String expected) { // if (expected != null) { // assertNotNull(actual); // assertThat(actual).isEqualTo(TADecimal.valueOf(expected)); // } else { // assertNull(actual); // } // }
import au.net.woodberry.ta.toolbox.indicators.StubDataTestUtils; import eu.verdelhan.ta4j.TADecimal; import eu.verdelhan.ta4j.TimeSeries; import eu.verdelhan.ta4j.indicators.simple.ClosePriceIndicator; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.junit.Test; import static au.net.woodberry.ta.toolbox.indicators.Assertions.assertDecimalEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull;
public void testNullAtrIndicatorThrowsException() { TimeSeries data = new TimeSeries(StubDataTestUtils.createTickData("/TEST_TRADERS_ATR_STOP_LOSS_TC1.stub", DTF)); new TradersATRStopLossIndicator(null, new ClosePriceIndicator(data), DISPLACEMENT_FACTOR); } @Test(expected = IllegalArgumentException.class) public void testNullReferenceIndicatorThrowsException() { TimeSeries data = new TimeSeries(StubDataTestUtils.createTickData("/TEST_TRADERS_ATR_STOP_LOSS_TC1.stub", DTF)); new TradersATRStopLossIndicator(new AverageTrueRangeIndicator(data, LOOKBACK_PERIODS), null, DISPLACEMENT_FACTOR); } @Test(expected = IllegalArgumentException.class) public void testZeroDisplacementFactorThrowsException() { TimeSeries data = new TimeSeries(StubDataTestUtils.createTickData("/TEST_TRADERS_ATR_STOP_LOSS_TC1.stub", DTF)); new TradersATRStopLossIndicator(new AverageTrueRangeIndicator(data, LOOKBACK_PERIODS), new ClosePriceIndicator(data), 0); } @Test public void testTradersAtrStopLossLessThanAtrLookBackValueIsNull() { TimeSeries data = new TimeSeries(StubDataTestUtils.createTickData("/TEST_TRADERS_ATR_STOP_LOSS_TC1.stub", DTF)); TradersATRStopLossIndicator tradersAtrStopLossIndicator = new TradersATRStopLossIndicator(new AverageTrueRangeIndicator(data, LOOKBACK_PERIODS), new ClosePriceIndicator(data), DISPLACEMENT_FACTOR); assertNull(tradersAtrStopLossIndicator.getValue(13)); } @Test public void testTradersAtrStopLossValueAtLookBackPosition() { TimeSeries data = new TimeSeries(StubDataTestUtils.createTickData("/TEST_TRADERS_ATR_STOP_LOSS_TC1.stub", DTF)); TradersATRStopLossIndicator tradersAtrStopLossIndicator = new TradersATRStopLossIndicator(new AverageTrueRangeIndicator(data, LOOKBACK_PERIODS), new ClosePriceIndicator(data), DISPLACEMENT_FACTOR); TADecimal tradersAtr = tradersAtrStopLossIndicator.getValue(14); assertNotNull(tradersAtr);
// Path: src/test/java/au/net/woodberry/ta/toolbox/indicators/StubDataTestUtils.java // public class StubDataTestUtils { // // private static final String SEPARATOR = ","; // private static final String COMMENT_LINE = "#"; // private static final int TIMESTAMP = 0; // private static final int OPEN = 1; // private static final int HIGH = 2; // private static final int LOW = 3; // private static final int CLOSE = 4; // private static final int VOLUME = 5; // // private StubDataTestUtils() {} // // public static List<Tick> createTickData(String stubData) { // return createTickData(stubData, SEPARATOR, null, null); // } // // public static List<Tick> createTickData(String stubData, DateTimeFormatter dtf) { // return createTickData(stubData, SEPARATOR, null, dtf); // } // // public static List<Tick> createTickData(String stubData, String separator, Pattern header, DateTimeFormatter dtf) { // List<Tick> ticks = new ArrayList<>(); // BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(StubDataTestUtils.class.getResourceAsStream(stubData))); // String line; // try { // while ((line = bufferedReader.readLine()) != null) { // String[] data = line.split(separator); // if (data == null || (header != null && header.matcher(line).matches()) || line.startsWith(COMMENT_LINE)) { // Headers, comments, no data // continue; // } // DateTime dt = dtf != null ? DateTime.parse(data[TIMESTAMP], dtf) : DateTime.parse(data[TIMESTAMP]); // Tick tick = new Tick(dt, Double.parseDouble(data[OPEN]), Double.parseDouble(data[HIGH]), Double.parseDouble(data[LOW]), // Double.parseDouble(data[CLOSE]), Double.parseDouble(data[VOLUME])); // ticks.add(tick); // } // bufferedReader.close(); // } catch (IOException e) { // throw new RuntimeException(e); // } // return ticks; // } // } // // Path: src/test/java/au/net/woodberry/ta/toolbox/indicators/Assertions.java // public static void assertDecimalEquals(TADecimal actual, String expected) { // if (expected != null) { // assertNotNull(actual); // assertThat(actual).isEqualTo(TADecimal.valueOf(expected)); // } else { // assertNull(actual); // } // } // Path: src/test/java/au/net/woodberry/ta/toolbox/indicators/volatility/TradersATRStopLossIndicatorTest.java import au.net.woodberry.ta.toolbox.indicators.StubDataTestUtils; import eu.verdelhan.ta4j.TADecimal; import eu.verdelhan.ta4j.TimeSeries; import eu.verdelhan.ta4j.indicators.simple.ClosePriceIndicator; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.junit.Test; import static au.net.woodberry.ta.toolbox.indicators.Assertions.assertDecimalEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; public void testNullAtrIndicatorThrowsException() { TimeSeries data = new TimeSeries(StubDataTestUtils.createTickData("/TEST_TRADERS_ATR_STOP_LOSS_TC1.stub", DTF)); new TradersATRStopLossIndicator(null, new ClosePriceIndicator(data), DISPLACEMENT_FACTOR); } @Test(expected = IllegalArgumentException.class) public void testNullReferenceIndicatorThrowsException() { TimeSeries data = new TimeSeries(StubDataTestUtils.createTickData("/TEST_TRADERS_ATR_STOP_LOSS_TC1.stub", DTF)); new TradersATRStopLossIndicator(new AverageTrueRangeIndicator(data, LOOKBACK_PERIODS), null, DISPLACEMENT_FACTOR); } @Test(expected = IllegalArgumentException.class) public void testZeroDisplacementFactorThrowsException() { TimeSeries data = new TimeSeries(StubDataTestUtils.createTickData("/TEST_TRADERS_ATR_STOP_LOSS_TC1.stub", DTF)); new TradersATRStopLossIndicator(new AverageTrueRangeIndicator(data, LOOKBACK_PERIODS), new ClosePriceIndicator(data), 0); } @Test public void testTradersAtrStopLossLessThanAtrLookBackValueIsNull() { TimeSeries data = new TimeSeries(StubDataTestUtils.createTickData("/TEST_TRADERS_ATR_STOP_LOSS_TC1.stub", DTF)); TradersATRStopLossIndicator tradersAtrStopLossIndicator = new TradersATRStopLossIndicator(new AverageTrueRangeIndicator(data, LOOKBACK_PERIODS), new ClosePriceIndicator(data), DISPLACEMENT_FACTOR); assertNull(tradersAtrStopLossIndicator.getValue(13)); } @Test public void testTradersAtrStopLossValueAtLookBackPosition() { TimeSeries data = new TimeSeries(StubDataTestUtils.createTickData("/TEST_TRADERS_ATR_STOP_LOSS_TC1.stub", DTF)); TradersATRStopLossIndicator tradersAtrStopLossIndicator = new TradersATRStopLossIndicator(new AverageTrueRangeIndicator(data, LOOKBACK_PERIODS), new ClosePriceIndicator(data), DISPLACEMENT_FACTOR); TADecimal tradersAtr = tradersAtrStopLossIndicator.getValue(14); assertNotNull(tradersAtr);
assertDecimalEquals(tradersAtr, 5742.2857);
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/carbon/CarbonServerHandler.java
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/config/Rollup.java // public class Rollup { // // private int rollup; // private int period; // // public Rollup(String s) { // String[] ss = s.split(":"); // rollup = Integer.parseInt(ss[0].substring(0, ss[0].length() - 1)); // period = (int) (Long.parseLong(ss[1].substring(0, ss[1].length() - 1)) / rollup); // } // // public int getRollup() { // return rollup; // } // // public void setRollup(int rollup) { // this.rollup = rollup; // } // // public int getPeriod() { // return period; // } // // public void setPeriod(int period) { // this.period = period; // } // // @Override // public String toString() { // return "Rollup{" + // "rollup=" + rollup + // ", period=" + period + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/MetricReceivedEvent.java // public class MetricReceivedEvent extends AbstractMetricEvent { // // public MetricReceivedEvent(Metric metric) { // super(metric); // } // }
import com.google.common.base.CharMatcher; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.CharsetUtil; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.config.Rollup; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.MetricReceivedEvent; import org.apache.log4j.Logger;
package net.iponweb.disthene.carbon; /** * @author Andrei Ivanov */ public class CarbonServerHandler extends ChannelInboundHandlerAdapter { private Logger logger = Logger.getLogger(CarbonServerHandler.class);
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/config/Rollup.java // public class Rollup { // // private int rollup; // private int period; // // public Rollup(String s) { // String[] ss = s.split(":"); // rollup = Integer.parseInt(ss[0].substring(0, ss[0].length() - 1)); // period = (int) (Long.parseLong(ss[1].substring(0, ss[1].length() - 1)) / rollup); // } // // public int getRollup() { // return rollup; // } // // public void setRollup(int rollup) { // this.rollup = rollup; // } // // public int getPeriod() { // return period; // } // // public void setPeriod(int period) { // this.period = period; // } // // @Override // public String toString() { // return "Rollup{" + // "rollup=" + rollup + // ", period=" + period + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/MetricReceivedEvent.java // public class MetricReceivedEvent extends AbstractMetricEvent { // // public MetricReceivedEvent(Metric metric) { // super(metric); // } // } // Path: src/main/java/net/iponweb/disthene/carbon/CarbonServerHandler.java import com.google.common.base.CharMatcher; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.CharsetUtil; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.config.Rollup; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.MetricReceivedEvent; import org.apache.log4j.Logger; package net.iponweb.disthene.carbon; /** * @author Andrei Ivanov */ public class CarbonServerHandler extends ChannelInboundHandlerAdapter { private Logger logger = Logger.getLogger(CarbonServerHandler.class);
private MBassador<DistheneEvent> bus;
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/carbon/CarbonServerHandler.java
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/config/Rollup.java // public class Rollup { // // private int rollup; // private int period; // // public Rollup(String s) { // String[] ss = s.split(":"); // rollup = Integer.parseInt(ss[0].substring(0, ss[0].length() - 1)); // period = (int) (Long.parseLong(ss[1].substring(0, ss[1].length() - 1)) / rollup); // } // // public int getRollup() { // return rollup; // } // // public void setRollup(int rollup) { // this.rollup = rollup; // } // // public int getPeriod() { // return period; // } // // public void setPeriod(int period) { // this.period = period; // } // // @Override // public String toString() { // return "Rollup{" + // "rollup=" + rollup + // ", period=" + period + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/MetricReceivedEvent.java // public class MetricReceivedEvent extends AbstractMetricEvent { // // public MetricReceivedEvent(Metric metric) { // super(metric); // } // }
import com.google.common.base.CharMatcher; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.CharsetUtil; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.config.Rollup; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.MetricReceivedEvent; import org.apache.log4j.Logger;
package net.iponweb.disthene.carbon; /** * @author Andrei Ivanov */ public class CarbonServerHandler extends ChannelInboundHandlerAdapter { private Logger logger = Logger.getLogger(CarbonServerHandler.class); private MBassador<DistheneEvent> bus;
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/config/Rollup.java // public class Rollup { // // private int rollup; // private int period; // // public Rollup(String s) { // String[] ss = s.split(":"); // rollup = Integer.parseInt(ss[0].substring(0, ss[0].length() - 1)); // period = (int) (Long.parseLong(ss[1].substring(0, ss[1].length() - 1)) / rollup); // } // // public int getRollup() { // return rollup; // } // // public void setRollup(int rollup) { // this.rollup = rollup; // } // // public int getPeriod() { // return period; // } // // public void setPeriod(int period) { // this.period = period; // } // // @Override // public String toString() { // return "Rollup{" + // "rollup=" + rollup + // ", period=" + period + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/MetricReceivedEvent.java // public class MetricReceivedEvent extends AbstractMetricEvent { // // public MetricReceivedEvent(Metric metric) { // super(metric); // } // } // Path: src/main/java/net/iponweb/disthene/carbon/CarbonServerHandler.java import com.google.common.base.CharMatcher; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.CharsetUtil; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.config.Rollup; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.MetricReceivedEvent; import org.apache.log4j.Logger; package net.iponweb.disthene.carbon; /** * @author Andrei Ivanov */ public class CarbonServerHandler extends ChannelInboundHandlerAdapter { private Logger logger = Logger.getLogger(CarbonServerHandler.class); private MBassador<DistheneEvent> bus;
private Rollup rollup;
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/carbon/CarbonServerHandler.java
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/config/Rollup.java // public class Rollup { // // private int rollup; // private int period; // // public Rollup(String s) { // String[] ss = s.split(":"); // rollup = Integer.parseInt(ss[0].substring(0, ss[0].length() - 1)); // period = (int) (Long.parseLong(ss[1].substring(0, ss[1].length() - 1)) / rollup); // } // // public int getRollup() { // return rollup; // } // // public void setRollup(int rollup) { // this.rollup = rollup; // } // // public int getPeriod() { // return period; // } // // public void setPeriod(int period) { // this.period = period; // } // // @Override // public String toString() { // return "Rollup{" + // "rollup=" + rollup + // ", period=" + period + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/MetricReceivedEvent.java // public class MetricReceivedEvent extends AbstractMetricEvent { // // public MetricReceivedEvent(Metric metric) { // super(metric); // } // }
import com.google.common.base.CharMatcher; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.CharsetUtil; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.config.Rollup; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.MetricReceivedEvent; import org.apache.log4j.Logger;
package net.iponweb.disthene.carbon; /** * @author Andrei Ivanov */ public class CarbonServerHandler extends ChannelInboundHandlerAdapter { private Logger logger = Logger.getLogger(CarbonServerHandler.class); private MBassador<DistheneEvent> bus; private Rollup rollup; public CarbonServerHandler(MBassador<DistheneEvent> bus, Rollup rollup) { this.bus = bus; this.rollup = rollup; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf in = (ByteBuf) msg; try {
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/config/Rollup.java // public class Rollup { // // private int rollup; // private int period; // // public Rollup(String s) { // String[] ss = s.split(":"); // rollup = Integer.parseInt(ss[0].substring(0, ss[0].length() - 1)); // period = (int) (Long.parseLong(ss[1].substring(0, ss[1].length() - 1)) / rollup); // } // // public int getRollup() { // return rollup; // } // // public void setRollup(int rollup) { // this.rollup = rollup; // } // // public int getPeriod() { // return period; // } // // public void setPeriod(int period) { // this.period = period; // } // // @Override // public String toString() { // return "Rollup{" + // "rollup=" + rollup + // ", period=" + period + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/MetricReceivedEvent.java // public class MetricReceivedEvent extends AbstractMetricEvent { // // public MetricReceivedEvent(Metric metric) { // super(metric); // } // } // Path: src/main/java/net/iponweb/disthene/carbon/CarbonServerHandler.java import com.google.common.base.CharMatcher; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.CharsetUtil; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.config.Rollup; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.MetricReceivedEvent; import org.apache.log4j.Logger; package net.iponweb.disthene.carbon; /** * @author Andrei Ivanov */ public class CarbonServerHandler extends ChannelInboundHandlerAdapter { private Logger logger = Logger.getLogger(CarbonServerHandler.class); private MBassador<DistheneEvent> bus; private Rollup rollup; public CarbonServerHandler(MBassador<DistheneEvent> bus, Rollup rollup) { this.bus = bus; this.rollup = rollup; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf in = (ByteBuf) msg; try {
final Metric metric = new Metric(in.toString(CharsetUtil.UTF_8).trim(), rollup);
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/carbon/CarbonServerHandler.java
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/config/Rollup.java // public class Rollup { // // private int rollup; // private int period; // // public Rollup(String s) { // String[] ss = s.split(":"); // rollup = Integer.parseInt(ss[0].substring(0, ss[0].length() - 1)); // period = (int) (Long.parseLong(ss[1].substring(0, ss[1].length() - 1)) / rollup); // } // // public int getRollup() { // return rollup; // } // // public void setRollup(int rollup) { // this.rollup = rollup; // } // // public int getPeriod() { // return period; // } // // public void setPeriod(int period) { // this.period = period; // } // // @Override // public String toString() { // return "Rollup{" + // "rollup=" + rollup + // ", period=" + period + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/MetricReceivedEvent.java // public class MetricReceivedEvent extends AbstractMetricEvent { // // public MetricReceivedEvent(Metric metric) { // super(metric); // } // }
import com.google.common.base.CharMatcher; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.CharsetUtil; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.config.Rollup; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.MetricReceivedEvent; import org.apache.log4j.Logger;
package net.iponweb.disthene.carbon; /** * @author Andrei Ivanov */ public class CarbonServerHandler extends ChannelInboundHandlerAdapter { private Logger logger = Logger.getLogger(CarbonServerHandler.class); private MBassador<DistheneEvent> bus; private Rollup rollup; public CarbonServerHandler(MBassador<DistheneEvent> bus, Rollup rollup) { this.bus = bus; this.rollup = rollup; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf in = (ByteBuf) msg; try { final Metric metric = new Metric(in.toString(CharsetUtil.UTF_8).trim(), rollup); if ((System.currentTimeMillis() / 1000L) - metric.getTimestamp() > 3600) { logger.warn("Metric is from distant past (older than 1 hour): " + metric); } if (CharMatcher.ASCII.matchesAllOf(metric.getPath()) && CharMatcher.ASCII.matchesAllOf(metric.getTenant())) {
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/config/Rollup.java // public class Rollup { // // private int rollup; // private int period; // // public Rollup(String s) { // String[] ss = s.split(":"); // rollup = Integer.parseInt(ss[0].substring(0, ss[0].length() - 1)); // period = (int) (Long.parseLong(ss[1].substring(0, ss[1].length() - 1)) / rollup); // } // // public int getRollup() { // return rollup; // } // // public void setRollup(int rollup) { // this.rollup = rollup; // } // // public int getPeriod() { // return period; // } // // public void setPeriod(int period) { // this.period = period; // } // // @Override // public String toString() { // return "Rollup{" + // "rollup=" + rollup + // ", period=" + period + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/MetricReceivedEvent.java // public class MetricReceivedEvent extends AbstractMetricEvent { // // public MetricReceivedEvent(Metric metric) { // super(metric); // } // } // Path: src/main/java/net/iponweb/disthene/carbon/CarbonServerHandler.java import com.google.common.base.CharMatcher; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.CharsetUtil; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.config.Rollup; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.MetricReceivedEvent; import org.apache.log4j.Logger; package net.iponweb.disthene.carbon; /** * @author Andrei Ivanov */ public class CarbonServerHandler extends ChannelInboundHandlerAdapter { private Logger logger = Logger.getLogger(CarbonServerHandler.class); private MBassador<DistheneEvent> bus; private Rollup rollup; public CarbonServerHandler(MBassador<DistheneEvent> bus, Rollup rollup) { this.bus = bus; this.rollup = rollup; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf in = (ByteBuf) msg; try { final Metric metric = new Metric(in.toString(CharsetUtil.UTF_8).trim(), rollup); if ((System.currentTimeMillis() / 1000L) - metric.getTimestamp() > 3600) { logger.warn("Metric is from distant past (older than 1 hour): " + metric); } if (CharMatcher.ASCII.matchesAllOf(metric.getPath()) && CharMatcher.ASCII.matchesAllOf(metric.getTenant())) {
bus.post(new MetricReceivedEvent(metric)).now();
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/service/store/BatchWriterThread.java
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/StoreErrorEvent.java // public class StoreErrorEvent implements DistheneEvent { // // private int count; // // public StoreErrorEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // // Path: src/main/java/net/iponweb/disthene/events/StoreSuccessEvent.java // public class StoreSuccessEvent implements DistheneEvent{ // // private int count; // // public StoreSuccessEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // }
import com.datastax.driver.core.*; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.StoreErrorEvent; import net.iponweb.disthene.events.StoreSuccessEvent; import org.apache.log4j.Logger; import java.util.*; import java.util.concurrent.Executor;
package net.iponweb.disthene.service.store; /** * @author Andrei Ivanov */ class BatchWriterThread extends WriterThread { //todo: interval via config? private static final long INTERVAL = 60_000; private Logger logger = Logger.getLogger(BatchWriterThread.class); private int batchSize; private List<Statement> statements = new LinkedList<>(); private long lastFlushTimestamp = System.currentTimeMillis();
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/StoreErrorEvent.java // public class StoreErrorEvent implements DistheneEvent { // // private int count; // // public StoreErrorEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // // Path: src/main/java/net/iponweb/disthene/events/StoreSuccessEvent.java // public class StoreSuccessEvent implements DistheneEvent{ // // private int count; // // public StoreSuccessEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // Path: src/main/java/net/iponweb/disthene/service/store/BatchWriterThread.java import com.datastax.driver.core.*; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.StoreErrorEvent; import net.iponweb.disthene.events.StoreSuccessEvent; import org.apache.log4j.Logger; import java.util.*; import java.util.concurrent.Executor; package net.iponweb.disthene.service.store; /** * @author Andrei Ivanov */ class BatchWriterThread extends WriterThread { //todo: interval via config? private static final long INTERVAL = 60_000; private Logger logger = Logger.getLogger(BatchWriterThread.class); private int batchSize; private List<Statement> statements = new LinkedList<>(); private long lastFlushTimestamp = System.currentTimeMillis();
BatchWriterThread(String name, MBassador<DistheneEvent> bus, Session session, PreparedStatement statement, Queue<Metric> metrics, Executor executor, int batchSize) {
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/service/store/BatchWriterThread.java
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/StoreErrorEvent.java // public class StoreErrorEvent implements DistheneEvent { // // private int count; // // public StoreErrorEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // // Path: src/main/java/net/iponweb/disthene/events/StoreSuccessEvent.java // public class StoreSuccessEvent implements DistheneEvent{ // // private int count; // // public StoreSuccessEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // }
import com.datastax.driver.core.*; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.StoreErrorEvent; import net.iponweb.disthene.events.StoreSuccessEvent; import org.apache.log4j.Logger; import java.util.*; import java.util.concurrent.Executor;
package net.iponweb.disthene.service.store; /** * @author Andrei Ivanov */ class BatchWriterThread extends WriterThread { //todo: interval via config? private static final long INTERVAL = 60_000; private Logger logger = Logger.getLogger(BatchWriterThread.class); private int batchSize; private List<Statement> statements = new LinkedList<>(); private long lastFlushTimestamp = System.currentTimeMillis();
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/StoreErrorEvent.java // public class StoreErrorEvent implements DistheneEvent { // // private int count; // // public StoreErrorEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // // Path: src/main/java/net/iponweb/disthene/events/StoreSuccessEvent.java // public class StoreSuccessEvent implements DistheneEvent{ // // private int count; // // public StoreSuccessEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // Path: src/main/java/net/iponweb/disthene/service/store/BatchWriterThread.java import com.datastax.driver.core.*; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.StoreErrorEvent; import net.iponweb.disthene.events.StoreSuccessEvent; import org.apache.log4j.Logger; import java.util.*; import java.util.concurrent.Executor; package net.iponweb.disthene.service.store; /** * @author Andrei Ivanov */ class BatchWriterThread extends WriterThread { //todo: interval via config? private static final long INTERVAL = 60_000; private Logger logger = Logger.getLogger(BatchWriterThread.class); private int batchSize; private List<Statement> statements = new LinkedList<>(); private long lastFlushTimestamp = System.currentTimeMillis();
BatchWriterThread(String name, MBassador<DistheneEvent> bus, Session session, PreparedStatement statement, Queue<Metric> metrics, Executor executor, int batchSize) {
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/service/store/BatchWriterThread.java
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/StoreErrorEvent.java // public class StoreErrorEvent implements DistheneEvent { // // private int count; // // public StoreErrorEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // // Path: src/main/java/net/iponweb/disthene/events/StoreSuccessEvent.java // public class StoreSuccessEvent implements DistheneEvent{ // // private int count; // // public StoreSuccessEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // }
import com.datastax.driver.core.*; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.StoreErrorEvent; import net.iponweb.disthene.events.StoreSuccessEvent; import org.apache.log4j.Logger; import java.util.*; import java.util.concurrent.Executor;
metric.getTenant(), metric.getRollup(), metric.getPeriod(), metric.getPath(), metric.getTimestamp() ) ); if (statements.size() >= batchSize || (lastFlushTimestamp < System.currentTimeMillis() - INTERVAL)) { lastFlushTimestamp = System.currentTimeMillis(); flush(); } } private void flush() { List<List<Statement>> batches = splitByToken(); for (List<Statement> batchStatements : batches) { BatchStatement batch = new BatchStatement(BatchStatement.Type.UNLOGGED); final int batchSize = batchStatements.size(); for (Statement s : batchStatements) { batch.add(s); } ResultSetFuture future = session.executeAsync(batch); Futures.addCallback(future, new FutureCallback<ResultSet>() { @Override public void onSuccess(ResultSet result) {
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/StoreErrorEvent.java // public class StoreErrorEvent implements DistheneEvent { // // private int count; // // public StoreErrorEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // // Path: src/main/java/net/iponweb/disthene/events/StoreSuccessEvent.java // public class StoreSuccessEvent implements DistheneEvent{ // // private int count; // // public StoreSuccessEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // Path: src/main/java/net/iponweb/disthene/service/store/BatchWriterThread.java import com.datastax.driver.core.*; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.StoreErrorEvent; import net.iponweb.disthene.events.StoreSuccessEvent; import org.apache.log4j.Logger; import java.util.*; import java.util.concurrent.Executor; metric.getTenant(), metric.getRollup(), metric.getPeriod(), metric.getPath(), metric.getTimestamp() ) ); if (statements.size() >= batchSize || (lastFlushTimestamp < System.currentTimeMillis() - INTERVAL)) { lastFlushTimestamp = System.currentTimeMillis(); flush(); } } private void flush() { List<List<Statement>> batches = splitByToken(); for (List<Statement> batchStatements : batches) { BatchStatement batch = new BatchStatement(BatchStatement.Type.UNLOGGED); final int batchSize = batchStatements.size(); for (Statement s : batchStatements) { batch.add(s); } ResultSetFuture future = session.executeAsync(batch); Futures.addCallback(future, new FutureCallback<ResultSet>() { @Override public void onSuccess(ResultSet result) {
bus.post(new StoreSuccessEvent(batchSize)).now();
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/service/store/BatchWriterThread.java
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/StoreErrorEvent.java // public class StoreErrorEvent implements DistheneEvent { // // private int count; // // public StoreErrorEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // // Path: src/main/java/net/iponweb/disthene/events/StoreSuccessEvent.java // public class StoreSuccessEvent implements DistheneEvent{ // // private int count; // // public StoreSuccessEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // }
import com.datastax.driver.core.*; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.StoreErrorEvent; import net.iponweb.disthene.events.StoreSuccessEvent; import org.apache.log4j.Logger; import java.util.*; import java.util.concurrent.Executor;
) ); if (statements.size() >= batchSize || (lastFlushTimestamp < System.currentTimeMillis() - INTERVAL)) { lastFlushTimestamp = System.currentTimeMillis(); flush(); } } private void flush() { List<List<Statement>> batches = splitByToken(); for (List<Statement> batchStatements : batches) { BatchStatement batch = new BatchStatement(BatchStatement.Type.UNLOGGED); final int batchSize = batchStatements.size(); for (Statement s : batchStatements) { batch.add(s); } ResultSetFuture future = session.executeAsync(batch); Futures.addCallback(future, new FutureCallback<ResultSet>() { @Override public void onSuccess(ResultSet result) { bus.post(new StoreSuccessEvent(batchSize)).now(); } @Override public void onFailure(Throwable t) {
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/StoreErrorEvent.java // public class StoreErrorEvent implements DistheneEvent { // // private int count; // // public StoreErrorEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // // Path: src/main/java/net/iponweb/disthene/events/StoreSuccessEvent.java // public class StoreSuccessEvent implements DistheneEvent{ // // private int count; // // public StoreSuccessEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // Path: src/main/java/net/iponweb/disthene/service/store/BatchWriterThread.java import com.datastax.driver.core.*; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.StoreErrorEvent; import net.iponweb.disthene.events.StoreSuccessEvent; import org.apache.log4j.Logger; import java.util.*; import java.util.concurrent.Executor; ) ); if (statements.size() >= batchSize || (lastFlushTimestamp < System.currentTimeMillis() - INTERVAL)) { lastFlushTimestamp = System.currentTimeMillis(); flush(); } } private void flush() { List<List<Statement>> batches = splitByToken(); for (List<Statement> batchStatements : batches) { BatchStatement batch = new BatchStatement(BatchStatement.Type.UNLOGGED); final int batchSize = batchStatements.size(); for (Statement s : batchStatements) { batch.add(s); } ResultSetFuture future = session.executeAsync(batch); Futures.addCallback(future, new FutureCallback<ResultSet>() { @Override public void onSuccess(ResultSet result) { bus.post(new StoreSuccessEvent(batchSize)).now(); } @Override public void onFailure(Throwable t) {
bus.post(new StoreErrorEvent(batchSize)).now();
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/service/metric/MetricService.java
// Path: src/main/java/net/iponweb/disthene/service/blacklist/BlacklistService.java // public class BlacklistService { // // private Map<String, Pattern> rules = new HashMap<>(); // // public BlacklistService(BlackListConfiguration blackListConfiguration) { // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // } // // public boolean isBlackListed(Metric metric) { // Pattern pattern = rules.get(metric.getTenant()); // if (pattern != null) { // Matcher matcher = pattern.matcher(metric.getPath()); // return matcher.matches(); // } else { // return false; // } // } // // public void setRules(BlackListConfiguration blackListConfiguration) { // Map<String, Pattern> rules = new HashMap<>(); // // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // // this.rules = rules; // } // } // // Path: src/main/java/net/iponweb/disthene/config/DistheneConfiguration.java // @SuppressWarnings("UnusedDeclaration") // public final class DistheneConfiguration { // private CarbonConfiguration carbon; // private StoreConfiguration store; // private IndexConfiguration index; // private StatsConfiguration stats; // // // public CarbonConfiguration getCarbon() { // return carbon; // } // // public void setCarbon(CarbonConfiguration carbon) { // this.carbon = carbon; // } // // public StoreConfiguration getStore() { // return store; // } // // public void setStore(StoreConfiguration store) { // this.store = store; // } // // public IndexConfiguration getIndex() { // return index; // } // // public void setIndex(IndexConfiguration index) { // this.index = index; // } // // public StatsConfiguration getStats() { // return stats; // } // // public void setStats(StatsConfiguration stats) { // this.stats = stats; // } // // @Override // public String toString() { // return "DistheneConfiguration{" + // "carbon=" + carbon + // ", store=" + store + // ", index=" + index + // ", stats=" + stats + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/MetricAggregateEvent.java // public class MetricAggregateEvent extends AbstractMetricEvent { // // public MetricAggregateEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricReceivedEvent.java // public class MetricReceivedEvent extends AbstractMetricEvent { // // public MetricReceivedEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricStoreEvent.java // public class MetricStoreEvent extends AbstractMetricEvent { // public MetricStoreEvent(Metric metric) { // super(metric); // } // }
import net.engio.mbassy.bus.MBassador; import net.engio.mbassy.listener.Handler; import net.engio.mbassy.listener.Listener; import net.engio.mbassy.listener.References; import net.iponweb.disthene.service.blacklist.BlacklistService; import net.iponweb.disthene.config.DistheneConfiguration; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.MetricAggregateEvent; import net.iponweb.disthene.events.MetricReceivedEvent; import net.iponweb.disthene.events.MetricStoreEvent;
package net.iponweb.disthene.service.metric; /** * @author Andrei Ivanov */ @Listener(references= References.Strong) public class MetricService {
// Path: src/main/java/net/iponweb/disthene/service/blacklist/BlacklistService.java // public class BlacklistService { // // private Map<String, Pattern> rules = new HashMap<>(); // // public BlacklistService(BlackListConfiguration blackListConfiguration) { // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // } // // public boolean isBlackListed(Metric metric) { // Pattern pattern = rules.get(metric.getTenant()); // if (pattern != null) { // Matcher matcher = pattern.matcher(metric.getPath()); // return matcher.matches(); // } else { // return false; // } // } // // public void setRules(BlackListConfiguration blackListConfiguration) { // Map<String, Pattern> rules = new HashMap<>(); // // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // // this.rules = rules; // } // } // // Path: src/main/java/net/iponweb/disthene/config/DistheneConfiguration.java // @SuppressWarnings("UnusedDeclaration") // public final class DistheneConfiguration { // private CarbonConfiguration carbon; // private StoreConfiguration store; // private IndexConfiguration index; // private StatsConfiguration stats; // // // public CarbonConfiguration getCarbon() { // return carbon; // } // // public void setCarbon(CarbonConfiguration carbon) { // this.carbon = carbon; // } // // public StoreConfiguration getStore() { // return store; // } // // public void setStore(StoreConfiguration store) { // this.store = store; // } // // public IndexConfiguration getIndex() { // return index; // } // // public void setIndex(IndexConfiguration index) { // this.index = index; // } // // public StatsConfiguration getStats() { // return stats; // } // // public void setStats(StatsConfiguration stats) { // this.stats = stats; // } // // @Override // public String toString() { // return "DistheneConfiguration{" + // "carbon=" + carbon + // ", store=" + store + // ", index=" + index + // ", stats=" + stats + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/MetricAggregateEvent.java // public class MetricAggregateEvent extends AbstractMetricEvent { // // public MetricAggregateEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricReceivedEvent.java // public class MetricReceivedEvent extends AbstractMetricEvent { // // public MetricReceivedEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricStoreEvent.java // public class MetricStoreEvent extends AbstractMetricEvent { // public MetricStoreEvent(Metric metric) { // super(metric); // } // } // Path: src/main/java/net/iponweb/disthene/service/metric/MetricService.java import net.engio.mbassy.bus.MBassador; import net.engio.mbassy.listener.Handler; import net.engio.mbassy.listener.Listener; import net.engio.mbassy.listener.References; import net.iponweb.disthene.service.blacklist.BlacklistService; import net.iponweb.disthene.config.DistheneConfiguration; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.MetricAggregateEvent; import net.iponweb.disthene.events.MetricReceivedEvent; import net.iponweb.disthene.events.MetricStoreEvent; package net.iponweb.disthene.service.metric; /** * @author Andrei Ivanov */ @Listener(references= References.Strong) public class MetricService {
private MBassador<DistheneEvent> bus;
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/service/metric/MetricService.java
// Path: src/main/java/net/iponweb/disthene/service/blacklist/BlacklistService.java // public class BlacklistService { // // private Map<String, Pattern> rules = new HashMap<>(); // // public BlacklistService(BlackListConfiguration blackListConfiguration) { // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // } // // public boolean isBlackListed(Metric metric) { // Pattern pattern = rules.get(metric.getTenant()); // if (pattern != null) { // Matcher matcher = pattern.matcher(metric.getPath()); // return matcher.matches(); // } else { // return false; // } // } // // public void setRules(BlackListConfiguration blackListConfiguration) { // Map<String, Pattern> rules = new HashMap<>(); // // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // // this.rules = rules; // } // } // // Path: src/main/java/net/iponweb/disthene/config/DistheneConfiguration.java // @SuppressWarnings("UnusedDeclaration") // public final class DistheneConfiguration { // private CarbonConfiguration carbon; // private StoreConfiguration store; // private IndexConfiguration index; // private StatsConfiguration stats; // // // public CarbonConfiguration getCarbon() { // return carbon; // } // // public void setCarbon(CarbonConfiguration carbon) { // this.carbon = carbon; // } // // public StoreConfiguration getStore() { // return store; // } // // public void setStore(StoreConfiguration store) { // this.store = store; // } // // public IndexConfiguration getIndex() { // return index; // } // // public void setIndex(IndexConfiguration index) { // this.index = index; // } // // public StatsConfiguration getStats() { // return stats; // } // // public void setStats(StatsConfiguration stats) { // this.stats = stats; // } // // @Override // public String toString() { // return "DistheneConfiguration{" + // "carbon=" + carbon + // ", store=" + store + // ", index=" + index + // ", stats=" + stats + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/MetricAggregateEvent.java // public class MetricAggregateEvent extends AbstractMetricEvent { // // public MetricAggregateEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricReceivedEvent.java // public class MetricReceivedEvent extends AbstractMetricEvent { // // public MetricReceivedEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricStoreEvent.java // public class MetricStoreEvent extends AbstractMetricEvent { // public MetricStoreEvent(Metric metric) { // super(metric); // } // }
import net.engio.mbassy.bus.MBassador; import net.engio.mbassy.listener.Handler; import net.engio.mbassy.listener.Listener; import net.engio.mbassy.listener.References; import net.iponweb.disthene.service.blacklist.BlacklistService; import net.iponweb.disthene.config.DistheneConfiguration; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.MetricAggregateEvent; import net.iponweb.disthene.events.MetricReceivedEvent; import net.iponweb.disthene.events.MetricStoreEvent;
package net.iponweb.disthene.service.metric; /** * @author Andrei Ivanov */ @Listener(references= References.Strong) public class MetricService { private MBassador<DistheneEvent> bus;
// Path: src/main/java/net/iponweb/disthene/service/blacklist/BlacklistService.java // public class BlacklistService { // // private Map<String, Pattern> rules = new HashMap<>(); // // public BlacklistService(BlackListConfiguration blackListConfiguration) { // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // } // // public boolean isBlackListed(Metric metric) { // Pattern pattern = rules.get(metric.getTenant()); // if (pattern != null) { // Matcher matcher = pattern.matcher(metric.getPath()); // return matcher.matches(); // } else { // return false; // } // } // // public void setRules(BlackListConfiguration blackListConfiguration) { // Map<String, Pattern> rules = new HashMap<>(); // // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // // this.rules = rules; // } // } // // Path: src/main/java/net/iponweb/disthene/config/DistheneConfiguration.java // @SuppressWarnings("UnusedDeclaration") // public final class DistheneConfiguration { // private CarbonConfiguration carbon; // private StoreConfiguration store; // private IndexConfiguration index; // private StatsConfiguration stats; // // // public CarbonConfiguration getCarbon() { // return carbon; // } // // public void setCarbon(CarbonConfiguration carbon) { // this.carbon = carbon; // } // // public StoreConfiguration getStore() { // return store; // } // // public void setStore(StoreConfiguration store) { // this.store = store; // } // // public IndexConfiguration getIndex() { // return index; // } // // public void setIndex(IndexConfiguration index) { // this.index = index; // } // // public StatsConfiguration getStats() { // return stats; // } // // public void setStats(StatsConfiguration stats) { // this.stats = stats; // } // // @Override // public String toString() { // return "DistheneConfiguration{" + // "carbon=" + carbon + // ", store=" + store + // ", index=" + index + // ", stats=" + stats + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/MetricAggregateEvent.java // public class MetricAggregateEvent extends AbstractMetricEvent { // // public MetricAggregateEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricReceivedEvent.java // public class MetricReceivedEvent extends AbstractMetricEvent { // // public MetricReceivedEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricStoreEvent.java // public class MetricStoreEvent extends AbstractMetricEvent { // public MetricStoreEvent(Metric metric) { // super(metric); // } // } // Path: src/main/java/net/iponweb/disthene/service/metric/MetricService.java import net.engio.mbassy.bus.MBassador; import net.engio.mbassy.listener.Handler; import net.engio.mbassy.listener.Listener; import net.engio.mbassy.listener.References; import net.iponweb.disthene.service.blacklist.BlacklistService; import net.iponweb.disthene.config.DistheneConfiguration; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.MetricAggregateEvent; import net.iponweb.disthene.events.MetricReceivedEvent; import net.iponweb.disthene.events.MetricStoreEvent; package net.iponweb.disthene.service.metric; /** * @author Andrei Ivanov */ @Listener(references= References.Strong) public class MetricService { private MBassador<DistheneEvent> bus;
private BlacklistService blacklistService;
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/service/metric/MetricService.java
// Path: src/main/java/net/iponweb/disthene/service/blacklist/BlacklistService.java // public class BlacklistService { // // private Map<String, Pattern> rules = new HashMap<>(); // // public BlacklistService(BlackListConfiguration blackListConfiguration) { // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // } // // public boolean isBlackListed(Metric metric) { // Pattern pattern = rules.get(metric.getTenant()); // if (pattern != null) { // Matcher matcher = pattern.matcher(metric.getPath()); // return matcher.matches(); // } else { // return false; // } // } // // public void setRules(BlackListConfiguration blackListConfiguration) { // Map<String, Pattern> rules = new HashMap<>(); // // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // // this.rules = rules; // } // } // // Path: src/main/java/net/iponweb/disthene/config/DistheneConfiguration.java // @SuppressWarnings("UnusedDeclaration") // public final class DistheneConfiguration { // private CarbonConfiguration carbon; // private StoreConfiguration store; // private IndexConfiguration index; // private StatsConfiguration stats; // // // public CarbonConfiguration getCarbon() { // return carbon; // } // // public void setCarbon(CarbonConfiguration carbon) { // this.carbon = carbon; // } // // public StoreConfiguration getStore() { // return store; // } // // public void setStore(StoreConfiguration store) { // this.store = store; // } // // public IndexConfiguration getIndex() { // return index; // } // // public void setIndex(IndexConfiguration index) { // this.index = index; // } // // public StatsConfiguration getStats() { // return stats; // } // // public void setStats(StatsConfiguration stats) { // this.stats = stats; // } // // @Override // public String toString() { // return "DistheneConfiguration{" + // "carbon=" + carbon + // ", store=" + store + // ", index=" + index + // ", stats=" + stats + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/MetricAggregateEvent.java // public class MetricAggregateEvent extends AbstractMetricEvent { // // public MetricAggregateEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricReceivedEvent.java // public class MetricReceivedEvent extends AbstractMetricEvent { // // public MetricReceivedEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricStoreEvent.java // public class MetricStoreEvent extends AbstractMetricEvent { // public MetricStoreEvent(Metric metric) { // super(metric); // } // }
import net.engio.mbassy.bus.MBassador; import net.engio.mbassy.listener.Handler; import net.engio.mbassy.listener.Listener; import net.engio.mbassy.listener.References; import net.iponweb.disthene.service.blacklist.BlacklistService; import net.iponweb.disthene.config.DistheneConfiguration; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.MetricAggregateEvent; import net.iponweb.disthene.events.MetricReceivedEvent; import net.iponweb.disthene.events.MetricStoreEvent;
package net.iponweb.disthene.service.metric; /** * @author Andrei Ivanov */ @Listener(references= References.Strong) public class MetricService { private MBassador<DistheneEvent> bus; private BlacklistService blacklistService;
// Path: src/main/java/net/iponweb/disthene/service/blacklist/BlacklistService.java // public class BlacklistService { // // private Map<String, Pattern> rules = new HashMap<>(); // // public BlacklistService(BlackListConfiguration blackListConfiguration) { // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // } // // public boolean isBlackListed(Metric metric) { // Pattern pattern = rules.get(metric.getTenant()); // if (pattern != null) { // Matcher matcher = pattern.matcher(metric.getPath()); // return matcher.matches(); // } else { // return false; // } // } // // public void setRules(BlackListConfiguration blackListConfiguration) { // Map<String, Pattern> rules = new HashMap<>(); // // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // // this.rules = rules; // } // } // // Path: src/main/java/net/iponweb/disthene/config/DistheneConfiguration.java // @SuppressWarnings("UnusedDeclaration") // public final class DistheneConfiguration { // private CarbonConfiguration carbon; // private StoreConfiguration store; // private IndexConfiguration index; // private StatsConfiguration stats; // // // public CarbonConfiguration getCarbon() { // return carbon; // } // // public void setCarbon(CarbonConfiguration carbon) { // this.carbon = carbon; // } // // public StoreConfiguration getStore() { // return store; // } // // public void setStore(StoreConfiguration store) { // this.store = store; // } // // public IndexConfiguration getIndex() { // return index; // } // // public void setIndex(IndexConfiguration index) { // this.index = index; // } // // public StatsConfiguration getStats() { // return stats; // } // // public void setStats(StatsConfiguration stats) { // this.stats = stats; // } // // @Override // public String toString() { // return "DistheneConfiguration{" + // "carbon=" + carbon + // ", store=" + store + // ", index=" + index + // ", stats=" + stats + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/MetricAggregateEvent.java // public class MetricAggregateEvent extends AbstractMetricEvent { // // public MetricAggregateEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricReceivedEvent.java // public class MetricReceivedEvent extends AbstractMetricEvent { // // public MetricReceivedEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricStoreEvent.java // public class MetricStoreEvent extends AbstractMetricEvent { // public MetricStoreEvent(Metric metric) { // super(metric); // } // } // Path: src/main/java/net/iponweb/disthene/service/metric/MetricService.java import net.engio.mbassy.bus.MBassador; import net.engio.mbassy.listener.Handler; import net.engio.mbassy.listener.Listener; import net.engio.mbassy.listener.References; import net.iponweb.disthene.service.blacklist.BlacklistService; import net.iponweb.disthene.config.DistheneConfiguration; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.MetricAggregateEvent; import net.iponweb.disthene.events.MetricReceivedEvent; import net.iponweb.disthene.events.MetricStoreEvent; package net.iponweb.disthene.service.metric; /** * @author Andrei Ivanov */ @Listener(references= References.Strong) public class MetricService { private MBassador<DistheneEvent> bus; private BlacklistService blacklistService;
private DistheneConfiguration distheneConfiguration;
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/service/metric/MetricService.java
// Path: src/main/java/net/iponweb/disthene/service/blacklist/BlacklistService.java // public class BlacklistService { // // private Map<String, Pattern> rules = new HashMap<>(); // // public BlacklistService(BlackListConfiguration blackListConfiguration) { // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // } // // public boolean isBlackListed(Metric metric) { // Pattern pattern = rules.get(metric.getTenant()); // if (pattern != null) { // Matcher matcher = pattern.matcher(metric.getPath()); // return matcher.matches(); // } else { // return false; // } // } // // public void setRules(BlackListConfiguration blackListConfiguration) { // Map<String, Pattern> rules = new HashMap<>(); // // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // // this.rules = rules; // } // } // // Path: src/main/java/net/iponweb/disthene/config/DistheneConfiguration.java // @SuppressWarnings("UnusedDeclaration") // public final class DistheneConfiguration { // private CarbonConfiguration carbon; // private StoreConfiguration store; // private IndexConfiguration index; // private StatsConfiguration stats; // // // public CarbonConfiguration getCarbon() { // return carbon; // } // // public void setCarbon(CarbonConfiguration carbon) { // this.carbon = carbon; // } // // public StoreConfiguration getStore() { // return store; // } // // public void setStore(StoreConfiguration store) { // this.store = store; // } // // public IndexConfiguration getIndex() { // return index; // } // // public void setIndex(IndexConfiguration index) { // this.index = index; // } // // public StatsConfiguration getStats() { // return stats; // } // // public void setStats(StatsConfiguration stats) { // this.stats = stats; // } // // @Override // public String toString() { // return "DistheneConfiguration{" + // "carbon=" + carbon + // ", store=" + store + // ", index=" + index + // ", stats=" + stats + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/MetricAggregateEvent.java // public class MetricAggregateEvent extends AbstractMetricEvent { // // public MetricAggregateEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricReceivedEvent.java // public class MetricReceivedEvent extends AbstractMetricEvent { // // public MetricReceivedEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricStoreEvent.java // public class MetricStoreEvent extends AbstractMetricEvent { // public MetricStoreEvent(Metric metric) { // super(metric); // } // }
import net.engio.mbassy.bus.MBassador; import net.engio.mbassy.listener.Handler; import net.engio.mbassy.listener.Listener; import net.engio.mbassy.listener.References; import net.iponweb.disthene.service.blacklist.BlacklistService; import net.iponweb.disthene.config.DistheneConfiguration; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.MetricAggregateEvent; import net.iponweb.disthene.events.MetricReceivedEvent; import net.iponweb.disthene.events.MetricStoreEvent;
package net.iponweb.disthene.service.metric; /** * @author Andrei Ivanov */ @Listener(references= References.Strong) public class MetricService { private MBassador<DistheneEvent> bus; private BlacklistService blacklistService; private DistheneConfiguration distheneConfiguration; public MetricService(MBassador<DistheneEvent> bus, BlacklistService blacklistService, DistheneConfiguration distheneConfiguration) { this.bus = bus; this.blacklistService = blacklistService; this.distheneConfiguration = distheneConfiguration; bus.subscribe(this); } @Handler(rejectSubtypes = false)
// Path: src/main/java/net/iponweb/disthene/service/blacklist/BlacklistService.java // public class BlacklistService { // // private Map<String, Pattern> rules = new HashMap<>(); // // public BlacklistService(BlackListConfiguration blackListConfiguration) { // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // } // // public boolean isBlackListed(Metric metric) { // Pattern pattern = rules.get(metric.getTenant()); // if (pattern != null) { // Matcher matcher = pattern.matcher(metric.getPath()); // return matcher.matches(); // } else { // return false; // } // } // // public void setRules(BlackListConfiguration blackListConfiguration) { // Map<String, Pattern> rules = new HashMap<>(); // // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // // this.rules = rules; // } // } // // Path: src/main/java/net/iponweb/disthene/config/DistheneConfiguration.java // @SuppressWarnings("UnusedDeclaration") // public final class DistheneConfiguration { // private CarbonConfiguration carbon; // private StoreConfiguration store; // private IndexConfiguration index; // private StatsConfiguration stats; // // // public CarbonConfiguration getCarbon() { // return carbon; // } // // public void setCarbon(CarbonConfiguration carbon) { // this.carbon = carbon; // } // // public StoreConfiguration getStore() { // return store; // } // // public void setStore(StoreConfiguration store) { // this.store = store; // } // // public IndexConfiguration getIndex() { // return index; // } // // public void setIndex(IndexConfiguration index) { // this.index = index; // } // // public StatsConfiguration getStats() { // return stats; // } // // public void setStats(StatsConfiguration stats) { // this.stats = stats; // } // // @Override // public String toString() { // return "DistheneConfiguration{" + // "carbon=" + carbon + // ", store=" + store + // ", index=" + index + // ", stats=" + stats + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/MetricAggregateEvent.java // public class MetricAggregateEvent extends AbstractMetricEvent { // // public MetricAggregateEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricReceivedEvent.java // public class MetricReceivedEvent extends AbstractMetricEvent { // // public MetricReceivedEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricStoreEvent.java // public class MetricStoreEvent extends AbstractMetricEvent { // public MetricStoreEvent(Metric metric) { // super(metric); // } // } // Path: src/main/java/net/iponweb/disthene/service/metric/MetricService.java import net.engio.mbassy.bus.MBassador; import net.engio.mbassy.listener.Handler; import net.engio.mbassy.listener.Listener; import net.engio.mbassy.listener.References; import net.iponweb.disthene.service.blacklist.BlacklistService; import net.iponweb.disthene.config.DistheneConfiguration; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.MetricAggregateEvent; import net.iponweb.disthene.events.MetricReceivedEvent; import net.iponweb.disthene.events.MetricStoreEvent; package net.iponweb.disthene.service.metric; /** * @author Andrei Ivanov */ @Listener(references= References.Strong) public class MetricService { private MBassador<DistheneEvent> bus; private BlacklistService blacklistService; private DistheneConfiguration distheneConfiguration; public MetricService(MBassador<DistheneEvent> bus, BlacklistService blacklistService, DistheneConfiguration distheneConfiguration) { this.bus = bus; this.blacklistService = blacklistService; this.distheneConfiguration = distheneConfiguration; bus.subscribe(this); } @Handler(rejectSubtypes = false)
public void handle(MetricReceivedEvent metricReceivedEvent) {
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/service/metric/MetricService.java
// Path: src/main/java/net/iponweb/disthene/service/blacklist/BlacklistService.java // public class BlacklistService { // // private Map<String, Pattern> rules = new HashMap<>(); // // public BlacklistService(BlackListConfiguration blackListConfiguration) { // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // } // // public boolean isBlackListed(Metric metric) { // Pattern pattern = rules.get(metric.getTenant()); // if (pattern != null) { // Matcher matcher = pattern.matcher(metric.getPath()); // return matcher.matches(); // } else { // return false; // } // } // // public void setRules(BlackListConfiguration blackListConfiguration) { // Map<String, Pattern> rules = new HashMap<>(); // // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // // this.rules = rules; // } // } // // Path: src/main/java/net/iponweb/disthene/config/DistheneConfiguration.java // @SuppressWarnings("UnusedDeclaration") // public final class DistheneConfiguration { // private CarbonConfiguration carbon; // private StoreConfiguration store; // private IndexConfiguration index; // private StatsConfiguration stats; // // // public CarbonConfiguration getCarbon() { // return carbon; // } // // public void setCarbon(CarbonConfiguration carbon) { // this.carbon = carbon; // } // // public StoreConfiguration getStore() { // return store; // } // // public void setStore(StoreConfiguration store) { // this.store = store; // } // // public IndexConfiguration getIndex() { // return index; // } // // public void setIndex(IndexConfiguration index) { // this.index = index; // } // // public StatsConfiguration getStats() { // return stats; // } // // public void setStats(StatsConfiguration stats) { // this.stats = stats; // } // // @Override // public String toString() { // return "DistheneConfiguration{" + // "carbon=" + carbon + // ", store=" + store + // ", index=" + index + // ", stats=" + stats + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/MetricAggregateEvent.java // public class MetricAggregateEvent extends AbstractMetricEvent { // // public MetricAggregateEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricReceivedEvent.java // public class MetricReceivedEvent extends AbstractMetricEvent { // // public MetricReceivedEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricStoreEvent.java // public class MetricStoreEvent extends AbstractMetricEvent { // public MetricStoreEvent(Metric metric) { // super(metric); // } // }
import net.engio.mbassy.bus.MBassador; import net.engio.mbassy.listener.Handler; import net.engio.mbassy.listener.Listener; import net.engio.mbassy.listener.References; import net.iponweb.disthene.service.blacklist.BlacklistService; import net.iponweb.disthene.config.DistheneConfiguration; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.MetricAggregateEvent; import net.iponweb.disthene.events.MetricReceivedEvent; import net.iponweb.disthene.events.MetricStoreEvent;
package net.iponweb.disthene.service.metric; /** * @author Andrei Ivanov */ @Listener(references= References.Strong) public class MetricService { private MBassador<DistheneEvent> bus; private BlacklistService blacklistService; private DistheneConfiguration distheneConfiguration; public MetricService(MBassador<DistheneEvent> bus, BlacklistService blacklistService, DistheneConfiguration distheneConfiguration) { this.bus = bus; this.blacklistService = blacklistService; this.distheneConfiguration = distheneConfiguration; bus.subscribe(this); } @Handler(rejectSubtypes = false) public void handle(MetricReceivedEvent metricReceivedEvent) { if (!blacklistService.isBlackListed(metricReceivedEvent.getMetric())) { if (distheneConfiguration.getCarbon().getAggregateBaseRollup()) {
// Path: src/main/java/net/iponweb/disthene/service/blacklist/BlacklistService.java // public class BlacklistService { // // private Map<String, Pattern> rules = new HashMap<>(); // // public BlacklistService(BlackListConfiguration blackListConfiguration) { // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // } // // public boolean isBlackListed(Metric metric) { // Pattern pattern = rules.get(metric.getTenant()); // if (pattern != null) { // Matcher matcher = pattern.matcher(metric.getPath()); // return matcher.matches(); // } else { // return false; // } // } // // public void setRules(BlackListConfiguration blackListConfiguration) { // Map<String, Pattern> rules = new HashMap<>(); // // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // // this.rules = rules; // } // } // // Path: src/main/java/net/iponweb/disthene/config/DistheneConfiguration.java // @SuppressWarnings("UnusedDeclaration") // public final class DistheneConfiguration { // private CarbonConfiguration carbon; // private StoreConfiguration store; // private IndexConfiguration index; // private StatsConfiguration stats; // // // public CarbonConfiguration getCarbon() { // return carbon; // } // // public void setCarbon(CarbonConfiguration carbon) { // this.carbon = carbon; // } // // public StoreConfiguration getStore() { // return store; // } // // public void setStore(StoreConfiguration store) { // this.store = store; // } // // public IndexConfiguration getIndex() { // return index; // } // // public void setIndex(IndexConfiguration index) { // this.index = index; // } // // public StatsConfiguration getStats() { // return stats; // } // // public void setStats(StatsConfiguration stats) { // this.stats = stats; // } // // @Override // public String toString() { // return "DistheneConfiguration{" + // "carbon=" + carbon + // ", store=" + store + // ", index=" + index + // ", stats=" + stats + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/MetricAggregateEvent.java // public class MetricAggregateEvent extends AbstractMetricEvent { // // public MetricAggregateEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricReceivedEvent.java // public class MetricReceivedEvent extends AbstractMetricEvent { // // public MetricReceivedEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricStoreEvent.java // public class MetricStoreEvent extends AbstractMetricEvent { // public MetricStoreEvent(Metric metric) { // super(metric); // } // } // Path: src/main/java/net/iponweb/disthene/service/metric/MetricService.java import net.engio.mbassy.bus.MBassador; import net.engio.mbassy.listener.Handler; import net.engio.mbassy.listener.Listener; import net.engio.mbassy.listener.References; import net.iponweb.disthene.service.blacklist.BlacklistService; import net.iponweb.disthene.config.DistheneConfiguration; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.MetricAggregateEvent; import net.iponweb.disthene.events.MetricReceivedEvent; import net.iponweb.disthene.events.MetricStoreEvent; package net.iponweb.disthene.service.metric; /** * @author Andrei Ivanov */ @Listener(references= References.Strong) public class MetricService { private MBassador<DistheneEvent> bus; private BlacklistService blacklistService; private DistheneConfiguration distheneConfiguration; public MetricService(MBassador<DistheneEvent> bus, BlacklistService blacklistService, DistheneConfiguration distheneConfiguration) { this.bus = bus; this.blacklistService = blacklistService; this.distheneConfiguration = distheneConfiguration; bus.subscribe(this); } @Handler(rejectSubtypes = false) public void handle(MetricReceivedEvent metricReceivedEvent) { if (!blacklistService.isBlackListed(metricReceivedEvent.getMetric())) { if (distheneConfiguration.getCarbon().getAggregateBaseRollup()) {
bus.post(new MetricAggregateEvent(metricReceivedEvent.getMetric())).now();
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/service/metric/MetricService.java
// Path: src/main/java/net/iponweb/disthene/service/blacklist/BlacklistService.java // public class BlacklistService { // // private Map<String, Pattern> rules = new HashMap<>(); // // public BlacklistService(BlackListConfiguration blackListConfiguration) { // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // } // // public boolean isBlackListed(Metric metric) { // Pattern pattern = rules.get(metric.getTenant()); // if (pattern != null) { // Matcher matcher = pattern.matcher(metric.getPath()); // return matcher.matches(); // } else { // return false; // } // } // // public void setRules(BlackListConfiguration blackListConfiguration) { // Map<String, Pattern> rules = new HashMap<>(); // // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // // this.rules = rules; // } // } // // Path: src/main/java/net/iponweb/disthene/config/DistheneConfiguration.java // @SuppressWarnings("UnusedDeclaration") // public final class DistheneConfiguration { // private CarbonConfiguration carbon; // private StoreConfiguration store; // private IndexConfiguration index; // private StatsConfiguration stats; // // // public CarbonConfiguration getCarbon() { // return carbon; // } // // public void setCarbon(CarbonConfiguration carbon) { // this.carbon = carbon; // } // // public StoreConfiguration getStore() { // return store; // } // // public void setStore(StoreConfiguration store) { // this.store = store; // } // // public IndexConfiguration getIndex() { // return index; // } // // public void setIndex(IndexConfiguration index) { // this.index = index; // } // // public StatsConfiguration getStats() { // return stats; // } // // public void setStats(StatsConfiguration stats) { // this.stats = stats; // } // // @Override // public String toString() { // return "DistheneConfiguration{" + // "carbon=" + carbon + // ", store=" + store + // ", index=" + index + // ", stats=" + stats + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/MetricAggregateEvent.java // public class MetricAggregateEvent extends AbstractMetricEvent { // // public MetricAggregateEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricReceivedEvent.java // public class MetricReceivedEvent extends AbstractMetricEvent { // // public MetricReceivedEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricStoreEvent.java // public class MetricStoreEvent extends AbstractMetricEvent { // public MetricStoreEvent(Metric metric) { // super(metric); // } // }
import net.engio.mbassy.bus.MBassador; import net.engio.mbassy.listener.Handler; import net.engio.mbassy.listener.Listener; import net.engio.mbassy.listener.References; import net.iponweb.disthene.service.blacklist.BlacklistService; import net.iponweb.disthene.config.DistheneConfiguration; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.MetricAggregateEvent; import net.iponweb.disthene.events.MetricReceivedEvent; import net.iponweb.disthene.events.MetricStoreEvent;
package net.iponweb.disthene.service.metric; /** * @author Andrei Ivanov */ @Listener(references= References.Strong) public class MetricService { private MBassador<DistheneEvent> bus; private BlacklistService blacklistService; private DistheneConfiguration distheneConfiguration; public MetricService(MBassador<DistheneEvent> bus, BlacklistService blacklistService, DistheneConfiguration distheneConfiguration) { this.bus = bus; this.blacklistService = blacklistService; this.distheneConfiguration = distheneConfiguration; bus.subscribe(this); } @Handler(rejectSubtypes = false) public void handle(MetricReceivedEvent metricReceivedEvent) { if (!blacklistService.isBlackListed(metricReceivedEvent.getMetric())) { if (distheneConfiguration.getCarbon().getAggregateBaseRollup()) { bus.post(new MetricAggregateEvent(metricReceivedEvent.getMetric())).now(); } else {
// Path: src/main/java/net/iponweb/disthene/service/blacklist/BlacklistService.java // public class BlacklistService { // // private Map<String, Pattern> rules = new HashMap<>(); // // public BlacklistService(BlackListConfiguration blackListConfiguration) { // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // } // // public boolean isBlackListed(Metric metric) { // Pattern pattern = rules.get(metric.getTenant()); // if (pattern != null) { // Matcher matcher = pattern.matcher(metric.getPath()); // return matcher.matches(); // } else { // return false; // } // } // // public void setRules(BlackListConfiguration blackListConfiguration) { // Map<String, Pattern> rules = new HashMap<>(); // // for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { // rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); // } // // this.rules = rules; // } // } // // Path: src/main/java/net/iponweb/disthene/config/DistheneConfiguration.java // @SuppressWarnings("UnusedDeclaration") // public final class DistheneConfiguration { // private CarbonConfiguration carbon; // private StoreConfiguration store; // private IndexConfiguration index; // private StatsConfiguration stats; // // // public CarbonConfiguration getCarbon() { // return carbon; // } // // public void setCarbon(CarbonConfiguration carbon) { // this.carbon = carbon; // } // // public StoreConfiguration getStore() { // return store; // } // // public void setStore(StoreConfiguration store) { // this.store = store; // } // // public IndexConfiguration getIndex() { // return index; // } // // public void setIndex(IndexConfiguration index) { // this.index = index; // } // // public StatsConfiguration getStats() { // return stats; // } // // public void setStats(StatsConfiguration stats) { // this.stats = stats; // } // // @Override // public String toString() { // return "DistheneConfiguration{" + // "carbon=" + carbon + // ", store=" + store + // ", index=" + index + // ", stats=" + stats + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/MetricAggregateEvent.java // public class MetricAggregateEvent extends AbstractMetricEvent { // // public MetricAggregateEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricReceivedEvent.java // public class MetricReceivedEvent extends AbstractMetricEvent { // // public MetricReceivedEvent(Metric metric) { // super(metric); // } // } // // Path: src/main/java/net/iponweb/disthene/events/MetricStoreEvent.java // public class MetricStoreEvent extends AbstractMetricEvent { // public MetricStoreEvent(Metric metric) { // super(metric); // } // } // Path: src/main/java/net/iponweb/disthene/service/metric/MetricService.java import net.engio.mbassy.bus.MBassador; import net.engio.mbassy.listener.Handler; import net.engio.mbassy.listener.Listener; import net.engio.mbassy.listener.References; import net.iponweb.disthene.service.blacklist.BlacklistService; import net.iponweb.disthene.config.DistheneConfiguration; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.MetricAggregateEvent; import net.iponweb.disthene.events.MetricReceivedEvent; import net.iponweb.disthene.events.MetricStoreEvent; package net.iponweb.disthene.service.metric; /** * @author Andrei Ivanov */ @Listener(references= References.Strong) public class MetricService { private MBassador<DistheneEvent> bus; private BlacklistService blacklistService; private DistheneConfiguration distheneConfiguration; public MetricService(MBassador<DistheneEvent> bus, BlacklistService blacklistService, DistheneConfiguration distheneConfiguration) { this.bus = bus; this.blacklistService = blacklistService; this.distheneConfiguration = distheneConfiguration; bus.subscribe(this); } @Handler(rejectSubtypes = false) public void handle(MetricReceivedEvent metricReceivedEvent) { if (!blacklistService.isBlackListed(metricReceivedEvent.getMetric())) { if (distheneConfiguration.getCarbon().getAggregateBaseRollup()) { bus.post(new MetricAggregateEvent(metricReceivedEvent.getMetric())).now(); } else {
bus.post(new MetricStoreEvent(metricReceivedEvent.getMetric())).now();
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/service/blacklist/BlacklistService.java
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/config/BlackListConfiguration.java // public class BlackListConfiguration { // // private Map<String, List<String>> rules = new HashMap<>(); // // public BlackListConfiguration(Map<String, List<String>> rules) { // this.rules = rules; // } // // public Map<String, List<String>> getRules() { // return rules; // } // // public void setRules(Map<String, List<String>> rules) { // this.rules = rules; // } // // @Override // public String toString() { // return "BlackListConfiguration{" + // "rules=" + rules + // '}'; // } // }
import com.google.common.base.Joiner; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.config.BlackListConfiguration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern;
package net.iponweb.disthene.service.blacklist; /** * @author Andrei Ivanov */ public class BlacklistService { private Map<String, Pattern> rules = new HashMap<>();
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/config/BlackListConfiguration.java // public class BlackListConfiguration { // // private Map<String, List<String>> rules = new HashMap<>(); // // public BlackListConfiguration(Map<String, List<String>> rules) { // this.rules = rules; // } // // public Map<String, List<String>> getRules() { // return rules; // } // // public void setRules(Map<String, List<String>> rules) { // this.rules = rules; // } // // @Override // public String toString() { // return "BlackListConfiguration{" + // "rules=" + rules + // '}'; // } // } // Path: src/main/java/net/iponweb/disthene/service/blacklist/BlacklistService.java import com.google.common.base.Joiner; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.config.BlackListConfiguration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; package net.iponweb.disthene.service.blacklist; /** * @author Andrei Ivanov */ public class BlacklistService { private Map<String, Pattern> rules = new HashMap<>();
public BlacklistService(BlackListConfiguration blackListConfiguration) {
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/service/blacklist/BlacklistService.java
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/config/BlackListConfiguration.java // public class BlackListConfiguration { // // private Map<String, List<String>> rules = new HashMap<>(); // // public BlackListConfiguration(Map<String, List<String>> rules) { // this.rules = rules; // } // // public Map<String, List<String>> getRules() { // return rules; // } // // public void setRules(Map<String, List<String>> rules) { // this.rules = rules; // } // // @Override // public String toString() { // return "BlackListConfiguration{" + // "rules=" + rules + // '}'; // } // }
import com.google.common.base.Joiner; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.config.BlackListConfiguration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern;
package net.iponweb.disthene.service.blacklist; /** * @author Andrei Ivanov */ public class BlacklistService { private Map<String, Pattern> rules = new HashMap<>(); public BlacklistService(BlackListConfiguration blackListConfiguration) { for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); } }
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/config/BlackListConfiguration.java // public class BlackListConfiguration { // // private Map<String, List<String>> rules = new HashMap<>(); // // public BlackListConfiguration(Map<String, List<String>> rules) { // this.rules = rules; // } // // public Map<String, List<String>> getRules() { // return rules; // } // // public void setRules(Map<String, List<String>> rules) { // this.rules = rules; // } // // @Override // public String toString() { // return "BlackListConfiguration{" + // "rules=" + rules + // '}'; // } // } // Path: src/main/java/net/iponweb/disthene/service/blacklist/BlacklistService.java import com.google.common.base.Joiner; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.config.BlackListConfiguration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; package net.iponweb.disthene.service.blacklist; /** * @author Andrei Ivanov */ public class BlacklistService { private Map<String, Pattern> rules = new HashMap<>(); public BlacklistService(BlackListConfiguration blackListConfiguration) { for(Map.Entry<String, List<String>> entry : blackListConfiguration.getRules().entrySet()) { rules.put(entry.getKey(), Pattern.compile(Joiner.on("|").skipNulls().join(entry.getValue()))); } }
public boolean isBlackListed(Metric metric) {
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/service/index/IndexThread.java
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // }
import net.iponweb.disthene.bean.Metric; import org.apache.log4j.Logger; import org.elasticsearch.action.bulk.BulkProcessor; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.get.MultiGetItemResponse; import org.elasticsearch.action.get.MultiGetRequestBuilder; import org.elasticsearch.action.get.MultiGetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentFactory; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Queue;
package net.iponweb.disthene.service.index; /** * @author Andrei Ivanov */ public class IndexThread extends Thread { private Logger logger = Logger.getLogger(IndexThread.class); protected volatile boolean shutdown = false; private TransportClient client;
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // Path: src/main/java/net/iponweb/disthene/service/index/IndexThread.java import net.iponweb.disthene.bean.Metric; import org.apache.log4j.Logger; import org.elasticsearch.action.bulk.BulkProcessor; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.get.MultiGetItemResponse; import org.elasticsearch.action.get.MultiGetRequestBuilder; import org.elasticsearch.action.get.MultiGetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentFactory; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Queue; package net.iponweb.disthene.service.index; /** * @author Andrei Ivanov */ public class IndexThread extends Thread { private Logger logger = Logger.getLogger(IndexThread.class); protected volatile boolean shutdown = false; private TransportClient client;
protected Queue<Metric> metrics;
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/carbon/CarbonServer.java
// Path: src/main/java/net/iponweb/disthene/config/DistheneConfiguration.java // @SuppressWarnings("UnusedDeclaration") // public final class DistheneConfiguration { // private CarbonConfiguration carbon; // private StoreConfiguration store; // private IndexConfiguration index; // private StatsConfiguration stats; // // // public CarbonConfiguration getCarbon() { // return carbon; // } // // public void setCarbon(CarbonConfiguration carbon) { // this.carbon = carbon; // } // // public StoreConfiguration getStore() { // return store; // } // // public void setStore(StoreConfiguration store) { // this.store = store; // } // // public IndexConfiguration getIndex() { // return index; // } // // public void setIndex(IndexConfiguration index) { // this.index = index; // } // // public StatsConfiguration getStats() { // return stats; // } // // public void setStats(StatsConfiguration stats) { // this.stats = stats; // } // // @Override // public String toString() { // return "DistheneConfiguration{" + // "carbon=" + carbon + // ", store=" + store + // ", index=" + index + // ", stats=" + stats + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // }
import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.DelimiterBasedFrameDecoder; import io.netty.handler.codec.Delimiters; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.config.DistheneConfiguration; import net.iponweb.disthene.events.DistheneEvent; import org.apache.log4j.Logger;
package net.iponweb.disthene.carbon; /** * @author Andrei Ivanov */ public class CarbonServer { private static final int MAX_FRAME_LENGTH = 8192 ; private Logger logger = Logger.getLogger(CarbonServer.class);
// Path: src/main/java/net/iponweb/disthene/config/DistheneConfiguration.java // @SuppressWarnings("UnusedDeclaration") // public final class DistheneConfiguration { // private CarbonConfiguration carbon; // private StoreConfiguration store; // private IndexConfiguration index; // private StatsConfiguration stats; // // // public CarbonConfiguration getCarbon() { // return carbon; // } // // public void setCarbon(CarbonConfiguration carbon) { // this.carbon = carbon; // } // // public StoreConfiguration getStore() { // return store; // } // // public void setStore(StoreConfiguration store) { // this.store = store; // } // // public IndexConfiguration getIndex() { // return index; // } // // public void setIndex(IndexConfiguration index) { // this.index = index; // } // // public StatsConfiguration getStats() { // return stats; // } // // public void setStats(StatsConfiguration stats) { // this.stats = stats; // } // // @Override // public String toString() { // return "DistheneConfiguration{" + // "carbon=" + carbon + // ", store=" + store + // ", index=" + index + // ", stats=" + stats + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // Path: src/main/java/net/iponweb/disthene/carbon/CarbonServer.java import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.DelimiterBasedFrameDecoder; import io.netty.handler.codec.Delimiters; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.config.DistheneConfiguration; import net.iponweb.disthene.events.DistheneEvent; import org.apache.log4j.Logger; package net.iponweb.disthene.carbon; /** * @author Andrei Ivanov */ public class CarbonServer { private static final int MAX_FRAME_LENGTH = 8192 ; private Logger logger = Logger.getLogger(CarbonServer.class);
private DistheneConfiguration configuration;
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/carbon/CarbonServer.java
// Path: src/main/java/net/iponweb/disthene/config/DistheneConfiguration.java // @SuppressWarnings("UnusedDeclaration") // public final class DistheneConfiguration { // private CarbonConfiguration carbon; // private StoreConfiguration store; // private IndexConfiguration index; // private StatsConfiguration stats; // // // public CarbonConfiguration getCarbon() { // return carbon; // } // // public void setCarbon(CarbonConfiguration carbon) { // this.carbon = carbon; // } // // public StoreConfiguration getStore() { // return store; // } // // public void setStore(StoreConfiguration store) { // this.store = store; // } // // public IndexConfiguration getIndex() { // return index; // } // // public void setIndex(IndexConfiguration index) { // this.index = index; // } // // public StatsConfiguration getStats() { // return stats; // } // // public void setStats(StatsConfiguration stats) { // this.stats = stats; // } // // @Override // public String toString() { // return "DistheneConfiguration{" + // "carbon=" + carbon + // ", store=" + store + // ", index=" + index + // ", stats=" + stats + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // }
import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.DelimiterBasedFrameDecoder; import io.netty.handler.codec.Delimiters; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.config.DistheneConfiguration; import net.iponweb.disthene.events.DistheneEvent; import org.apache.log4j.Logger;
package net.iponweb.disthene.carbon; /** * @author Andrei Ivanov */ public class CarbonServer { private static final int MAX_FRAME_LENGTH = 8192 ; private Logger logger = Logger.getLogger(CarbonServer.class); private DistheneConfiguration configuration; private EventLoopGroup bossGroup = new NioEventLoopGroup(); private EventLoopGroup workerGroup = new NioEventLoopGroup();
// Path: src/main/java/net/iponweb/disthene/config/DistheneConfiguration.java // @SuppressWarnings("UnusedDeclaration") // public final class DistheneConfiguration { // private CarbonConfiguration carbon; // private StoreConfiguration store; // private IndexConfiguration index; // private StatsConfiguration stats; // // // public CarbonConfiguration getCarbon() { // return carbon; // } // // public void setCarbon(CarbonConfiguration carbon) { // this.carbon = carbon; // } // // public StoreConfiguration getStore() { // return store; // } // // public void setStore(StoreConfiguration store) { // this.store = store; // } // // public IndexConfiguration getIndex() { // return index; // } // // public void setIndex(IndexConfiguration index) { // this.index = index; // } // // public StatsConfiguration getStats() { // return stats; // } // // public void setStats(StatsConfiguration stats) { // this.stats = stats; // } // // @Override // public String toString() { // return "DistheneConfiguration{" + // "carbon=" + carbon + // ", store=" + store + // ", index=" + index + // ", stats=" + stats + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // Path: src/main/java/net/iponweb/disthene/carbon/CarbonServer.java import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.DelimiterBasedFrameDecoder; import io.netty.handler.codec.Delimiters; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.config.DistheneConfiguration; import net.iponweb.disthene.events.DistheneEvent; import org.apache.log4j.Logger; package net.iponweb.disthene.carbon; /** * @author Andrei Ivanov */ public class CarbonServer { private static final int MAX_FRAME_LENGTH = 8192 ; private Logger logger = Logger.getLogger(CarbonServer.class); private DistheneConfiguration configuration; private EventLoopGroup bossGroup = new NioEventLoopGroup(); private EventLoopGroup workerGroup = new NioEventLoopGroup();
private MBassador<DistheneEvent> bus;
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/service/store/WriterThread.java
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // }
import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.Session; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.events.DistheneEvent; import java.util.Queue; import java.util.concurrent.Executor;
package net.iponweb.disthene.service.store; /** * @author Andrei Ivanov */ public abstract class WriterThread extends Thread { protected volatile boolean shutdown = false;
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // Path: src/main/java/net/iponweb/disthene/service/store/WriterThread.java import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.Session; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.events.DistheneEvent; import java.util.Queue; import java.util.concurrent.Executor; package net.iponweb.disthene.service.store; /** * @author Andrei Ivanov */ public abstract class WriterThread extends Thread { protected volatile boolean shutdown = false;
protected MBassador<DistheneEvent> bus;
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/service/store/WriterThread.java
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // }
import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.Session; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.events.DistheneEvent; import java.util.Queue; import java.util.concurrent.Executor;
package net.iponweb.disthene.service.store; /** * @author Andrei Ivanov */ public abstract class WriterThread extends Thread { protected volatile boolean shutdown = false; protected MBassador<DistheneEvent> bus; protected Session session; protected PreparedStatement statement;
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // Path: src/main/java/net/iponweb/disthene/service/store/WriterThread.java import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.Session; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.events.DistheneEvent; import java.util.Queue; import java.util.concurrent.Executor; package net.iponweb.disthene.service.store; /** * @author Andrei Ivanov */ public abstract class WriterThread extends Thread { protected volatile boolean shutdown = false; protected MBassador<DistheneEvent> bus; protected Session session; protected PreparedStatement statement;
protected Queue<Metric> metrics;
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/config/StoreConfiguration.java
// Path: src/main/java/net/iponweb/disthene/util/CassandraLoadBalancingPolicies.java // public class CassandraLoadBalancingPolicies { // // public static final String tokenAwarePolicy = "TokenAwarePolicy"; // public static final String tokenDcAwareRoundRobinPolicy = "TokenDcAwareRoundRobinPolicy"; // public static final String tokenLatencyAwarePolicy = "TokenLatencyAwarePolicy"; // // public static LoadBalancingPolicy getLoadBalancingPolicy(String policy) { // LoadBalancingPolicy loadBalancingPolicy; // switch (policy) { // case tokenAwarePolicy: // loadBalancingPolicy = new TokenAwarePolicy(new RoundRobinPolicy()); // break; // case tokenDcAwareRoundRobinPolicy: // loadBalancingPolicy = new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().build()); // break; // case tokenLatencyAwarePolicy: // loadBalancingPolicy = new TokenAwarePolicy(LatencyAwarePolicy.builder(new RoundRobinPolicy()).build()); // break; // default: // throw new IllegalArgumentException("Cassandra load balancing policy can be " + tokenAwarePolicy + " ," + tokenLatencyAwarePolicy // + " ," + tokenDcAwareRoundRobinPolicy); // } // return loadBalancingPolicy; // } // }
import net.iponweb.disthene.util.CassandraLoadBalancingPolicies; import java.util.ArrayList; import java.util.List;
package net.iponweb.disthene.config; /** * @author Andrei Ivanov */ public class StoreConfiguration { private List<String> cluster = new ArrayList<>(); private String keyspace; private String columnFamily; private String userName; private String userPassword; private int port; private int maxConnections; private int readTimeout; private int connectTimeout; private int maxRequests; private boolean batch; private int batchSize; private int pool;
// Path: src/main/java/net/iponweb/disthene/util/CassandraLoadBalancingPolicies.java // public class CassandraLoadBalancingPolicies { // // public static final String tokenAwarePolicy = "TokenAwarePolicy"; // public static final String tokenDcAwareRoundRobinPolicy = "TokenDcAwareRoundRobinPolicy"; // public static final String tokenLatencyAwarePolicy = "TokenLatencyAwarePolicy"; // // public static LoadBalancingPolicy getLoadBalancingPolicy(String policy) { // LoadBalancingPolicy loadBalancingPolicy; // switch (policy) { // case tokenAwarePolicy: // loadBalancingPolicy = new TokenAwarePolicy(new RoundRobinPolicy()); // break; // case tokenDcAwareRoundRobinPolicy: // loadBalancingPolicy = new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().build()); // break; // case tokenLatencyAwarePolicy: // loadBalancingPolicy = new TokenAwarePolicy(LatencyAwarePolicy.builder(new RoundRobinPolicy()).build()); // break; // default: // throw new IllegalArgumentException("Cassandra load balancing policy can be " + tokenAwarePolicy + " ," + tokenLatencyAwarePolicy // + " ," + tokenDcAwareRoundRobinPolicy); // } // return loadBalancingPolicy; // } // } // Path: src/main/java/net/iponweb/disthene/config/StoreConfiguration.java import net.iponweb.disthene.util.CassandraLoadBalancingPolicies; import java.util.ArrayList; import java.util.List; package net.iponweb.disthene.config; /** * @author Andrei Ivanov */ public class StoreConfiguration { private List<String> cluster = new ArrayList<>(); private String keyspace; private String columnFamily; private String userName; private String userPassword; private int port; private int maxConnections; private int readTimeout; private int connectTimeout; private int maxRequests; private boolean batch; private int batchSize; private int pool;
private String loadBalancingPolicyName = CassandraLoadBalancingPolicies.tokenDcAwareRoundRobinPolicy;
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/bean/Metric.java
// Path: src/main/java/net/iponweb/disthene/config/Rollup.java // public class Rollup { // // private int rollup; // private int period; // // public Rollup(String s) { // String[] ss = s.split(":"); // rollup = Integer.parseInt(ss[0].substring(0, ss[0].length() - 1)); // period = (int) (Long.parseLong(ss[1].substring(0, ss[1].length() - 1)) / rollup); // } // // public int getRollup() { // return rollup; // } // // public void setRollup(int rollup) { // this.rollup = rollup; // } // // public int getPeriod() { // return period; // } // // public void setPeriod(int period) { // this.period = period; // } // // @Override // public String toString() { // return "Rollup{" + // "rollup=" + rollup + // ", period=" + period + // '}'; // } // }
import net.iponweb.disthene.config.Rollup;
package net.iponweb.disthene.bean; /** * @author Andrei Ivanov */ public class Metric { private MetricKey key; private double value;
// Path: src/main/java/net/iponweb/disthene/config/Rollup.java // public class Rollup { // // private int rollup; // private int period; // // public Rollup(String s) { // String[] ss = s.split(":"); // rollup = Integer.parseInt(ss[0].substring(0, ss[0].length() - 1)); // period = (int) (Long.parseLong(ss[1].substring(0, ss[1].length() - 1)) / rollup); // } // // public int getRollup() { // return rollup; // } // // public void setRollup(int rollup) { // this.rollup = rollup; // } // // public int getPeriod() { // return period; // } // // public void setPeriod(int period) { // this.period = period; // } // // @Override // public String toString() { // return "Rollup{" + // "rollup=" + rollup + // ", period=" + period + // '}'; // } // } // Path: src/main/java/net/iponweb/disthene/bean/Metric.java import net.iponweb.disthene.config.Rollup; package net.iponweb.disthene.bean; /** * @author Andrei Ivanov */ public class Metric { private MetricKey key; private double value;
public Metric(String input, Rollup rollup) {
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/service/store/SingleWriterThread.java
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/StoreErrorEvent.java // public class StoreErrorEvent implements DistheneEvent { // // private int count; // // public StoreErrorEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // // Path: src/main/java/net/iponweb/disthene/events/StoreSuccessEvent.java // public class StoreSuccessEvent implements DistheneEvent{ // // private int count; // // public StoreSuccessEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // }
import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.ResultSetFuture; import com.datastax.driver.core.Session; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.StoreErrorEvent; import net.iponweb.disthene.events.StoreSuccessEvent; import org.apache.log4j.Logger; import java.util.Collections; import java.util.Queue; import java.util.concurrent.Executor;
package net.iponweb.disthene.service.store; /** * @author Andrei Ivanov */ public class SingleWriterThread extends WriterThread { private Logger logger = Logger.getLogger(SingleWriterThread.class);
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/StoreErrorEvent.java // public class StoreErrorEvent implements DistheneEvent { // // private int count; // // public StoreErrorEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // // Path: src/main/java/net/iponweb/disthene/events/StoreSuccessEvent.java // public class StoreSuccessEvent implements DistheneEvent{ // // private int count; // // public StoreSuccessEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // Path: src/main/java/net/iponweb/disthene/service/store/SingleWriterThread.java import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.ResultSetFuture; import com.datastax.driver.core.Session; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.StoreErrorEvent; import net.iponweb.disthene.events.StoreSuccessEvent; import org.apache.log4j.Logger; import java.util.Collections; import java.util.Queue; import java.util.concurrent.Executor; package net.iponweb.disthene.service.store; /** * @author Andrei Ivanov */ public class SingleWriterThread extends WriterThread { private Logger logger = Logger.getLogger(SingleWriterThread.class);
public SingleWriterThread(String name, MBassador<DistheneEvent> bus, Session session, PreparedStatement statement, Queue<Metric> metrics, Executor executor) {
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/service/store/SingleWriterThread.java
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/StoreErrorEvent.java // public class StoreErrorEvent implements DistheneEvent { // // private int count; // // public StoreErrorEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // // Path: src/main/java/net/iponweb/disthene/events/StoreSuccessEvent.java // public class StoreSuccessEvent implements DistheneEvent{ // // private int count; // // public StoreSuccessEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // }
import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.ResultSetFuture; import com.datastax.driver.core.Session; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.StoreErrorEvent; import net.iponweb.disthene.events.StoreSuccessEvent; import org.apache.log4j.Logger; import java.util.Collections; import java.util.Queue; import java.util.concurrent.Executor;
package net.iponweb.disthene.service.store; /** * @author Andrei Ivanov */ public class SingleWriterThread extends WriterThread { private Logger logger = Logger.getLogger(SingleWriterThread.class);
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/StoreErrorEvent.java // public class StoreErrorEvent implements DistheneEvent { // // private int count; // // public StoreErrorEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // // Path: src/main/java/net/iponweb/disthene/events/StoreSuccessEvent.java // public class StoreSuccessEvent implements DistheneEvent{ // // private int count; // // public StoreSuccessEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // Path: src/main/java/net/iponweb/disthene/service/store/SingleWriterThread.java import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.ResultSetFuture; import com.datastax.driver.core.Session; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.StoreErrorEvent; import net.iponweb.disthene.events.StoreSuccessEvent; import org.apache.log4j.Logger; import java.util.Collections; import java.util.Queue; import java.util.concurrent.Executor; package net.iponweb.disthene.service.store; /** * @author Andrei Ivanov */ public class SingleWriterThread extends WriterThread { private Logger logger = Logger.getLogger(SingleWriterThread.class);
public SingleWriterThread(String name, MBassador<DistheneEvent> bus, Session session, PreparedStatement statement, Queue<Metric> metrics, Executor executor) {
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/service/store/SingleWriterThread.java
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/StoreErrorEvent.java // public class StoreErrorEvent implements DistheneEvent { // // private int count; // // public StoreErrorEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // // Path: src/main/java/net/iponweb/disthene/events/StoreSuccessEvent.java // public class StoreSuccessEvent implements DistheneEvent{ // // private int count; // // public StoreSuccessEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // }
import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.ResultSetFuture; import com.datastax.driver.core.Session; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.StoreErrorEvent; import net.iponweb.disthene.events.StoreSuccessEvent; import org.apache.log4j.Logger; import java.util.Collections; import java.util.Queue; import java.util.concurrent.Executor;
@Override public void run() { while (!shutdown) { Metric metric = metrics.poll(); if (metric != null) { store(metric); } else { try { Thread.sleep(100); } catch (InterruptedException ignored) { } } } } private void store(Metric metric) { ResultSetFuture future = session.executeAsync(statement.bind( metric.getRollup() * metric.getPeriod(), Collections.singletonList(metric.getValue()), metric.getTenant(), metric.getRollup(), metric.getPeriod(), metric.getPath(), metric.getTimestamp() )); Futures.addCallback(future, new FutureCallback<ResultSet>() { @Override public void onSuccess(ResultSet result) {
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/StoreErrorEvent.java // public class StoreErrorEvent implements DistheneEvent { // // private int count; // // public StoreErrorEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // // Path: src/main/java/net/iponweb/disthene/events/StoreSuccessEvent.java // public class StoreSuccessEvent implements DistheneEvent{ // // private int count; // // public StoreSuccessEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // Path: src/main/java/net/iponweb/disthene/service/store/SingleWriterThread.java import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.ResultSetFuture; import com.datastax.driver.core.Session; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.StoreErrorEvent; import net.iponweb.disthene.events.StoreSuccessEvent; import org.apache.log4j.Logger; import java.util.Collections; import java.util.Queue; import java.util.concurrent.Executor; @Override public void run() { while (!shutdown) { Metric metric = metrics.poll(); if (metric != null) { store(metric); } else { try { Thread.sleep(100); } catch (InterruptedException ignored) { } } } } private void store(Metric metric) { ResultSetFuture future = session.executeAsync(statement.bind( metric.getRollup() * metric.getPeriod(), Collections.singletonList(metric.getValue()), metric.getTenant(), metric.getRollup(), metric.getPeriod(), metric.getPath(), metric.getTimestamp() )); Futures.addCallback(future, new FutureCallback<ResultSet>() { @Override public void onSuccess(ResultSet result) {
bus.post(new StoreSuccessEvent(1)).now();
EinsamHauer/disthene
src/main/java/net/iponweb/disthene/service/store/SingleWriterThread.java
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/StoreErrorEvent.java // public class StoreErrorEvent implements DistheneEvent { // // private int count; // // public StoreErrorEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // // Path: src/main/java/net/iponweb/disthene/events/StoreSuccessEvent.java // public class StoreSuccessEvent implements DistheneEvent{ // // private int count; // // public StoreSuccessEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // }
import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.ResultSetFuture; import com.datastax.driver.core.Session; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.StoreErrorEvent; import net.iponweb.disthene.events.StoreSuccessEvent; import org.apache.log4j.Logger; import java.util.Collections; import java.util.Queue; import java.util.concurrent.Executor;
} else { try { Thread.sleep(100); } catch (InterruptedException ignored) { } } } } private void store(Metric metric) { ResultSetFuture future = session.executeAsync(statement.bind( metric.getRollup() * metric.getPeriod(), Collections.singletonList(metric.getValue()), metric.getTenant(), metric.getRollup(), metric.getPeriod(), metric.getPath(), metric.getTimestamp() )); Futures.addCallback(future, new FutureCallback<ResultSet>() { @Override public void onSuccess(ResultSet result) { bus.post(new StoreSuccessEvent(1)).now(); } @SuppressWarnings("NullableProblems") @Override public void onFailure(Throwable t) {
// Path: src/main/java/net/iponweb/disthene/bean/Metric.java // public class Metric { // // private MetricKey key; // private double value; // // public Metric(String input, Rollup rollup) { // String[] splitInput = input.split("\\s"); // // We were interning tenant and path here - we are going to store them all (or almost so) constantly anyhow in multiple places // // In fact this also work for a moderate metrics stream. Once we start receiving 10s of millions different metrics, it tends to degrade quite a bit // // So, leaving this only for tenant // this.key = new MetricKey( // splitInput.length >=4 ? splitInput[3].intern() : "NONE", // splitInput[0], // rollup.getRollup(), // rollup.getPeriod(), // normalizeTimestamp(Long.parseLong(splitInput[2]), rollup)); // this.value = Double.parseDouble(splitInput[1]); // } // // public Metric(String tenant, String path, int rollup, int period, double value, long timestamp) { // this.key = new MetricKey(tenant, path, rollup, period, timestamp); // this.value = value; // } // // public Metric(MetricKey key, double value) { // this.key = key; // this.value = value; // } // // private long normalizeTimestamp(long timestamp, Rollup rollup) { // return (timestamp / rollup.getRollup()) * rollup.getRollup(); // } // // public String getId() { // return getTenant() + "_" + getPath(); // } // // public String getTenant() { // return key.getTenant(); // } // // public String getPath() { // return key.getPath(); // } // // public int getRollup() { // return key.getRollup(); // } // // public int getPeriod() { // return key.getPeriod(); // } // // public double getValue() { // return value; // } // // public void setValue(double value) { // this.value = value; // } // // public long getTimestamp() { // return key.getTimestamp(); // } // // @Override // public String toString() { // return "Metric{" + // "key=" + key + // ", value=" + value + // '}'; // } // } // // Path: src/main/java/net/iponweb/disthene/events/DistheneEvent.java // public interface DistheneEvent { // } // // Path: src/main/java/net/iponweb/disthene/events/StoreErrorEvent.java // public class StoreErrorEvent implements DistheneEvent { // // private int count; // // public StoreErrorEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // // Path: src/main/java/net/iponweb/disthene/events/StoreSuccessEvent.java // public class StoreSuccessEvent implements DistheneEvent{ // // private int count; // // public StoreSuccessEvent(int count) { // this.count = count; // } // // public int getCount() { // return count; // } // } // Path: src/main/java/net/iponweb/disthene/service/store/SingleWriterThread.java import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.ResultSetFuture; import com.datastax.driver.core.Session; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import net.engio.mbassy.bus.MBassador; import net.iponweb.disthene.bean.Metric; import net.iponweb.disthene.events.DistheneEvent; import net.iponweb.disthene.events.StoreErrorEvent; import net.iponweb.disthene.events.StoreSuccessEvent; import org.apache.log4j.Logger; import java.util.Collections; import java.util.Queue; import java.util.concurrent.Executor; } else { try { Thread.sleep(100); } catch (InterruptedException ignored) { } } } } private void store(Metric metric) { ResultSetFuture future = session.executeAsync(statement.bind( metric.getRollup() * metric.getPeriod(), Collections.singletonList(metric.getValue()), metric.getTenant(), metric.getRollup(), metric.getPeriod(), metric.getPath(), metric.getTimestamp() )); Futures.addCallback(future, new FutureCallback<ResultSet>() { @Override public void onSuccess(ResultSet result) { bus.post(new StoreSuccessEvent(1)).now(); } @SuppressWarnings("NullableProblems") @Override public void onFailure(Throwable t) {
bus.post(new StoreErrorEvent(1)).now();
tomdw/java-modules-context-boot
samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/DefaultFailingSpeakerService.java
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerCheckedException.java // public class NoSpeakerCheckedException extends Exception { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerRuntimeException.java // public class NoSpeakerRuntimeException extends RuntimeException { // }
import javax.inject.Named; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerCheckedException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerRuntimeException;
package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal; @Named public class DefaultFailingSpeakerService implements FailingSpeakerService { public static FailingSpeakerService provider() { return provideByInterfaceSoThatADynamicProxyWillBeCreatedWhichShouldNotWrapExceptions(); } private static FailingSpeakerService provideByInterfaceSoThatADynamicProxyWillBeCreatedWhichShouldNotWrapExceptions() {
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerCheckedException.java // public class NoSpeakerCheckedException extends Exception { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerRuntimeException.java // public class NoSpeakerRuntimeException extends RuntimeException { // } // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/DefaultFailingSpeakerService.java import javax.inject.Named; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerCheckedException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerRuntimeException; package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal; @Named public class DefaultFailingSpeakerService implements FailingSpeakerService { public static FailingSpeakerService provider() { return provideByInterfaceSoThatADynamicProxyWillBeCreatedWhichShouldNotWrapExceptions(); } private static FailingSpeakerService provideByInterfaceSoThatADynamicProxyWillBeCreatedWhichShouldNotWrapExceptions() {
return ModuleServiceProvider.provide(FailingSpeakerService.class);
tomdw/java-modules-context-boot
samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/DefaultFailingSpeakerService.java
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerCheckedException.java // public class NoSpeakerCheckedException extends Exception { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerRuntimeException.java // public class NoSpeakerRuntimeException extends RuntimeException { // }
import javax.inject.Named; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerCheckedException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerRuntimeException;
package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal; @Named public class DefaultFailingSpeakerService implements FailingSpeakerService { public static FailingSpeakerService provider() { return provideByInterfaceSoThatADynamicProxyWillBeCreatedWhichShouldNotWrapExceptions(); } private static FailingSpeakerService provideByInterfaceSoThatADynamicProxyWillBeCreatedWhichShouldNotWrapExceptions() { return ModuleServiceProvider.provide(FailingSpeakerService.class); } @Override public String getSpeakerNameButThrowsRuntimeException() {
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerCheckedException.java // public class NoSpeakerCheckedException extends Exception { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerRuntimeException.java // public class NoSpeakerRuntimeException extends RuntimeException { // } // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/DefaultFailingSpeakerService.java import javax.inject.Named; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerCheckedException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerRuntimeException; package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal; @Named public class DefaultFailingSpeakerService implements FailingSpeakerService { public static FailingSpeakerService provider() { return provideByInterfaceSoThatADynamicProxyWillBeCreatedWhichShouldNotWrapExceptions(); } private static FailingSpeakerService provideByInterfaceSoThatADynamicProxyWillBeCreatedWhichShouldNotWrapExceptions() { return ModuleServiceProvider.provide(FailingSpeakerService.class); } @Override public String getSpeakerNameButThrowsRuntimeException() {
throw new NoSpeakerRuntimeException();
tomdw/java-modules-context-boot
samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/DefaultFailingSpeakerService.java
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerCheckedException.java // public class NoSpeakerCheckedException extends Exception { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerRuntimeException.java // public class NoSpeakerRuntimeException extends RuntimeException { // }
import javax.inject.Named; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerCheckedException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerRuntimeException;
package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal; @Named public class DefaultFailingSpeakerService implements FailingSpeakerService { public static FailingSpeakerService provider() { return provideByInterfaceSoThatADynamicProxyWillBeCreatedWhichShouldNotWrapExceptions(); } private static FailingSpeakerService provideByInterfaceSoThatADynamicProxyWillBeCreatedWhichShouldNotWrapExceptions() { return ModuleServiceProvider.provide(FailingSpeakerService.class); } @Override public String getSpeakerNameButThrowsRuntimeException() { throw new NoSpeakerRuntimeException(); } @Override
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerCheckedException.java // public class NoSpeakerCheckedException extends Exception { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerRuntimeException.java // public class NoSpeakerRuntimeException extends RuntimeException { // } // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/DefaultFailingSpeakerService.java import javax.inject.Named; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerCheckedException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerRuntimeException; package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal; @Named public class DefaultFailingSpeakerService implements FailingSpeakerService { public static FailingSpeakerService provider() { return provideByInterfaceSoThatADynamicProxyWillBeCreatedWhichShouldNotWrapExceptions(); } private static FailingSpeakerService provideByInterfaceSoThatADynamicProxyWillBeCreatedWhichShouldNotWrapExceptions() { return ModuleServiceProvider.provide(FailingSpeakerService.class); } @Override public String getSpeakerNameButThrowsRuntimeException() { throw new NoSpeakerRuntimeException(); } @Override
public String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException {
tomdw/java-modules-context-boot
samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/NamedSpeakerServiceProvider.java
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // }
import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService;
package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal; public class NamedSpeakerServiceProvider { public static NamedSpeakerService provider() {
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/NamedSpeakerServiceProvider.java import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal; public class NamedSpeakerServiceProvider { public static NamedSpeakerService provider() {
return ModuleServiceProvider.provide(NamedSpeakerService.class, "otherNamedSpeakerService");
tomdw/java-modules-context-boot
integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestService.java
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import java.util.List; import javax.inject.Named; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
package io.github.tomdw.java.modules.spring.integration.tests; @Named public class IntegrationTestService implements ApplicationContextAware { @ModuleServiceReference
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestService.java import java.util.List; import javax.inject.Named; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; package io.github.tomdw.java.modules.spring.integration.tests; @Named public class IntegrationTestService implements ApplicationContextAware { @ModuleServiceReference
private SpeakerService speakerService;
tomdw/java-modules-context-boot
integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestService.java
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import java.util.List; import javax.inject.Named; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
package io.github.tomdw.java.modules.spring.integration.tests; @Named public class IntegrationTestService implements ApplicationContextAware { @ModuleServiceReference private SpeakerService speakerService; @ModuleServiceReference @Named("multipleSpeakerServiceList")
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestService.java import java.util.List; import javax.inject.Named; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; package io.github.tomdw.java.modules.spring.integration.tests; @Named public class IntegrationTestService implements ApplicationContextAware { @ModuleServiceReference private SpeakerService speakerService; @ModuleServiceReference @Named("multipleSpeakerServiceList")
private List<MultipleSpeakerService> multipleSpeakerServices;
tomdw/java-modules-context-boot
integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestService.java
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import java.util.List; import javax.inject.Named; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
package io.github.tomdw.java.modules.spring.integration.tests; @Named public class IntegrationTestService implements ApplicationContextAware { @ModuleServiceReference private SpeakerService speakerService; @ModuleServiceReference @Named("multipleSpeakerServiceList") private List<MultipleSpeakerService> multipleSpeakerServices; @ModuleServiceReference
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestService.java import java.util.List; import javax.inject.Named; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; package io.github.tomdw.java.modules.spring.integration.tests; @Named public class IntegrationTestService implements ApplicationContextAware { @ModuleServiceReference private SpeakerService speakerService; @ModuleServiceReference @Named("multipleSpeakerServiceList") private List<MultipleSpeakerService> multipleSpeakerServices; @ModuleServiceReference
private NamedSpeakerService namedSpeakerService;
tomdw/java-modules-context-boot
integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestService.java
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import java.util.List; import javax.inject.Named; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
package io.github.tomdw.java.modules.spring.integration.tests; @Named public class IntegrationTestService implements ApplicationContextAware { @ModuleServiceReference private SpeakerService speakerService; @ModuleServiceReference @Named("multipleSpeakerServiceList") private List<MultipleSpeakerService> multipleSpeakerServices; @ModuleServiceReference private NamedSpeakerService namedSpeakerService; @ModuleServiceReference @Named("multipleSpeakerWithGenericsServiceList")
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestService.java import java.util.List; import javax.inject.Named; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; package io.github.tomdw.java.modules.spring.integration.tests; @Named public class IntegrationTestService implements ApplicationContextAware { @ModuleServiceReference private SpeakerService speakerService; @ModuleServiceReference @Named("multipleSpeakerServiceList") private List<MultipleSpeakerService> multipleSpeakerServices; @ModuleServiceReference private NamedSpeakerService namedSpeakerService; @ModuleServiceReference @Named("multipleSpeakerWithGenericsServiceList")
private List<MultipleSpeakerWithGenericsService<?>> multipleSpeakerWithGenericsServices;
tomdw/java-modules-context-boot
samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/DefaultSpeakerService.java
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import javax.inject.Named; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal; @Named public class DefaultSpeakerService implements SpeakerService { public static SpeakerService provider() {
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/DefaultSpeakerService.java import javax.inject.Named; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal; @Named public class DefaultSpeakerService implements SpeakerService { public static SpeakerService provider() {
return ModuleServiceProvider.provide(SpeakerService.class);
tomdw/java-modules-context-boot
integration-tests-spring-boot/src/test/java/io/github/tomdw/java/modules/spring/boot/starter/tests/JavaModulesContextBootStarterTest.java
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleContextBooter.java // public class ModuleContextBooter { // // public static void boot() { // ModuleContextRegistry.boot(); // } // // public static void boot(GenericApplicationContext defaultApplicationContext) { // ModuleContextRegistry.boot(defaultApplicationContext); // } // // public static void reset() { // ModuleContextRegistry.reset(); // } // // public static GenericApplicationContext getContextFor(Module module) { // return ModuleContextRegistry.getContextFor(module); // } // // public static void main(String... commandLineArguments) { // ModuleContextBooter.boot(); // } // // } // // Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // }
import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericApplicationContext; import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider;
package io.github.tomdw.java.modules.spring.boot.starter.tests; @SpringBootTest(classes = SpringBootTestApplication.class) public class JavaModulesContextBootStarterTest { @Autowired private ApplicationContext applicationContext; @Test public void springBootApplicationContextIsStartedAndDetectsOwnBeans() { assertThat(applicationContext).isNotNull(); assertThat(applicationContext.getBean(DummyTestBean.class)).isNotNull(); } @Test public void springBootStarterAutoConfiguresSpringApplicationContextForEveryModuleWithModuleContextAnnotation() { String[] expectedModuleNames = {"io.github.tomdw.java.modules.spring.samples.basicapplication.application", "io.github.tomdw.java.modules.spring.samples.basicapplication.speaker"}; List<Module> modulesWithModuleContextAnnotation = ModuleLayer.boot().modules().stream().filter(module -> List.of(expectedModuleNames).contains(module.getName())).collect(Collectors.toList()); assertThat(modulesWithModuleContextAnnotation.stream().map(Module::getName)).containsExactlyInAnyOrder(expectedModuleNames); modulesWithModuleContextAnnotation.forEach( module -> {
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleContextBooter.java // public class ModuleContextBooter { // // public static void boot() { // ModuleContextRegistry.boot(); // } // // public static void boot(GenericApplicationContext defaultApplicationContext) { // ModuleContextRegistry.boot(defaultApplicationContext); // } // // public static void reset() { // ModuleContextRegistry.reset(); // } // // public static GenericApplicationContext getContextFor(Module module) { // return ModuleContextRegistry.getContextFor(module); // } // // public static void main(String... commandLineArguments) { // ModuleContextBooter.boot(); // } // // } // // Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // Path: integration-tests-spring-boot/src/test/java/io/github/tomdw/java/modules/spring/boot/starter/tests/JavaModulesContextBootStarterTest.java import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericApplicationContext; import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; package io.github.tomdw.java.modules.spring.boot.starter.tests; @SpringBootTest(classes = SpringBootTestApplication.class) public class JavaModulesContextBootStarterTest { @Autowired private ApplicationContext applicationContext; @Test public void springBootApplicationContextIsStartedAndDetectsOwnBeans() { assertThat(applicationContext).isNotNull(); assertThat(applicationContext.getBean(DummyTestBean.class)).isNotNull(); } @Test public void springBootStarterAutoConfiguresSpringApplicationContextForEveryModuleWithModuleContextAnnotation() { String[] expectedModuleNames = {"io.github.tomdw.java.modules.spring.samples.basicapplication.application", "io.github.tomdw.java.modules.spring.samples.basicapplication.speaker"}; List<Module> modulesWithModuleContextAnnotation = ModuleLayer.boot().modules().stream().filter(module -> List.of(expectedModuleNames).contains(module.getName())).collect(Collectors.toList()); assertThat(modulesWithModuleContextAnnotation.stream().map(Module::getName)).containsExactlyInAnyOrder(expectedModuleNames); modulesWithModuleContextAnnotation.forEach( module -> {
GenericApplicationContext context = ModuleContextBooter.getContextFor(module);
tomdw/java-modules-context-boot
integration-tests-spring-boot/src/test/java/io/github/tomdw/java/modules/spring/boot/starter/tests/JavaModulesContextBootStarterTest.java
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleContextBooter.java // public class ModuleContextBooter { // // public static void boot() { // ModuleContextRegistry.boot(); // } // // public static void boot(GenericApplicationContext defaultApplicationContext) { // ModuleContextRegistry.boot(defaultApplicationContext); // } // // public static void reset() { // ModuleContextRegistry.reset(); // } // // public static GenericApplicationContext getContextFor(Module module) { // return ModuleContextRegistry.getContextFor(module); // } // // public static void main(String... commandLineArguments) { // ModuleContextBooter.boot(); // } // // } // // Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // }
import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericApplicationContext; import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider;
package io.github.tomdw.java.modules.spring.boot.starter.tests; @SpringBootTest(classes = SpringBootTestApplication.class) public class JavaModulesContextBootStarterTest { @Autowired private ApplicationContext applicationContext; @Test public void springBootApplicationContextIsStartedAndDetectsOwnBeans() { assertThat(applicationContext).isNotNull(); assertThat(applicationContext.getBean(DummyTestBean.class)).isNotNull(); } @Test public void springBootStarterAutoConfiguresSpringApplicationContextForEveryModuleWithModuleContextAnnotation() { String[] expectedModuleNames = {"io.github.tomdw.java.modules.spring.samples.basicapplication.application", "io.github.tomdw.java.modules.spring.samples.basicapplication.speaker"}; List<Module> modulesWithModuleContextAnnotation = ModuleLayer.boot().modules().stream().filter(module -> List.of(expectedModuleNames).contains(module.getName())).collect(Collectors.toList()); assertThat(modulesWithModuleContextAnnotation.stream().map(Module::getName)).containsExactlyInAnyOrder(expectedModuleNames); modulesWithModuleContextAnnotation.forEach( module -> { GenericApplicationContext context = ModuleContextBooter.getContextFor(module); assertThat(context).withFailMessage("A context should have been created for module " + module.getName()).isNotNull(); assertThat(context.isActive()).withFailMessage("The context should be active for module " + module.getName()).isTrue(); } ); } @Test public void moduleServiceProviderLooksForBeansInMainSpringBootContextWhenCallingModuleHasNoModuleContextAnnotation() {
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleContextBooter.java // public class ModuleContextBooter { // // public static void boot() { // ModuleContextRegistry.boot(); // } // // public static void boot(GenericApplicationContext defaultApplicationContext) { // ModuleContextRegistry.boot(defaultApplicationContext); // } // // public static void reset() { // ModuleContextRegistry.reset(); // } // // public static GenericApplicationContext getContextFor(Module module) { // return ModuleContextRegistry.getContextFor(module); // } // // public static void main(String... commandLineArguments) { // ModuleContextBooter.boot(); // } // // } // // Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // Path: integration-tests-spring-boot/src/test/java/io/github/tomdw/java/modules/spring/boot/starter/tests/JavaModulesContextBootStarterTest.java import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericApplicationContext; import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; package io.github.tomdw.java.modules.spring.boot.starter.tests; @SpringBootTest(classes = SpringBootTestApplication.class) public class JavaModulesContextBootStarterTest { @Autowired private ApplicationContext applicationContext; @Test public void springBootApplicationContextIsStartedAndDetectsOwnBeans() { assertThat(applicationContext).isNotNull(); assertThat(applicationContext.getBean(DummyTestBean.class)).isNotNull(); } @Test public void springBootStarterAutoConfiguresSpringApplicationContextForEveryModuleWithModuleContextAnnotation() { String[] expectedModuleNames = {"io.github.tomdw.java.modules.spring.samples.basicapplication.application", "io.github.tomdw.java.modules.spring.samples.basicapplication.speaker"}; List<Module> modulesWithModuleContextAnnotation = ModuleLayer.boot().modules().stream().filter(module -> List.of(expectedModuleNames).contains(module.getName())).collect(Collectors.toList()); assertThat(modulesWithModuleContextAnnotation.stream().map(Module::getName)).containsExactlyInAnyOrder(expectedModuleNames); modulesWithModuleContextAnnotation.forEach( module -> { GenericApplicationContext context = ModuleContextBooter.getContextFor(module); assertThat(context).withFailMessage("A context should have been created for module " + module.getName()).isNotNull(); assertThat(context.isActive()).withFailMessage("The context should be active for module " + module.getName()).isTrue(); } ); } @Test public void moduleServiceProviderLooksForBeansInMainSpringBootContextWhenCallingModuleHasNoModuleContextAnnotation() {
DummyTestBean providedBean = ModuleServiceProvider.provide(DummyTestBean.class);
tomdw/java-modules-context-boot
integration-tests/src/test/java/io/github/tomdw/java/modules/spring/integration/tests/JavaModulesSpringContextBootIntegrationTest.java
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleContextBooter.java // public class ModuleContextBooter { // // public static void boot() { // ModuleContextRegistry.boot(); // } // // public static void boot(GenericApplicationContext defaultApplicationContext) { // ModuleContextRegistry.boot(defaultApplicationContext); // } // // public static void reset() { // ModuleContextRegistry.reset(); // } // // public static GenericApplicationContext getContextFor(Module module) { // return ModuleContextRegistry.getContextFor(module); // } // // public static void main(String... commandLineArguments) { // ModuleContextBooter.boot(); // } // // } // // Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerCheckedException.java // public class NoSpeakerCheckedException extends Exception { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerRuntimeException.java // public class NoSpeakerRuntimeException extends RuntimeException { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; import java.util.ServiceLoader; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.context.support.GenericApplicationContext; import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerCheckedException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerRuntimeException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
package io.github.tomdw.java.modules.spring.integration.tests; public class JavaModulesSpringContextBootIntegrationTest { @AfterEach public void reset() {
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleContextBooter.java // public class ModuleContextBooter { // // public static void boot() { // ModuleContextRegistry.boot(); // } // // public static void boot(GenericApplicationContext defaultApplicationContext) { // ModuleContextRegistry.boot(defaultApplicationContext); // } // // public static void reset() { // ModuleContextRegistry.reset(); // } // // public static GenericApplicationContext getContextFor(Module module) { // return ModuleContextRegistry.getContextFor(module); // } // // public static void main(String... commandLineArguments) { // ModuleContextBooter.boot(); // } // // } // // Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerCheckedException.java // public class NoSpeakerCheckedException extends Exception { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerRuntimeException.java // public class NoSpeakerRuntimeException extends RuntimeException { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: integration-tests/src/test/java/io/github/tomdw/java/modules/spring/integration/tests/JavaModulesSpringContextBootIntegrationTest.java import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; import java.util.ServiceLoader; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.context.support.GenericApplicationContext; import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerCheckedException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerRuntimeException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; package io.github.tomdw.java.modules.spring.integration.tests; public class JavaModulesSpringContextBootIntegrationTest { @AfterEach public void reset() {
ModuleContextBooter.reset();
tomdw/java-modules-context-boot
integration-tests/src/test/java/io/github/tomdw/java/modules/spring/integration/tests/JavaModulesSpringContextBootIntegrationTest.java
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleContextBooter.java // public class ModuleContextBooter { // // public static void boot() { // ModuleContextRegistry.boot(); // } // // public static void boot(GenericApplicationContext defaultApplicationContext) { // ModuleContextRegistry.boot(defaultApplicationContext); // } // // public static void reset() { // ModuleContextRegistry.reset(); // } // // public static GenericApplicationContext getContextFor(Module module) { // return ModuleContextRegistry.getContextFor(module); // } // // public static void main(String... commandLineArguments) { // ModuleContextBooter.boot(); // } // // } // // Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerCheckedException.java // public class NoSpeakerCheckedException extends Exception { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerRuntimeException.java // public class NoSpeakerRuntimeException extends RuntimeException { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; import java.util.ServiceLoader; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.context.support.GenericApplicationContext; import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerCheckedException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerRuntimeException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
assertThat(modulesWithModuleContextAnnotation.stream().map(Module::getName)).containsExactlyInAnyOrder(expectedModuleNames); modulesWithModuleContextAnnotation.forEach( module -> { GenericApplicationContext context = ModuleContextBooter.getContextFor(module); assertThat(context).withFailMessage("A context should have been created for module " + module.getName()).isNotNull(); assertThat(context.isActive()).withFailMessage("The context should be active for module " + module.getName()).isTrue(); } ); } @Test public void singleServiceFromOtherModuleCanBeInjectedUsingModuleServiceReferenceOnField() { ModuleContextBooter.main(); IntegrationTestService testConfig = IntegrationTestService.getApplicationContext().getBean(IntegrationTestService.class); assertThat(testConfig).isNotNull(); assertThat(testConfig.getSpeakerService()).withFailMessage("No SpeakerService injected").isNotNull(); assertThat(testConfig.getSpeakerService().getName()).withFailMessage("Wrong SpeakerService injected").isEqualTo("Default"); } @Test public void serviceListFromOtherModuleCanBeInjectedUsingModuleServiceReferenceOnField() { ModuleContextBooter.main(); IntegrationTestService testConfig = IntegrationTestService.getApplicationContext().getBean(IntegrationTestService.class); assertThat(testConfig).isNotNull(); assertThat(testConfig.getMultipleSpeakerServices()).withFailMessage("No MultipleSpeakerService(s) injected").isNotNull();
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleContextBooter.java // public class ModuleContextBooter { // // public static void boot() { // ModuleContextRegistry.boot(); // } // // public static void boot(GenericApplicationContext defaultApplicationContext) { // ModuleContextRegistry.boot(defaultApplicationContext); // } // // public static void reset() { // ModuleContextRegistry.reset(); // } // // public static GenericApplicationContext getContextFor(Module module) { // return ModuleContextRegistry.getContextFor(module); // } // // public static void main(String... commandLineArguments) { // ModuleContextBooter.boot(); // } // // } // // Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerCheckedException.java // public class NoSpeakerCheckedException extends Exception { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerRuntimeException.java // public class NoSpeakerRuntimeException extends RuntimeException { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: integration-tests/src/test/java/io/github/tomdw/java/modules/spring/integration/tests/JavaModulesSpringContextBootIntegrationTest.java import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; import java.util.ServiceLoader; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.context.support.GenericApplicationContext; import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerCheckedException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerRuntimeException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; assertThat(modulesWithModuleContextAnnotation.stream().map(Module::getName)).containsExactlyInAnyOrder(expectedModuleNames); modulesWithModuleContextAnnotation.forEach( module -> { GenericApplicationContext context = ModuleContextBooter.getContextFor(module); assertThat(context).withFailMessage("A context should have been created for module " + module.getName()).isNotNull(); assertThat(context.isActive()).withFailMessage("The context should be active for module " + module.getName()).isTrue(); } ); } @Test public void singleServiceFromOtherModuleCanBeInjectedUsingModuleServiceReferenceOnField() { ModuleContextBooter.main(); IntegrationTestService testConfig = IntegrationTestService.getApplicationContext().getBean(IntegrationTestService.class); assertThat(testConfig).isNotNull(); assertThat(testConfig.getSpeakerService()).withFailMessage("No SpeakerService injected").isNotNull(); assertThat(testConfig.getSpeakerService().getName()).withFailMessage("Wrong SpeakerService injected").isEqualTo("Default"); } @Test public void serviceListFromOtherModuleCanBeInjectedUsingModuleServiceReferenceOnField() { ModuleContextBooter.main(); IntegrationTestService testConfig = IntegrationTestService.getApplicationContext().getBean(IntegrationTestService.class); assertThat(testConfig).isNotNull(); assertThat(testConfig.getMultipleSpeakerServices()).withFailMessage("No MultipleSpeakerService(s) injected").isNotNull();
assertThat(testConfig.getMultipleSpeakerServices().stream().map(MultipleSpeakerService::getName)).containsExactlyInAnyOrder("Default", "Other");
tomdw/java-modules-context-boot
integration-tests/src/test/java/io/github/tomdw/java/modules/spring/integration/tests/JavaModulesSpringContextBootIntegrationTest.java
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleContextBooter.java // public class ModuleContextBooter { // // public static void boot() { // ModuleContextRegistry.boot(); // } // // public static void boot(GenericApplicationContext defaultApplicationContext) { // ModuleContextRegistry.boot(defaultApplicationContext); // } // // public static void reset() { // ModuleContextRegistry.reset(); // } // // public static GenericApplicationContext getContextFor(Module module) { // return ModuleContextRegistry.getContextFor(module); // } // // public static void main(String... commandLineArguments) { // ModuleContextBooter.boot(); // } // // } // // Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerCheckedException.java // public class NoSpeakerCheckedException extends Exception { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerRuntimeException.java // public class NoSpeakerRuntimeException extends RuntimeException { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; import java.util.ServiceLoader; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.context.support.GenericApplicationContext; import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerCheckedException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerRuntimeException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
assertThat(testConfig).isNotNull(); assertThat(testConfig.getMultipleSpeakerServices()).withFailMessage("No MultipleSpeakerService(s) injected").isNotNull(); assertThat(testConfig.getMultipleSpeakerServices().stream().map(MultipleSpeakerService::getName)).containsExactlyInAnyOrder("Default", "Other"); } @Test public void singleServiceFromOtherModuleCanBeRetrievedSpecificallyOnBeanNameOnConstructorParameter() { ModuleContextBooter.main(); IntegrationTestUsingConstructorInjectionService testConfig = IntegrationTestUsingConstructorInjectionService.getApplicationContext().getBean(IntegrationTestUsingConstructorInjectionService.class); assertThat(testConfig).isNotNull(); assertThat(testConfig.getNamedSpeakerService().getSpeakerName()).isEqualTo("otherNamedSpeakerServiceName"); } @Test public void serviceListFromOtherModuleWithGenericsCanBeInjectedUsingModuleServiceReferenceOnConstructorParameter() { ModuleContextBooter.main(); IntegrationTestUsingConstructorInjectionService testConfig = IntegrationTestUsingConstructorInjectionService.getApplicationContext().getBean(IntegrationTestUsingConstructorInjectionService.class); assertThat(testConfig).isNotNull(); assertThat(testConfig.getMultipleSpeakerWithGenericsServices()).withFailMessage("No MultipleSpeakerWithGenericsService(s) injected").isNotNull(); assertThat(testConfig.getMultipleSpeakerWithGenericsServices().get(0).getMultipleSpeakerName()).asString().isEqualTo("myMultipleGenericSpeakerName"); } @Test public void usingModuleServiceProviderBeforeExplicitBootIsSupported() {
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleContextBooter.java // public class ModuleContextBooter { // // public static void boot() { // ModuleContextRegistry.boot(); // } // // public static void boot(GenericApplicationContext defaultApplicationContext) { // ModuleContextRegistry.boot(defaultApplicationContext); // } // // public static void reset() { // ModuleContextRegistry.reset(); // } // // public static GenericApplicationContext getContextFor(Module module) { // return ModuleContextRegistry.getContextFor(module); // } // // public static void main(String... commandLineArguments) { // ModuleContextBooter.boot(); // } // // } // // Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerCheckedException.java // public class NoSpeakerCheckedException extends Exception { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerRuntimeException.java // public class NoSpeakerRuntimeException extends RuntimeException { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: integration-tests/src/test/java/io/github/tomdw/java/modules/spring/integration/tests/JavaModulesSpringContextBootIntegrationTest.java import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; import java.util.ServiceLoader; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.context.support.GenericApplicationContext; import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerCheckedException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerRuntimeException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; assertThat(testConfig).isNotNull(); assertThat(testConfig.getMultipleSpeakerServices()).withFailMessage("No MultipleSpeakerService(s) injected").isNotNull(); assertThat(testConfig.getMultipleSpeakerServices().stream().map(MultipleSpeakerService::getName)).containsExactlyInAnyOrder("Default", "Other"); } @Test public void singleServiceFromOtherModuleCanBeRetrievedSpecificallyOnBeanNameOnConstructorParameter() { ModuleContextBooter.main(); IntegrationTestUsingConstructorInjectionService testConfig = IntegrationTestUsingConstructorInjectionService.getApplicationContext().getBean(IntegrationTestUsingConstructorInjectionService.class); assertThat(testConfig).isNotNull(); assertThat(testConfig.getNamedSpeakerService().getSpeakerName()).isEqualTo("otherNamedSpeakerServiceName"); } @Test public void serviceListFromOtherModuleWithGenericsCanBeInjectedUsingModuleServiceReferenceOnConstructorParameter() { ModuleContextBooter.main(); IntegrationTestUsingConstructorInjectionService testConfig = IntegrationTestUsingConstructorInjectionService.getApplicationContext().getBean(IntegrationTestUsingConstructorInjectionService.class); assertThat(testConfig).isNotNull(); assertThat(testConfig.getMultipleSpeakerWithGenericsServices()).withFailMessage("No MultipleSpeakerWithGenericsService(s) injected").isNotNull(); assertThat(testConfig.getMultipleSpeakerWithGenericsServices().get(0).getMultipleSpeakerName()).asString().isEqualTo("myMultipleGenericSpeakerName"); } @Test public void usingModuleServiceProviderBeforeExplicitBootIsSupported() {
SpeakerService singleSpeakerService = ModuleServiceProvider.provide(SpeakerService.class);
tomdw/java-modules-context-boot
integration-tests/src/test/java/io/github/tomdw/java/modules/spring/integration/tests/JavaModulesSpringContextBootIntegrationTest.java
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleContextBooter.java // public class ModuleContextBooter { // // public static void boot() { // ModuleContextRegistry.boot(); // } // // public static void boot(GenericApplicationContext defaultApplicationContext) { // ModuleContextRegistry.boot(defaultApplicationContext); // } // // public static void reset() { // ModuleContextRegistry.reset(); // } // // public static GenericApplicationContext getContextFor(Module module) { // return ModuleContextRegistry.getContextFor(module); // } // // public static void main(String... commandLineArguments) { // ModuleContextBooter.boot(); // } // // } // // Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerCheckedException.java // public class NoSpeakerCheckedException extends Exception { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerRuntimeException.java // public class NoSpeakerRuntimeException extends RuntimeException { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; import java.util.ServiceLoader; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.context.support.GenericApplicationContext; import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerCheckedException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerRuntimeException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
assertThat(testConfig).isNotNull(); assertThat(testConfig.getMultipleSpeakerServices()).withFailMessage("No MultipleSpeakerService(s) injected").isNotNull(); assertThat(testConfig.getMultipleSpeakerServices().stream().map(MultipleSpeakerService::getName)).containsExactlyInAnyOrder("Default", "Other"); } @Test public void singleServiceFromOtherModuleCanBeRetrievedSpecificallyOnBeanNameOnConstructorParameter() { ModuleContextBooter.main(); IntegrationTestUsingConstructorInjectionService testConfig = IntegrationTestUsingConstructorInjectionService.getApplicationContext().getBean(IntegrationTestUsingConstructorInjectionService.class); assertThat(testConfig).isNotNull(); assertThat(testConfig.getNamedSpeakerService().getSpeakerName()).isEqualTo("otherNamedSpeakerServiceName"); } @Test public void serviceListFromOtherModuleWithGenericsCanBeInjectedUsingModuleServiceReferenceOnConstructorParameter() { ModuleContextBooter.main(); IntegrationTestUsingConstructorInjectionService testConfig = IntegrationTestUsingConstructorInjectionService.getApplicationContext().getBean(IntegrationTestUsingConstructorInjectionService.class); assertThat(testConfig).isNotNull(); assertThat(testConfig.getMultipleSpeakerWithGenericsServices()).withFailMessage("No MultipleSpeakerWithGenericsService(s) injected").isNotNull(); assertThat(testConfig.getMultipleSpeakerWithGenericsServices().get(0).getMultipleSpeakerName()).asString().isEqualTo("myMultipleGenericSpeakerName"); } @Test public void usingModuleServiceProviderBeforeExplicitBootIsSupported() {
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleContextBooter.java // public class ModuleContextBooter { // // public static void boot() { // ModuleContextRegistry.boot(); // } // // public static void boot(GenericApplicationContext defaultApplicationContext) { // ModuleContextRegistry.boot(defaultApplicationContext); // } // // public static void reset() { // ModuleContextRegistry.reset(); // } // // public static GenericApplicationContext getContextFor(Module module) { // return ModuleContextRegistry.getContextFor(module); // } // // public static void main(String... commandLineArguments) { // ModuleContextBooter.boot(); // } // // } // // Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerCheckedException.java // public class NoSpeakerCheckedException extends Exception { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerRuntimeException.java // public class NoSpeakerRuntimeException extends RuntimeException { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: integration-tests/src/test/java/io/github/tomdw/java/modules/spring/integration/tests/JavaModulesSpringContextBootIntegrationTest.java import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; import java.util.ServiceLoader; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.context.support.GenericApplicationContext; import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerCheckedException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerRuntimeException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; assertThat(testConfig).isNotNull(); assertThat(testConfig.getMultipleSpeakerServices()).withFailMessage("No MultipleSpeakerService(s) injected").isNotNull(); assertThat(testConfig.getMultipleSpeakerServices().stream().map(MultipleSpeakerService::getName)).containsExactlyInAnyOrder("Default", "Other"); } @Test public void singleServiceFromOtherModuleCanBeRetrievedSpecificallyOnBeanNameOnConstructorParameter() { ModuleContextBooter.main(); IntegrationTestUsingConstructorInjectionService testConfig = IntegrationTestUsingConstructorInjectionService.getApplicationContext().getBean(IntegrationTestUsingConstructorInjectionService.class); assertThat(testConfig).isNotNull(); assertThat(testConfig.getNamedSpeakerService().getSpeakerName()).isEqualTo("otherNamedSpeakerServiceName"); } @Test public void serviceListFromOtherModuleWithGenericsCanBeInjectedUsingModuleServiceReferenceOnConstructorParameter() { ModuleContextBooter.main(); IntegrationTestUsingConstructorInjectionService testConfig = IntegrationTestUsingConstructorInjectionService.getApplicationContext().getBean(IntegrationTestUsingConstructorInjectionService.class); assertThat(testConfig).isNotNull(); assertThat(testConfig.getMultipleSpeakerWithGenericsServices()).withFailMessage("No MultipleSpeakerWithGenericsService(s) injected").isNotNull(); assertThat(testConfig.getMultipleSpeakerWithGenericsServices().get(0).getMultipleSpeakerName()).asString().isEqualTo("myMultipleGenericSpeakerName"); } @Test public void usingModuleServiceProviderBeforeExplicitBootIsSupported() {
SpeakerService singleSpeakerService = ModuleServiceProvider.provide(SpeakerService.class);
tomdw/java-modules-context-boot
integration-tests/src/test/java/io/github/tomdw/java/modules/spring/integration/tests/JavaModulesSpringContextBootIntegrationTest.java
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleContextBooter.java // public class ModuleContextBooter { // // public static void boot() { // ModuleContextRegistry.boot(); // } // // public static void boot(GenericApplicationContext defaultApplicationContext) { // ModuleContextRegistry.boot(defaultApplicationContext); // } // // public static void reset() { // ModuleContextRegistry.reset(); // } // // public static GenericApplicationContext getContextFor(Module module) { // return ModuleContextRegistry.getContextFor(module); // } // // public static void main(String... commandLineArguments) { // ModuleContextBooter.boot(); // } // // } // // Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerCheckedException.java // public class NoSpeakerCheckedException extends Exception { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerRuntimeException.java // public class NoSpeakerRuntimeException extends RuntimeException { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; import java.util.ServiceLoader; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.context.support.GenericApplicationContext; import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerCheckedException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerRuntimeException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
assertThat(testConfig.getMultipleSpeakerWithGenericsServices()).withFailMessage("No MultipleSpeakerWithGenericsService(s) injected").isNotNull(); assertThat(testConfig.getMultipleSpeakerWithGenericsServices().get(0).getMultipleSpeakerName()).asString().isEqualTo("myMultipleGenericSpeakerName"); } @Test public void usingModuleServiceProviderBeforeExplicitBootIsSupported() { SpeakerService singleSpeakerService = ModuleServiceProvider.provide(SpeakerService.class); assertThat(singleSpeakerService).isNotNull(); ModuleContextBooter.boot(); GenericApplicationContext contextForModule = ModuleContextBooter.getContextFor(SpeakerService.class.getModule()); assertThat(contextForModule).isNotNull(); } @Test public void bootingModuleContextBooterMultipleTimesIsNotAProblem() { ModuleContextBooter.boot(); ModuleContextBooter.boot(); GenericApplicationContext contextForModule = ModuleContextBooter.getContextFor(SpeakerService.class.getModule()); assertThat(contextForModule).isNotNull(); } @Test public void aDynamicProxiedServiceShouldStillThrowExceptionsAsIfTheServiceIsNotProxiedMeaningExceptionsShouldNotBeWrappedInOtherExceptions() { ModuleContextBooter.main();
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleContextBooter.java // public class ModuleContextBooter { // // public static void boot() { // ModuleContextRegistry.boot(); // } // // public static void boot(GenericApplicationContext defaultApplicationContext) { // ModuleContextRegistry.boot(defaultApplicationContext); // } // // public static void reset() { // ModuleContextRegistry.reset(); // } // // public static GenericApplicationContext getContextFor(Module module) { // return ModuleContextRegistry.getContextFor(module); // } // // public static void main(String... commandLineArguments) { // ModuleContextBooter.boot(); // } // // } // // Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerCheckedException.java // public class NoSpeakerCheckedException extends Exception { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerRuntimeException.java // public class NoSpeakerRuntimeException extends RuntimeException { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: integration-tests/src/test/java/io/github/tomdw/java/modules/spring/integration/tests/JavaModulesSpringContextBootIntegrationTest.java import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; import java.util.ServiceLoader; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.context.support.GenericApplicationContext; import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerCheckedException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerRuntimeException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; assertThat(testConfig.getMultipleSpeakerWithGenericsServices()).withFailMessage("No MultipleSpeakerWithGenericsService(s) injected").isNotNull(); assertThat(testConfig.getMultipleSpeakerWithGenericsServices().get(0).getMultipleSpeakerName()).asString().isEqualTo("myMultipleGenericSpeakerName"); } @Test public void usingModuleServiceProviderBeforeExplicitBootIsSupported() { SpeakerService singleSpeakerService = ModuleServiceProvider.provide(SpeakerService.class); assertThat(singleSpeakerService).isNotNull(); ModuleContextBooter.boot(); GenericApplicationContext contextForModule = ModuleContextBooter.getContextFor(SpeakerService.class.getModule()); assertThat(contextForModule).isNotNull(); } @Test public void bootingModuleContextBooterMultipleTimesIsNotAProblem() { ModuleContextBooter.boot(); ModuleContextBooter.boot(); GenericApplicationContext contextForModule = ModuleContextBooter.getContextFor(SpeakerService.class.getModule()); assertThat(contextForModule).isNotNull(); } @Test public void aDynamicProxiedServiceShouldStillThrowExceptionsAsIfTheServiceIsNotProxiedMeaningExceptionsShouldNotBeWrappedInOtherExceptions() { ModuleContextBooter.main();
ServiceLoader<FailingSpeakerService> failingSpeakerServiceServiceLoader = ServiceLoader.load(FailingSpeakerService.class);
tomdw/java-modules-context-boot
integration-tests/src/test/java/io/github/tomdw/java/modules/spring/integration/tests/JavaModulesSpringContextBootIntegrationTest.java
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleContextBooter.java // public class ModuleContextBooter { // // public static void boot() { // ModuleContextRegistry.boot(); // } // // public static void boot(GenericApplicationContext defaultApplicationContext) { // ModuleContextRegistry.boot(defaultApplicationContext); // } // // public static void reset() { // ModuleContextRegistry.reset(); // } // // public static GenericApplicationContext getContextFor(Module module) { // return ModuleContextRegistry.getContextFor(module); // } // // public static void main(String... commandLineArguments) { // ModuleContextBooter.boot(); // } // // } // // Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerCheckedException.java // public class NoSpeakerCheckedException extends Exception { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerRuntimeException.java // public class NoSpeakerRuntimeException extends RuntimeException { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; import java.util.ServiceLoader; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.context.support.GenericApplicationContext; import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerCheckedException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerRuntimeException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
} @Test public void usingModuleServiceProviderBeforeExplicitBootIsSupported() { SpeakerService singleSpeakerService = ModuleServiceProvider.provide(SpeakerService.class); assertThat(singleSpeakerService).isNotNull(); ModuleContextBooter.boot(); GenericApplicationContext contextForModule = ModuleContextBooter.getContextFor(SpeakerService.class.getModule()); assertThat(contextForModule).isNotNull(); } @Test public void bootingModuleContextBooterMultipleTimesIsNotAProblem() { ModuleContextBooter.boot(); ModuleContextBooter.boot(); GenericApplicationContext contextForModule = ModuleContextBooter.getContextFor(SpeakerService.class.getModule()); assertThat(contextForModule).isNotNull(); } @Test public void aDynamicProxiedServiceShouldStillThrowExceptionsAsIfTheServiceIsNotProxiedMeaningExceptionsShouldNotBeWrappedInOtherExceptions() { ModuleContextBooter.main(); ServiceLoader<FailingSpeakerService> failingSpeakerServiceServiceLoader = ServiceLoader.load(FailingSpeakerService.class); FailingSpeakerService failingSpeakerService = failingSpeakerServiceServiceLoader.findFirst().orElseThrow();
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleContextBooter.java // public class ModuleContextBooter { // // public static void boot() { // ModuleContextRegistry.boot(); // } // // public static void boot(GenericApplicationContext defaultApplicationContext) { // ModuleContextRegistry.boot(defaultApplicationContext); // } // // public static void reset() { // ModuleContextRegistry.reset(); // } // // public static GenericApplicationContext getContextFor(Module module) { // return ModuleContextRegistry.getContextFor(module); // } // // public static void main(String... commandLineArguments) { // ModuleContextBooter.boot(); // } // // } // // Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerCheckedException.java // public class NoSpeakerCheckedException extends Exception { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerRuntimeException.java // public class NoSpeakerRuntimeException extends RuntimeException { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: integration-tests/src/test/java/io/github/tomdw/java/modules/spring/integration/tests/JavaModulesSpringContextBootIntegrationTest.java import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; import java.util.ServiceLoader; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.context.support.GenericApplicationContext; import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerCheckedException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerRuntimeException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; } @Test public void usingModuleServiceProviderBeforeExplicitBootIsSupported() { SpeakerService singleSpeakerService = ModuleServiceProvider.provide(SpeakerService.class); assertThat(singleSpeakerService).isNotNull(); ModuleContextBooter.boot(); GenericApplicationContext contextForModule = ModuleContextBooter.getContextFor(SpeakerService.class.getModule()); assertThat(contextForModule).isNotNull(); } @Test public void bootingModuleContextBooterMultipleTimesIsNotAProblem() { ModuleContextBooter.boot(); ModuleContextBooter.boot(); GenericApplicationContext contextForModule = ModuleContextBooter.getContextFor(SpeakerService.class.getModule()); assertThat(contextForModule).isNotNull(); } @Test public void aDynamicProxiedServiceShouldStillThrowExceptionsAsIfTheServiceIsNotProxiedMeaningExceptionsShouldNotBeWrappedInOtherExceptions() { ModuleContextBooter.main(); ServiceLoader<FailingSpeakerService> failingSpeakerServiceServiceLoader = ServiceLoader.load(FailingSpeakerService.class); FailingSpeakerService failingSpeakerService = failingSpeakerServiceServiceLoader.findFirst().orElseThrow();
assertThatThrownBy(failingSpeakerService::getSpeakerNameButThrowsCheckedException).isInstanceOf(NoSpeakerCheckedException.class);
tomdw/java-modules-context-boot
integration-tests/src/test/java/io/github/tomdw/java/modules/spring/integration/tests/JavaModulesSpringContextBootIntegrationTest.java
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleContextBooter.java // public class ModuleContextBooter { // // public static void boot() { // ModuleContextRegistry.boot(); // } // // public static void boot(GenericApplicationContext defaultApplicationContext) { // ModuleContextRegistry.boot(defaultApplicationContext); // } // // public static void reset() { // ModuleContextRegistry.reset(); // } // // public static GenericApplicationContext getContextFor(Module module) { // return ModuleContextRegistry.getContextFor(module); // } // // public static void main(String... commandLineArguments) { // ModuleContextBooter.boot(); // } // // } // // Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerCheckedException.java // public class NoSpeakerCheckedException extends Exception { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerRuntimeException.java // public class NoSpeakerRuntimeException extends RuntimeException { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; import java.util.ServiceLoader; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.context.support.GenericApplicationContext; import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerCheckedException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerRuntimeException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
@Test public void usingModuleServiceProviderBeforeExplicitBootIsSupported() { SpeakerService singleSpeakerService = ModuleServiceProvider.provide(SpeakerService.class); assertThat(singleSpeakerService).isNotNull(); ModuleContextBooter.boot(); GenericApplicationContext contextForModule = ModuleContextBooter.getContextFor(SpeakerService.class.getModule()); assertThat(contextForModule).isNotNull(); } @Test public void bootingModuleContextBooterMultipleTimesIsNotAProblem() { ModuleContextBooter.boot(); ModuleContextBooter.boot(); GenericApplicationContext contextForModule = ModuleContextBooter.getContextFor(SpeakerService.class.getModule()); assertThat(contextForModule).isNotNull(); } @Test public void aDynamicProxiedServiceShouldStillThrowExceptionsAsIfTheServiceIsNotProxiedMeaningExceptionsShouldNotBeWrappedInOtherExceptions() { ModuleContextBooter.main(); ServiceLoader<FailingSpeakerService> failingSpeakerServiceServiceLoader = ServiceLoader.load(FailingSpeakerService.class); FailingSpeakerService failingSpeakerService = failingSpeakerServiceServiceLoader.findFirst().orElseThrow(); assertThatThrownBy(failingSpeakerService::getSpeakerNameButThrowsCheckedException).isInstanceOf(NoSpeakerCheckedException.class);
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleContextBooter.java // public class ModuleContextBooter { // // public static void boot() { // ModuleContextRegistry.boot(); // } // // public static void boot(GenericApplicationContext defaultApplicationContext) { // ModuleContextRegistry.boot(defaultApplicationContext); // } // // public static void reset() { // ModuleContextRegistry.reset(); // } // // public static GenericApplicationContext getContextFor(Module module) { // return ModuleContextRegistry.getContextFor(module); // } // // public static void main(String... commandLineArguments) { // ModuleContextBooter.boot(); // } // // } // // Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerCheckedException.java // public class NoSpeakerCheckedException extends Exception { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NoSpeakerRuntimeException.java // public class NoSpeakerRuntimeException extends RuntimeException { // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: integration-tests/src/test/java/io/github/tomdw/java/modules/spring/integration/tests/JavaModulesSpringContextBootIntegrationTest.java import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; import java.util.ServiceLoader; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.context.support.GenericApplicationContext; import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerCheckedException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NoSpeakerRuntimeException; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; @Test public void usingModuleServiceProviderBeforeExplicitBootIsSupported() { SpeakerService singleSpeakerService = ModuleServiceProvider.provide(SpeakerService.class); assertThat(singleSpeakerService).isNotNull(); ModuleContextBooter.boot(); GenericApplicationContext contextForModule = ModuleContextBooter.getContextFor(SpeakerService.class.getModule()); assertThat(contextForModule).isNotNull(); } @Test public void bootingModuleContextBooterMultipleTimesIsNotAProblem() { ModuleContextBooter.boot(); ModuleContextBooter.boot(); GenericApplicationContext contextForModule = ModuleContextBooter.getContextFor(SpeakerService.class.getModule()); assertThat(contextForModule).isNotNull(); } @Test public void aDynamicProxiedServiceShouldStillThrowExceptionsAsIfTheServiceIsNotProxiedMeaningExceptionsShouldNotBeWrappedInOtherExceptions() { ModuleContextBooter.main(); ServiceLoader<FailingSpeakerService> failingSpeakerServiceServiceLoader = ServiceLoader.load(FailingSpeakerService.class); FailingSpeakerService failingSpeakerService = failingSpeakerServiceServiceLoader.findFirst().orElseThrow(); assertThatThrownBy(failingSpeakerService::getSpeakerNameButThrowsCheckedException).isInstanceOf(NoSpeakerCheckedException.class);
assertThatThrownBy(failingSpeakerService::getSpeakerNameButThrowsRuntimeException).isInstanceOf(NoSpeakerRuntimeException.class);
tomdw/java-modules-context-boot
samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/OtherMultipleSpeakerService.java
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // }
import javax.inject.Named; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService;
package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal; @Named public class OtherMultipleSpeakerService implements MultipleSpeakerService { public static MultipleSpeakerService provider() {
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/OtherMultipleSpeakerService.java import javax.inject.Named; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal; @Named public class OtherMultipleSpeakerService implements MultipleSpeakerService { public static MultipleSpeakerService provider() {
return ModuleServiceProvider.provide(MultipleSpeakerService.class, "otherMultipleSpeakerService");
tomdw/java-modules-context-boot
samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/MultipleSpeakerWithGenericsServiceProvider.java
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // }
import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider;
package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal; public class MultipleSpeakerWithGenericsServiceProvider { public static DefaultMultipleSpeakerWithGenericsService provider() {
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/MultipleSpeakerWithGenericsServiceProvider.java import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal; public class MultipleSpeakerWithGenericsServiceProvider { public static DefaultMultipleSpeakerWithGenericsService provider() {
return ModuleServiceProvider.provide(DefaultMultipleSpeakerWithGenericsService.class);
tomdw/java-modules-context-boot
samples/basicapplication/application/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/internal/MessageGenerator.java
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import java.util.List; import javax.inject.Named; import org.springframework.beans.factory.InitializingBean; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
package io.github.tomdw.java.modules.spring.samples.basicapplication.internal; @Named public class MessageGenerator implements InitializingBean { @ModuleServiceReference
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: samples/basicapplication/application/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/internal/MessageGenerator.java import java.util.List; import javax.inject.Named; import org.springframework.beans.factory.InitializingBean; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; package io.github.tomdw.java.modules.spring.samples.basicapplication.internal; @Named public class MessageGenerator implements InitializingBean { @ModuleServiceReference
private SpeakerService speakerService;
tomdw/java-modules-context-boot
samples/basicapplication/application/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/internal/MessageGenerator.java
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import java.util.List; import javax.inject.Named; import org.springframework.beans.factory.InitializingBean; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
package io.github.tomdw.java.modules.spring.samples.basicapplication.internal; @Named public class MessageGenerator implements InitializingBean { @ModuleServiceReference private SpeakerService speakerService; @ModuleServiceReference @Named("multipleSpeakerServiceList")
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: samples/basicapplication/application/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/internal/MessageGenerator.java import java.util.List; import javax.inject.Named; import org.springframework.beans.factory.InitializingBean; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; package io.github.tomdw.java.modules.spring.samples.basicapplication.internal; @Named public class MessageGenerator implements InitializingBean { @ModuleServiceReference private SpeakerService speakerService; @ModuleServiceReference @Named("multipleSpeakerServiceList")
private List<MultipleSpeakerService> multipleSpeakerServices;
tomdw/java-modules-context-boot
java-modules-context-boot-starter/src/main/java/io/github/tomdw/java/modules/context/boot/starter/JavaModulesContextBootApplicationContextInitializer.java
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleContextBooter.java // public class ModuleContextBooter { // // public static void boot() { // ModuleContextRegistry.boot(); // } // // public static void boot(GenericApplicationContext defaultApplicationContext) { // ModuleContextRegistry.boot(defaultApplicationContext); // } // // public static void reset() { // ModuleContextRegistry.reset(); // } // // public static GenericApplicationContext getContextFor(Module module) { // return ModuleContextRegistry.getContextFor(module); // } // // public static void main(String... commandLineArguments) { // ModuleContextBooter.boot(); // } // // }
import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter;
package io.github.tomdw.java.modules.context.boot.starter; @Component @Order(Ordered.HIGHEST_PRECEDENCE) public class JavaModulesContextBootApplicationContextInitializer implements ApplicationContextInitializer<GenericApplicationContext> { private static final System.Logger LOGGER = System.getLogger(JavaModulesContextBootApplicationContextInitializer.class.getName()); @Override public void initialize(GenericApplicationContext applicationContext) { LOGGER.log(System.Logger.Level.INFO, "Spring Boot Starter for Java Module Context activated ...");
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleContextBooter.java // public class ModuleContextBooter { // // public static void boot() { // ModuleContextRegistry.boot(); // } // // public static void boot(GenericApplicationContext defaultApplicationContext) { // ModuleContextRegistry.boot(defaultApplicationContext); // } // // public static void reset() { // ModuleContextRegistry.reset(); // } // // public static GenericApplicationContext getContextFor(Module module) { // return ModuleContextRegistry.getContextFor(module); // } // // public static void main(String... commandLineArguments) { // ModuleContextBooter.boot(); // } // // } // Path: java-modules-context-boot-starter/src/main/java/io/github/tomdw/java/modules/context/boot/starter/JavaModulesContextBootApplicationContextInitializer.java import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import io.github.tomdw.java.modules.context.boot.api.ModuleContextBooter; package io.github.tomdw.java.modules.context.boot.starter; @Component @Order(Ordered.HIGHEST_PRECEDENCE) public class JavaModulesContextBootApplicationContextInitializer implements ApplicationContextInitializer<GenericApplicationContext> { private static final System.Logger LOGGER = System.getLogger(JavaModulesContextBootApplicationContextInitializer.class.getName()); @Override public void initialize(GenericApplicationContext applicationContext) { LOGGER.log(System.Logger.Level.INFO, "Spring Boot Starter for Java Module Context activated ...");
ModuleContextBooter.boot(applicationContext);
tomdw/java-modules-context-boot
integration-tests-spring-boot/src/main/java/io/github/tomdw/java/modules/spring/boot/starter/tests/DummyTestBean.java
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import org.springframework.stereotype.Component; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
package io.github.tomdw.java.modules.spring.boot.starter.tests; @Component public class DummyTestBean { @ModuleServiceReference
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: integration-tests-spring-boot/src/main/java/io/github/tomdw/java/modules/spring/boot/starter/tests/DummyTestBean.java import org.springframework.stereotype.Component; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; package io.github.tomdw.java.modules.spring.boot.starter.tests; @Component public class DummyTestBean { @ModuleServiceReference
private SpeakerService speakerService;
tomdw/java-modules-context-boot
samples/basicapplication/application/src/main/java/module-info.java
// Path: samples/basicapplication/application/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/internal/MainApplicationConfiguration.java // @Configuration // @ComponentScan // public class MainApplicationConfiguration { // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import io.github.tomdw.java.modules.spring.samples.basicapplication.internal.MainApplicationConfiguration; import io.github.tomdw.java.modules.context.boot.api.ModuleContext; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
@ModuleContext(mainConfigurationClass = MainApplicationConfiguration.class) module io.github.tomdw.java.modules.spring.samples.basicapplication.application { requires io.github.tomdw.java.modules.spring.samples.basicapplication.speaker; requires io.github.tomdw.java.modules.context.boot; opens io.github.tomdw.java.modules.spring.samples.basicapplication.internal to spring.beans, spring.core, spring.context;
// Path: samples/basicapplication/application/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/internal/MainApplicationConfiguration.java // @Configuration // @ComponentScan // public class MainApplicationConfiguration { // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: samples/basicapplication/application/src/main/java/module-info.java import io.github.tomdw.java.modules.spring.samples.basicapplication.internal.MainApplicationConfiguration; import io.github.tomdw.java.modules.context.boot.api.ModuleContext; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; @ModuleContext(mainConfigurationClass = MainApplicationConfiguration.class) module io.github.tomdw.java.modules.spring.samples.basicapplication.application { requires io.github.tomdw.java.modules.spring.samples.basicapplication.speaker; requires io.github.tomdw.java.modules.context.boot; opens io.github.tomdw.java.modules.spring.samples.basicapplication.internal to spring.beans, spring.core, spring.context;
uses SpeakerService;
tomdw/java-modules-context-boot
samples/basicapplication/application/src/main/java/module-info.java
// Path: samples/basicapplication/application/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/internal/MainApplicationConfiguration.java // @Configuration // @ComponentScan // public class MainApplicationConfiguration { // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import io.github.tomdw.java.modules.spring.samples.basicapplication.internal.MainApplicationConfiguration; import io.github.tomdw.java.modules.context.boot.api.ModuleContext; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
@ModuleContext(mainConfigurationClass = MainApplicationConfiguration.class) module io.github.tomdw.java.modules.spring.samples.basicapplication.application { requires io.github.tomdw.java.modules.spring.samples.basicapplication.speaker; requires io.github.tomdw.java.modules.context.boot; opens io.github.tomdw.java.modules.spring.samples.basicapplication.internal to spring.beans, spring.core, spring.context; uses SpeakerService;
// Path: samples/basicapplication/application/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/internal/MainApplicationConfiguration.java // @Configuration // @ComponentScan // public class MainApplicationConfiguration { // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: samples/basicapplication/application/src/main/java/module-info.java import io.github.tomdw.java.modules.spring.samples.basicapplication.internal.MainApplicationConfiguration; import io.github.tomdw.java.modules.context.boot.api.ModuleContext; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; @ModuleContext(mainConfigurationClass = MainApplicationConfiguration.class) module io.github.tomdw.java.modules.spring.samples.basicapplication.application { requires io.github.tomdw.java.modules.spring.samples.basicapplication.speaker; requires io.github.tomdw.java.modules.context.boot; opens io.github.tomdw.java.modules.spring.samples.basicapplication.internal to spring.beans, spring.core, spring.context; uses SpeakerService;
uses MultipleSpeakerService;
tomdw/java-modules-context-boot
samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/DefaultMultipleSpeakerService.java
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // }
import javax.inject.Named; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService;
package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal; @Named public class DefaultMultipleSpeakerService implements MultipleSpeakerService { public static MultipleSpeakerService provider() {
// Path: java-modules-context-boot/src/main/java/io/github/tomdw/java/modules/context/boot/api/ModuleServiceProvider.java // public class ModuleServiceProvider { // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass); // } // // public static <SERVICETYPE> SERVICETYPE provide(Class<SERVICETYPE> servicetypeClass, String serviceName) { // return ModuleContextRegistry.retrieveInstanceFromContext(servicetypeClass, serviceName); // } // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/internal/DefaultMultipleSpeakerService.java import javax.inject.Named; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceProvider; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; package io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.internal; @Named public class DefaultMultipleSpeakerService implements MultipleSpeakerService { public static MultipleSpeakerService provider() {
return ModuleServiceProvider.provide(MultipleSpeakerService.class, "defaultMultipleSpeakerService");
tomdw/java-modules-context-boot
integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestUsingConstructorInjectionService.java
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import java.util.List; import javax.inject.Named; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
package io.github.tomdw.java.modules.spring.integration.tests; @Named public class IntegrationTestUsingConstructorInjectionService implements ApplicationContextAware {
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestUsingConstructorInjectionService.java import java.util.List; import javax.inject.Named; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; package io.github.tomdw.java.modules.spring.integration.tests; @Named public class IntegrationTestUsingConstructorInjectionService implements ApplicationContextAware {
private final SpeakerService speakerService;
tomdw/java-modules-context-boot
integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestUsingConstructorInjectionService.java
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import java.util.List; import javax.inject.Named; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
package io.github.tomdw.java.modules.spring.integration.tests; @Named public class IntegrationTestUsingConstructorInjectionService implements ApplicationContextAware { private final SpeakerService speakerService;
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestUsingConstructorInjectionService.java import java.util.List; import javax.inject.Named; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; package io.github.tomdw.java.modules.spring.integration.tests; @Named public class IntegrationTestUsingConstructorInjectionService implements ApplicationContextAware { private final SpeakerService speakerService;
private final List<MultipleSpeakerService> multipleSpeakerServices;
tomdw/java-modules-context-boot
integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestUsingConstructorInjectionService.java
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import java.util.List; import javax.inject.Named; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
package io.github.tomdw.java.modules.spring.integration.tests; @Named public class IntegrationTestUsingConstructorInjectionService implements ApplicationContextAware { private final SpeakerService speakerService; private final List<MultipleSpeakerService> multipleSpeakerServices;
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestUsingConstructorInjectionService.java import java.util.List; import javax.inject.Named; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; package io.github.tomdw.java.modules.spring.integration.tests; @Named public class IntegrationTestUsingConstructorInjectionService implements ApplicationContextAware { private final SpeakerService speakerService; private final List<MultipleSpeakerService> multipleSpeakerServices;
private final NamedSpeakerService namedSpeakerService;
tomdw/java-modules-context-boot
integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestUsingConstructorInjectionService.java
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import java.util.List; import javax.inject.Named; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
package io.github.tomdw.java.modules.spring.integration.tests; @Named public class IntegrationTestUsingConstructorInjectionService implements ApplicationContextAware { private final SpeakerService speakerService; private final List<MultipleSpeakerService> multipleSpeakerServices; private final NamedSpeakerService namedSpeakerService;
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestUsingConstructorInjectionService.java import java.util.List; import javax.inject.Named; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import io.github.tomdw.java.modules.context.boot.api.ModuleServiceReference; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; package io.github.tomdw.java.modules.spring.integration.tests; @Named public class IntegrationTestUsingConstructorInjectionService implements ApplicationContextAware { private final SpeakerService speakerService; private final List<MultipleSpeakerService> multipleSpeakerServices; private final NamedSpeakerService namedSpeakerService;
private final List<MultipleSpeakerWithGenericsService<?>> multipleSpeakerWithGenericsServices;
tomdw/java-modules-context-boot
integration-tests-spring-boot/src/main/java/module-info.java
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
open module io.github.tomdw.java.modules.spring.integration.tests.spring.boot { requires spring.boot.autoconfigure; requires spring.context; requires io.github.tomdw.java.modules.context.boot.starter; requires io.github.tomdw.java.modules.context.boot; requires io.github.tomdw.java.modules.spring.samples.basicapplication.application; requires io.github.tomdw.java.modules.spring.samples.basicapplication.speaker;
// Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: integration-tests-spring-boot/src/main/java/module-info.java import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; open module io.github.tomdw.java.modules.spring.integration.tests.spring.boot { requires spring.boot.autoconfigure; requires spring.context; requires io.github.tomdw.java.modules.context.boot.starter; requires io.github.tomdw.java.modules.context.boot; requires io.github.tomdw.java.modules.spring.samples.basicapplication.application; requires io.github.tomdw.java.modules.spring.samples.basicapplication.speaker;
uses SpeakerService;
tomdw/java-modules-context-boot
integration-tests/src/main/java/module-info.java
// Path: integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestConfiguration.java // @Configuration // @Import(value = {IntegrationTestUsingConstructorInjectionService.class, IntegrationTestService.class}) // public class IntegrationTestConfiguration { // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import io.github.tomdw.java.modules.context.boot.api.ModuleContext; import io.github.tomdw.java.modules.spring.integration.tests.IntegrationTestConfiguration; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
@ModuleContext(mainConfigurationClass = IntegrationTestConfiguration.class) module io.github.tomdw.java.modules.spring.integration.tests { requires io.github.tomdw.java.modules.context.boot; requires io.github.tomdw.java.modules.spring.samples.basicapplication.application; requires io.github.tomdw.java.modules.spring.samples.basicapplication.speaker;
// Path: integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestConfiguration.java // @Configuration // @Import(value = {IntegrationTestUsingConstructorInjectionService.class, IntegrationTestService.class}) // public class IntegrationTestConfiguration { // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: integration-tests/src/main/java/module-info.java import io.github.tomdw.java.modules.context.boot.api.ModuleContext; import io.github.tomdw.java.modules.spring.integration.tests.IntegrationTestConfiguration; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; @ModuleContext(mainConfigurationClass = IntegrationTestConfiguration.class) module io.github.tomdw.java.modules.spring.integration.tests { requires io.github.tomdw.java.modules.context.boot; requires io.github.tomdw.java.modules.spring.samples.basicapplication.application; requires io.github.tomdw.java.modules.spring.samples.basicapplication.speaker;
uses SpeakerService;
tomdw/java-modules-context-boot
integration-tests/src/main/java/module-info.java
// Path: integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestConfiguration.java // @Configuration // @Import(value = {IntegrationTestUsingConstructorInjectionService.class, IntegrationTestService.class}) // public class IntegrationTestConfiguration { // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import io.github.tomdw.java.modules.context.boot.api.ModuleContext; import io.github.tomdw.java.modules.spring.integration.tests.IntegrationTestConfiguration; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
@ModuleContext(mainConfigurationClass = IntegrationTestConfiguration.class) module io.github.tomdw.java.modules.spring.integration.tests { requires io.github.tomdw.java.modules.context.boot; requires io.github.tomdw.java.modules.spring.samples.basicapplication.application; requires io.github.tomdw.java.modules.spring.samples.basicapplication.speaker; uses SpeakerService;
// Path: integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestConfiguration.java // @Configuration // @Import(value = {IntegrationTestUsingConstructorInjectionService.class, IntegrationTestService.class}) // public class IntegrationTestConfiguration { // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: integration-tests/src/main/java/module-info.java import io.github.tomdw.java.modules.context.boot.api.ModuleContext; import io.github.tomdw.java.modules.spring.integration.tests.IntegrationTestConfiguration; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; @ModuleContext(mainConfigurationClass = IntegrationTestConfiguration.class) module io.github.tomdw.java.modules.spring.integration.tests { requires io.github.tomdw.java.modules.context.boot; requires io.github.tomdw.java.modules.spring.samples.basicapplication.application; requires io.github.tomdw.java.modules.spring.samples.basicapplication.speaker; uses SpeakerService;
uses MultipleSpeakerService;
tomdw/java-modules-context-boot
integration-tests/src/main/java/module-info.java
// Path: integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestConfiguration.java // @Configuration // @Import(value = {IntegrationTestUsingConstructorInjectionService.class, IntegrationTestService.class}) // public class IntegrationTestConfiguration { // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import io.github.tomdw.java.modules.context.boot.api.ModuleContext; import io.github.tomdw.java.modules.spring.integration.tests.IntegrationTestConfiguration; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
@ModuleContext(mainConfigurationClass = IntegrationTestConfiguration.class) module io.github.tomdw.java.modules.spring.integration.tests { requires io.github.tomdw.java.modules.context.boot; requires io.github.tomdw.java.modules.spring.samples.basicapplication.application; requires io.github.tomdw.java.modules.spring.samples.basicapplication.speaker; uses SpeakerService; uses MultipleSpeakerService;
// Path: integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestConfiguration.java // @Configuration // @Import(value = {IntegrationTestUsingConstructorInjectionService.class, IntegrationTestService.class}) // public class IntegrationTestConfiguration { // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: integration-tests/src/main/java/module-info.java import io.github.tomdw.java.modules.context.boot.api.ModuleContext; import io.github.tomdw.java.modules.spring.integration.tests.IntegrationTestConfiguration; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; @ModuleContext(mainConfigurationClass = IntegrationTestConfiguration.class) module io.github.tomdw.java.modules.spring.integration.tests { requires io.github.tomdw.java.modules.context.boot; requires io.github.tomdw.java.modules.spring.samples.basicapplication.application; requires io.github.tomdw.java.modules.spring.samples.basicapplication.speaker; uses SpeakerService; uses MultipleSpeakerService;
uses NamedSpeakerService;
tomdw/java-modules-context-boot
integration-tests/src/main/java/module-info.java
// Path: integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestConfiguration.java // @Configuration // @Import(value = {IntegrationTestUsingConstructorInjectionService.class, IntegrationTestService.class}) // public class IntegrationTestConfiguration { // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import io.github.tomdw.java.modules.context.boot.api.ModuleContext; import io.github.tomdw.java.modules.spring.integration.tests.IntegrationTestConfiguration; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
@ModuleContext(mainConfigurationClass = IntegrationTestConfiguration.class) module io.github.tomdw.java.modules.spring.integration.tests { requires io.github.tomdw.java.modules.context.boot; requires io.github.tomdw.java.modules.spring.samples.basicapplication.application; requires io.github.tomdw.java.modules.spring.samples.basicapplication.speaker; uses SpeakerService; uses MultipleSpeakerService; uses NamedSpeakerService;
// Path: integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestConfiguration.java // @Configuration // @Import(value = {IntegrationTestUsingConstructorInjectionService.class, IntegrationTestService.class}) // public class IntegrationTestConfiguration { // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: integration-tests/src/main/java/module-info.java import io.github.tomdw.java.modules.context.boot.api.ModuleContext; import io.github.tomdw.java.modules.spring.integration.tests.IntegrationTestConfiguration; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; @ModuleContext(mainConfigurationClass = IntegrationTestConfiguration.class) module io.github.tomdw.java.modules.spring.integration.tests { requires io.github.tomdw.java.modules.context.boot; requires io.github.tomdw.java.modules.spring.samples.basicapplication.application; requires io.github.tomdw.java.modules.spring.samples.basicapplication.speaker; uses SpeakerService; uses MultipleSpeakerService; uses NamedSpeakerService;
uses MultipleSpeakerWithGenericsService;
tomdw/java-modules-context-boot
integration-tests/src/main/java/module-info.java
// Path: integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestConfiguration.java // @Configuration // @Import(value = {IntegrationTestUsingConstructorInjectionService.class, IntegrationTestService.class}) // public class IntegrationTestConfiguration { // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // }
import io.github.tomdw.java.modules.context.boot.api.ModuleContext; import io.github.tomdw.java.modules.spring.integration.tests.IntegrationTestConfiguration; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
@ModuleContext(mainConfigurationClass = IntegrationTestConfiguration.class) module io.github.tomdw.java.modules.spring.integration.tests { requires io.github.tomdw.java.modules.context.boot; requires io.github.tomdw.java.modules.spring.samples.basicapplication.application; requires io.github.tomdw.java.modules.spring.samples.basicapplication.speaker; uses SpeakerService; uses MultipleSpeakerService; uses NamedSpeakerService; uses MultipleSpeakerWithGenericsService;
// Path: integration-tests/src/main/java/io/github/tomdw/java/modules/spring/integration/tests/IntegrationTestConfiguration.java // @Configuration // @Import(value = {IntegrationTestUsingConstructorInjectionService.class, IntegrationTestService.class}) // public class IntegrationTestConfiguration { // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/FailingSpeakerService.java // public interface FailingSpeakerService { // // String getSpeakerNameButThrowsRuntimeException(); // // String getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException; // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerService.java // public interface MultipleSpeakerService { // String getName(); // void speak(String message); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/MultipleSpeakerWithGenericsService.java // public interface MultipleSpeakerWithGenericsService<T> { // // T getMultipleSpeakerName(); // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/NamedSpeakerService.java // public interface NamedSpeakerService { // // String getSpeakerName(); // // } // // Path: samples/basicapplication/speaker/src/main/java/io/github/tomdw/java/modules/spring/samples/basicapplication/speaker/api/SpeakerService.java // public interface SpeakerService { // String getName(); // void speak(String message); // } // Path: integration-tests/src/main/java/module-info.java import io.github.tomdw.java.modules.context.boot.api.ModuleContext; import io.github.tomdw.java.modules.spring.integration.tests.IntegrationTestConfiguration; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService; @ModuleContext(mainConfigurationClass = IntegrationTestConfiguration.class) module io.github.tomdw.java.modules.spring.integration.tests { requires io.github.tomdw.java.modules.context.boot; requires io.github.tomdw.java.modules.spring.samples.basicapplication.application; requires io.github.tomdw.java.modules.spring.samples.basicapplication.speaker; uses SpeakerService; uses MultipleSpeakerService; uses NamedSpeakerService; uses MultipleSpeakerWithGenericsService;
uses FailingSpeakerService;
PeterCxy/BlackLight
src/us/shandian/blacklight/support/Emoticons.java
// Path: src/us/shandian/blacklight/support/adapter/EmoticonAdapter.java // public class EmoticonAdapter extends BaseAdapter // { // private static ArrayList<String> mNames = new ArrayList<String>(); // private static ArrayList<Bitmap> mBitmaps = new ArrayList<Bitmap>(); // // private LayoutInflater mInflater; // // public EmoticonAdapter(Context context) { // mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); // } // // @Override // public int getCount() { // return mNames.size(); // } // // @Override // public String getItem(int position) { // return mNames.get(position); // } // // @Override // public long getItemId(int position) { // return position; // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // if (position >= mNames.size()){ // return convertView; // } else { // View v = mInflater.inflate(R.layout.emoticon_view, null); // ImageView iv = (ImageView) v.findViewById(R.id.emoticon_image); // iv.setImageBitmap(mBitmaps.get(position)); // return v; // } // } // // public static void init() { // for (Entry<String, Bitmap> entry : Emoticons.EMOTICON_BITMAPS.entrySet()) { // if (!mNames.contains(entry.getKey()) && !mBitmaps.contains(entry.getValue())) { // mNames.add(entry.getKey()); // mBitmaps.add(entry.getValue()); // } // } // } // // }
import android.content.Context; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.util.HashMap; import us.shandian.blacklight.support.adapter.EmoticonAdapter;
EMOTICONS.put("[不想上班]", "lxh_buxiangshangban.png"); EMOTICONS.put("[困死了]", "lxh_kunsile.png"); EMOTICONS.put("[许愿]", "lxh_xuyuan.png"); EMOTICONS.put("[丘比特]", "lxh_qiubite.png"); EMOTICONS.put("[有鸭梨]", "lxh_youyali.png"); EMOTICONS.put("[想一想]", "lxh_xiangyixiang.png"); EMOTICONS.put("[躁狂症]", "lxh_kuangzaozheng.png"); EMOTICONS.put("[转发]", "lxh_zhuanfa.png"); EMOTICONS.put("[互相膜拜]", "lxh_xianghumobai.png"); EMOTICONS.put("[雷锋]", "lxh_leifeng.png"); EMOTICONS.put("[杰克逊]", "lxh_jiekexun.png"); EMOTICONS.put("[玫瑰]", "lxh_meigui.png"); EMOTICONS.put("[hold住]", "lxh_holdzhu.png"); EMOTICONS.put("[群体围观]", "lxh_quntiweiguan.png"); EMOTICONS.put("[推荐]", "lxh_tuijian.png"); EMOTICONS.put("[赞啊]", "lxh_zana.png"); EMOTICONS.put("[被电]", "lxh_beidian.png"); EMOTICONS.put("[霹雳]", "lxh_pili.png"); } public static void init(Context context) { AssetManager am = context.getAssets(); for (String key : EMOTICONS.keySet()) { try { Bitmap bitmap = BitmapFactory.decodeStream(am.open(EMOTICONS.get(key))); EMOTICON_BITMAPS.put(key, bitmap); } catch (Exception e) { // just jump it } }
// Path: src/us/shandian/blacklight/support/adapter/EmoticonAdapter.java // public class EmoticonAdapter extends BaseAdapter // { // private static ArrayList<String> mNames = new ArrayList<String>(); // private static ArrayList<Bitmap> mBitmaps = new ArrayList<Bitmap>(); // // private LayoutInflater mInflater; // // public EmoticonAdapter(Context context) { // mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); // } // // @Override // public int getCount() { // return mNames.size(); // } // // @Override // public String getItem(int position) { // return mNames.get(position); // } // // @Override // public long getItemId(int position) { // return position; // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // if (position >= mNames.size()){ // return convertView; // } else { // View v = mInflater.inflate(R.layout.emoticon_view, null); // ImageView iv = (ImageView) v.findViewById(R.id.emoticon_image); // iv.setImageBitmap(mBitmaps.get(position)); // return v; // } // } // // public static void init() { // for (Entry<String, Bitmap> entry : Emoticons.EMOTICON_BITMAPS.entrySet()) { // if (!mNames.contains(entry.getKey()) && !mBitmaps.contains(entry.getValue())) { // mNames.add(entry.getKey()); // mBitmaps.add(entry.getValue()); // } // } // } // // } // Path: src/us/shandian/blacklight/support/Emoticons.java import android.content.Context; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.util.HashMap; import us.shandian.blacklight.support.adapter.EmoticonAdapter; EMOTICONS.put("[不想上班]", "lxh_buxiangshangban.png"); EMOTICONS.put("[困死了]", "lxh_kunsile.png"); EMOTICONS.put("[许愿]", "lxh_xuyuan.png"); EMOTICONS.put("[丘比特]", "lxh_qiubite.png"); EMOTICONS.put("[有鸭梨]", "lxh_youyali.png"); EMOTICONS.put("[想一想]", "lxh_xiangyixiang.png"); EMOTICONS.put("[躁狂症]", "lxh_kuangzaozheng.png"); EMOTICONS.put("[转发]", "lxh_zhuanfa.png"); EMOTICONS.put("[互相膜拜]", "lxh_xianghumobai.png"); EMOTICONS.put("[雷锋]", "lxh_leifeng.png"); EMOTICONS.put("[杰克逊]", "lxh_jiekexun.png"); EMOTICONS.put("[玫瑰]", "lxh_meigui.png"); EMOTICONS.put("[hold住]", "lxh_holdzhu.png"); EMOTICONS.put("[群体围观]", "lxh_quntiweiguan.png"); EMOTICONS.put("[推荐]", "lxh_tuijian.png"); EMOTICONS.put("[赞啊]", "lxh_zana.png"); EMOTICONS.put("[被电]", "lxh_beidian.png"); EMOTICONS.put("[霹雳]", "lxh_pili.png"); } public static void init(Context context) { AssetManager am = context.getAssets(); for (String key : EMOTICONS.keySet()) { try { Bitmap bitmap = BitmapFactory.decodeStream(am.open(EMOTICONS.get(key))); EMOTICON_BITMAPS.put(key, bitmap); } catch (Exception e) { // just jump it } }
EmoticonAdapter.init();
PeterCxy/BlackLight
src/us/shandian/blacklight/cache/login/LoginApiCache.java
// Path: src/us/shandian/blacklight/api/BaseApi.java // public abstract class BaseApi // { // private static final String TAG = BaseApi.class.getSimpleName(); // // // Http Methods // protected static final String HTTP_GET = HttpUtility.GET; // protected static final String HTTP_POST = HttpUtility.POST; // // // Access Token // private static String mAccessToken; // // protected static JSONObject request(String url, WeiboParameters params, String method) throws Exception { // return request(mAccessToken, url, params, method, JSONObject.class); // } // // protected static JSONArray requestArray(String url, WeiboParameters params, String method) throws Exception { // return request(mAccessToken, url, params, method, JSONArray.class); // } // // protected static <T> T request(String token, String url, WeiboParameters params, String method, Class<T> jsonClass) throws Exception { // if (token == null) { // return null; // } else { // params.put("access_token", token); // String jsonData = HttpUtility.doRequest(url, params, method); // // if (DEBUG) { // Log.d(TAG, "jsonData = " + jsonData); // } // // if (jsonData != null && jsonData.contains("{")) { // return jsonClass.getConstructor(String.class).newInstance(jsonData); // } else { // return null; // } // } // } // // protected static JSONObject requestWithoutAccessToken(String url, WeiboParameters params, String method) throws Exception { // String jsonData = HttpUtility.doRequest(url, params, method); // // if (DEBUG) { // Log.d(TAG, "jsonData = " + jsonData); // } // // if (jsonData != null && jsonData.contains("{")) { // return new JSONObject(jsonData); // } else { // return null; // } // } // // public static String getAccessToken() { // return mAccessToken; // } // // public static void setAccessToken(String token) { // mAccessToken = token; // } // } // // Path: src/us/shandian/blacklight/api/login/LoginApi.java // public class LoginApi extends BaseApi // { // private static final String TAG = LoginApi.class.getSimpleName(); // // // Returns token and expire date // public static String[] login(String appId, String appSecret, String username, String passwd) { // WeiboParameters params = new WeiboParameters(); // params.put("username", username); // params.put("password", passwd); // params.put("client_id", appId); // params.put("client_secret", appSecret); // params.put("grant_type", "password"); // // try { // JSONObject json = requestWithoutAccessToken(Constants.OAUTH2_ACCESS_TOKEN, params, HTTP_POST); // return new String[]{json.optString("access_token"), json.optString("expires_in")}; // } catch (Exception e) { // if (DEBUG) { // Log.e(TAG, "login error:" + e.getClass().getSimpleName()); // } // return null; // } // } // } // // Path: src/us/shandian/blacklight/api/user/AccountApi.java // public class AccountApi extends BaseApi // { // public static String getUid() { // try { // JSONObject json = request(Constants.GET_UID, new WeiboParameters(), HTTP_GET); // return json.optString("uid"); // } catch (Exception e) { // return null; // } // } // }
import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import us.shandian.blacklight.api.BaseApi; import us.shandian.blacklight.api.login.LoginApi; import us.shandian.blacklight.api.user.AccountApi; import static us.shandian.blacklight.BuildConfig.DEBUG;
/* * Copyright (C) 2014 Peter Cai * * This file is part of BlackLight * * BlackLight is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BlackLight 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 Public License for more details. * * You should have received a copy of the GNU General Public License * along with BlackLight. If not, see <http://www.gnu.org/licenses/>. */ package us.shandian.blacklight.cache.login; public class LoginApiCache { private static final String TAG = LoginApiCache.class.getSimpleName(); private SharedPreferences mPrefs; private String mAccessToken; private String mUid; private long mExpireDate; private String mAppId; private String mAppSecret; public LoginApiCache(Context context) { mPrefs = context.getSharedPreferences("access_token", Context.MODE_PRIVATE); mAccessToken = mPrefs.getString("access_token", null); mUid = mPrefs.getString("uid", null); mExpireDate = mPrefs.getLong("expires_in", Long.MIN_VALUE); mAppId = mPrefs.getString("app_id", null); mAppSecret = mPrefs.getString("app_secret", null); if (mAccessToken != null) {
// Path: src/us/shandian/blacklight/api/BaseApi.java // public abstract class BaseApi // { // private static final String TAG = BaseApi.class.getSimpleName(); // // // Http Methods // protected static final String HTTP_GET = HttpUtility.GET; // protected static final String HTTP_POST = HttpUtility.POST; // // // Access Token // private static String mAccessToken; // // protected static JSONObject request(String url, WeiboParameters params, String method) throws Exception { // return request(mAccessToken, url, params, method, JSONObject.class); // } // // protected static JSONArray requestArray(String url, WeiboParameters params, String method) throws Exception { // return request(mAccessToken, url, params, method, JSONArray.class); // } // // protected static <T> T request(String token, String url, WeiboParameters params, String method, Class<T> jsonClass) throws Exception { // if (token == null) { // return null; // } else { // params.put("access_token", token); // String jsonData = HttpUtility.doRequest(url, params, method); // // if (DEBUG) { // Log.d(TAG, "jsonData = " + jsonData); // } // // if (jsonData != null && jsonData.contains("{")) { // return jsonClass.getConstructor(String.class).newInstance(jsonData); // } else { // return null; // } // } // } // // protected static JSONObject requestWithoutAccessToken(String url, WeiboParameters params, String method) throws Exception { // String jsonData = HttpUtility.doRequest(url, params, method); // // if (DEBUG) { // Log.d(TAG, "jsonData = " + jsonData); // } // // if (jsonData != null && jsonData.contains("{")) { // return new JSONObject(jsonData); // } else { // return null; // } // } // // public static String getAccessToken() { // return mAccessToken; // } // // public static void setAccessToken(String token) { // mAccessToken = token; // } // } // // Path: src/us/shandian/blacklight/api/login/LoginApi.java // public class LoginApi extends BaseApi // { // private static final String TAG = LoginApi.class.getSimpleName(); // // // Returns token and expire date // public static String[] login(String appId, String appSecret, String username, String passwd) { // WeiboParameters params = new WeiboParameters(); // params.put("username", username); // params.put("password", passwd); // params.put("client_id", appId); // params.put("client_secret", appSecret); // params.put("grant_type", "password"); // // try { // JSONObject json = requestWithoutAccessToken(Constants.OAUTH2_ACCESS_TOKEN, params, HTTP_POST); // return new String[]{json.optString("access_token"), json.optString("expires_in")}; // } catch (Exception e) { // if (DEBUG) { // Log.e(TAG, "login error:" + e.getClass().getSimpleName()); // } // return null; // } // } // } // // Path: src/us/shandian/blacklight/api/user/AccountApi.java // public class AccountApi extends BaseApi // { // public static String getUid() { // try { // JSONObject json = request(Constants.GET_UID, new WeiboParameters(), HTTP_GET); // return json.optString("uid"); // } catch (Exception e) { // return null; // } // } // } // Path: src/us/shandian/blacklight/cache/login/LoginApiCache.java import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import us.shandian.blacklight.api.BaseApi; import us.shandian.blacklight.api.login.LoginApi; import us.shandian.blacklight.api.user.AccountApi; import static us.shandian.blacklight.BuildConfig.DEBUG; /* * Copyright (C) 2014 Peter Cai * * This file is part of BlackLight * * BlackLight is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BlackLight 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 Public License for more details. * * You should have received a copy of the GNU General Public License * along with BlackLight. If not, see <http://www.gnu.org/licenses/>. */ package us.shandian.blacklight.cache.login; public class LoginApiCache { private static final String TAG = LoginApiCache.class.getSimpleName(); private SharedPreferences mPrefs; private String mAccessToken; private String mUid; private long mExpireDate; private String mAppId; private String mAppSecret; public LoginApiCache(Context context) { mPrefs = context.getSharedPreferences("access_token", Context.MODE_PRIVATE); mAccessToken = mPrefs.getString("access_token", null); mUid = mPrefs.getString("uid", null); mExpireDate = mPrefs.getLong("expires_in", Long.MIN_VALUE); mAppId = mPrefs.getString("app_id", null); mAppSecret = mPrefs.getString("app_secret", null); if (mAccessToken != null) {
BaseApi.setAccessToken(mAccessToken);
PeterCxy/BlackLight
src/us/shandian/blacklight/cache/login/LoginApiCache.java
// Path: src/us/shandian/blacklight/api/BaseApi.java // public abstract class BaseApi // { // private static final String TAG = BaseApi.class.getSimpleName(); // // // Http Methods // protected static final String HTTP_GET = HttpUtility.GET; // protected static final String HTTP_POST = HttpUtility.POST; // // // Access Token // private static String mAccessToken; // // protected static JSONObject request(String url, WeiboParameters params, String method) throws Exception { // return request(mAccessToken, url, params, method, JSONObject.class); // } // // protected static JSONArray requestArray(String url, WeiboParameters params, String method) throws Exception { // return request(mAccessToken, url, params, method, JSONArray.class); // } // // protected static <T> T request(String token, String url, WeiboParameters params, String method, Class<T> jsonClass) throws Exception { // if (token == null) { // return null; // } else { // params.put("access_token", token); // String jsonData = HttpUtility.doRequest(url, params, method); // // if (DEBUG) { // Log.d(TAG, "jsonData = " + jsonData); // } // // if (jsonData != null && jsonData.contains("{")) { // return jsonClass.getConstructor(String.class).newInstance(jsonData); // } else { // return null; // } // } // } // // protected static JSONObject requestWithoutAccessToken(String url, WeiboParameters params, String method) throws Exception { // String jsonData = HttpUtility.doRequest(url, params, method); // // if (DEBUG) { // Log.d(TAG, "jsonData = " + jsonData); // } // // if (jsonData != null && jsonData.contains("{")) { // return new JSONObject(jsonData); // } else { // return null; // } // } // // public static String getAccessToken() { // return mAccessToken; // } // // public static void setAccessToken(String token) { // mAccessToken = token; // } // } // // Path: src/us/shandian/blacklight/api/login/LoginApi.java // public class LoginApi extends BaseApi // { // private static final String TAG = LoginApi.class.getSimpleName(); // // // Returns token and expire date // public static String[] login(String appId, String appSecret, String username, String passwd) { // WeiboParameters params = new WeiboParameters(); // params.put("username", username); // params.put("password", passwd); // params.put("client_id", appId); // params.put("client_secret", appSecret); // params.put("grant_type", "password"); // // try { // JSONObject json = requestWithoutAccessToken(Constants.OAUTH2_ACCESS_TOKEN, params, HTTP_POST); // return new String[]{json.optString("access_token"), json.optString("expires_in")}; // } catch (Exception e) { // if (DEBUG) { // Log.e(TAG, "login error:" + e.getClass().getSimpleName()); // } // return null; // } // } // } // // Path: src/us/shandian/blacklight/api/user/AccountApi.java // public class AccountApi extends BaseApi // { // public static String getUid() { // try { // JSONObject json = request(Constants.GET_UID, new WeiboParameters(), HTTP_GET); // return json.optString("uid"); // } catch (Exception e) { // return null; // } // } // }
import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import us.shandian.blacklight.api.BaseApi; import us.shandian.blacklight.api.login.LoginApi; import us.shandian.blacklight.api.user.AccountApi; import static us.shandian.blacklight.BuildConfig.DEBUG;
/* * Copyright (C) 2014 Peter Cai * * This file is part of BlackLight * * BlackLight is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BlackLight 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 Public License for more details. * * You should have received a copy of the GNU General Public License * along with BlackLight. If not, see <http://www.gnu.org/licenses/>. */ package us.shandian.blacklight.cache.login; public class LoginApiCache { private static final String TAG = LoginApiCache.class.getSimpleName(); private SharedPreferences mPrefs; private String mAccessToken; private String mUid; private long mExpireDate; private String mAppId; private String mAppSecret; public LoginApiCache(Context context) { mPrefs = context.getSharedPreferences("access_token", Context.MODE_PRIVATE); mAccessToken = mPrefs.getString("access_token", null); mUid = mPrefs.getString("uid", null); mExpireDate = mPrefs.getLong("expires_in", Long.MIN_VALUE); mAppId = mPrefs.getString("app_id", null); mAppSecret = mPrefs.getString("app_secret", null); if (mAccessToken != null) { BaseApi.setAccessToken(mAccessToken); } } public void login(String appId, String appSecret, String username, String passwd) { if (mAccessToken == null || mExpireDate == Long.MIN_VALUE) { if (DEBUG) { Log.d(TAG, "access token not initialized, running login function"); }
// Path: src/us/shandian/blacklight/api/BaseApi.java // public abstract class BaseApi // { // private static final String TAG = BaseApi.class.getSimpleName(); // // // Http Methods // protected static final String HTTP_GET = HttpUtility.GET; // protected static final String HTTP_POST = HttpUtility.POST; // // // Access Token // private static String mAccessToken; // // protected static JSONObject request(String url, WeiboParameters params, String method) throws Exception { // return request(mAccessToken, url, params, method, JSONObject.class); // } // // protected static JSONArray requestArray(String url, WeiboParameters params, String method) throws Exception { // return request(mAccessToken, url, params, method, JSONArray.class); // } // // protected static <T> T request(String token, String url, WeiboParameters params, String method, Class<T> jsonClass) throws Exception { // if (token == null) { // return null; // } else { // params.put("access_token", token); // String jsonData = HttpUtility.doRequest(url, params, method); // // if (DEBUG) { // Log.d(TAG, "jsonData = " + jsonData); // } // // if (jsonData != null && jsonData.contains("{")) { // return jsonClass.getConstructor(String.class).newInstance(jsonData); // } else { // return null; // } // } // } // // protected static JSONObject requestWithoutAccessToken(String url, WeiboParameters params, String method) throws Exception { // String jsonData = HttpUtility.doRequest(url, params, method); // // if (DEBUG) { // Log.d(TAG, "jsonData = " + jsonData); // } // // if (jsonData != null && jsonData.contains("{")) { // return new JSONObject(jsonData); // } else { // return null; // } // } // // public static String getAccessToken() { // return mAccessToken; // } // // public static void setAccessToken(String token) { // mAccessToken = token; // } // } // // Path: src/us/shandian/blacklight/api/login/LoginApi.java // public class LoginApi extends BaseApi // { // private static final String TAG = LoginApi.class.getSimpleName(); // // // Returns token and expire date // public static String[] login(String appId, String appSecret, String username, String passwd) { // WeiboParameters params = new WeiboParameters(); // params.put("username", username); // params.put("password", passwd); // params.put("client_id", appId); // params.put("client_secret", appSecret); // params.put("grant_type", "password"); // // try { // JSONObject json = requestWithoutAccessToken(Constants.OAUTH2_ACCESS_TOKEN, params, HTTP_POST); // return new String[]{json.optString("access_token"), json.optString("expires_in")}; // } catch (Exception e) { // if (DEBUG) { // Log.e(TAG, "login error:" + e.getClass().getSimpleName()); // } // return null; // } // } // } // // Path: src/us/shandian/blacklight/api/user/AccountApi.java // public class AccountApi extends BaseApi // { // public static String getUid() { // try { // JSONObject json = request(Constants.GET_UID, new WeiboParameters(), HTTP_GET); // return json.optString("uid"); // } catch (Exception e) { // return null; // } // } // } // Path: src/us/shandian/blacklight/cache/login/LoginApiCache.java import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import us.shandian.blacklight.api.BaseApi; import us.shandian.blacklight.api.login.LoginApi; import us.shandian.blacklight.api.user.AccountApi; import static us.shandian.blacklight.BuildConfig.DEBUG; /* * Copyright (C) 2014 Peter Cai * * This file is part of BlackLight * * BlackLight is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BlackLight 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 Public License for more details. * * You should have received a copy of the GNU General Public License * along with BlackLight. If not, see <http://www.gnu.org/licenses/>. */ package us.shandian.blacklight.cache.login; public class LoginApiCache { private static final String TAG = LoginApiCache.class.getSimpleName(); private SharedPreferences mPrefs; private String mAccessToken; private String mUid; private long mExpireDate; private String mAppId; private String mAppSecret; public LoginApiCache(Context context) { mPrefs = context.getSharedPreferences("access_token", Context.MODE_PRIVATE); mAccessToken = mPrefs.getString("access_token", null); mUid = mPrefs.getString("uid", null); mExpireDate = mPrefs.getLong("expires_in", Long.MIN_VALUE); mAppId = mPrefs.getString("app_id", null); mAppSecret = mPrefs.getString("app_secret", null); if (mAccessToken != null) { BaseApi.setAccessToken(mAccessToken); } } public void login(String appId, String appSecret, String username, String passwd) { if (mAccessToken == null || mExpireDate == Long.MIN_VALUE) { if (DEBUG) { Log.d(TAG, "access token not initialized, running login function"); }
String[] result = LoginApi.login(appId, appSecret, username, passwd);
PeterCxy/BlackLight
src/us/shandian/blacklight/cache/login/LoginApiCache.java
// Path: src/us/shandian/blacklight/api/BaseApi.java // public abstract class BaseApi // { // private static final String TAG = BaseApi.class.getSimpleName(); // // // Http Methods // protected static final String HTTP_GET = HttpUtility.GET; // protected static final String HTTP_POST = HttpUtility.POST; // // // Access Token // private static String mAccessToken; // // protected static JSONObject request(String url, WeiboParameters params, String method) throws Exception { // return request(mAccessToken, url, params, method, JSONObject.class); // } // // protected static JSONArray requestArray(String url, WeiboParameters params, String method) throws Exception { // return request(mAccessToken, url, params, method, JSONArray.class); // } // // protected static <T> T request(String token, String url, WeiboParameters params, String method, Class<T> jsonClass) throws Exception { // if (token == null) { // return null; // } else { // params.put("access_token", token); // String jsonData = HttpUtility.doRequest(url, params, method); // // if (DEBUG) { // Log.d(TAG, "jsonData = " + jsonData); // } // // if (jsonData != null && jsonData.contains("{")) { // return jsonClass.getConstructor(String.class).newInstance(jsonData); // } else { // return null; // } // } // } // // protected static JSONObject requestWithoutAccessToken(String url, WeiboParameters params, String method) throws Exception { // String jsonData = HttpUtility.doRequest(url, params, method); // // if (DEBUG) { // Log.d(TAG, "jsonData = " + jsonData); // } // // if (jsonData != null && jsonData.contains("{")) { // return new JSONObject(jsonData); // } else { // return null; // } // } // // public static String getAccessToken() { // return mAccessToken; // } // // public static void setAccessToken(String token) { // mAccessToken = token; // } // } // // Path: src/us/shandian/blacklight/api/login/LoginApi.java // public class LoginApi extends BaseApi // { // private static final String TAG = LoginApi.class.getSimpleName(); // // // Returns token and expire date // public static String[] login(String appId, String appSecret, String username, String passwd) { // WeiboParameters params = new WeiboParameters(); // params.put("username", username); // params.put("password", passwd); // params.put("client_id", appId); // params.put("client_secret", appSecret); // params.put("grant_type", "password"); // // try { // JSONObject json = requestWithoutAccessToken(Constants.OAUTH2_ACCESS_TOKEN, params, HTTP_POST); // return new String[]{json.optString("access_token"), json.optString("expires_in")}; // } catch (Exception e) { // if (DEBUG) { // Log.e(TAG, "login error:" + e.getClass().getSimpleName()); // } // return null; // } // } // } // // Path: src/us/shandian/blacklight/api/user/AccountApi.java // public class AccountApi extends BaseApi // { // public static String getUid() { // try { // JSONObject json = request(Constants.GET_UID, new WeiboParameters(), HTTP_GET); // return json.optString("uid"); // } catch (Exception e) { // return null; // } // } // }
import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import us.shandian.blacklight.api.BaseApi; import us.shandian.blacklight.api.login.LoginApi; import us.shandian.blacklight.api.user.AccountApi; import static us.shandian.blacklight.BuildConfig.DEBUG;
private String mAppSecret; public LoginApiCache(Context context) { mPrefs = context.getSharedPreferences("access_token", Context.MODE_PRIVATE); mAccessToken = mPrefs.getString("access_token", null); mUid = mPrefs.getString("uid", null); mExpireDate = mPrefs.getLong("expires_in", Long.MIN_VALUE); mAppId = mPrefs.getString("app_id", null); mAppSecret = mPrefs.getString("app_secret", null); if (mAccessToken != null) { BaseApi.setAccessToken(mAccessToken); } } public void login(String appId, String appSecret, String username, String passwd) { if (mAccessToken == null || mExpireDate == Long.MIN_VALUE) { if (DEBUG) { Log.d(TAG, "access token not initialized, running login function"); } String[] result = LoginApi.login(appId, appSecret, username, passwd); if (result != null) { if (DEBUG) { Log.d(TAG, "result got, loading to cache"); } mAccessToken = result[0]; BaseApi.setAccessToken(mAccessToken); mExpireDate = System.currentTimeMillis() + Long.valueOf(result[1]) * 1000; mAppId = appId; mAppSecret = appSecret;
// Path: src/us/shandian/blacklight/api/BaseApi.java // public abstract class BaseApi // { // private static final String TAG = BaseApi.class.getSimpleName(); // // // Http Methods // protected static final String HTTP_GET = HttpUtility.GET; // protected static final String HTTP_POST = HttpUtility.POST; // // // Access Token // private static String mAccessToken; // // protected static JSONObject request(String url, WeiboParameters params, String method) throws Exception { // return request(mAccessToken, url, params, method, JSONObject.class); // } // // protected static JSONArray requestArray(String url, WeiboParameters params, String method) throws Exception { // return request(mAccessToken, url, params, method, JSONArray.class); // } // // protected static <T> T request(String token, String url, WeiboParameters params, String method, Class<T> jsonClass) throws Exception { // if (token == null) { // return null; // } else { // params.put("access_token", token); // String jsonData = HttpUtility.doRequest(url, params, method); // // if (DEBUG) { // Log.d(TAG, "jsonData = " + jsonData); // } // // if (jsonData != null && jsonData.contains("{")) { // return jsonClass.getConstructor(String.class).newInstance(jsonData); // } else { // return null; // } // } // } // // protected static JSONObject requestWithoutAccessToken(String url, WeiboParameters params, String method) throws Exception { // String jsonData = HttpUtility.doRequest(url, params, method); // // if (DEBUG) { // Log.d(TAG, "jsonData = " + jsonData); // } // // if (jsonData != null && jsonData.contains("{")) { // return new JSONObject(jsonData); // } else { // return null; // } // } // // public static String getAccessToken() { // return mAccessToken; // } // // public static void setAccessToken(String token) { // mAccessToken = token; // } // } // // Path: src/us/shandian/blacklight/api/login/LoginApi.java // public class LoginApi extends BaseApi // { // private static final String TAG = LoginApi.class.getSimpleName(); // // // Returns token and expire date // public static String[] login(String appId, String appSecret, String username, String passwd) { // WeiboParameters params = new WeiboParameters(); // params.put("username", username); // params.put("password", passwd); // params.put("client_id", appId); // params.put("client_secret", appSecret); // params.put("grant_type", "password"); // // try { // JSONObject json = requestWithoutAccessToken(Constants.OAUTH2_ACCESS_TOKEN, params, HTTP_POST); // return new String[]{json.optString("access_token"), json.optString("expires_in")}; // } catch (Exception e) { // if (DEBUG) { // Log.e(TAG, "login error:" + e.getClass().getSimpleName()); // } // return null; // } // } // } // // Path: src/us/shandian/blacklight/api/user/AccountApi.java // public class AccountApi extends BaseApi // { // public static String getUid() { // try { // JSONObject json = request(Constants.GET_UID, new WeiboParameters(), HTTP_GET); // return json.optString("uid"); // } catch (Exception e) { // return null; // } // } // } // Path: src/us/shandian/blacklight/cache/login/LoginApiCache.java import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import us.shandian.blacklight.api.BaseApi; import us.shandian.blacklight.api.login.LoginApi; import us.shandian.blacklight.api.user.AccountApi; import static us.shandian.blacklight.BuildConfig.DEBUG; private String mAppSecret; public LoginApiCache(Context context) { mPrefs = context.getSharedPreferences("access_token", Context.MODE_PRIVATE); mAccessToken = mPrefs.getString("access_token", null); mUid = mPrefs.getString("uid", null); mExpireDate = mPrefs.getLong("expires_in", Long.MIN_VALUE); mAppId = mPrefs.getString("app_id", null); mAppSecret = mPrefs.getString("app_secret", null); if (mAccessToken != null) { BaseApi.setAccessToken(mAccessToken); } } public void login(String appId, String appSecret, String username, String passwd) { if (mAccessToken == null || mExpireDate == Long.MIN_VALUE) { if (DEBUG) { Log.d(TAG, "access token not initialized, running login function"); } String[] result = LoginApi.login(appId, appSecret, username, passwd); if (result != null) { if (DEBUG) { Log.d(TAG, "result got, loading to cache"); } mAccessToken = result[0]; BaseApi.setAccessToken(mAccessToken); mExpireDate = System.currentTimeMillis() + Long.valueOf(result[1]) * 1000; mAppId = appId; mAppSecret = appSecret;
mUid = AccountApi.getUid();
PeterCxy/BlackLight
src/us/shandian/blacklight/ui/common/HackyTextView.java
// Path: src/us/shandian/blacklight/support/HackyMovementMethod.java // public class HackyMovementMethod extends LinkMovementMethod // { // private static final String TAG = HackyMovementMethod.class.getSimpleName(); // // private static HackyMovementMethod sInstance; // // private BackgroundColorSpan mGray; // // private boolean mIsLinkHit = false; // // public static HackyMovementMethod getInstance() { // if (sInstance == null) { // sInstance = new HackyMovementMethod(); // } // // return sInstance; // } // // @Override // public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { // if (mGray == null) { // mGray = new BackgroundColorSpan(widget.getContext().getResources().getColor(R.color.selector_gray)); // } // // mIsLinkHit = false; // // int action = event.getAction(); // // if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP) { // int x = (int) event.getX(); // int y = (int) event.getY(); // // if (DEBUG) { // Log.d(TAG, "x = " + x + " y = " + y); // } // // x -= widget.getTotalPaddingLeft(); // y -= widget.getTotalPaddingTop(); // // if (DEBUG) { // Log.d(TAG, "x = " + x + " y = " + y); // } // // x += widget.getScrollX(); // y += widget.getScrollY(); // // int line = widget.getLayout().getLineForVertical(y); // int offset = widget.getLayout().getOffsetForHorizontal(line, x); // // ClickableSpan[] spans = buffer.getSpans(offset, offset, ClickableSpan.class); // // if (DEBUG) { // Log.d(TAG, "x = " + x + " y = " + y); // Log.d(TAG, "line = " + line + " offset = " + offset); // Log.d(TAG, "spans.lenth = " + spans.length); // } // // if (spans.length != 0) { // int start = buffer.getSpanStart(spans[0]); // int end = buffer.getSpanEnd(spans[0]); // // mIsLinkHit = true; // // if (action == MotionEvent.ACTION_DOWN) { // if (DEBUG) { // Log.d(TAG, "Down event detected"); // } // // buffer.setSpan(mGray, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // } else if (action == MotionEvent.ACTION_UP) { // if (DEBUG) { // Log.d(TAG, "Up event detected"); // } // // spans[0].onClick(widget); // // buffer.removeSpan(mGray); // } // // return true; // } // } else { // buffer.removeSpan(mGray); // } // // return Touch.onTouchEvent(widget, buffer, event); // } // // public boolean isLinkHit() { // boolean ret = mIsLinkHit; // mIsLinkHit = false; // return ret; // } // }
import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.TextView; import android.text.method.MovementMethod; import us.shandian.blacklight.support.HackyMovementMethod;
/* * Copyright (C) 2014 Peter Cai * * This file is part of BlackLight * * BlackLight is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BlackLight 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 Public License for more details. * * You should have received a copy of the GNU General Public License * along with BlackLight. If not, see <http://www.gnu.org/licenses/>. */ package us.shandian.blacklight.ui.common; /* Hack to fix conflict between MovementMethod and OnClickListener */ public class HackyTextView extends TextView { public HackyTextView(Context context) { super(context); } public HackyTextView(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onTouchEvent(MotionEvent event) { boolean ret = super.onTouchEvent(event); MovementMethod method = getMovementMethod();
// Path: src/us/shandian/blacklight/support/HackyMovementMethod.java // public class HackyMovementMethod extends LinkMovementMethod // { // private static final String TAG = HackyMovementMethod.class.getSimpleName(); // // private static HackyMovementMethod sInstance; // // private BackgroundColorSpan mGray; // // private boolean mIsLinkHit = false; // // public static HackyMovementMethod getInstance() { // if (sInstance == null) { // sInstance = new HackyMovementMethod(); // } // // return sInstance; // } // // @Override // public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { // if (mGray == null) { // mGray = new BackgroundColorSpan(widget.getContext().getResources().getColor(R.color.selector_gray)); // } // // mIsLinkHit = false; // // int action = event.getAction(); // // if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP) { // int x = (int) event.getX(); // int y = (int) event.getY(); // // if (DEBUG) { // Log.d(TAG, "x = " + x + " y = " + y); // } // // x -= widget.getTotalPaddingLeft(); // y -= widget.getTotalPaddingTop(); // // if (DEBUG) { // Log.d(TAG, "x = " + x + " y = " + y); // } // // x += widget.getScrollX(); // y += widget.getScrollY(); // // int line = widget.getLayout().getLineForVertical(y); // int offset = widget.getLayout().getOffsetForHorizontal(line, x); // // ClickableSpan[] spans = buffer.getSpans(offset, offset, ClickableSpan.class); // // if (DEBUG) { // Log.d(TAG, "x = " + x + " y = " + y); // Log.d(TAG, "line = " + line + " offset = " + offset); // Log.d(TAG, "spans.lenth = " + spans.length); // } // // if (spans.length != 0) { // int start = buffer.getSpanStart(spans[0]); // int end = buffer.getSpanEnd(spans[0]); // // mIsLinkHit = true; // // if (action == MotionEvent.ACTION_DOWN) { // if (DEBUG) { // Log.d(TAG, "Down event detected"); // } // // buffer.setSpan(mGray, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // } else if (action == MotionEvent.ACTION_UP) { // if (DEBUG) { // Log.d(TAG, "Up event detected"); // } // // spans[0].onClick(widget); // // buffer.removeSpan(mGray); // } // // return true; // } // } else { // buffer.removeSpan(mGray); // } // // return Touch.onTouchEvent(widget, buffer, event); // } // // public boolean isLinkHit() { // boolean ret = mIsLinkHit; // mIsLinkHit = false; // return ret; // } // } // Path: src/us/shandian/blacklight/ui/common/HackyTextView.java import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.TextView; import android.text.method.MovementMethod; import us.shandian.blacklight.support.HackyMovementMethod; /* * Copyright (C) 2014 Peter Cai * * This file is part of BlackLight * * BlackLight is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BlackLight 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 Public License for more details. * * You should have received a copy of the GNU General Public License * along with BlackLight. If not, see <http://www.gnu.org/licenses/>. */ package us.shandian.blacklight.ui.common; /* Hack to fix conflict between MovementMethod and OnClickListener */ public class HackyTextView extends TextView { public HackyTextView(Context context) { super(context); } public HackyTextView(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onTouchEvent(MotionEvent event) { boolean ret = super.onTouchEvent(event); MovementMethod method = getMovementMethod();
if (method instanceof HackyMovementMethod) {
PeterCxy/BlackLight
src/us/shandian/blacklight/ui/common/EmoticonFragment.java
// Path: src/us/shandian/blacklight/support/adapter/EmoticonAdapter.java // public class EmoticonAdapter extends BaseAdapter // { // private static ArrayList<String> mNames = new ArrayList<String>(); // private static ArrayList<Bitmap> mBitmaps = new ArrayList<Bitmap>(); // // private LayoutInflater mInflater; // // public EmoticonAdapter(Context context) { // mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); // } // // @Override // public int getCount() { // return mNames.size(); // } // // @Override // public String getItem(int position) { // return mNames.get(position); // } // // @Override // public long getItemId(int position) { // return position; // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // if (position >= mNames.size()){ // return convertView; // } else { // View v = mInflater.inflate(R.layout.emoticon_view, null); // ImageView iv = (ImageView) v.findViewById(R.id.emoticon_image); // iv.setImageBitmap(mBitmaps.get(position)); // return v; // } // } // // public static void init() { // for (Entry<String, Bitmap> entry : Emoticons.EMOTICON_BITMAPS.entrySet()) { // if (!mNames.contains(entry.getKey()) && !mBitmaps.contains(entry.getValue())) { // mNames.add(entry.getKey()); // mBitmaps.add(entry.getValue()); // } // } // } // // }
import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.GridView; import android.os.Bundle; import us.shandian.blacklight.R; import us.shandian.blacklight.support.adapter.EmoticonAdapter;
/* * Copyright (C) 2014 Peter Cai * * This file is part of BlackLight * * BlackLight is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BlackLight 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 Public License for more details. * * You should have received a copy of the GNU General Public License * along with BlackLight. If not, see <http://www.gnu.org/licenses/>. */ package us.shandian.blacklight.ui.common; public class EmoticonFragment extends Fragment implements AdapterView.OnItemClickListener { public static interface EmoticonListener { public void onEmoticonSelected(String name); } private GridView mGrid;
// Path: src/us/shandian/blacklight/support/adapter/EmoticonAdapter.java // public class EmoticonAdapter extends BaseAdapter // { // private static ArrayList<String> mNames = new ArrayList<String>(); // private static ArrayList<Bitmap> mBitmaps = new ArrayList<Bitmap>(); // // private LayoutInflater mInflater; // // public EmoticonAdapter(Context context) { // mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); // } // // @Override // public int getCount() { // return mNames.size(); // } // // @Override // public String getItem(int position) { // return mNames.get(position); // } // // @Override // public long getItemId(int position) { // return position; // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // if (position >= mNames.size()){ // return convertView; // } else { // View v = mInflater.inflate(R.layout.emoticon_view, null); // ImageView iv = (ImageView) v.findViewById(R.id.emoticon_image); // iv.setImageBitmap(mBitmaps.get(position)); // return v; // } // } // // public static void init() { // for (Entry<String, Bitmap> entry : Emoticons.EMOTICON_BITMAPS.entrySet()) { // if (!mNames.contains(entry.getKey()) && !mBitmaps.contains(entry.getValue())) { // mNames.add(entry.getKey()); // mBitmaps.add(entry.getValue()); // } // } // } // // } // Path: src/us/shandian/blacklight/ui/common/EmoticonFragment.java import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.GridView; import android.os.Bundle; import us.shandian.blacklight.R; import us.shandian.blacklight.support.adapter.EmoticonAdapter; /* * Copyright (C) 2014 Peter Cai * * This file is part of BlackLight * * BlackLight is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BlackLight 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 Public License for more details. * * You should have received a copy of the GNU General Public License * along with BlackLight. If not, see <http://www.gnu.org/licenses/>. */ package us.shandian.blacklight.ui.common; public class EmoticonFragment extends Fragment implements AdapterView.OnItemClickListener { public static interface EmoticonListener { public void onEmoticonSelected(String name); } private GridView mGrid;
private EmoticonAdapter mAdapter;
PeterCxy/BlackLight
src/us/shandian/blacklight/model/CommentListModel.java
// Path: src/us/shandian/blacklight/support/SpannableStringUtils.java // public class SpannableStringUtils // { // private static final String TAG = SpannableStringUtils.class.getSimpleName(); // // private static final Pattern PATTERN_WEB = Pattern.compile("http://[a-zA-Z0-9+&@#/%?=~_\\-|!:,\\.;]*[a-zA-Z0-9+&@#/%=~_|]"); // private static final Pattern PATTERN_TOPIC = Pattern.compile("#[\\p{Print}\\p{InCJKUnifiedIdeographs}&&[^#]]+#"); // private static final Pattern PATTERN_MENTION = Pattern.compile("@[\\w\\p{InCJKUnifiedIdeographs}-]{1,26}"); // private static final Pattern PATTERN_EMOTICON = Pattern.compile("\\[(\\S+?)\\]"); // // private static final String HTTP_SCHEME = "http://"; // private static final String TOPIC_SCHEME = "us.shandian.blacklight.topic://"; // private static final String MENTION_SCHEME = "us.shandian.blacklight.user://"; // // public static SpannableString span(String text) { // SpannableString ss = SpannableString.valueOf(text); // Linkify.addLinks(ss, PATTERN_WEB, HTTP_SCHEME); // Linkify.addLinks(ss, PATTERN_TOPIC, TOPIC_SCHEME); // Linkify.addLinks(ss, PATTERN_MENTION, MENTION_SCHEME); // // // Convert to our own span // URLSpan[] spans = ss.getSpans(0, ss.length(), URLSpan.class); // for (URLSpan span : spans) { // WeiboSpan s = new WeiboSpan(span.getURL()); // int start = ss.getSpanStart(span); // int end = ss.getSpanEnd(span); // ss.removeSpan(span); // ss.setSpan(s, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // } // // // Match Emoticons // Matcher matcher = PATTERN_EMOTICON.matcher(ss); // while (matcher.find()) { // // Don't be too long // if (matcher.end() - matcher.start() < 8) { // String iconName = matcher.group(0); // Bitmap bitmap = Emoticons.EMOTICON_BITMAPS.get(iconName); // // if (bitmap != null) { // ImageSpan span = new ImageSpan(bitmap, ImageSpan.ALIGN_BASELINE); // ss.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // } // } // } // // return ss; // } // // public static SpannableString getSpan(MessageModel msg) { // if (msg.span == null) { // // if (DEBUG) { // Log.d(TAG, msg.id + " span is null"); // } // // msg.span = span(msg.text); // } // // return msg.span; // } // // public static SpannableString getOrigSpan(MessageModel orig) { // if (orig.origSpan == null) { // // if (DEBUG) { // Log.d(TAG, orig.id + " origSpan is null"); // } // // String username = ""; // // if (orig.user != null) { // username = orig.user.getName(); // username = "@" + username + ":"; // } // // orig.origSpan = span(username + orig.text); // } // // return orig.origSpan; // } // }
import android.os.Parcel; import android.os.Parcelable; import java.util.ArrayList; import java.util.List; import us.shandian.blacklight.support.SpannableStringUtils;
/* * Copyright (C) 2014 Peter Cai * * This file is part of BlackLight * * BlackLight is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BlackLight 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 Public License for more details. * * You should have received a copy of the GNU General Public License * along with BlackLight. If not, see <http://www.gnu.org/licenses/>. */ package us.shandian.blacklight.model; /* A list of comments */ public class CommentListModel extends MessageListModel { private List<CommentModel> comments = new ArrayList<CommentModel>(); @Override public void spanAll() { super.spanAll(); for (CommentModel comment : comments) { if (comment.reply_comment != null) {
// Path: src/us/shandian/blacklight/support/SpannableStringUtils.java // public class SpannableStringUtils // { // private static final String TAG = SpannableStringUtils.class.getSimpleName(); // // private static final Pattern PATTERN_WEB = Pattern.compile("http://[a-zA-Z0-9+&@#/%?=~_\\-|!:,\\.;]*[a-zA-Z0-9+&@#/%=~_|]"); // private static final Pattern PATTERN_TOPIC = Pattern.compile("#[\\p{Print}\\p{InCJKUnifiedIdeographs}&&[^#]]+#"); // private static final Pattern PATTERN_MENTION = Pattern.compile("@[\\w\\p{InCJKUnifiedIdeographs}-]{1,26}"); // private static final Pattern PATTERN_EMOTICON = Pattern.compile("\\[(\\S+?)\\]"); // // private static final String HTTP_SCHEME = "http://"; // private static final String TOPIC_SCHEME = "us.shandian.blacklight.topic://"; // private static final String MENTION_SCHEME = "us.shandian.blacklight.user://"; // // public static SpannableString span(String text) { // SpannableString ss = SpannableString.valueOf(text); // Linkify.addLinks(ss, PATTERN_WEB, HTTP_SCHEME); // Linkify.addLinks(ss, PATTERN_TOPIC, TOPIC_SCHEME); // Linkify.addLinks(ss, PATTERN_MENTION, MENTION_SCHEME); // // // Convert to our own span // URLSpan[] spans = ss.getSpans(0, ss.length(), URLSpan.class); // for (URLSpan span : spans) { // WeiboSpan s = new WeiboSpan(span.getURL()); // int start = ss.getSpanStart(span); // int end = ss.getSpanEnd(span); // ss.removeSpan(span); // ss.setSpan(s, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // } // // // Match Emoticons // Matcher matcher = PATTERN_EMOTICON.matcher(ss); // while (matcher.find()) { // // Don't be too long // if (matcher.end() - matcher.start() < 8) { // String iconName = matcher.group(0); // Bitmap bitmap = Emoticons.EMOTICON_BITMAPS.get(iconName); // // if (bitmap != null) { // ImageSpan span = new ImageSpan(bitmap, ImageSpan.ALIGN_BASELINE); // ss.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // } // } // } // // return ss; // } // // public static SpannableString getSpan(MessageModel msg) { // if (msg.span == null) { // // if (DEBUG) { // Log.d(TAG, msg.id + " span is null"); // } // // msg.span = span(msg.text); // } // // return msg.span; // } // // public static SpannableString getOrigSpan(MessageModel orig) { // if (orig.origSpan == null) { // // if (DEBUG) { // Log.d(TAG, orig.id + " origSpan is null"); // } // // String username = ""; // // if (orig.user != null) { // username = orig.user.getName(); // username = "@" + username + ":"; // } // // orig.origSpan = span(username + orig.text); // } // // return orig.origSpan; // } // } // Path: src/us/shandian/blacklight/model/CommentListModel.java import android.os.Parcel; import android.os.Parcelable; import java.util.ArrayList; import java.util.List; import us.shandian.blacklight.support.SpannableStringUtils; /* * Copyright (C) 2014 Peter Cai * * This file is part of BlackLight * * BlackLight is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BlackLight 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 Public License for more details. * * You should have received a copy of the GNU General Public License * along with BlackLight. If not, see <http://www.gnu.org/licenses/>. */ package us.shandian.blacklight.model; /* A list of comments */ public class CommentListModel extends MessageListModel { private List<CommentModel> comments = new ArrayList<CommentModel>(); @Override public void spanAll() { super.spanAll(); for (CommentModel comment : comments) { if (comment.reply_comment != null) {
comment.reply_comment.origSpan = SpannableStringUtils.getOrigSpan(comment.reply_comment);
PeterCxy/BlackLight
src/us/shandian/blacklight/ui/search/AtUserSuggestDialog.java
// Path: src/us/shandian/blacklight/support/AsyncTask.java // public abstract class AsyncTask<Params, Progress, Result> // { // private static final String TAG = AsyncTask.class.getSimpleName(); // // private static class AsyncResult<Data> { // public AsyncTask task; // public Data[] data; // // public AsyncResult(AsyncTask task, Data... data) { // this.task = task; // this.data = data; // } // } // // private static final int MSG_FINISH = 1000; // private static final int MSG_PROGRESS = 1001; // // private static Handler sInternalHandler = new Handler() { // @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) // @Override // public void handleMessage(Message msg) { // AsyncResult result = (AsyncResult) msg.obj; // switch (msg.what) { // case MSG_FINISH: // result.task.onPostExecute(result.data[0]); // break; // case MSG_PROGRESS: // result.task.onProgressUpdate(result.data); // break; // } // } // }; // // private Params[] mParams; // // private Thread mThread = new Thread(new Runnable() { // @Override // public void run() { // CrashHandler.register(); // // try { // Result result = doInBackground(mParams); // sInternalHandler.sendMessage(sInternalHandler.obtainMessage(MSG_FINISH, new AsyncResult<Result>(AsyncTask.this, result))); // } catch (Exception e) { // // Don't crash the whole app // if (DEBUG) { // Log.d(TAG, e.getClass().getSimpleName() + " caught when running background task. Printing stack trace."); // Log.d(TAG, Log.getStackTraceString(e)); // } // } // // Thread.currentThread().interrupt(); // } // }); // // protected void onPostExecute(Result result) {} // // protected abstract Result doInBackground(Params... params); // // protected void onPreExecute() {} // // protected void onProgressUpdate(Progress... progress) {} // // protected void publishProgress(Progress... progress) { // sInternalHandler.sendMessage(sInternalHandler.obtainMessage(MSG_PROGRESS, new AsyncResult<Progress>(this, progress))); // } // // public void execute(Params... params) { // onPreExecute(); // mParams = params; // mThread.start(); // } // }
import us.shandian.blacklight.R; import us.shandian.blacklight.api.search.SearchApi; import us.shandian.blacklight.support.AsyncTask; import android.widget.*; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import java.util.ArrayList;
// Views setContentView(R.layout.at_user_dialog); mText = (EditText) findViewById(R.id.at_user_text); mSearch = findViewById(R.id.at_user_search); mList = (ListView) findViewById(R.id.at_user_list); mSearch.setOnClickListener(this); mList.setOnItemClickListener(this); } @Override public void onClick(View v) { if (mLoading) return; new SearchTask().execute(mText.getText().toString()); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (mListener != null && mStrs != null && position < mStrs.length) { mListener.onChooseUser(mStrs[position]); dismiss(); } } public void setListener(AtUserListener listener) { mListener = listener; }
// Path: src/us/shandian/blacklight/support/AsyncTask.java // public abstract class AsyncTask<Params, Progress, Result> // { // private static final String TAG = AsyncTask.class.getSimpleName(); // // private static class AsyncResult<Data> { // public AsyncTask task; // public Data[] data; // // public AsyncResult(AsyncTask task, Data... data) { // this.task = task; // this.data = data; // } // } // // private static final int MSG_FINISH = 1000; // private static final int MSG_PROGRESS = 1001; // // private static Handler sInternalHandler = new Handler() { // @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) // @Override // public void handleMessage(Message msg) { // AsyncResult result = (AsyncResult) msg.obj; // switch (msg.what) { // case MSG_FINISH: // result.task.onPostExecute(result.data[0]); // break; // case MSG_PROGRESS: // result.task.onProgressUpdate(result.data); // break; // } // } // }; // // private Params[] mParams; // // private Thread mThread = new Thread(new Runnable() { // @Override // public void run() { // CrashHandler.register(); // // try { // Result result = doInBackground(mParams); // sInternalHandler.sendMessage(sInternalHandler.obtainMessage(MSG_FINISH, new AsyncResult<Result>(AsyncTask.this, result))); // } catch (Exception e) { // // Don't crash the whole app // if (DEBUG) { // Log.d(TAG, e.getClass().getSimpleName() + " caught when running background task. Printing stack trace."); // Log.d(TAG, Log.getStackTraceString(e)); // } // } // // Thread.currentThread().interrupt(); // } // }); // // protected void onPostExecute(Result result) {} // // protected abstract Result doInBackground(Params... params); // // protected void onPreExecute() {} // // protected void onProgressUpdate(Progress... progress) {} // // protected void publishProgress(Progress... progress) { // sInternalHandler.sendMessage(sInternalHandler.obtainMessage(MSG_PROGRESS, new AsyncResult<Progress>(this, progress))); // } // // public void execute(Params... params) { // onPreExecute(); // mParams = params; // mThread.start(); // } // } // Path: src/us/shandian/blacklight/ui/search/AtUserSuggestDialog.java import us.shandian.blacklight.R; import us.shandian.blacklight.api.search.SearchApi; import us.shandian.blacklight.support.AsyncTask; import android.widget.*; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import java.util.ArrayList; // Views setContentView(R.layout.at_user_dialog); mText = (EditText) findViewById(R.id.at_user_text); mSearch = findViewById(R.id.at_user_search); mList = (ListView) findViewById(R.id.at_user_list); mSearch.setOnClickListener(this); mList.setOnItemClickListener(this); } @Override public void onClick(View v) { if (mLoading) return; new SearchTask().execute(mText.getText().toString()); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (mListener != null && mStrs != null && position < mStrs.length) { mListener.onChooseUser(mStrs[position]); dismiss(); } } public void setListener(AtUserListener listener) { mListener = listener; }
private class SearchTask extends AsyncTask<String, Void, String[]> {
PeterCxy/BlackLight
src/us/shandian/blacklight/model/MessageListModel.java
// Path: src/us/shandian/blacklight/support/SpannableStringUtils.java // public class SpannableStringUtils // { // private static final String TAG = SpannableStringUtils.class.getSimpleName(); // // private static final Pattern PATTERN_WEB = Pattern.compile("http://[a-zA-Z0-9+&@#/%?=~_\\-|!:,\\.;]*[a-zA-Z0-9+&@#/%=~_|]"); // private static final Pattern PATTERN_TOPIC = Pattern.compile("#[\\p{Print}\\p{InCJKUnifiedIdeographs}&&[^#]]+#"); // private static final Pattern PATTERN_MENTION = Pattern.compile("@[\\w\\p{InCJKUnifiedIdeographs}-]{1,26}"); // private static final Pattern PATTERN_EMOTICON = Pattern.compile("\\[(\\S+?)\\]"); // // private static final String HTTP_SCHEME = "http://"; // private static final String TOPIC_SCHEME = "us.shandian.blacklight.topic://"; // private static final String MENTION_SCHEME = "us.shandian.blacklight.user://"; // // public static SpannableString span(String text) { // SpannableString ss = SpannableString.valueOf(text); // Linkify.addLinks(ss, PATTERN_WEB, HTTP_SCHEME); // Linkify.addLinks(ss, PATTERN_TOPIC, TOPIC_SCHEME); // Linkify.addLinks(ss, PATTERN_MENTION, MENTION_SCHEME); // // // Convert to our own span // URLSpan[] spans = ss.getSpans(0, ss.length(), URLSpan.class); // for (URLSpan span : spans) { // WeiboSpan s = new WeiboSpan(span.getURL()); // int start = ss.getSpanStart(span); // int end = ss.getSpanEnd(span); // ss.removeSpan(span); // ss.setSpan(s, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // } // // // Match Emoticons // Matcher matcher = PATTERN_EMOTICON.matcher(ss); // while (matcher.find()) { // // Don't be too long // if (matcher.end() - matcher.start() < 8) { // String iconName = matcher.group(0); // Bitmap bitmap = Emoticons.EMOTICON_BITMAPS.get(iconName); // // if (bitmap != null) { // ImageSpan span = new ImageSpan(bitmap, ImageSpan.ALIGN_BASELINE); // ss.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // } // } // } // // return ss; // } // // public static SpannableString getSpan(MessageModel msg) { // if (msg.span == null) { // // if (DEBUG) { // Log.d(TAG, msg.id + " span is null"); // } // // msg.span = span(msg.text); // } // // return msg.span; // } // // public static SpannableString getOrigSpan(MessageModel orig) { // if (orig.origSpan == null) { // // if (DEBUG) { // Log.d(TAG, orig.id + " origSpan is null"); // } // // String username = ""; // // if (orig.user != null) { // username = orig.user.getName(); // username = "@" + username + ":"; // } // // orig.origSpan = span(username + orig.text); // } // // return orig.origSpan; // } // }
import android.os.Parcel; import android.os.Parcelable; import java.util.ArrayList; import java.util.List; import us.shandian.blacklight.support.SpannableStringUtils;
/* * Copyright (C) 2014 Peter Cai * * This file is part of BlackLight * * BlackLight is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BlackLight 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 Public License for more details. * * You should have received a copy of the GNU General Public License * along with BlackLight. If not, see <http://www.gnu.org/licenses/>. */ package us.shandian.blacklight.model; /* List of messages From timelines credits to: qii author: PeterCxy */ public class MessageListModel extends BaseListModel<MessageModel, MessageListModel> { private class AD { public long id = -1; public String mark = ""; @Override public boolean equals(Object o) { if (o instanceof AD) { return ((AD) o).id == id; } else { return super.equals(o); } } @Override public int hashCode() { return String.valueOf(id).hashCode(); } } private List<MessageModel> statuses = new ArrayList<MessageModel>(); private List<AD> ad = new ArrayList<AD>(); public void spanAll() { for (MessageModel msg : getList()) {
// Path: src/us/shandian/blacklight/support/SpannableStringUtils.java // public class SpannableStringUtils // { // private static final String TAG = SpannableStringUtils.class.getSimpleName(); // // private static final Pattern PATTERN_WEB = Pattern.compile("http://[a-zA-Z0-9+&@#/%?=~_\\-|!:,\\.;]*[a-zA-Z0-9+&@#/%=~_|]"); // private static final Pattern PATTERN_TOPIC = Pattern.compile("#[\\p{Print}\\p{InCJKUnifiedIdeographs}&&[^#]]+#"); // private static final Pattern PATTERN_MENTION = Pattern.compile("@[\\w\\p{InCJKUnifiedIdeographs}-]{1,26}"); // private static final Pattern PATTERN_EMOTICON = Pattern.compile("\\[(\\S+?)\\]"); // // private static final String HTTP_SCHEME = "http://"; // private static final String TOPIC_SCHEME = "us.shandian.blacklight.topic://"; // private static final String MENTION_SCHEME = "us.shandian.blacklight.user://"; // // public static SpannableString span(String text) { // SpannableString ss = SpannableString.valueOf(text); // Linkify.addLinks(ss, PATTERN_WEB, HTTP_SCHEME); // Linkify.addLinks(ss, PATTERN_TOPIC, TOPIC_SCHEME); // Linkify.addLinks(ss, PATTERN_MENTION, MENTION_SCHEME); // // // Convert to our own span // URLSpan[] spans = ss.getSpans(0, ss.length(), URLSpan.class); // for (URLSpan span : spans) { // WeiboSpan s = new WeiboSpan(span.getURL()); // int start = ss.getSpanStart(span); // int end = ss.getSpanEnd(span); // ss.removeSpan(span); // ss.setSpan(s, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // } // // // Match Emoticons // Matcher matcher = PATTERN_EMOTICON.matcher(ss); // while (matcher.find()) { // // Don't be too long // if (matcher.end() - matcher.start() < 8) { // String iconName = matcher.group(0); // Bitmap bitmap = Emoticons.EMOTICON_BITMAPS.get(iconName); // // if (bitmap != null) { // ImageSpan span = new ImageSpan(bitmap, ImageSpan.ALIGN_BASELINE); // ss.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // } // } // } // // return ss; // } // // public static SpannableString getSpan(MessageModel msg) { // if (msg.span == null) { // // if (DEBUG) { // Log.d(TAG, msg.id + " span is null"); // } // // msg.span = span(msg.text); // } // // return msg.span; // } // // public static SpannableString getOrigSpan(MessageModel orig) { // if (orig.origSpan == null) { // // if (DEBUG) { // Log.d(TAG, orig.id + " origSpan is null"); // } // // String username = ""; // // if (orig.user != null) { // username = orig.user.getName(); // username = "@" + username + ":"; // } // // orig.origSpan = span(username + orig.text); // } // // return orig.origSpan; // } // } // Path: src/us/shandian/blacklight/model/MessageListModel.java import android.os.Parcel; import android.os.Parcelable; import java.util.ArrayList; import java.util.List; import us.shandian.blacklight.support.SpannableStringUtils; /* * Copyright (C) 2014 Peter Cai * * This file is part of BlackLight * * BlackLight is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BlackLight 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 Public License for more details. * * You should have received a copy of the GNU General Public License * along with BlackLight. If not, see <http://www.gnu.org/licenses/>. */ package us.shandian.blacklight.model; /* List of messages From timelines credits to: qii author: PeterCxy */ public class MessageListModel extends BaseListModel<MessageModel, MessageListModel> { private class AD { public long id = -1; public String mark = ""; @Override public boolean equals(Object o) { if (o instanceof AD) { return ((AD) o).id == id; } else { return super.equals(o); } } @Override public int hashCode() { return String.valueOf(id).hashCode(); } } private List<MessageModel> statuses = new ArrayList<MessageModel>(); private List<AD> ad = new ArrayList<AD>(); public void spanAll() { for (MessageModel msg : getList()) {
msg.span = SpannableStringUtils.getSpan(msg);
PeterCxy/BlackLight
src/us/shandian/blacklight/ui/statuses/HomeTimeLineFragment.java
// Path: src/us/shandian/blacklight/support/Utility.java // public static boolean hasSmartBar() { // try { // Method method = Class.forName("android.os.Build").getMethod("hasSmartBar"); // return ((Boolean) method.invoke(null)).booleanValue(); // } catch (Exception e) { // } // // if (Build.DEVICE.equals("mx2") || Build.DEVICE.equals("mx3")) { // return true; // } else if (Build.DEVICE.equals("mx") || Build.DEVICE.equals("m9")) { // return false; // } // // return false; // }
import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import us.shandian.blacklight.R; import static us.shandian.blacklight.support.Utility.hasSmartBar;
package us.shandian.blacklight.ui.statuses; public class HomeTimeLineFragment extends TimeLineFragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ setHasOptionsMenu(true); return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
// Path: src/us/shandian/blacklight/support/Utility.java // public static boolean hasSmartBar() { // try { // Method method = Class.forName("android.os.Build").getMethod("hasSmartBar"); // return ((Boolean) method.invoke(null)).booleanValue(); // } catch (Exception e) { // } // // if (Build.DEVICE.equals("mx2") || Build.DEVICE.equals("mx3")) { // return true; // } else if (Build.DEVICE.equals("mx") || Build.DEVICE.equals("m9")) { // return false; // } // // return false; // } // Path: src/us/shandian/blacklight/ui/statuses/HomeTimeLineFragment.java import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import us.shandian.blacklight.R; import static us.shandian.blacklight.support.Utility.hasSmartBar; package us.shandian.blacklight.ui.statuses; public class HomeTimeLineFragment extends TimeLineFragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ setHasOptionsMenu(true); return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
if (hasSmartBar()){
Nauktis/SolarFlux
src/main/java/com/nauktis/core/gui/BaseModContainer.java
// Path: src/main/java/com/nauktis/core/utility/Utils.java // public final class Utils { // public static final Random RANDOM = new Random(); // // /** // * Utility class, no public constructor. // */ // private Utils() { // // } // // /** // * Returns true for server side world. // */ // public static boolean isServer(World pWorld) { // return !pWorld.isRemote; // } // // /** // * Returns true for client side world. // */ // public static boolean isClient(World pWorld) { // return pWorld.isRemote; // } // // /** // * Returns true if the player has a usable wrench equipped. // */ // public static boolean hasUsableWrench(EntityPlayer pPlayer, int pX, int pY, int pZ) { // ItemStack tool = pPlayer.getCurrentEquippedItem(); // if (tool != null) { // if (ModAPIManager.INSTANCE.hasAPI("BuildCraftAPI|tools") && tool.getItem() instanceof IToolWrench && ((IToolWrench) tool.getItem()) // .canWrench(pPlayer, pX, pY, pZ)) { // return true; // } // } // return false; // } // // /** // * Spawns an ItemStack in the World. No motion in X and Z axis. // */ // public static void spawnItemStack(World pWorld, int pX, int pY, int pZ, ItemStack pItemStack) { // EntityItem entityItem = new EntityItem(pWorld, pX + 0.5, pY + 0.5, pZ + 0.5, pItemStack); // entityItem.motionX = 0; // entityItem.motionZ = 0; // pWorld.spawnEntityInWorld(entityItem); // } // // /** // * Returns true if the two ItemStacks contains exactly the same item without taking stack size into account. // * Credit to Pahimar. // */ // public static boolean itemStacksEqualIgnoreStackSize(ItemStack pItemStack1, ItemStack pItemStack2) { // if (pItemStack1 != null && pItemStack2 != null) { // // Compare itemID // if (Item.getIdFromItem(pItemStack1.getItem()) - Item.getIdFromItem(pItemStack2.getItem()) == 0) { // // Compare item // if (pItemStack1.getItem() == pItemStack2.getItem()) { // // Compare meta // if (pItemStack1.getItemDamage() == pItemStack2.getItemDamage()) { // // Compare NBT presence // if (pItemStack1.hasTagCompound() && pItemStack2.hasTagCompound()) { // // Compare NBT // if (ItemStack.areItemStackTagsEqual(pItemStack1, pItemStack2)) { // return true; // } // } else if (!pItemStack1.hasTagCompound() && !pItemStack2.hasTagCompound()) { // return true; // } // } // } // } // } // return false; // } // // public static boolean isShiftKeyDown() { // return Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); // } // }
import com.google.common.collect.Maps; import com.nauktis.core.utility.Utils; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import java.util.List; import java.util.Map;
} } } protected void addPlayerActionSlotsToContainer(InventoryPlayer pInventoryPlayer, int pLeft, int pTop) { for (int actionBarSlotIndex = 0; actionBarSlotIndex < 9; ++actionBarSlotIndex) { this.addSlotToContainer(new Slot(pInventoryPlayer, actionBarSlotIndex, pLeft + actionBarSlotIndex * 18, pTop)); } } /** * Tries to add an ItemStack to slots in the range specified. It will first try to merge to an existing stack before using an empty one. * * @returns true if a slot was found. */ @Override protected boolean mergeItemStack(ItemStack pItemStack, int pSlotMin, int pSlotMax, boolean pAscending) { boolean slotFound = false; int currentSlotIndex = pAscending ? pSlotMax - 1 : pSlotMin; Slot slot; ItemStack stackInSlot; // Try to merge to an existing ItemStack if (pItemStack.isStackable()) { while (pItemStack.stackSize > 0 && (!pAscending && currentSlotIndex < pSlotMax || pAscending && currentSlotIndex >= pSlotMin)) { slot = getSlot(currentSlotIndex); stackInSlot = slot.getStack();
// Path: src/main/java/com/nauktis/core/utility/Utils.java // public final class Utils { // public static final Random RANDOM = new Random(); // // /** // * Utility class, no public constructor. // */ // private Utils() { // // } // // /** // * Returns true for server side world. // */ // public static boolean isServer(World pWorld) { // return !pWorld.isRemote; // } // // /** // * Returns true for client side world. // */ // public static boolean isClient(World pWorld) { // return pWorld.isRemote; // } // // /** // * Returns true if the player has a usable wrench equipped. // */ // public static boolean hasUsableWrench(EntityPlayer pPlayer, int pX, int pY, int pZ) { // ItemStack tool = pPlayer.getCurrentEquippedItem(); // if (tool != null) { // if (ModAPIManager.INSTANCE.hasAPI("BuildCraftAPI|tools") && tool.getItem() instanceof IToolWrench && ((IToolWrench) tool.getItem()) // .canWrench(pPlayer, pX, pY, pZ)) { // return true; // } // } // return false; // } // // /** // * Spawns an ItemStack in the World. No motion in X and Z axis. // */ // public static void spawnItemStack(World pWorld, int pX, int pY, int pZ, ItemStack pItemStack) { // EntityItem entityItem = new EntityItem(pWorld, pX + 0.5, pY + 0.5, pZ + 0.5, pItemStack); // entityItem.motionX = 0; // entityItem.motionZ = 0; // pWorld.spawnEntityInWorld(entityItem); // } // // /** // * Returns true if the two ItemStacks contains exactly the same item without taking stack size into account. // * Credit to Pahimar. // */ // public static boolean itemStacksEqualIgnoreStackSize(ItemStack pItemStack1, ItemStack pItemStack2) { // if (pItemStack1 != null && pItemStack2 != null) { // // Compare itemID // if (Item.getIdFromItem(pItemStack1.getItem()) - Item.getIdFromItem(pItemStack2.getItem()) == 0) { // // Compare item // if (pItemStack1.getItem() == pItemStack2.getItem()) { // // Compare meta // if (pItemStack1.getItemDamage() == pItemStack2.getItemDamage()) { // // Compare NBT presence // if (pItemStack1.hasTagCompound() && pItemStack2.hasTagCompound()) { // // Compare NBT // if (ItemStack.areItemStackTagsEqual(pItemStack1, pItemStack2)) { // return true; // } // } else if (!pItemStack1.hasTagCompound() && !pItemStack2.hasTagCompound()) { // return true; // } // } // } // } // } // return false; // } // // public static boolean isShiftKeyDown() { // return Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); // } // } // Path: src/main/java/com/nauktis/core/gui/BaseModContainer.java import com.google.common.collect.Maps; import com.nauktis.core.utility.Utils; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import java.util.List; import java.util.Map; } } } protected void addPlayerActionSlotsToContainer(InventoryPlayer pInventoryPlayer, int pLeft, int pTop) { for (int actionBarSlotIndex = 0; actionBarSlotIndex < 9; ++actionBarSlotIndex) { this.addSlotToContainer(new Slot(pInventoryPlayer, actionBarSlotIndex, pLeft + actionBarSlotIndex * 18, pTop)); } } /** * Tries to add an ItemStack to slots in the range specified. It will first try to merge to an existing stack before using an empty one. * * @returns true if a slot was found. */ @Override protected boolean mergeItemStack(ItemStack pItemStack, int pSlotMin, int pSlotMax, boolean pAscending) { boolean slotFound = false; int currentSlotIndex = pAscending ? pSlotMax - 1 : pSlotMin; Slot slot; ItemStack stackInSlot; // Try to merge to an existing ItemStack if (pItemStack.isStackable()) { while (pItemStack.stackSize > 0 && (!pAscending && currentSlotIndex < pSlotMax || pAscending && currentSlotIndex >= pSlotMin)) { slot = getSlot(currentSlotIndex); stackInSlot = slot.getStack();
if (slot.isItemValid(pItemStack) && Utils.itemStacksEqualIgnoreStackSize(pItemStack, stackInSlot)) {
Nauktis/SolarFlux
src/main/java/com/nauktis/core/block/BaseModBlock.java
// Path: src/main/java/com/nauktis/core/block/icon/IBlockIconHandler.java // public interface IBlockIconHandler { // IIcon getIcon(int pSide, int pMetadata); // // IIcon getIcon(IBlockAccess pBlockAccess, int pX, int pY, int pZ, int pSide); // // void registerBlockIcons(IIconRegister pIconRegister); // }
import com.nauktis.core.block.icon.IBlockIconHandler; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import static com.google.common.base.Preconditions.checkNotNull;
package com.nauktis.core.block; public class BaseModBlock extends Block { private final String mModId;
// Path: src/main/java/com/nauktis/core/block/icon/IBlockIconHandler.java // public interface IBlockIconHandler { // IIcon getIcon(int pSide, int pMetadata); // // IIcon getIcon(IBlockAccess pBlockAccess, int pX, int pY, int pZ, int pSide); // // void registerBlockIcons(IIconRegister pIconRegister); // } // Path: src/main/java/com/nauktis/core/block/BaseModBlock.java import com.nauktis.core.block.icon.IBlockIconHandler; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import static com.google.common.base.Preconditions.checkNotNull; package com.nauktis.core.block; public class BaseModBlock extends Block { private final String mModId;
private final IBlockIconHandler mBlockIconHandler;
Nauktis/SolarFlux
src/main/java/com/nauktis/solarflux/blocks/StatefulEnergyStorage.java
// Path: src/main/java/com/nauktis/solarflux/reference/NBTConstants.java // public final class NBTConstants { // private static final String NBT_PREFIX = "SF"; // public static final String TIER_INDEX = NBT_PREFIX + "TierIndex"; // public static final String ITEMS = NBT_PREFIX + "Items"; // public static final String SLOT = NBT_PREFIX + "Slot"; // public static final String ENERGY = NBT_PREFIX + "Energy"; // // private static final String TOOLTIP_PREFIX = NBT_PREFIX + "TL"; // public static final String TOOLTIP_UPGRADE_COUNT = TOOLTIP_PREFIX + "UpgradeCount"; // public static final String TOOLTIP_TRANSFER_RATE = TOOLTIP_PREFIX + "TransferRate"; // public static final String TOOLTIP_CAPACITY = TOOLTIP_PREFIX + "Capacity"; // // private NBTConstants() { // // } // }
import cofh.api.energy.IEnergyReceiver; import cofh.api.energy.IEnergyStorage; import com.google.common.base.Objects; import com.nauktis.solarflux.reference.NBTConstants; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection;
package com.nauktis.solarflux.blocks; public class StatefulEnergyStorage implements IEnergyStorage { protected int mEnergy; protected int mCapacity; protected int mMaxTransferReceive; protected int mMaxTransferExtract; public StatefulEnergyStorage(int pCapacity) { this(pCapacity, pCapacity, pCapacity); } public StatefulEnergyStorage(int pCapacity, int pMaxTransfer) { this(pCapacity, pMaxTransfer, pMaxTransfer); } public StatefulEnergyStorage(int pCapacity, int pMaxTransferReceive, int pMaxTransferExtract) { mCapacity = pCapacity; mMaxTransferReceive = pMaxTransferReceive; mMaxTransferExtract = pMaxTransferExtract; } public void readFromNBT(NBTTagCompound pNbt) {
// Path: src/main/java/com/nauktis/solarflux/reference/NBTConstants.java // public final class NBTConstants { // private static final String NBT_PREFIX = "SF"; // public static final String TIER_INDEX = NBT_PREFIX + "TierIndex"; // public static final String ITEMS = NBT_PREFIX + "Items"; // public static final String SLOT = NBT_PREFIX + "Slot"; // public static final String ENERGY = NBT_PREFIX + "Energy"; // // private static final String TOOLTIP_PREFIX = NBT_PREFIX + "TL"; // public static final String TOOLTIP_UPGRADE_COUNT = TOOLTIP_PREFIX + "UpgradeCount"; // public static final String TOOLTIP_TRANSFER_RATE = TOOLTIP_PREFIX + "TransferRate"; // public static final String TOOLTIP_CAPACITY = TOOLTIP_PREFIX + "Capacity"; // // private NBTConstants() { // // } // } // Path: src/main/java/com/nauktis/solarflux/blocks/StatefulEnergyStorage.java import cofh.api.energy.IEnergyReceiver; import cofh.api.energy.IEnergyStorage; import com.google.common.base.Objects; import com.nauktis.solarflux.reference.NBTConstants; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; package com.nauktis.solarflux.blocks; public class StatefulEnergyStorage implements IEnergyStorage { protected int mEnergy; protected int mCapacity; protected int mMaxTransferReceive; protected int mMaxTransferExtract; public StatefulEnergyStorage(int pCapacity) { this(pCapacity, pCapacity, pCapacity); } public StatefulEnergyStorage(int pCapacity, int pMaxTransfer) { this(pCapacity, pMaxTransfer, pMaxTransfer); } public StatefulEnergyStorage(int pCapacity, int pMaxTransferReceive, int pMaxTransferExtract) { mCapacity = pCapacity; mMaxTransferReceive = pMaxTransferReceive; mMaxTransferExtract = pMaxTransferExtract; } public void readFromNBT(NBTTagCompound pNbt) {
setEnergyStored(pNbt.getInteger(NBTConstants.ENERGY));
Nauktis/SolarFlux
src/main/java/com/nauktis/core/block/BaseModBlockWithTileEntity.java
// Path: src/main/java/com/nauktis/core/block/icon/IBlockIconHandler.java // public interface IBlockIconHandler { // IIcon getIcon(int pSide, int pMetadata); // // IIcon getIcon(IBlockAccess pBlockAccess, int pX, int pY, int pZ, int pSide); // // void registerBlockIcons(IIconRegister pIconRegister); // } // // Path: src/main/java/com/nauktis/core/utility/Utils.java // public final class Utils { // public static final Random RANDOM = new Random(); // // /** // * Utility class, no public constructor. // */ // private Utils() { // // } // // /** // * Returns true for server side world. // */ // public static boolean isServer(World pWorld) { // return !pWorld.isRemote; // } // // /** // * Returns true for client side world. // */ // public static boolean isClient(World pWorld) { // return pWorld.isRemote; // } // // /** // * Returns true if the player has a usable wrench equipped. // */ // public static boolean hasUsableWrench(EntityPlayer pPlayer, int pX, int pY, int pZ) { // ItemStack tool = pPlayer.getCurrentEquippedItem(); // if (tool != null) { // if (ModAPIManager.INSTANCE.hasAPI("BuildCraftAPI|tools") && tool.getItem() instanceof IToolWrench && ((IToolWrench) tool.getItem()) // .canWrench(pPlayer, pX, pY, pZ)) { // return true; // } // } // return false; // } // // /** // * Spawns an ItemStack in the World. No motion in X and Z axis. // */ // public static void spawnItemStack(World pWorld, int pX, int pY, int pZ, ItemStack pItemStack) { // EntityItem entityItem = new EntityItem(pWorld, pX + 0.5, pY + 0.5, pZ + 0.5, pItemStack); // entityItem.motionX = 0; // entityItem.motionZ = 0; // pWorld.spawnEntityInWorld(entityItem); // } // // /** // * Returns true if the two ItemStacks contains exactly the same item without taking stack size into account. // * Credit to Pahimar. // */ // public static boolean itemStacksEqualIgnoreStackSize(ItemStack pItemStack1, ItemStack pItemStack2) { // if (pItemStack1 != null && pItemStack2 != null) { // // Compare itemID // if (Item.getIdFromItem(pItemStack1.getItem()) - Item.getIdFromItem(pItemStack2.getItem()) == 0) { // // Compare item // if (pItemStack1.getItem() == pItemStack2.getItem()) { // // Compare meta // if (pItemStack1.getItemDamage() == pItemStack2.getItemDamage()) { // // Compare NBT presence // if (pItemStack1.hasTagCompound() && pItemStack2.hasTagCompound()) { // // Compare NBT // if (ItemStack.areItemStackTagsEqual(pItemStack1, pItemStack2)) { // return true; // } // } else if (!pItemStack1.hasTagCompound() && !pItemStack2.hasTagCompound()) { // return true; // } // } // } // } // } // return false; // } // // public static boolean isShiftKeyDown() { // return Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); // } // }
import com.nauktis.core.block.icon.IBlockIconHandler; import com.nauktis.core.utility.Utils; import net.minecraft.block.Block; import net.minecraft.block.ITileEntityProvider; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World;
package com.nauktis.core.block; public abstract class BaseModBlockWithTileEntity extends BaseModBlock implements ITileEntityProvider { public BaseModBlockWithTileEntity(String pModId, String pName, IBlockIconHandler pBlockIconHandler) { super(pModId, pName, pBlockIconHandler); isBlockContainer = true; } @Override public void breakBlock(World pWorld, int pX, int pY, int pZ, Block pBlock, int pMeta) { dropInventory(pWorld, pX, pY, pZ); super.breakBlock(pWorld, pX, pY, pZ, pBlock, pMeta); } @Override public boolean onBlockEventReceived(World pWorld, int pX, int pY, int pZ, int pEventNumber, int pEventArgument) { super.onBlockEventReceived(pWorld, pX, pY, pZ, pEventNumber, pEventArgument); TileEntity tileentity = pWorld.getTileEntity(pX, pY, pZ); if (tileentity != null) { return tileentity.receiveClientEvent(pEventNumber, pEventArgument); } return false; } /** * If the block has a TileEntity that has an inventory, this method will drop all of its content. */ protected void dropInventory(World pWorld, int pX, int pY, int pZ) { TileEntity tileEntity = pWorld.getTileEntity(pX, pY, pZ); if (tileEntity instanceof IInventory) { IInventory inventory = (IInventory) tileEntity; for (int i = 0; i < inventory.getSizeInventory(); i++) { ItemStack itemStack = inventory.getStackInSlot(i); if (itemStack != null && itemStack.stackSize > 0) {
// Path: src/main/java/com/nauktis/core/block/icon/IBlockIconHandler.java // public interface IBlockIconHandler { // IIcon getIcon(int pSide, int pMetadata); // // IIcon getIcon(IBlockAccess pBlockAccess, int pX, int pY, int pZ, int pSide); // // void registerBlockIcons(IIconRegister pIconRegister); // } // // Path: src/main/java/com/nauktis/core/utility/Utils.java // public final class Utils { // public static final Random RANDOM = new Random(); // // /** // * Utility class, no public constructor. // */ // private Utils() { // // } // // /** // * Returns true for server side world. // */ // public static boolean isServer(World pWorld) { // return !pWorld.isRemote; // } // // /** // * Returns true for client side world. // */ // public static boolean isClient(World pWorld) { // return pWorld.isRemote; // } // // /** // * Returns true if the player has a usable wrench equipped. // */ // public static boolean hasUsableWrench(EntityPlayer pPlayer, int pX, int pY, int pZ) { // ItemStack tool = pPlayer.getCurrentEquippedItem(); // if (tool != null) { // if (ModAPIManager.INSTANCE.hasAPI("BuildCraftAPI|tools") && tool.getItem() instanceof IToolWrench && ((IToolWrench) tool.getItem()) // .canWrench(pPlayer, pX, pY, pZ)) { // return true; // } // } // return false; // } // // /** // * Spawns an ItemStack in the World. No motion in X and Z axis. // */ // public static void spawnItemStack(World pWorld, int pX, int pY, int pZ, ItemStack pItemStack) { // EntityItem entityItem = new EntityItem(pWorld, pX + 0.5, pY + 0.5, pZ + 0.5, pItemStack); // entityItem.motionX = 0; // entityItem.motionZ = 0; // pWorld.spawnEntityInWorld(entityItem); // } // // /** // * Returns true if the two ItemStacks contains exactly the same item without taking stack size into account. // * Credit to Pahimar. // */ // public static boolean itemStacksEqualIgnoreStackSize(ItemStack pItemStack1, ItemStack pItemStack2) { // if (pItemStack1 != null && pItemStack2 != null) { // // Compare itemID // if (Item.getIdFromItem(pItemStack1.getItem()) - Item.getIdFromItem(pItemStack2.getItem()) == 0) { // // Compare item // if (pItemStack1.getItem() == pItemStack2.getItem()) { // // Compare meta // if (pItemStack1.getItemDamage() == pItemStack2.getItemDamage()) { // // Compare NBT presence // if (pItemStack1.hasTagCompound() && pItemStack2.hasTagCompound()) { // // Compare NBT // if (ItemStack.areItemStackTagsEqual(pItemStack1, pItemStack2)) { // return true; // } // } else if (!pItemStack1.hasTagCompound() && !pItemStack2.hasTagCompound()) { // return true; // } // } // } // } // } // return false; // } // // public static boolean isShiftKeyDown() { // return Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); // } // } // Path: src/main/java/com/nauktis/core/block/BaseModBlockWithTileEntity.java import com.nauktis.core.block.icon.IBlockIconHandler; import com.nauktis.core.utility.Utils; import net.minecraft.block.Block; import net.minecraft.block.ITileEntityProvider; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; package com.nauktis.core.block; public abstract class BaseModBlockWithTileEntity extends BaseModBlock implements ITileEntityProvider { public BaseModBlockWithTileEntity(String pModId, String pName, IBlockIconHandler pBlockIconHandler) { super(pModId, pName, pBlockIconHandler); isBlockContainer = true; } @Override public void breakBlock(World pWorld, int pX, int pY, int pZ, Block pBlock, int pMeta) { dropInventory(pWorld, pX, pY, pZ); super.breakBlock(pWorld, pX, pY, pZ, pBlock, pMeta); } @Override public boolean onBlockEventReceived(World pWorld, int pX, int pY, int pZ, int pEventNumber, int pEventArgument) { super.onBlockEventReceived(pWorld, pX, pY, pZ, pEventNumber, pEventArgument); TileEntity tileentity = pWorld.getTileEntity(pX, pY, pZ); if (tileentity != null) { return tileentity.receiveClientEvent(pEventNumber, pEventArgument); } return false; } /** * If the block has a TileEntity that has an inventory, this method will drop all of its content. */ protected void dropInventory(World pWorld, int pX, int pY, int pZ) { TileEntity tileEntity = pWorld.getTileEntity(pX, pY, pZ); if (tileEntity instanceof IInventory) { IInventory inventory = (IInventory) tileEntity; for (int i = 0; i < inventory.getSizeInventory(); i++) { ItemStack itemStack = inventory.getStackInSlot(i); if (itemStack != null && itemStack.stackSize > 0) {
Utils.spawnItemStack(pWorld, pX, pY, pZ, itemStack.copy());
Nauktis/SolarFlux
src/main/java/com/nauktis/solarflux/items/UpgradeItem.java
// Path: src/main/java/com/nauktis/core/utility/Color.java // public enum Color { // BLACK("\u00a70"), // WHITE("\u00a7f"), // GREY("\u00a77"), // AQUA("\u00a7b"), // GREEN("\u00a7a"), // RED("\u00a7c"), // YELLOW("\u00a7e"); // // public final String mColorCode; // // Color(String pColorCode) { // mColorCode = pColorCode; // } // // @Override // public String toString() { // return mColorCode; // } // } // // Path: src/main/java/com/nauktis/core/utility/Utils.java // public final class Utils { // public static final Random RANDOM = new Random(); // // /** // * Utility class, no public constructor. // */ // private Utils() { // // } // // /** // * Returns true for server side world. // */ // public static boolean isServer(World pWorld) { // return !pWorld.isRemote; // } // // /** // * Returns true for client side world. // */ // public static boolean isClient(World pWorld) { // return pWorld.isRemote; // } // // /** // * Returns true if the player has a usable wrench equipped. // */ // public static boolean hasUsableWrench(EntityPlayer pPlayer, int pX, int pY, int pZ) { // ItemStack tool = pPlayer.getCurrentEquippedItem(); // if (tool != null) { // if (ModAPIManager.INSTANCE.hasAPI("BuildCraftAPI|tools") && tool.getItem() instanceof IToolWrench && ((IToolWrench) tool.getItem()) // .canWrench(pPlayer, pX, pY, pZ)) { // return true; // } // } // return false; // } // // /** // * Spawns an ItemStack in the World. No motion in X and Z axis. // */ // public static void spawnItemStack(World pWorld, int pX, int pY, int pZ, ItemStack pItemStack) { // EntityItem entityItem = new EntityItem(pWorld, pX + 0.5, pY + 0.5, pZ + 0.5, pItemStack); // entityItem.motionX = 0; // entityItem.motionZ = 0; // pWorld.spawnEntityInWorld(entityItem); // } // // /** // * Returns true if the two ItemStacks contains exactly the same item without taking stack size into account. // * Credit to Pahimar. // */ // public static boolean itemStacksEqualIgnoreStackSize(ItemStack pItemStack1, ItemStack pItemStack2) { // if (pItemStack1 != null && pItemStack2 != null) { // // Compare itemID // if (Item.getIdFromItem(pItemStack1.getItem()) - Item.getIdFromItem(pItemStack2.getItem()) == 0) { // // Compare item // if (pItemStack1.getItem() == pItemStack2.getItem()) { // // Compare meta // if (pItemStack1.getItemDamage() == pItemStack2.getItemDamage()) { // // Compare NBT presence // if (pItemStack1.hasTagCompound() && pItemStack2.hasTagCompound()) { // // Compare NBT // if (ItemStack.areItemStackTagsEqual(pItemStack1, pItemStack2)) { // return true; // } // } else if (!pItemStack1.hasTagCompound() && !pItemStack2.hasTagCompound()) { // return true; // } // } // } // } // } // return false; // } // // public static boolean isShiftKeyDown() { // return Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); // } // }
import com.google.common.collect.Lists; import com.nauktis.core.utility.Color; import com.nauktis.core.utility.Utils; import com.nauktis.solarflux.utility.Lang; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import java.util.List;
package com.nauktis.solarflux.items; public class UpgradeItem extends SFItem { private final int mMaximumPerSolarPanel; private final List<String> mUpgradeInfos = Lists.newArrayList(); public UpgradeItem(String pName, int pMaximumPerSolarPanel, List<String> pUpgradeInfos) { super(pName); mMaximumPerSolarPanel = pMaximumPerSolarPanel; mUpgradeInfos.addAll(pUpgradeInfos); } @Override public void addInformation(ItemStack pItemStack, EntityPlayer pEntityPlayer, List pList, boolean pBoolean) { super.addInformation(pItemStack, pEntityPlayer, pList, pBoolean);
// Path: src/main/java/com/nauktis/core/utility/Color.java // public enum Color { // BLACK("\u00a70"), // WHITE("\u00a7f"), // GREY("\u00a77"), // AQUA("\u00a7b"), // GREEN("\u00a7a"), // RED("\u00a7c"), // YELLOW("\u00a7e"); // // public final String mColorCode; // // Color(String pColorCode) { // mColorCode = pColorCode; // } // // @Override // public String toString() { // return mColorCode; // } // } // // Path: src/main/java/com/nauktis/core/utility/Utils.java // public final class Utils { // public static final Random RANDOM = new Random(); // // /** // * Utility class, no public constructor. // */ // private Utils() { // // } // // /** // * Returns true for server side world. // */ // public static boolean isServer(World pWorld) { // return !pWorld.isRemote; // } // // /** // * Returns true for client side world. // */ // public static boolean isClient(World pWorld) { // return pWorld.isRemote; // } // // /** // * Returns true if the player has a usable wrench equipped. // */ // public static boolean hasUsableWrench(EntityPlayer pPlayer, int pX, int pY, int pZ) { // ItemStack tool = pPlayer.getCurrentEquippedItem(); // if (tool != null) { // if (ModAPIManager.INSTANCE.hasAPI("BuildCraftAPI|tools") && tool.getItem() instanceof IToolWrench && ((IToolWrench) tool.getItem()) // .canWrench(pPlayer, pX, pY, pZ)) { // return true; // } // } // return false; // } // // /** // * Spawns an ItemStack in the World. No motion in X and Z axis. // */ // public static void spawnItemStack(World pWorld, int pX, int pY, int pZ, ItemStack pItemStack) { // EntityItem entityItem = new EntityItem(pWorld, pX + 0.5, pY + 0.5, pZ + 0.5, pItemStack); // entityItem.motionX = 0; // entityItem.motionZ = 0; // pWorld.spawnEntityInWorld(entityItem); // } // // /** // * Returns true if the two ItemStacks contains exactly the same item without taking stack size into account. // * Credit to Pahimar. // */ // public static boolean itemStacksEqualIgnoreStackSize(ItemStack pItemStack1, ItemStack pItemStack2) { // if (pItemStack1 != null && pItemStack2 != null) { // // Compare itemID // if (Item.getIdFromItem(pItemStack1.getItem()) - Item.getIdFromItem(pItemStack2.getItem()) == 0) { // // Compare item // if (pItemStack1.getItem() == pItemStack2.getItem()) { // // Compare meta // if (pItemStack1.getItemDamage() == pItemStack2.getItemDamage()) { // // Compare NBT presence // if (pItemStack1.hasTagCompound() && pItemStack2.hasTagCompound()) { // // Compare NBT // if (ItemStack.areItemStackTagsEqual(pItemStack1, pItemStack2)) { // return true; // } // } else if (!pItemStack1.hasTagCompound() && !pItemStack2.hasTagCompound()) { // return true; // } // } // } // } // } // return false; // } // // public static boolean isShiftKeyDown() { // return Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); // } // } // Path: src/main/java/com/nauktis/solarflux/items/UpgradeItem.java import com.google.common.collect.Lists; import com.nauktis.core.utility.Color; import com.nauktis.core.utility.Utils; import com.nauktis.solarflux.utility.Lang; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import java.util.List; package com.nauktis.solarflux.items; public class UpgradeItem extends SFItem { private final int mMaximumPerSolarPanel; private final List<String> mUpgradeInfos = Lists.newArrayList(); public UpgradeItem(String pName, int pMaximumPerSolarPanel, List<String> pUpgradeInfos) { super(pName); mMaximumPerSolarPanel = pMaximumPerSolarPanel; mUpgradeInfos.addAll(pUpgradeInfos); } @Override public void addInformation(ItemStack pItemStack, EntityPlayer pEntityPlayer, List pList, boolean pBoolean) { super.addInformation(pItemStack, pEntityPlayer, pList, pBoolean);
if (Utils.isShiftKeyDown()) {
Nauktis/SolarFlux
src/main/java/com/nauktis/solarflux/items/UpgradeItem.java
// Path: src/main/java/com/nauktis/core/utility/Color.java // public enum Color { // BLACK("\u00a70"), // WHITE("\u00a7f"), // GREY("\u00a77"), // AQUA("\u00a7b"), // GREEN("\u00a7a"), // RED("\u00a7c"), // YELLOW("\u00a7e"); // // public final String mColorCode; // // Color(String pColorCode) { // mColorCode = pColorCode; // } // // @Override // public String toString() { // return mColorCode; // } // } // // Path: src/main/java/com/nauktis/core/utility/Utils.java // public final class Utils { // public static final Random RANDOM = new Random(); // // /** // * Utility class, no public constructor. // */ // private Utils() { // // } // // /** // * Returns true for server side world. // */ // public static boolean isServer(World pWorld) { // return !pWorld.isRemote; // } // // /** // * Returns true for client side world. // */ // public static boolean isClient(World pWorld) { // return pWorld.isRemote; // } // // /** // * Returns true if the player has a usable wrench equipped. // */ // public static boolean hasUsableWrench(EntityPlayer pPlayer, int pX, int pY, int pZ) { // ItemStack tool = pPlayer.getCurrentEquippedItem(); // if (tool != null) { // if (ModAPIManager.INSTANCE.hasAPI("BuildCraftAPI|tools") && tool.getItem() instanceof IToolWrench && ((IToolWrench) tool.getItem()) // .canWrench(pPlayer, pX, pY, pZ)) { // return true; // } // } // return false; // } // // /** // * Spawns an ItemStack in the World. No motion in X and Z axis. // */ // public static void spawnItemStack(World pWorld, int pX, int pY, int pZ, ItemStack pItemStack) { // EntityItem entityItem = new EntityItem(pWorld, pX + 0.5, pY + 0.5, pZ + 0.5, pItemStack); // entityItem.motionX = 0; // entityItem.motionZ = 0; // pWorld.spawnEntityInWorld(entityItem); // } // // /** // * Returns true if the two ItemStacks contains exactly the same item without taking stack size into account. // * Credit to Pahimar. // */ // public static boolean itemStacksEqualIgnoreStackSize(ItemStack pItemStack1, ItemStack pItemStack2) { // if (pItemStack1 != null && pItemStack2 != null) { // // Compare itemID // if (Item.getIdFromItem(pItemStack1.getItem()) - Item.getIdFromItem(pItemStack2.getItem()) == 0) { // // Compare item // if (pItemStack1.getItem() == pItemStack2.getItem()) { // // Compare meta // if (pItemStack1.getItemDamage() == pItemStack2.getItemDamage()) { // // Compare NBT presence // if (pItemStack1.hasTagCompound() && pItemStack2.hasTagCompound()) { // // Compare NBT // if (ItemStack.areItemStackTagsEqual(pItemStack1, pItemStack2)) { // return true; // } // } else if (!pItemStack1.hasTagCompound() && !pItemStack2.hasTagCompound()) { // return true; // } // } // } // } // } // return false; // } // // public static boolean isShiftKeyDown() { // return Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); // } // }
import com.google.common.collect.Lists; import com.nauktis.core.utility.Color; import com.nauktis.core.utility.Utils; import com.nauktis.solarflux.utility.Lang; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import java.util.List;
package com.nauktis.solarflux.items; public class UpgradeItem extends SFItem { private final int mMaximumPerSolarPanel; private final List<String> mUpgradeInfos = Lists.newArrayList(); public UpgradeItem(String pName, int pMaximumPerSolarPanel, List<String> pUpgradeInfos) { super(pName); mMaximumPerSolarPanel = pMaximumPerSolarPanel; mUpgradeInfos.addAll(pUpgradeInfos); } @Override public void addInformation(ItemStack pItemStack, EntityPlayer pEntityPlayer, List pList, boolean pBoolean) { super.addInformation(pItemStack, pEntityPlayer, pList, pBoolean); if (Utils.isShiftKeyDown()) {
// Path: src/main/java/com/nauktis/core/utility/Color.java // public enum Color { // BLACK("\u00a70"), // WHITE("\u00a7f"), // GREY("\u00a77"), // AQUA("\u00a7b"), // GREEN("\u00a7a"), // RED("\u00a7c"), // YELLOW("\u00a7e"); // // public final String mColorCode; // // Color(String pColorCode) { // mColorCode = pColorCode; // } // // @Override // public String toString() { // return mColorCode; // } // } // // Path: src/main/java/com/nauktis/core/utility/Utils.java // public final class Utils { // public static final Random RANDOM = new Random(); // // /** // * Utility class, no public constructor. // */ // private Utils() { // // } // // /** // * Returns true for server side world. // */ // public static boolean isServer(World pWorld) { // return !pWorld.isRemote; // } // // /** // * Returns true for client side world. // */ // public static boolean isClient(World pWorld) { // return pWorld.isRemote; // } // // /** // * Returns true if the player has a usable wrench equipped. // */ // public static boolean hasUsableWrench(EntityPlayer pPlayer, int pX, int pY, int pZ) { // ItemStack tool = pPlayer.getCurrentEquippedItem(); // if (tool != null) { // if (ModAPIManager.INSTANCE.hasAPI("BuildCraftAPI|tools") && tool.getItem() instanceof IToolWrench && ((IToolWrench) tool.getItem()) // .canWrench(pPlayer, pX, pY, pZ)) { // return true; // } // } // return false; // } // // /** // * Spawns an ItemStack in the World. No motion in X and Z axis. // */ // public static void spawnItemStack(World pWorld, int pX, int pY, int pZ, ItemStack pItemStack) { // EntityItem entityItem = new EntityItem(pWorld, pX + 0.5, pY + 0.5, pZ + 0.5, pItemStack); // entityItem.motionX = 0; // entityItem.motionZ = 0; // pWorld.spawnEntityInWorld(entityItem); // } // // /** // * Returns true if the two ItemStacks contains exactly the same item without taking stack size into account. // * Credit to Pahimar. // */ // public static boolean itemStacksEqualIgnoreStackSize(ItemStack pItemStack1, ItemStack pItemStack2) { // if (pItemStack1 != null && pItemStack2 != null) { // // Compare itemID // if (Item.getIdFromItem(pItemStack1.getItem()) - Item.getIdFromItem(pItemStack2.getItem()) == 0) { // // Compare item // if (pItemStack1.getItem() == pItemStack2.getItem()) { // // Compare meta // if (pItemStack1.getItemDamage() == pItemStack2.getItemDamage()) { // // Compare NBT presence // if (pItemStack1.hasTagCompound() && pItemStack2.hasTagCompound()) { // // Compare NBT // if (ItemStack.areItemStackTagsEqual(pItemStack1, pItemStack2)) { // return true; // } // } else if (!pItemStack1.hasTagCompound() && !pItemStack2.hasTagCompound()) { // return true; // } // } // } // } // } // return false; // } // // public static boolean isShiftKeyDown() { // return Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); // } // } // Path: src/main/java/com/nauktis/solarflux/items/UpgradeItem.java import com.google.common.collect.Lists; import com.nauktis.core.utility.Color; import com.nauktis.core.utility.Utils; import com.nauktis.solarflux.utility.Lang; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import java.util.List; package com.nauktis.solarflux.items; public class UpgradeItem extends SFItem { private final int mMaximumPerSolarPanel; private final List<String> mUpgradeInfos = Lists.newArrayList(); public UpgradeItem(String pName, int pMaximumPerSolarPanel, List<String> pUpgradeInfos) { super(pName); mMaximumPerSolarPanel = pMaximumPerSolarPanel; mUpgradeInfos.addAll(pUpgradeInfos); } @Override public void addInformation(ItemStack pItemStack, EntityPlayer pEntityPlayer, List pList, boolean pBoolean) { super.addInformation(pItemStack, pEntityPlayer, pList, pBoolean); if (Utils.isShiftKeyDown()) {
pList.add(Color.AQUA + Lang.localise("solar.panel.upgrade") + Color.GREY);
DevLeoko/AdvancedBan
bukkit/src/main/java/me/leoko/advancedban/bukkit/listener/InternalListener.java
// Path: bukkit/src/main/java/me/leoko/advancedban/bukkit/event/PunishmentEvent.java // public class PunishmentEvent extends Event { // // private static final HandlerList handlers = new HandlerList(); // // private final Punishment punishment; // // public PunishmentEvent(Punishment punishment) { // super(false); // this.punishment = punishment; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public Punishment getPunishment() { // return this.punishment; // } // } // // Path: bukkit/src/main/java/me/leoko/advancedban/bukkit/event/RevokePunishmentEvent.java // public class RevokePunishmentEvent extends Event { // private static final HandlerList handlers = new HandlerList(); // private final Punishment punishment; // private final boolean massClear; // // public RevokePunishmentEvent(Punishment punishment, boolean massClear) { // super(false); // this.punishment = punishment; // this.massClear = massClear; // } // // public Punishment getPunishment() { // return punishment; // } // // public boolean isMassClear() { // return massClear; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: core/src/main/java/me/leoko/advancedban/utils/PunishmentType.java // public enum PunishmentType { // BAN("Ban", null, false, "ab.ban.perma"), // TEMP_BAN("Tempban", BAN, true, "ab.ban.temp"), // IP_BAN("Ipban", BAN, false, "ab.ipban.perma"), // TEMP_IP_BAN("Tempipban", BAN, true, "ab.ipban.temp"), // MUTE("Mute", null, false, "ab.mute.perma"), // TEMP_MUTE("Tempmute", MUTE, true, "ab.mute.temp"), // WARNING("Warn", null, false, "ab.warn.perma"), // TEMP_WARNING("Tempwarn", WARNING, true, "ab.warn.temp"), // KICK("Kick", null, false, "ab.kick.use"), // NOTE("Note", null, false, "ab.note.use"); // // private final String name; // private final String perms; // private final PunishmentType basic; // private final boolean temp; // // PunishmentType(String name, PunishmentType basic, boolean temp, String perms) { // this.name = name; // this.basic = basic; // this.temp = temp; // this.perms = perms; // } // // public static PunishmentType fromCommandName(String cmd) { // switch (cmd) { // case "ban": // return BAN; // case "tempban": // return TEMP_BAN; // case "ban-ip": // case "banip": // case "ipban": // return IP_BAN; // case "tempipban": // case "tipban": // return TEMP_IP_BAN; // case "mute": // return MUTE; // case "tempmute": // return TEMP_MUTE; // case "warn": // return WARNING; // case "note": // return NOTE; // case "tempwarn": // return TEMP_WARNING; // case "kick": // return KICK; // default: // return null; // } // } // // public String getName() { // return name; // } // // public String getPerms() { // return perms; // } // // public boolean isTemp() { // return temp; // } // // public String getConfSection(String path) { // return name+"."+path; // } // // public PunishmentType getBasic() { // return basic == null ? this : basic; // } // // public PunishmentType getPermanent() { // if(this == IP_BAN || this == TEMP_IP_BAN) // return IP_BAN; // // return getBasic(); // } // // public boolean isIpOrientated() { // return this == IP_BAN || this == TEMP_IP_BAN; // } // }
import me.leoko.advancedban.bukkit.event.PunishmentEvent; import me.leoko.advancedban.bukkit.event.RevokePunishmentEvent; import me.leoko.advancedban.utils.PunishmentType; import org.bukkit.BanList; import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import java.util.Date;
package me.leoko.advancedban.bukkit.listener; /** * * @author Beelzebu */ public class InternalListener implements Listener { @EventHandler
// Path: bukkit/src/main/java/me/leoko/advancedban/bukkit/event/PunishmentEvent.java // public class PunishmentEvent extends Event { // // private static final HandlerList handlers = new HandlerList(); // // private final Punishment punishment; // // public PunishmentEvent(Punishment punishment) { // super(false); // this.punishment = punishment; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public Punishment getPunishment() { // return this.punishment; // } // } // // Path: bukkit/src/main/java/me/leoko/advancedban/bukkit/event/RevokePunishmentEvent.java // public class RevokePunishmentEvent extends Event { // private static final HandlerList handlers = new HandlerList(); // private final Punishment punishment; // private final boolean massClear; // // public RevokePunishmentEvent(Punishment punishment, boolean massClear) { // super(false); // this.punishment = punishment; // this.massClear = massClear; // } // // public Punishment getPunishment() { // return punishment; // } // // public boolean isMassClear() { // return massClear; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: core/src/main/java/me/leoko/advancedban/utils/PunishmentType.java // public enum PunishmentType { // BAN("Ban", null, false, "ab.ban.perma"), // TEMP_BAN("Tempban", BAN, true, "ab.ban.temp"), // IP_BAN("Ipban", BAN, false, "ab.ipban.perma"), // TEMP_IP_BAN("Tempipban", BAN, true, "ab.ipban.temp"), // MUTE("Mute", null, false, "ab.mute.perma"), // TEMP_MUTE("Tempmute", MUTE, true, "ab.mute.temp"), // WARNING("Warn", null, false, "ab.warn.perma"), // TEMP_WARNING("Tempwarn", WARNING, true, "ab.warn.temp"), // KICK("Kick", null, false, "ab.kick.use"), // NOTE("Note", null, false, "ab.note.use"); // // private final String name; // private final String perms; // private final PunishmentType basic; // private final boolean temp; // // PunishmentType(String name, PunishmentType basic, boolean temp, String perms) { // this.name = name; // this.basic = basic; // this.temp = temp; // this.perms = perms; // } // // public static PunishmentType fromCommandName(String cmd) { // switch (cmd) { // case "ban": // return BAN; // case "tempban": // return TEMP_BAN; // case "ban-ip": // case "banip": // case "ipban": // return IP_BAN; // case "tempipban": // case "tipban": // return TEMP_IP_BAN; // case "mute": // return MUTE; // case "tempmute": // return TEMP_MUTE; // case "warn": // return WARNING; // case "note": // return NOTE; // case "tempwarn": // return TEMP_WARNING; // case "kick": // return KICK; // default: // return null; // } // } // // public String getName() { // return name; // } // // public String getPerms() { // return perms; // } // // public boolean isTemp() { // return temp; // } // // public String getConfSection(String path) { // return name+"."+path; // } // // public PunishmentType getBasic() { // return basic == null ? this : basic; // } // // public PunishmentType getPermanent() { // if(this == IP_BAN || this == TEMP_IP_BAN) // return IP_BAN; // // return getBasic(); // } // // public boolean isIpOrientated() { // return this == IP_BAN || this == TEMP_IP_BAN; // } // } // Path: bukkit/src/main/java/me/leoko/advancedban/bukkit/listener/InternalListener.java import me.leoko.advancedban.bukkit.event.PunishmentEvent; import me.leoko.advancedban.bukkit.event.RevokePunishmentEvent; import me.leoko.advancedban.utils.PunishmentType; import org.bukkit.BanList; import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import java.util.Date; package me.leoko.advancedban.bukkit.listener; /** * * @author Beelzebu */ public class InternalListener implements Listener { @EventHandler
public void onPunish(PunishmentEvent e) {
DevLeoko/AdvancedBan
bukkit/src/main/java/me/leoko/advancedban/bukkit/listener/InternalListener.java
// Path: bukkit/src/main/java/me/leoko/advancedban/bukkit/event/PunishmentEvent.java // public class PunishmentEvent extends Event { // // private static final HandlerList handlers = new HandlerList(); // // private final Punishment punishment; // // public PunishmentEvent(Punishment punishment) { // super(false); // this.punishment = punishment; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public Punishment getPunishment() { // return this.punishment; // } // } // // Path: bukkit/src/main/java/me/leoko/advancedban/bukkit/event/RevokePunishmentEvent.java // public class RevokePunishmentEvent extends Event { // private static final HandlerList handlers = new HandlerList(); // private final Punishment punishment; // private final boolean massClear; // // public RevokePunishmentEvent(Punishment punishment, boolean massClear) { // super(false); // this.punishment = punishment; // this.massClear = massClear; // } // // public Punishment getPunishment() { // return punishment; // } // // public boolean isMassClear() { // return massClear; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: core/src/main/java/me/leoko/advancedban/utils/PunishmentType.java // public enum PunishmentType { // BAN("Ban", null, false, "ab.ban.perma"), // TEMP_BAN("Tempban", BAN, true, "ab.ban.temp"), // IP_BAN("Ipban", BAN, false, "ab.ipban.perma"), // TEMP_IP_BAN("Tempipban", BAN, true, "ab.ipban.temp"), // MUTE("Mute", null, false, "ab.mute.perma"), // TEMP_MUTE("Tempmute", MUTE, true, "ab.mute.temp"), // WARNING("Warn", null, false, "ab.warn.perma"), // TEMP_WARNING("Tempwarn", WARNING, true, "ab.warn.temp"), // KICK("Kick", null, false, "ab.kick.use"), // NOTE("Note", null, false, "ab.note.use"); // // private final String name; // private final String perms; // private final PunishmentType basic; // private final boolean temp; // // PunishmentType(String name, PunishmentType basic, boolean temp, String perms) { // this.name = name; // this.basic = basic; // this.temp = temp; // this.perms = perms; // } // // public static PunishmentType fromCommandName(String cmd) { // switch (cmd) { // case "ban": // return BAN; // case "tempban": // return TEMP_BAN; // case "ban-ip": // case "banip": // case "ipban": // return IP_BAN; // case "tempipban": // case "tipban": // return TEMP_IP_BAN; // case "mute": // return MUTE; // case "tempmute": // return TEMP_MUTE; // case "warn": // return WARNING; // case "note": // return NOTE; // case "tempwarn": // return TEMP_WARNING; // case "kick": // return KICK; // default: // return null; // } // } // // public String getName() { // return name; // } // // public String getPerms() { // return perms; // } // // public boolean isTemp() { // return temp; // } // // public String getConfSection(String path) { // return name+"."+path; // } // // public PunishmentType getBasic() { // return basic == null ? this : basic; // } // // public PunishmentType getPermanent() { // if(this == IP_BAN || this == TEMP_IP_BAN) // return IP_BAN; // // return getBasic(); // } // // public boolean isIpOrientated() { // return this == IP_BAN || this == TEMP_IP_BAN; // } // }
import me.leoko.advancedban.bukkit.event.PunishmentEvent; import me.leoko.advancedban.bukkit.event.RevokePunishmentEvent; import me.leoko.advancedban.utils.PunishmentType; import org.bukkit.BanList; import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import java.util.Date;
package me.leoko.advancedban.bukkit.listener; /** * * @author Beelzebu */ public class InternalListener implements Listener { @EventHandler public void onPunish(PunishmentEvent e) { BanList banlist;
// Path: bukkit/src/main/java/me/leoko/advancedban/bukkit/event/PunishmentEvent.java // public class PunishmentEvent extends Event { // // private static final HandlerList handlers = new HandlerList(); // // private final Punishment punishment; // // public PunishmentEvent(Punishment punishment) { // super(false); // this.punishment = punishment; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public Punishment getPunishment() { // return this.punishment; // } // } // // Path: bukkit/src/main/java/me/leoko/advancedban/bukkit/event/RevokePunishmentEvent.java // public class RevokePunishmentEvent extends Event { // private static final HandlerList handlers = new HandlerList(); // private final Punishment punishment; // private final boolean massClear; // // public RevokePunishmentEvent(Punishment punishment, boolean massClear) { // super(false); // this.punishment = punishment; // this.massClear = massClear; // } // // public Punishment getPunishment() { // return punishment; // } // // public boolean isMassClear() { // return massClear; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: core/src/main/java/me/leoko/advancedban/utils/PunishmentType.java // public enum PunishmentType { // BAN("Ban", null, false, "ab.ban.perma"), // TEMP_BAN("Tempban", BAN, true, "ab.ban.temp"), // IP_BAN("Ipban", BAN, false, "ab.ipban.perma"), // TEMP_IP_BAN("Tempipban", BAN, true, "ab.ipban.temp"), // MUTE("Mute", null, false, "ab.mute.perma"), // TEMP_MUTE("Tempmute", MUTE, true, "ab.mute.temp"), // WARNING("Warn", null, false, "ab.warn.perma"), // TEMP_WARNING("Tempwarn", WARNING, true, "ab.warn.temp"), // KICK("Kick", null, false, "ab.kick.use"), // NOTE("Note", null, false, "ab.note.use"); // // private final String name; // private final String perms; // private final PunishmentType basic; // private final boolean temp; // // PunishmentType(String name, PunishmentType basic, boolean temp, String perms) { // this.name = name; // this.basic = basic; // this.temp = temp; // this.perms = perms; // } // // public static PunishmentType fromCommandName(String cmd) { // switch (cmd) { // case "ban": // return BAN; // case "tempban": // return TEMP_BAN; // case "ban-ip": // case "banip": // case "ipban": // return IP_BAN; // case "tempipban": // case "tipban": // return TEMP_IP_BAN; // case "mute": // return MUTE; // case "tempmute": // return TEMP_MUTE; // case "warn": // return WARNING; // case "note": // return NOTE; // case "tempwarn": // return TEMP_WARNING; // case "kick": // return KICK; // default: // return null; // } // } // // public String getName() { // return name; // } // // public String getPerms() { // return perms; // } // // public boolean isTemp() { // return temp; // } // // public String getConfSection(String path) { // return name+"."+path; // } // // public PunishmentType getBasic() { // return basic == null ? this : basic; // } // // public PunishmentType getPermanent() { // if(this == IP_BAN || this == TEMP_IP_BAN) // return IP_BAN; // // return getBasic(); // } // // public boolean isIpOrientated() { // return this == IP_BAN || this == TEMP_IP_BAN; // } // } // Path: bukkit/src/main/java/me/leoko/advancedban/bukkit/listener/InternalListener.java import me.leoko.advancedban.bukkit.event.PunishmentEvent; import me.leoko.advancedban.bukkit.event.RevokePunishmentEvent; import me.leoko.advancedban.utils.PunishmentType; import org.bukkit.BanList; import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import java.util.Date; package me.leoko.advancedban.bukkit.listener; /** * * @author Beelzebu */ public class InternalListener implements Listener { @EventHandler public void onPunish(PunishmentEvent e) { BanList banlist;
if (e.getPunishment().getType().equals(PunishmentType.BAN) || e.getPunishment().getType().equals(PunishmentType.TEMP_BAN)) {
DevLeoko/AdvancedBan
bukkit/src/main/java/me/leoko/advancedban/bukkit/listener/InternalListener.java
// Path: bukkit/src/main/java/me/leoko/advancedban/bukkit/event/PunishmentEvent.java // public class PunishmentEvent extends Event { // // private static final HandlerList handlers = new HandlerList(); // // private final Punishment punishment; // // public PunishmentEvent(Punishment punishment) { // super(false); // this.punishment = punishment; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public Punishment getPunishment() { // return this.punishment; // } // } // // Path: bukkit/src/main/java/me/leoko/advancedban/bukkit/event/RevokePunishmentEvent.java // public class RevokePunishmentEvent extends Event { // private static final HandlerList handlers = new HandlerList(); // private final Punishment punishment; // private final boolean massClear; // // public RevokePunishmentEvent(Punishment punishment, boolean massClear) { // super(false); // this.punishment = punishment; // this.massClear = massClear; // } // // public Punishment getPunishment() { // return punishment; // } // // public boolean isMassClear() { // return massClear; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: core/src/main/java/me/leoko/advancedban/utils/PunishmentType.java // public enum PunishmentType { // BAN("Ban", null, false, "ab.ban.perma"), // TEMP_BAN("Tempban", BAN, true, "ab.ban.temp"), // IP_BAN("Ipban", BAN, false, "ab.ipban.perma"), // TEMP_IP_BAN("Tempipban", BAN, true, "ab.ipban.temp"), // MUTE("Mute", null, false, "ab.mute.perma"), // TEMP_MUTE("Tempmute", MUTE, true, "ab.mute.temp"), // WARNING("Warn", null, false, "ab.warn.perma"), // TEMP_WARNING("Tempwarn", WARNING, true, "ab.warn.temp"), // KICK("Kick", null, false, "ab.kick.use"), // NOTE("Note", null, false, "ab.note.use"); // // private final String name; // private final String perms; // private final PunishmentType basic; // private final boolean temp; // // PunishmentType(String name, PunishmentType basic, boolean temp, String perms) { // this.name = name; // this.basic = basic; // this.temp = temp; // this.perms = perms; // } // // public static PunishmentType fromCommandName(String cmd) { // switch (cmd) { // case "ban": // return BAN; // case "tempban": // return TEMP_BAN; // case "ban-ip": // case "banip": // case "ipban": // return IP_BAN; // case "tempipban": // case "tipban": // return TEMP_IP_BAN; // case "mute": // return MUTE; // case "tempmute": // return TEMP_MUTE; // case "warn": // return WARNING; // case "note": // return NOTE; // case "tempwarn": // return TEMP_WARNING; // case "kick": // return KICK; // default: // return null; // } // } // // public String getName() { // return name; // } // // public String getPerms() { // return perms; // } // // public boolean isTemp() { // return temp; // } // // public String getConfSection(String path) { // return name+"."+path; // } // // public PunishmentType getBasic() { // return basic == null ? this : basic; // } // // public PunishmentType getPermanent() { // if(this == IP_BAN || this == TEMP_IP_BAN) // return IP_BAN; // // return getBasic(); // } // // public boolean isIpOrientated() { // return this == IP_BAN || this == TEMP_IP_BAN; // } // }
import me.leoko.advancedban.bukkit.event.PunishmentEvent; import me.leoko.advancedban.bukkit.event.RevokePunishmentEvent; import me.leoko.advancedban.utils.PunishmentType; import org.bukkit.BanList; import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import java.util.Date;
package me.leoko.advancedban.bukkit.listener; /** * * @author Beelzebu */ public class InternalListener implements Listener { @EventHandler public void onPunish(PunishmentEvent e) { BanList banlist; if (e.getPunishment().getType().equals(PunishmentType.BAN) || e.getPunishment().getType().equals(PunishmentType.TEMP_BAN)) { banlist = Bukkit.getBanList(BanList.Type.NAME); banlist.addBan(e.getPunishment().getName(), e.getPunishment().getReason(), new Date(e.getPunishment().getEnd()), e.getPunishment().getOperator()); } else if (e.getPunishment().getType().equals(PunishmentType.IP_BAN) || e.getPunishment().getType().equals(PunishmentType.TEMP_IP_BAN)) { banlist = Bukkit.getBanList(BanList.Type.IP); banlist.addBan(e.getPunishment().getName(), e.getPunishment().getReason(), new Date(e.getPunishment().getEnd()), e.getPunishment().getOperator()); } } @EventHandler
// Path: bukkit/src/main/java/me/leoko/advancedban/bukkit/event/PunishmentEvent.java // public class PunishmentEvent extends Event { // // private static final HandlerList handlers = new HandlerList(); // // private final Punishment punishment; // // public PunishmentEvent(Punishment punishment) { // super(false); // this.punishment = punishment; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public Punishment getPunishment() { // return this.punishment; // } // } // // Path: bukkit/src/main/java/me/leoko/advancedban/bukkit/event/RevokePunishmentEvent.java // public class RevokePunishmentEvent extends Event { // private static final HandlerList handlers = new HandlerList(); // private final Punishment punishment; // private final boolean massClear; // // public RevokePunishmentEvent(Punishment punishment, boolean massClear) { // super(false); // this.punishment = punishment; // this.massClear = massClear; // } // // public Punishment getPunishment() { // return punishment; // } // // public boolean isMassClear() { // return massClear; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: core/src/main/java/me/leoko/advancedban/utils/PunishmentType.java // public enum PunishmentType { // BAN("Ban", null, false, "ab.ban.perma"), // TEMP_BAN("Tempban", BAN, true, "ab.ban.temp"), // IP_BAN("Ipban", BAN, false, "ab.ipban.perma"), // TEMP_IP_BAN("Tempipban", BAN, true, "ab.ipban.temp"), // MUTE("Mute", null, false, "ab.mute.perma"), // TEMP_MUTE("Tempmute", MUTE, true, "ab.mute.temp"), // WARNING("Warn", null, false, "ab.warn.perma"), // TEMP_WARNING("Tempwarn", WARNING, true, "ab.warn.temp"), // KICK("Kick", null, false, "ab.kick.use"), // NOTE("Note", null, false, "ab.note.use"); // // private final String name; // private final String perms; // private final PunishmentType basic; // private final boolean temp; // // PunishmentType(String name, PunishmentType basic, boolean temp, String perms) { // this.name = name; // this.basic = basic; // this.temp = temp; // this.perms = perms; // } // // public static PunishmentType fromCommandName(String cmd) { // switch (cmd) { // case "ban": // return BAN; // case "tempban": // return TEMP_BAN; // case "ban-ip": // case "banip": // case "ipban": // return IP_BAN; // case "tempipban": // case "tipban": // return TEMP_IP_BAN; // case "mute": // return MUTE; // case "tempmute": // return TEMP_MUTE; // case "warn": // return WARNING; // case "note": // return NOTE; // case "tempwarn": // return TEMP_WARNING; // case "kick": // return KICK; // default: // return null; // } // } // // public String getName() { // return name; // } // // public String getPerms() { // return perms; // } // // public boolean isTemp() { // return temp; // } // // public String getConfSection(String path) { // return name+"."+path; // } // // public PunishmentType getBasic() { // return basic == null ? this : basic; // } // // public PunishmentType getPermanent() { // if(this == IP_BAN || this == TEMP_IP_BAN) // return IP_BAN; // // return getBasic(); // } // // public boolean isIpOrientated() { // return this == IP_BAN || this == TEMP_IP_BAN; // } // } // Path: bukkit/src/main/java/me/leoko/advancedban/bukkit/listener/InternalListener.java import me.leoko.advancedban.bukkit.event.PunishmentEvent; import me.leoko.advancedban.bukkit.event.RevokePunishmentEvent; import me.leoko.advancedban.utils.PunishmentType; import org.bukkit.BanList; import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import java.util.Date; package me.leoko.advancedban.bukkit.listener; /** * * @author Beelzebu */ public class InternalListener implements Listener { @EventHandler public void onPunish(PunishmentEvent e) { BanList banlist; if (e.getPunishment().getType().equals(PunishmentType.BAN) || e.getPunishment().getType().equals(PunishmentType.TEMP_BAN)) { banlist = Bukkit.getBanList(BanList.Type.NAME); banlist.addBan(e.getPunishment().getName(), e.getPunishment().getReason(), new Date(e.getPunishment().getEnd()), e.getPunishment().getOperator()); } else if (e.getPunishment().getType().equals(PunishmentType.IP_BAN) || e.getPunishment().getType().equals(PunishmentType.TEMP_IP_BAN)) { banlist = Bukkit.getBanList(BanList.Type.IP); banlist.addBan(e.getPunishment().getName(), e.getPunishment().getReason(), new Date(e.getPunishment().getEnd()), e.getPunishment().getOperator()); } } @EventHandler
public void onRevokePunishment(RevokePunishmentEvent e) {
DevLeoko/AdvancedBan
core/src/main/java/me/leoko/advancedban/utils/SQLQuery.java
// Path: core/src/main/java/me/leoko/advancedban/manager/DatabaseManager.java // public class DatabaseManager { // // private HikariDataSource dataSource; // private boolean useMySQL; // // private RowSetFactory factory; // // private static DatabaseManager instance = null; // // /** // * Get the instance of the command manager // * // * @return the database manager instance // */ // public static synchronized DatabaseManager get() { // return instance == null ? instance = new DatabaseManager() : instance; // } // // /** // * Initially connects to the database and sets up the required tables of they don't already exist. // * // * @param useMySQLServer whether to preferably use MySQL (uses HSQLDB as fallback) // */ // public void setup(boolean useMySQLServer) { // useMySQL = useMySQLServer; // // try { // dataSource = new DynamicDataSource(useMySQL).generateDataSource(); // } catch (ClassNotFoundException ex) { // Universal.get().log("§cERROR: Failed to configure data source!"); // Universal.get().debug(ex.getMessage()); // return; // } // // executeStatement(SQLQuery.CREATE_TABLE_PUNISHMENT); // executeStatement(SQLQuery.CREATE_TABLE_PUNISHMENT_HISTORY); // } // // /** // * Shuts down the HSQLDB if used. // */ // public void shutdown() { // if (!useMySQL) { // try(Connection connection = dataSource.getConnection(); final PreparedStatement statement = connection.prepareStatement("SHUTDOWN")){ // statement.execute(); // }catch (SQLException | NullPointerException exc){ // Universal.get().log("An unexpected error has occurred turning off the database"); // Universal.get().debugException(exc); // } // } // // dataSource.close(); // } // // private CachedRowSet createCachedRowSet() throws SQLException { // if (factory == null) { // factory = RowSetProvider.newFactory(); // } // return factory.createCachedRowSet(); // } // // /** // * Execute a sql statement without any results. // * // * @param sql the sql statement // * @param parameters the parameters // */ // public void executeStatement(SQLQuery sql, Object... parameters) { // executeStatement(sql, false, parameters); // } // // /** // * Execute a sql statement. // * // * @param sql the sql statement // * @param parameters the parameters // * @return the result set // */ // public ResultSet executeResultStatement(SQLQuery sql, Object... parameters) { // return executeStatement(sql, true, parameters); // } // // private ResultSet executeStatement(SQLQuery sql, boolean result, Object... parameters) { // return executeStatement(sql.toString(), result, parameters); // } // // private synchronized ResultSet executeStatement(String sql, boolean result, Object... parameters) { // try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(sql)) { // // for (int i = 0; i < parameters.length; i++) { // statement.setObject(i + 1, parameters[i]); // } // // if (result) { // CachedRowSet results = createCachedRowSet(); // results.populate(statement.executeQuery()); // return results; // } // statement.execute(); // } catch (SQLException ex) { // Universal.get().log( // "An unexpected error has occurred executing an Statement in the database\n" // + "Please check the plugins/AdvancedBan/logs/latest.log file and report this " // + "error in: https://github.com/DevLeoko/AdvancedBan/issues" // ); // Universal.get().debug("Query: \n" + sql); // Universal.get().debugSqlException(ex); // } catch (NullPointerException ex) { // Universal.get().log( // "An unexpected error has occurred connecting to the database\n" // + "Check if your MySQL data is correct and if your MySQL-Server is online\n" // + "Please check the plugins/AdvancedBan/logs/latest.log file and report this " // + "error in: https://github.com/DevLeoko/AdvancedBan/issues" // ); // Universal.get().debugException(ex); // } // return null; // } // // /** // * Check whether there is a valid connection to the database. // * // * @return whether there is a valid connection // */ // public boolean isConnectionValid() { // return dataSource.isRunning(); // } // // /** // * Check whether MySQL is actually used. // * // * @return whether MySQL is used // */ // public boolean isUseMySQL() { // return useMySQL; // } // }
import me.leoko.advancedban.manager.DatabaseManager;
"SELECT * FROM `Punishments` WHERE `id` = ?", "SELECT * FROM Punishments WHERE id = ?" ), SELECT_ALL_PUNISHMENTS( "SELECT * FROM `Punishments`", "SELECT * FROM Punishments" ), SELECT_ALL_PUNISHMENTS_HISTORY( "SELECT * FROM `PunishmentHistory`", "SELECT * FROM PunishmentHistory" ), SELECT_ALL_PUNISHMENTS_LIMIT( "SELECT * FROM `Punishments` ORDER BY `start` DESC LIMIT ?", "SELECT * FROM Punishments ORDER BY start DESC LIMIT ?" ), SELECT_ALL_PUNISHMENTS_HISTORY_LIMIT( "SELECT * FROM `PunishmentHistory` ORDER BY `start` DESC LIMIT ?", "SELECT * FROM PunishmentHistory ORDER BY start DESC LIMIT ?" ); private String mysql; private String hsqldb; SQLQuery(String mysql, String hsqldb) { this.mysql = mysql; this.hsqldb = hsqldb; } @Override public String toString() {
// Path: core/src/main/java/me/leoko/advancedban/manager/DatabaseManager.java // public class DatabaseManager { // // private HikariDataSource dataSource; // private boolean useMySQL; // // private RowSetFactory factory; // // private static DatabaseManager instance = null; // // /** // * Get the instance of the command manager // * // * @return the database manager instance // */ // public static synchronized DatabaseManager get() { // return instance == null ? instance = new DatabaseManager() : instance; // } // // /** // * Initially connects to the database and sets up the required tables of they don't already exist. // * // * @param useMySQLServer whether to preferably use MySQL (uses HSQLDB as fallback) // */ // public void setup(boolean useMySQLServer) { // useMySQL = useMySQLServer; // // try { // dataSource = new DynamicDataSource(useMySQL).generateDataSource(); // } catch (ClassNotFoundException ex) { // Universal.get().log("§cERROR: Failed to configure data source!"); // Universal.get().debug(ex.getMessage()); // return; // } // // executeStatement(SQLQuery.CREATE_TABLE_PUNISHMENT); // executeStatement(SQLQuery.CREATE_TABLE_PUNISHMENT_HISTORY); // } // // /** // * Shuts down the HSQLDB if used. // */ // public void shutdown() { // if (!useMySQL) { // try(Connection connection = dataSource.getConnection(); final PreparedStatement statement = connection.prepareStatement("SHUTDOWN")){ // statement.execute(); // }catch (SQLException | NullPointerException exc){ // Universal.get().log("An unexpected error has occurred turning off the database"); // Universal.get().debugException(exc); // } // } // // dataSource.close(); // } // // private CachedRowSet createCachedRowSet() throws SQLException { // if (factory == null) { // factory = RowSetProvider.newFactory(); // } // return factory.createCachedRowSet(); // } // // /** // * Execute a sql statement without any results. // * // * @param sql the sql statement // * @param parameters the parameters // */ // public void executeStatement(SQLQuery sql, Object... parameters) { // executeStatement(sql, false, parameters); // } // // /** // * Execute a sql statement. // * // * @param sql the sql statement // * @param parameters the parameters // * @return the result set // */ // public ResultSet executeResultStatement(SQLQuery sql, Object... parameters) { // return executeStatement(sql, true, parameters); // } // // private ResultSet executeStatement(SQLQuery sql, boolean result, Object... parameters) { // return executeStatement(sql.toString(), result, parameters); // } // // private synchronized ResultSet executeStatement(String sql, boolean result, Object... parameters) { // try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(sql)) { // // for (int i = 0; i < parameters.length; i++) { // statement.setObject(i + 1, parameters[i]); // } // // if (result) { // CachedRowSet results = createCachedRowSet(); // results.populate(statement.executeQuery()); // return results; // } // statement.execute(); // } catch (SQLException ex) { // Universal.get().log( // "An unexpected error has occurred executing an Statement in the database\n" // + "Please check the plugins/AdvancedBan/logs/latest.log file and report this " // + "error in: https://github.com/DevLeoko/AdvancedBan/issues" // ); // Universal.get().debug("Query: \n" + sql); // Universal.get().debugSqlException(ex); // } catch (NullPointerException ex) { // Universal.get().log( // "An unexpected error has occurred connecting to the database\n" // + "Check if your MySQL data is correct and if your MySQL-Server is online\n" // + "Please check the plugins/AdvancedBan/logs/latest.log file and report this " // + "error in: https://github.com/DevLeoko/AdvancedBan/issues" // ); // Universal.get().debugException(ex); // } // return null; // } // // /** // * Check whether there is a valid connection to the database. // * // * @return whether there is a valid connection // */ // public boolean isConnectionValid() { // return dataSource.isRunning(); // } // // /** // * Check whether MySQL is actually used. // * // * @return whether MySQL is used // */ // public boolean isUseMySQL() { // return useMySQL; // } // } // Path: core/src/main/java/me/leoko/advancedban/utils/SQLQuery.java import me.leoko.advancedban.manager.DatabaseManager; "SELECT * FROM `Punishments` WHERE `id` = ?", "SELECT * FROM Punishments WHERE id = ?" ), SELECT_ALL_PUNISHMENTS( "SELECT * FROM `Punishments`", "SELECT * FROM Punishments" ), SELECT_ALL_PUNISHMENTS_HISTORY( "SELECT * FROM `PunishmentHistory`", "SELECT * FROM PunishmentHistory" ), SELECT_ALL_PUNISHMENTS_LIMIT( "SELECT * FROM `Punishments` ORDER BY `start` DESC LIMIT ?", "SELECT * FROM Punishments ORDER BY start DESC LIMIT ?" ), SELECT_ALL_PUNISHMENTS_HISTORY_LIMIT( "SELECT * FROM `PunishmentHistory` ORDER BY `start` DESC LIMIT ?", "SELECT * FROM PunishmentHistory ORDER BY start DESC LIMIT ?" ); private String mysql; private String hsqldb; SQLQuery(String mysql, String hsqldb) { this.mysql = mysql; this.hsqldb = hsqldb; } @Override public String toString() {
return DatabaseManager.get().isUseMySQL() ? mysql : hsqldb;
DevLeoko/AdvancedBan
bungee/src/main/java/me/leoko/advancedban/bungee/cloud/CloudSupportHandler.java
// Path: bungee/src/main/java/me/leoko/advancedban/bungee/cloud/support/CloudNetV2Support.java // public class CloudNetV2Support implements CloudSupport { // // @Override // public void kick(UUID uniqueID, String reason) { // PlayerExecutorBridge.INSTANCE.kickPlayer(CloudServer.getInstance().getCloudPlayers().get(uniqueID), reason); // } // } // // Path: bungee/src/main/java/me/leoko/advancedban/bungee/cloud/support/CloudNetV3Support.java // public class CloudNetV3Support implements CloudSupport { // // @Override // public void kick(UUID uniqueID, String reason) { // CloudNetDriver.getInstance().getServicesRegistry().getFirstService(IPlayerManager.class).getPlayerExecutor(uniqueID).kick(reason); // } // }
import me.leoko.advancedban.bungee.cloud.support.CloudNetV2Support; import me.leoko.advancedban.bungee.cloud.support.CloudNetV3Support; import net.md_5.bungee.api.ProxyServer;
package me.leoko.advancedban.bungee.cloud; public class CloudSupportHandler { public static CloudSupport getCloudSystem(){ if (ProxyServer.getInstance().getPluginManager().getPlugin("CloudNet-Bridge") != null) {
// Path: bungee/src/main/java/me/leoko/advancedban/bungee/cloud/support/CloudNetV2Support.java // public class CloudNetV2Support implements CloudSupport { // // @Override // public void kick(UUID uniqueID, String reason) { // PlayerExecutorBridge.INSTANCE.kickPlayer(CloudServer.getInstance().getCloudPlayers().get(uniqueID), reason); // } // } // // Path: bungee/src/main/java/me/leoko/advancedban/bungee/cloud/support/CloudNetV3Support.java // public class CloudNetV3Support implements CloudSupport { // // @Override // public void kick(UUID uniqueID, String reason) { // CloudNetDriver.getInstance().getServicesRegistry().getFirstService(IPlayerManager.class).getPlayerExecutor(uniqueID).kick(reason); // } // } // Path: bungee/src/main/java/me/leoko/advancedban/bungee/cloud/CloudSupportHandler.java import me.leoko.advancedban.bungee.cloud.support.CloudNetV2Support; import me.leoko.advancedban.bungee.cloud.support.CloudNetV3Support; import net.md_5.bungee.api.ProxyServer; package me.leoko.advancedban.bungee.cloud; public class CloudSupportHandler { public static CloudSupport getCloudSystem(){ if (ProxyServer.getInstance().getPluginManager().getPlugin("CloudNet-Bridge") != null) {
return new CloudNetV3Support();
DevLeoko/AdvancedBan
bungee/src/main/java/me/leoko/advancedban/bungee/cloud/CloudSupportHandler.java
// Path: bungee/src/main/java/me/leoko/advancedban/bungee/cloud/support/CloudNetV2Support.java // public class CloudNetV2Support implements CloudSupport { // // @Override // public void kick(UUID uniqueID, String reason) { // PlayerExecutorBridge.INSTANCE.kickPlayer(CloudServer.getInstance().getCloudPlayers().get(uniqueID), reason); // } // } // // Path: bungee/src/main/java/me/leoko/advancedban/bungee/cloud/support/CloudNetV3Support.java // public class CloudNetV3Support implements CloudSupport { // // @Override // public void kick(UUID uniqueID, String reason) { // CloudNetDriver.getInstance().getServicesRegistry().getFirstService(IPlayerManager.class).getPlayerExecutor(uniqueID).kick(reason); // } // }
import me.leoko.advancedban.bungee.cloud.support.CloudNetV2Support; import me.leoko.advancedban.bungee.cloud.support.CloudNetV3Support; import net.md_5.bungee.api.ProxyServer;
package me.leoko.advancedban.bungee.cloud; public class CloudSupportHandler { public static CloudSupport getCloudSystem(){ if (ProxyServer.getInstance().getPluginManager().getPlugin("CloudNet-Bridge") != null) { return new CloudNetV3Support(); } if (ProxyServer.getInstance().getPluginManager().getPlugin("CloudNetAPI") != null) {
// Path: bungee/src/main/java/me/leoko/advancedban/bungee/cloud/support/CloudNetV2Support.java // public class CloudNetV2Support implements CloudSupport { // // @Override // public void kick(UUID uniqueID, String reason) { // PlayerExecutorBridge.INSTANCE.kickPlayer(CloudServer.getInstance().getCloudPlayers().get(uniqueID), reason); // } // } // // Path: bungee/src/main/java/me/leoko/advancedban/bungee/cloud/support/CloudNetV3Support.java // public class CloudNetV3Support implements CloudSupport { // // @Override // public void kick(UUID uniqueID, String reason) { // CloudNetDriver.getInstance().getServicesRegistry().getFirstService(IPlayerManager.class).getPlayerExecutor(uniqueID).kick(reason); // } // } // Path: bungee/src/main/java/me/leoko/advancedban/bungee/cloud/CloudSupportHandler.java import me.leoko.advancedban.bungee.cloud.support.CloudNetV2Support; import me.leoko.advancedban.bungee.cloud.support.CloudNetV3Support; import net.md_5.bungee.api.ProxyServer; package me.leoko.advancedban.bungee.cloud; public class CloudSupportHandler { public static CloudSupport getCloudSystem(){ if (ProxyServer.getInstance().getPluginManager().getPlugin("CloudNet-Bridge") != null) { return new CloudNetV3Support(); } if (ProxyServer.getInstance().getPluginManager().getPlugin("CloudNetAPI") != null) {
return new CloudNetV2Support();
DevLeoko/AdvancedBan
bukkit/src/main/java/me/leoko/advancedban/bukkit/listener/CommandReceiver.java
// Path: core/src/main/java/me/leoko/advancedban/manager/CommandManager.java // public class CommandManager { // // private static CommandManager instance = null; // // /** // * Get the instance of the command manager // * // * @return the command manager instance // */ // public static synchronized CommandManager get() { // return instance == null ? instance = new CommandManager() : instance; // } // // /** // * Handle/Perform a command. // * // * @param sender the sender which executes the command // * @param cmd the command name // * @param args the arguments for this command // */ // public void onCommand(final Object sender, final String cmd, final String[] args) { // Universal.get().getMethods().runAsync(() -> { // Command command = Command.getByName(cmd); // if (command == null) // return; // // String permission = command.getPermission(); // if (permission != null && !Universal.get().hasPerms(sender, permission)) { // MessageManager.sendMessage(sender, "General.NoPerms", true); // return; // } // // if (!command.validateArguments(args)) { // MessageManager.sendMessage(sender, command.getUsagePath(), true); // return; // } // // command.execute(sender, args); // }); // } // }
import me.leoko.advancedban.manager.CommandManager; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender;
package me.leoko.advancedban.bukkit.listener; /** * Created by Leoko @ dev.skamps.eu on 23.07.2016. */ public class CommandReceiver implements CommandExecutor { private static CommandReceiver instance = null; public static CommandReceiver get() { return instance == null ? instance = new CommandReceiver() : instance; } @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { if (strings.length > 0) { strings[0] = (Bukkit.getPlayer(strings[0]) != null ? Bukkit.getPlayer(strings[0]).getName() : strings[0]); }
// Path: core/src/main/java/me/leoko/advancedban/manager/CommandManager.java // public class CommandManager { // // private static CommandManager instance = null; // // /** // * Get the instance of the command manager // * // * @return the command manager instance // */ // public static synchronized CommandManager get() { // return instance == null ? instance = new CommandManager() : instance; // } // // /** // * Handle/Perform a command. // * // * @param sender the sender which executes the command // * @param cmd the command name // * @param args the arguments for this command // */ // public void onCommand(final Object sender, final String cmd, final String[] args) { // Universal.get().getMethods().runAsync(() -> { // Command command = Command.getByName(cmd); // if (command == null) // return; // // String permission = command.getPermission(); // if (permission != null && !Universal.get().hasPerms(sender, permission)) { // MessageManager.sendMessage(sender, "General.NoPerms", true); // return; // } // // if (!command.validateArguments(args)) { // MessageManager.sendMessage(sender, command.getUsagePath(), true); // return; // } // // command.execute(sender, args); // }); // } // } // Path: bukkit/src/main/java/me/leoko/advancedban/bukkit/listener/CommandReceiver.java import me.leoko.advancedban.manager.CommandManager; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; package me.leoko.advancedban.bukkit.listener; /** * Created by Leoko @ dev.skamps.eu on 23.07.2016. */ public class CommandReceiver implements CommandExecutor { private static CommandReceiver instance = null; public static CommandReceiver get() { return instance == null ? instance = new CommandReceiver() : instance; } @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { if (strings.length > 0) { strings[0] = (Bukkit.getPlayer(strings[0]) != null ? Bukkit.getPlayer(strings[0]).getName() : strings[0]); }
CommandManager.get().onCommand(commandSender, command.getName(), strings);
DevLeoko/AdvancedBan
bungee/src/main/java/me/leoko/advancedban/bungee/listener/CommandReceiverBungee.java
// Path: bungee/src/main/java/me/leoko/advancedban/bungee/BungeeMain.java // public class BungeeMain extends Plugin { // // private static BungeeMain instance; // // private static CloudSupport cloudSupport; // // // public static BungeeMain get() { // return instance; // } // // public static CloudSupport getCloudSupport() { // return cloudSupport; // } // // @Override // public void onEnable() { // instance = this; // Universal.get().setup(new BungeeMethods()); // ProxyServer.getInstance().getPluginManager().registerListener(this, new ConnectionListenerBungee()); // ProxyServer.getInstance().getPluginManager().registerListener(this, new ChatListenerBungee()); // ProxyServer.getInstance().getPluginManager().registerListener(this, new InternalListener()); // ProxyServer.getInstance().registerChannel("advancedban:main"); // // cloudSupport = CloudSupportHandler.getCloudSystem(); // // // if (ProxyServer.getInstance().getPluginManager().getPlugin("RedisBungee") != null) { // Universal.setRedis(true); // ProxyServer.getInstance().getPluginManager().registerListener(this, new PubSubMessageListener()); // RedisBungee.getApi().registerPubSubChannels("advancedban:main", "advancedban:connection"); // Universal.get().log("RedisBungee detected, hooking into it!"); // } // } // // @Override // public void onDisable() { // Universal.get().shutdown(); // } // } // // Path: core/src/main/java/me/leoko/advancedban/manager/CommandManager.java // public class CommandManager { // // private static CommandManager instance = null; // // /** // * Get the instance of the command manager // * // * @return the command manager instance // */ // public static synchronized CommandManager get() { // return instance == null ? instance = new CommandManager() : instance; // } // // /** // * Handle/Perform a command. // * // * @param sender the sender which executes the command // * @param cmd the command name // * @param args the arguments for this command // */ // public void onCommand(final Object sender, final String cmd, final String[] args) { // Universal.get().getMethods().runAsync(() -> { // Command command = Command.getByName(cmd); // if (command == null) // return; // // String permission = command.getPermission(); // if (permission != null && !Universal.get().hasPerms(sender, permission)) { // MessageManager.sendMessage(sender, "General.NoPerms", true); // return; // } // // if (!command.validateArguments(args)) { // MessageManager.sendMessage(sender, command.getUsagePath(), true); // return; // } // // command.execute(sender, args); // }); // } // }
import me.leoko.advancedban.bungee.BungeeMain; import me.leoko.advancedban.manager.CommandManager; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.plugin.Command;
package me.leoko.advancedban.bungee.listener; /** * Created by Leoko @ dev.skamps.eu on 24.07.2016. */ public class CommandReceiverBungee extends Command { public CommandReceiverBungee(String name) { super(name); } @Override public void execute(final CommandSender sender, final String[] args) { if (args.length > 0) {
// Path: bungee/src/main/java/me/leoko/advancedban/bungee/BungeeMain.java // public class BungeeMain extends Plugin { // // private static BungeeMain instance; // // private static CloudSupport cloudSupport; // // // public static BungeeMain get() { // return instance; // } // // public static CloudSupport getCloudSupport() { // return cloudSupport; // } // // @Override // public void onEnable() { // instance = this; // Universal.get().setup(new BungeeMethods()); // ProxyServer.getInstance().getPluginManager().registerListener(this, new ConnectionListenerBungee()); // ProxyServer.getInstance().getPluginManager().registerListener(this, new ChatListenerBungee()); // ProxyServer.getInstance().getPluginManager().registerListener(this, new InternalListener()); // ProxyServer.getInstance().registerChannel("advancedban:main"); // // cloudSupport = CloudSupportHandler.getCloudSystem(); // // // if (ProxyServer.getInstance().getPluginManager().getPlugin("RedisBungee") != null) { // Universal.setRedis(true); // ProxyServer.getInstance().getPluginManager().registerListener(this, new PubSubMessageListener()); // RedisBungee.getApi().registerPubSubChannels("advancedban:main", "advancedban:connection"); // Universal.get().log("RedisBungee detected, hooking into it!"); // } // } // // @Override // public void onDisable() { // Universal.get().shutdown(); // } // } // // Path: core/src/main/java/me/leoko/advancedban/manager/CommandManager.java // public class CommandManager { // // private static CommandManager instance = null; // // /** // * Get the instance of the command manager // * // * @return the command manager instance // */ // public static synchronized CommandManager get() { // return instance == null ? instance = new CommandManager() : instance; // } // // /** // * Handle/Perform a command. // * // * @param sender the sender which executes the command // * @param cmd the command name // * @param args the arguments for this command // */ // public void onCommand(final Object sender, final String cmd, final String[] args) { // Universal.get().getMethods().runAsync(() -> { // Command command = Command.getByName(cmd); // if (command == null) // return; // // String permission = command.getPermission(); // if (permission != null && !Universal.get().hasPerms(sender, permission)) { // MessageManager.sendMessage(sender, "General.NoPerms", true); // return; // } // // if (!command.validateArguments(args)) { // MessageManager.sendMessage(sender, command.getUsagePath(), true); // return; // } // // command.execute(sender, args); // }); // } // } // Path: bungee/src/main/java/me/leoko/advancedban/bungee/listener/CommandReceiverBungee.java import me.leoko.advancedban.bungee.BungeeMain; import me.leoko.advancedban.manager.CommandManager; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.plugin.Command; package me.leoko.advancedban.bungee.listener; /** * Created by Leoko @ dev.skamps.eu on 24.07.2016. */ public class CommandReceiverBungee extends Command { public CommandReceiverBungee(String name) { super(name); } @Override public void execute(final CommandSender sender, final String[] args) { if (args.length > 0) {
args[0] = (BungeeMain.get().getProxy().getPlayer(args[0]) != null ? BungeeMain.get().getProxy().getPlayer(args[0]).getName() : args[0]);
DevLeoko/AdvancedBan
bungee/src/main/java/me/leoko/advancedban/bungee/listener/CommandReceiverBungee.java
// Path: bungee/src/main/java/me/leoko/advancedban/bungee/BungeeMain.java // public class BungeeMain extends Plugin { // // private static BungeeMain instance; // // private static CloudSupport cloudSupport; // // // public static BungeeMain get() { // return instance; // } // // public static CloudSupport getCloudSupport() { // return cloudSupport; // } // // @Override // public void onEnable() { // instance = this; // Universal.get().setup(new BungeeMethods()); // ProxyServer.getInstance().getPluginManager().registerListener(this, new ConnectionListenerBungee()); // ProxyServer.getInstance().getPluginManager().registerListener(this, new ChatListenerBungee()); // ProxyServer.getInstance().getPluginManager().registerListener(this, new InternalListener()); // ProxyServer.getInstance().registerChannel("advancedban:main"); // // cloudSupport = CloudSupportHandler.getCloudSystem(); // // // if (ProxyServer.getInstance().getPluginManager().getPlugin("RedisBungee") != null) { // Universal.setRedis(true); // ProxyServer.getInstance().getPluginManager().registerListener(this, new PubSubMessageListener()); // RedisBungee.getApi().registerPubSubChannels("advancedban:main", "advancedban:connection"); // Universal.get().log("RedisBungee detected, hooking into it!"); // } // } // // @Override // public void onDisable() { // Universal.get().shutdown(); // } // } // // Path: core/src/main/java/me/leoko/advancedban/manager/CommandManager.java // public class CommandManager { // // private static CommandManager instance = null; // // /** // * Get the instance of the command manager // * // * @return the command manager instance // */ // public static synchronized CommandManager get() { // return instance == null ? instance = new CommandManager() : instance; // } // // /** // * Handle/Perform a command. // * // * @param sender the sender which executes the command // * @param cmd the command name // * @param args the arguments for this command // */ // public void onCommand(final Object sender, final String cmd, final String[] args) { // Universal.get().getMethods().runAsync(() -> { // Command command = Command.getByName(cmd); // if (command == null) // return; // // String permission = command.getPermission(); // if (permission != null && !Universal.get().hasPerms(sender, permission)) { // MessageManager.sendMessage(sender, "General.NoPerms", true); // return; // } // // if (!command.validateArguments(args)) { // MessageManager.sendMessage(sender, command.getUsagePath(), true); // return; // } // // command.execute(sender, args); // }); // } // }
import me.leoko.advancedban.bungee.BungeeMain; import me.leoko.advancedban.manager.CommandManager; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.plugin.Command;
package me.leoko.advancedban.bungee.listener; /** * Created by Leoko @ dev.skamps.eu on 24.07.2016. */ public class CommandReceiverBungee extends Command { public CommandReceiverBungee(String name) { super(name); } @Override public void execute(final CommandSender sender, final String[] args) { if (args.length > 0) { args[0] = (BungeeMain.get().getProxy().getPlayer(args[0]) != null ? BungeeMain.get().getProxy().getPlayer(args[0]).getName() : args[0]); }
// Path: bungee/src/main/java/me/leoko/advancedban/bungee/BungeeMain.java // public class BungeeMain extends Plugin { // // private static BungeeMain instance; // // private static CloudSupport cloudSupport; // // // public static BungeeMain get() { // return instance; // } // // public static CloudSupport getCloudSupport() { // return cloudSupport; // } // // @Override // public void onEnable() { // instance = this; // Universal.get().setup(new BungeeMethods()); // ProxyServer.getInstance().getPluginManager().registerListener(this, new ConnectionListenerBungee()); // ProxyServer.getInstance().getPluginManager().registerListener(this, new ChatListenerBungee()); // ProxyServer.getInstance().getPluginManager().registerListener(this, new InternalListener()); // ProxyServer.getInstance().registerChannel("advancedban:main"); // // cloudSupport = CloudSupportHandler.getCloudSystem(); // // // if (ProxyServer.getInstance().getPluginManager().getPlugin("RedisBungee") != null) { // Universal.setRedis(true); // ProxyServer.getInstance().getPluginManager().registerListener(this, new PubSubMessageListener()); // RedisBungee.getApi().registerPubSubChannels("advancedban:main", "advancedban:connection"); // Universal.get().log("RedisBungee detected, hooking into it!"); // } // } // // @Override // public void onDisable() { // Universal.get().shutdown(); // } // } // // Path: core/src/main/java/me/leoko/advancedban/manager/CommandManager.java // public class CommandManager { // // private static CommandManager instance = null; // // /** // * Get the instance of the command manager // * // * @return the command manager instance // */ // public static synchronized CommandManager get() { // return instance == null ? instance = new CommandManager() : instance; // } // // /** // * Handle/Perform a command. // * // * @param sender the sender which executes the command // * @param cmd the command name // * @param args the arguments for this command // */ // public void onCommand(final Object sender, final String cmd, final String[] args) { // Universal.get().getMethods().runAsync(() -> { // Command command = Command.getByName(cmd); // if (command == null) // return; // // String permission = command.getPermission(); // if (permission != null && !Universal.get().hasPerms(sender, permission)) { // MessageManager.sendMessage(sender, "General.NoPerms", true); // return; // } // // if (!command.validateArguments(args)) { // MessageManager.sendMessage(sender, command.getUsagePath(), true); // return; // } // // command.execute(sender, args); // }); // } // } // Path: bungee/src/main/java/me/leoko/advancedban/bungee/listener/CommandReceiverBungee.java import me.leoko.advancedban.bungee.BungeeMain; import me.leoko.advancedban.manager.CommandManager; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.plugin.Command; package me.leoko.advancedban.bungee.listener; /** * Created by Leoko @ dev.skamps.eu on 24.07.2016. */ public class CommandReceiverBungee extends Command { public CommandReceiverBungee(String name) { super(name); } @Override public void execute(final CommandSender sender, final String[] args) { if (args.length > 0) { args[0] = (BungeeMain.get().getProxy().getPlayer(args[0]) != null ? BungeeMain.get().getProxy().getPlayer(args[0]).getName() : args[0]); }
CommandManager.get().onCommand(sender, this.getName(), args);
jdereg/java-util
src/test/java/com/cedarsoftware/util/TestGraphComparator.java
// Path: src/main/java/com/cedarsoftware/util/DeepEquals.java // public static boolean deepEquals(Object a, Object b) // { // return deepEquals(a, b, new HashMap()); // } // // Path: src/main/java/com/cedarsoftware/util/GraphComparator.java // public enum Command // { // ARRAY_SET_ELEMENT("array.setElement"), // ARRAY_RESIZE("array.resize"), // OBJECT_ASSIGN_FIELD("object.assignField"), // OBJECT_ORPHAN("object.orphan"), // OBJECT_FIELD_TYPE_CHANGED("object.fieldTypeChanged"), // SET_ADD("set.add"), // SET_REMOVE("set.remove"), // MAP_PUT("map.put"), // MAP_REMOVE("map.remove"), // LIST_RESIZE("list.resize"), // LIST_SET_ELEMENT("list.setElement"); // // private String name; // Command(final String name) // { // this.name = name.intern(); // } // // public String getName() // { // return name; // } // // public static Command fromName(String name) // { // if (name == null || "".equals(name.trim())) // { // throw new IllegalArgumentException("Name is required for Command.forName()"); // } // // name = name.toLowerCase(); // for (Command t : Command.values()) // { // if (t.getName().equals(name)) // { // return t; // } // } // // throw new IllegalArgumentException("Unknown Command enum: " + name); // } // }
import com.cedarsoftware.util.io.JsonReader; import com.cedarsoftware.util.io.JsonWriter; import org.junit.Test; import java.util.*; import static com.cedarsoftware.util.DeepEquals.deepEquals; import static com.cedarsoftware.util.GraphComparator.Delta.Command.*; import static org.junit.Assert.*;
private final String name; private final int age; private final List<Pet> pets = new ArrayList<>(); private UnidentifiedObject(String name, int age) { this.name = name; this.age = age; } public void addPet(Pet p) { pets.add(p); } } @Test public void testAlpha() { // TODO: Need to find faster way to get last IP address (problem for unique id generator, not GraphComparator) UniqueIdGenerator.getUniqueId(); } @Test public void testSimpleObjectDifference() throws Exception { Person[] persons = createTwoPersons(); long id = persons[0].id; Person p2 = persons[1]; p2.first = "Jack";
// Path: src/main/java/com/cedarsoftware/util/DeepEquals.java // public static boolean deepEquals(Object a, Object b) // { // return deepEquals(a, b, new HashMap()); // } // // Path: src/main/java/com/cedarsoftware/util/GraphComparator.java // public enum Command // { // ARRAY_SET_ELEMENT("array.setElement"), // ARRAY_RESIZE("array.resize"), // OBJECT_ASSIGN_FIELD("object.assignField"), // OBJECT_ORPHAN("object.orphan"), // OBJECT_FIELD_TYPE_CHANGED("object.fieldTypeChanged"), // SET_ADD("set.add"), // SET_REMOVE("set.remove"), // MAP_PUT("map.put"), // MAP_REMOVE("map.remove"), // LIST_RESIZE("list.resize"), // LIST_SET_ELEMENT("list.setElement"); // // private String name; // Command(final String name) // { // this.name = name.intern(); // } // // public String getName() // { // return name; // } // // public static Command fromName(String name) // { // if (name == null || "".equals(name.trim())) // { // throw new IllegalArgumentException("Name is required for Command.forName()"); // } // // name = name.toLowerCase(); // for (Command t : Command.values()) // { // if (t.getName().equals(name)) // { // return t; // } // } // // throw new IllegalArgumentException("Unknown Command enum: " + name); // } // } // Path: src/test/java/com/cedarsoftware/util/TestGraphComparator.java import com.cedarsoftware.util.io.JsonReader; import com.cedarsoftware.util.io.JsonWriter; import org.junit.Test; import java.util.*; import static com.cedarsoftware.util.DeepEquals.deepEquals; import static com.cedarsoftware.util.GraphComparator.Delta.Command.*; import static org.junit.Assert.*; private final String name; private final int age; private final List<Pet> pets = new ArrayList<>(); private UnidentifiedObject(String name, int age) { this.name = name; this.age = age; } public void addPet(Pet p) { pets.add(p); } } @Test public void testAlpha() { // TODO: Need to find faster way to get last IP address (problem for unique id generator, not GraphComparator) UniqueIdGenerator.getUniqueId(); } @Test public void testSimpleObjectDifference() throws Exception { Person[] persons = createTwoPersons(); long id = persons[0].id; Person p2 = persons[1]; p2.first = "Jack";
assertFalse(deepEquals(persons[0], persons[1]));
jdereg/java-util
src/test/java/com/cedarsoftware/util/TestGraphComparator.java
// Path: src/main/java/com/cedarsoftware/util/DeepEquals.java // public static boolean deepEquals(Object a, Object b) // { // return deepEquals(a, b, new HashMap()); // } // // Path: src/main/java/com/cedarsoftware/util/GraphComparator.java // public enum Command // { // ARRAY_SET_ELEMENT("array.setElement"), // ARRAY_RESIZE("array.resize"), // OBJECT_ASSIGN_FIELD("object.assignField"), // OBJECT_ORPHAN("object.orphan"), // OBJECT_FIELD_TYPE_CHANGED("object.fieldTypeChanged"), // SET_ADD("set.add"), // SET_REMOVE("set.remove"), // MAP_PUT("map.put"), // MAP_REMOVE("map.remove"), // LIST_RESIZE("list.resize"), // LIST_SET_ELEMENT("list.setElement"); // // private String name; // Command(final String name) // { // this.name = name.intern(); // } // // public String getName() // { // return name; // } // // public static Command fromName(String name) // { // if (name == null || "".equals(name.trim())) // { // throw new IllegalArgumentException("Name is required for Command.forName()"); // } // // name = name.toLowerCase(); // for (Command t : Command.values()) // { // if (t.getName().equals(name)) // { // return t; // } // } // // throw new IllegalArgumentException("Unknown Command enum: " + name); // } // }
import com.cedarsoftware.util.io.JsonReader; import com.cedarsoftware.util.io.JsonWriter; import org.junit.Test; import java.util.*; import static com.cedarsoftware.util.DeepEquals.deepEquals; import static com.cedarsoftware.util.GraphComparator.Delta.Command.*; import static org.junit.Assert.*;
assertTrue(errors.size() == 1); GraphComparator.DeltaError error = errors.get(0); assertTrue(error.getError().contains("LIST_SET_ELEMENT")); assertTrue(error.getError().contains("failed")); } @Test public void testDeltaSetterGetter() { GraphComparator.Delta delta = new GraphComparator.Delta(0, "foo", null, null, null, null); delta.setCmd(OBJECT_ASSIGN_FIELD); assertEquals(OBJECT_ASSIGN_FIELD, delta.getCmd()); delta.setFieldName("field"); assertEquals("field", delta.getFieldName()); delta.setId(9); assertEquals(9, delta.getId()); delta.setOptionalKey(6); assertEquals(6, delta.getOptionalKey()); delta.setSourceValue('a'); assertEquals('a', delta.getSourceValue()); delta.setTargetValue(Boolean.TRUE); assertEquals(true, delta.getTargetValue()); assertNotNull(delta.toString()); } @Test public void testDeltaCommandBadEnums() throws Exception { try {
// Path: src/main/java/com/cedarsoftware/util/DeepEquals.java // public static boolean deepEquals(Object a, Object b) // { // return deepEquals(a, b, new HashMap()); // } // // Path: src/main/java/com/cedarsoftware/util/GraphComparator.java // public enum Command // { // ARRAY_SET_ELEMENT("array.setElement"), // ARRAY_RESIZE("array.resize"), // OBJECT_ASSIGN_FIELD("object.assignField"), // OBJECT_ORPHAN("object.orphan"), // OBJECT_FIELD_TYPE_CHANGED("object.fieldTypeChanged"), // SET_ADD("set.add"), // SET_REMOVE("set.remove"), // MAP_PUT("map.put"), // MAP_REMOVE("map.remove"), // LIST_RESIZE("list.resize"), // LIST_SET_ELEMENT("list.setElement"); // // private String name; // Command(final String name) // { // this.name = name.intern(); // } // // public String getName() // { // return name; // } // // public static Command fromName(String name) // { // if (name == null || "".equals(name.trim())) // { // throw new IllegalArgumentException("Name is required for Command.forName()"); // } // // name = name.toLowerCase(); // for (Command t : Command.values()) // { // if (t.getName().equals(name)) // { // return t; // } // } // // throw new IllegalArgumentException("Unknown Command enum: " + name); // } // } // Path: src/test/java/com/cedarsoftware/util/TestGraphComparator.java import com.cedarsoftware.util.io.JsonReader; import com.cedarsoftware.util.io.JsonWriter; import org.junit.Test; import java.util.*; import static com.cedarsoftware.util.DeepEquals.deepEquals; import static com.cedarsoftware.util.GraphComparator.Delta.Command.*; import static org.junit.Assert.*; assertTrue(errors.size() == 1); GraphComparator.DeltaError error = errors.get(0); assertTrue(error.getError().contains("LIST_SET_ELEMENT")); assertTrue(error.getError().contains("failed")); } @Test public void testDeltaSetterGetter() { GraphComparator.Delta delta = new GraphComparator.Delta(0, "foo", null, null, null, null); delta.setCmd(OBJECT_ASSIGN_FIELD); assertEquals(OBJECT_ASSIGN_FIELD, delta.getCmd()); delta.setFieldName("field"); assertEquals("field", delta.getFieldName()); delta.setId(9); assertEquals(9, delta.getId()); delta.setOptionalKey(6); assertEquals(6, delta.getOptionalKey()); delta.setSourceValue('a'); assertEquals('a', delta.getSourceValue()); delta.setTargetValue(Boolean.TRUE); assertEquals(true, delta.getTargetValue()); assertNotNull(delta.toString()); } @Test public void testDeltaCommandBadEnums() throws Exception { try {
GraphComparator.Delta.Command cmd = fromName(null);
jdereg/java-util
src/test/java/com/cedarsoftware/util/TestStringUtilities.java
// Path: src/main/java/com/cedarsoftware/util/StringUtilities.java // public static int hashCodeIgnoreCase(String s) // { // if (s == null) // { // return 0; // } // final int len = s.length(); // int hash = 0; // for (int i = 0; i < len; i++) // { // hash = 31 * hash + Character.toLowerCase((int)s.charAt(i)); // } // return hash; // }
import org.junit.Test; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Random; import java.util.Set; import java.util.TreeSet; import static com.cedarsoftware.util.StringUtilities.hashCodeIgnoreCase; import static org.junit.Assert.*;
} @Test(expected=IllegalArgumentException.class) public void testCreateStringWithInvalidEncoding() { StringUtilities.createString(new byte[] {102, 111, 111}, "baz"); } @Test public void testCreateUtf8String() { assertEquals("foo", StringUtilities.createUtf8String(new byte[] {102, 111, 111})); } @Test public void testCreateUtf8StringWithNull() { assertNull(null, StringUtilities.createUtf8String(null)); } @Test public void testCreateUtf8StringWithEmptyArray() { assertEquals("", StringUtilities.createUtf8String(new byte[]{})); } @Test public void testHashCodeIgnoreCase() { String s = "Hello"; String t = "HELLO";
// Path: src/main/java/com/cedarsoftware/util/StringUtilities.java // public static int hashCodeIgnoreCase(String s) // { // if (s == null) // { // return 0; // } // final int len = s.length(); // int hash = 0; // for (int i = 0; i < len; i++) // { // hash = 31 * hash + Character.toLowerCase((int)s.charAt(i)); // } // return hash; // } // Path: src/test/java/com/cedarsoftware/util/TestStringUtilities.java import org.junit.Test; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Random; import java.util.Set; import java.util.TreeSet; import static com.cedarsoftware.util.StringUtilities.hashCodeIgnoreCase; import static org.junit.Assert.*; } @Test(expected=IllegalArgumentException.class) public void testCreateStringWithInvalidEncoding() { StringUtilities.createString(new byte[] {102, 111, 111}, "baz"); } @Test public void testCreateUtf8String() { assertEquals("foo", StringUtilities.createUtf8String(new byte[] {102, 111, 111})); } @Test public void testCreateUtf8StringWithNull() { assertNull(null, StringUtilities.createUtf8String(null)); } @Test public void testCreateUtf8StringWithEmptyArray() { assertEquals("", StringUtilities.createUtf8String(new byte[]{})); } @Test public void testHashCodeIgnoreCase() { String s = "Hello"; String t = "HELLO";
assert hashCodeIgnoreCase(s) == hashCodeIgnoreCase(t);
jdereg/java-util
src/main/java/com/cedarsoftware/util/CaseInsensitiveMap.java
// Path: src/main/java/com/cedarsoftware/util/StringUtilities.java // public static int hashCodeIgnoreCase(String s) // { // if (s == null) // { // return 0; // } // final int len = s.length(); // int hash = 0; // for (int i = 0; i < len; i++) // { // hash = 31 * hash + Character.toLowerCase((int)s.charAt(i)); // } // return hash; // }
import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; import static com.cedarsoftware.util.StringUtilities.hashCodeIgnoreCase;
{ return (K)((CaseInsensitiveString)superKey).original; } return superKey; } public K getOriginalKey() { return super.getKey(); } public V setValue(V value) { return map.put(super.getKey(), value); } } /** * Class used to wrap String keys. This class ignores the * case of Strings when they are compared. Based on known usage, * null checks, proper instance, etc. are dropped. */ public static final class CaseInsensitiveString implements Comparable { private final String original; private final int hash; public CaseInsensitiveString(String string) { original = string;
// Path: src/main/java/com/cedarsoftware/util/StringUtilities.java // public static int hashCodeIgnoreCase(String s) // { // if (s == null) // { // return 0; // } // final int len = s.length(); // int hash = 0; // for (int i = 0; i < len; i++) // { // hash = 31 * hash + Character.toLowerCase((int)s.charAt(i)); // } // return hash; // } // Path: src/main/java/com/cedarsoftware/util/CaseInsensitiveMap.java import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; import static com.cedarsoftware.util.StringUtilities.hashCodeIgnoreCase; { return (K)((CaseInsensitiveString)superKey).original; } return superKey; } public K getOriginalKey() { return super.getKey(); } public V setValue(V value) { return map.put(super.getKey(), value); } } /** * Class used to wrap String keys. This class ignores the * case of Strings when they are compared. Based on known usage, * null checks, proper instance, etc. are dropped. */ public static final class CaseInsensitiveString implements Comparable { private final String original; private final int hash; public CaseInsensitiveString(String string) { original = string;
hash = hashCodeIgnoreCase(string); // no new String created unlike .toLowerCase()
jdereg/java-util
src/test/java/com/cedarsoftware/util/TestDeepEquals.java
// Path: src/main/java/com/cedarsoftware/util/DeepEquals.java // public static boolean deepEquals(Object a, Object b) // { // return deepEquals(a, b, new HashMap()); // } // // Path: src/main/java/com/cedarsoftware/util/DeepEquals.java // public static int deepHashCode(Object obj) // { // Set<Object> visited = new HashSet<>(); // LinkedList<Object> stack = new LinkedList<>(); // stack.addFirst(obj); // int hash = 0; // // while (!stack.isEmpty()) // { // obj = stack.removeFirst(); // if (obj == null || visited.contains(obj)) // { // continue; // } // // visited.add(obj); // // if (obj.getClass().isArray()) // { // final int len = Array.getLength(obj); // for (int i = 0; i < len; i++) // { // stack.addFirst(Array.get(obj, i)); // } // continue; // } // // if (obj instanceof Collection) // { // stack.addAll(0, (Collection)obj); // continue; // } // // if (obj instanceof Map) // { // stack.addAll(0, ((Map)obj).keySet()); // stack.addAll(0, ((Map)obj).values()); // continue; // } // // if (obj instanceof Double || obj instanceof Float) // { // // just take the integral value for hashcode // // equality tests things more comprehensively // stack.add(Math.round(((Number) obj).doubleValue())); // continue; // } // // if (hasCustomHashCode(obj.getClass())) // { // A real hashCode() method exists, call it. // hash += obj.hashCode(); // continue; // } // // Collection<Field> fields = ReflectionUtils.getDeepDeclaredFields(obj.getClass()); // for (Field field : fields) // { // try // { // stack.addFirst(field.get(obj)); // } // catch (Exception ignored) { } // } // } // return hash; // }
import org.agrona.collections.Object2ObjectHashMap; import org.junit.Test; import java.awt.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import java.util.*; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import static com.cedarsoftware.util.DeepEquals.deepEquals; import static com.cedarsoftware.util.DeepEquals.deepHashCode; import static java.lang.Math.*; import static java.util.Arrays.asList; import static org.junit.Assert.*;
package com.cedarsoftware.util; /** * @author John DeRegnaucourt * @author sapradhan8 * <br> * 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 <br> * <br> * http://www.apache.org/licenses/LICENSE-2.0 <br> * <br> * 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. */ public class TestDeepEquals { @Test public void testSameObjectEquals() { Date date1 = new Date(); Date date2 = date1;
// Path: src/main/java/com/cedarsoftware/util/DeepEquals.java // public static boolean deepEquals(Object a, Object b) // { // return deepEquals(a, b, new HashMap()); // } // // Path: src/main/java/com/cedarsoftware/util/DeepEquals.java // public static int deepHashCode(Object obj) // { // Set<Object> visited = new HashSet<>(); // LinkedList<Object> stack = new LinkedList<>(); // stack.addFirst(obj); // int hash = 0; // // while (!stack.isEmpty()) // { // obj = stack.removeFirst(); // if (obj == null || visited.contains(obj)) // { // continue; // } // // visited.add(obj); // // if (obj.getClass().isArray()) // { // final int len = Array.getLength(obj); // for (int i = 0; i < len; i++) // { // stack.addFirst(Array.get(obj, i)); // } // continue; // } // // if (obj instanceof Collection) // { // stack.addAll(0, (Collection)obj); // continue; // } // // if (obj instanceof Map) // { // stack.addAll(0, ((Map)obj).keySet()); // stack.addAll(0, ((Map)obj).values()); // continue; // } // // if (obj instanceof Double || obj instanceof Float) // { // // just take the integral value for hashcode // // equality tests things more comprehensively // stack.add(Math.round(((Number) obj).doubleValue())); // continue; // } // // if (hasCustomHashCode(obj.getClass())) // { // A real hashCode() method exists, call it. // hash += obj.hashCode(); // continue; // } // // Collection<Field> fields = ReflectionUtils.getDeepDeclaredFields(obj.getClass()); // for (Field field : fields) // { // try // { // stack.addFirst(field.get(obj)); // } // catch (Exception ignored) { } // } // } // return hash; // } // Path: src/test/java/com/cedarsoftware/util/TestDeepEquals.java import org.agrona.collections.Object2ObjectHashMap; import org.junit.Test; import java.awt.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import java.util.*; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import static com.cedarsoftware.util.DeepEquals.deepEquals; import static com.cedarsoftware.util.DeepEquals.deepHashCode; import static java.lang.Math.*; import static java.util.Arrays.asList; import static org.junit.Assert.*; package com.cedarsoftware.util; /** * @author John DeRegnaucourt * @author sapradhan8 * <br> * 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 <br> * <br> * http://www.apache.org/licenses/LICENSE-2.0 <br> * <br> * 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. */ public class TestDeepEquals { @Test public void testSameObjectEquals() { Date date1 = new Date(); Date date2 = date1;
assertTrue(deepEquals(date1, date2));
jdereg/java-util
src/test/java/com/cedarsoftware/util/TestDeepEquals.java
// Path: src/main/java/com/cedarsoftware/util/DeepEquals.java // public static boolean deepEquals(Object a, Object b) // { // return deepEquals(a, b, new HashMap()); // } // // Path: src/main/java/com/cedarsoftware/util/DeepEquals.java // public static int deepHashCode(Object obj) // { // Set<Object> visited = new HashSet<>(); // LinkedList<Object> stack = new LinkedList<>(); // stack.addFirst(obj); // int hash = 0; // // while (!stack.isEmpty()) // { // obj = stack.removeFirst(); // if (obj == null || visited.contains(obj)) // { // continue; // } // // visited.add(obj); // // if (obj.getClass().isArray()) // { // final int len = Array.getLength(obj); // for (int i = 0; i < len; i++) // { // stack.addFirst(Array.get(obj, i)); // } // continue; // } // // if (obj instanceof Collection) // { // stack.addAll(0, (Collection)obj); // continue; // } // // if (obj instanceof Map) // { // stack.addAll(0, ((Map)obj).keySet()); // stack.addAll(0, ((Map)obj).values()); // continue; // } // // if (obj instanceof Double || obj instanceof Float) // { // // just take the integral value for hashcode // // equality tests things more comprehensively // stack.add(Math.round(((Number) obj).doubleValue())); // continue; // } // // if (hasCustomHashCode(obj.getClass())) // { // A real hashCode() method exists, call it. // hash += obj.hashCode(); // continue; // } // // Collection<Field> fields = ReflectionUtils.getDeepDeclaredFields(obj.getClass()); // for (Field field : fields) // { // try // { // stack.addFirst(field.get(obj)); // } // catch (Exception ignored) { } // } // } // return hash; // }
import org.agrona.collections.Object2ObjectHashMap; import org.junit.Test; import java.awt.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import java.util.*; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import static com.cedarsoftware.util.DeepEquals.deepEquals; import static com.cedarsoftware.util.DeepEquals.deepHashCode; import static java.lang.Math.*; import static java.util.Arrays.asList; import static org.junit.Assert.*;
assertTrue(deepEquals(x1, x2)); // Proves that objects are being compared against the correct objects in each collection (all objects have same // hash code, so the unordered compare must handle checking item by item for hash-collided items) Set<DumbHash> d1 = new LinkedHashSet<>(); Set<DumbHash> d2 = new LinkedHashSet<>(); d1.add(new DumbHash("alpha")); d1.add(new DumbHash("bravo")); d1.add(new DumbHash("charlie")); d2.add(new DumbHash("bravo")); d2.add(new DumbHash("alpha")); d2.add(new DumbHash("charlie")); assert deepEquals(d1, d2); d2.clear(); d2.add(new DumbHash("bravo")); d2.add(new DumbHash("alpha")); d2.add(new DumbHash("delta")); assert !deepEquals(d2, d1); } @Test public void testEquivalentMaps() { Map map1 = new LinkedHashMap(); fillMap(map1); Map map2 = new HashMap(); fillMap(map2); assertTrue(deepEquals(map1, map2));
// Path: src/main/java/com/cedarsoftware/util/DeepEquals.java // public static boolean deepEquals(Object a, Object b) // { // return deepEquals(a, b, new HashMap()); // } // // Path: src/main/java/com/cedarsoftware/util/DeepEquals.java // public static int deepHashCode(Object obj) // { // Set<Object> visited = new HashSet<>(); // LinkedList<Object> stack = new LinkedList<>(); // stack.addFirst(obj); // int hash = 0; // // while (!stack.isEmpty()) // { // obj = stack.removeFirst(); // if (obj == null || visited.contains(obj)) // { // continue; // } // // visited.add(obj); // // if (obj.getClass().isArray()) // { // final int len = Array.getLength(obj); // for (int i = 0; i < len; i++) // { // stack.addFirst(Array.get(obj, i)); // } // continue; // } // // if (obj instanceof Collection) // { // stack.addAll(0, (Collection)obj); // continue; // } // // if (obj instanceof Map) // { // stack.addAll(0, ((Map)obj).keySet()); // stack.addAll(0, ((Map)obj).values()); // continue; // } // // if (obj instanceof Double || obj instanceof Float) // { // // just take the integral value for hashcode // // equality tests things more comprehensively // stack.add(Math.round(((Number) obj).doubleValue())); // continue; // } // // if (hasCustomHashCode(obj.getClass())) // { // A real hashCode() method exists, call it. // hash += obj.hashCode(); // continue; // } // // Collection<Field> fields = ReflectionUtils.getDeepDeclaredFields(obj.getClass()); // for (Field field : fields) // { // try // { // stack.addFirst(field.get(obj)); // } // catch (Exception ignored) { } // } // } // return hash; // } // Path: src/test/java/com/cedarsoftware/util/TestDeepEquals.java import org.agrona.collections.Object2ObjectHashMap; import org.junit.Test; import java.awt.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import java.util.*; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import static com.cedarsoftware.util.DeepEquals.deepEquals; import static com.cedarsoftware.util.DeepEquals.deepHashCode; import static java.lang.Math.*; import static java.util.Arrays.asList; import static org.junit.Assert.*; assertTrue(deepEquals(x1, x2)); // Proves that objects are being compared against the correct objects in each collection (all objects have same // hash code, so the unordered compare must handle checking item by item for hash-collided items) Set<DumbHash> d1 = new LinkedHashSet<>(); Set<DumbHash> d2 = new LinkedHashSet<>(); d1.add(new DumbHash("alpha")); d1.add(new DumbHash("bravo")); d1.add(new DumbHash("charlie")); d2.add(new DumbHash("bravo")); d2.add(new DumbHash("alpha")); d2.add(new DumbHash("charlie")); assert deepEquals(d1, d2); d2.clear(); d2.add(new DumbHash("bravo")); d2.add(new DumbHash("alpha")); d2.add(new DumbHash("delta")); assert !deepEquals(d2, d1); } @Test public void testEquivalentMaps() { Map map1 = new LinkedHashMap(); fillMap(map1); Map map2 = new HashMap(); fillMap(map2); assertTrue(deepEquals(map1, map2));
assertEquals(deepHashCode(map1), deepHashCode(map2));
jdereg/java-util
src/main/java/com/cedarsoftware/util/CaseInsensitiveSet.java
// Path: src/main/java/com/cedarsoftware/util/StringUtilities.java // public static int hashCodeIgnoreCase(String s) // { // if (s == null) // { // return 0; // } // final int len = s.length(); // int hash = 0; // for (int i = 0; i < len; i++) // { // hash = 31 * hash + Character.toLowerCase((int)s.charAt(i)); // } // return hash; // }
import java.util.*; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ConcurrentSkipListSet; import static com.cedarsoftware.util.StringUtilities.hashCodeIgnoreCase;
map = new CaseInsensitiveMap<>(collection.size()); } addAll(collection); } public CaseInsensitiveSet(Collection<? extends E> source, Map backingMap) { map = backingMap; addAll(source); } public CaseInsensitiveSet(int initialCapacity) { map = new CaseInsensitiveMap<>(initialCapacity); } public CaseInsensitiveSet(int initialCapacity, float loadFactor) { map = new CaseInsensitiveMap<>(initialCapacity, loadFactor); } public int hashCode() { int hash = 0; for (Object item : map.keySet()) { if (item != null) { if (item instanceof String) {
// Path: src/main/java/com/cedarsoftware/util/StringUtilities.java // public static int hashCodeIgnoreCase(String s) // { // if (s == null) // { // return 0; // } // final int len = s.length(); // int hash = 0; // for (int i = 0; i < len; i++) // { // hash = 31 * hash + Character.toLowerCase((int)s.charAt(i)); // } // return hash; // } // Path: src/main/java/com/cedarsoftware/util/CaseInsensitiveSet.java import java.util.*; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ConcurrentSkipListSet; import static com.cedarsoftware.util.StringUtilities.hashCodeIgnoreCase; map = new CaseInsensitiveMap<>(collection.size()); } addAll(collection); } public CaseInsensitiveSet(Collection<? extends E> source, Map backingMap) { map = backingMap; addAll(source); } public CaseInsensitiveSet(int initialCapacity) { map = new CaseInsensitiveMap<>(initialCapacity); } public CaseInsensitiveSet(int initialCapacity, float loadFactor) { map = new CaseInsensitiveMap<>(initialCapacity, loadFactor); } public int hashCode() { int hash = 0; for (Object item : map.keySet()) { if (item != null) { if (item instanceof String) {
hash += hashCodeIgnoreCase((String)item);