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
RxHandsOn/MarketData
marketdata-web/src/test/java/com/handson/rx/VwapServerTest.java
// Path: marketdata-common/src/main/java/com/handson/dto/Trade.java // public class Trade { // // public final String code; // public final int quantity; // public final double nominal; // // public Trade(String code, int quantity, double nominal) { // this.code = code; // this.quantity = quantity; // this.nominal = nominal; // } // // public static Trade fromJson(String input) { // return new Gson().fromJson(input, Trade.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Vwap.java // public class Vwap { // // public final String code; // public final double vwap; // public final double volume; // // public Vwap(String code) { // this.code = code; // this.vwap = 0; // this.volume = 0; // } // // public Vwap(String code, double vwap, double volume) { // this.code = code; // this.vwap = vwap; // this.volume = volume; // } // // public Vwap addTrade(Trade t) { // double volume = this.volume + t.quantity; // double vwap = (this.volume * this.vwap + t.nominal) / volume; // return new Vwap(t.code, vwap, volume); // } // // public static Vwap fromJson(String input) { // return new Gson().fromJson(input, Vwap.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // }
import com.handson.dto.Trade; import com.handson.dto.Vwap; import com.handson.infra.EventStreamClient; import com.handson.infra.HttpRequest; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import rx.observers.TestSubscriber; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import rx.subjects.TestSubject; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package com.handson.rx; public class VwapServerTest { private EventStreamClient tradeEventStreamClient; private TestScheduler scheduler; private VwapServer vwapServer; private TestSubject<String> tradeSourceSubject; @Before public void setUpServer() { tradeEventStreamClient = mock(EventStreamClient.class); scheduler = Schedulers.test(); vwapServer = new VwapServer(42, tradeEventStreamClient, scheduler); tradeSourceSubject = TestSubject.create(scheduler); when(tradeEventStreamClient.readServerSideEvents()).thenReturn(tradeSourceSubject); } /** * Test 10 */ @Test @Ignore public void should_generate_one_google_vwap_event_when_a_google_trade_is_done() { // given
// Path: marketdata-common/src/main/java/com/handson/dto/Trade.java // public class Trade { // // public final String code; // public final int quantity; // public final double nominal; // // public Trade(String code, int quantity, double nominal) { // this.code = code; // this.quantity = quantity; // this.nominal = nominal; // } // // public static Trade fromJson(String input) { // return new Gson().fromJson(input, Trade.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Vwap.java // public class Vwap { // // public final String code; // public final double vwap; // public final double volume; // // public Vwap(String code) { // this.code = code; // this.vwap = 0; // this.volume = 0; // } // // public Vwap(String code, double vwap, double volume) { // this.code = code; // this.vwap = vwap; // this.volume = volume; // } // // public Vwap addTrade(Trade t) { // double volume = this.volume + t.quantity; // double vwap = (this.volume * this.vwap + t.nominal) / volume; // return new Vwap(t.code, vwap, volume); // } // // public static Vwap fromJson(String input) { // return new Gson().fromJson(input, Vwap.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // } // Path: marketdata-web/src/test/java/com/handson/rx/VwapServerTest.java import com.handson.dto.Trade; import com.handson.dto.Vwap; import com.handson.infra.EventStreamClient; import com.handson.infra.HttpRequest; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import rx.observers.TestSubscriber; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import rx.subjects.TestSubject; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package com.handson.rx; public class VwapServerTest { private EventStreamClient tradeEventStreamClient; private TestScheduler scheduler; private VwapServer vwapServer; private TestSubject<String> tradeSourceSubject; @Before public void setUpServer() { tradeEventStreamClient = mock(EventStreamClient.class); scheduler = Schedulers.test(); vwapServer = new VwapServer(42, tradeEventStreamClient, scheduler); tradeSourceSubject = TestSubject.create(scheduler); when(tradeEventStreamClient.readServerSideEvents()).thenReturn(tradeSourceSubject); } /** * Test 10 */ @Test @Ignore public void should_generate_one_google_vwap_event_when_a_google_trade_is_done() { // given
TestSubscriber<Vwap> testSubscriber = new TestSubscriber<>();
RxHandsOn/MarketData
marketdata-web/src/test/java/com/handson/rx/VwapServerTest.java
// Path: marketdata-common/src/main/java/com/handson/dto/Trade.java // public class Trade { // // public final String code; // public final int quantity; // public final double nominal; // // public Trade(String code, int quantity, double nominal) { // this.code = code; // this.quantity = quantity; // this.nominal = nominal; // } // // public static Trade fromJson(String input) { // return new Gson().fromJson(input, Trade.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Vwap.java // public class Vwap { // // public final String code; // public final double vwap; // public final double volume; // // public Vwap(String code) { // this.code = code; // this.vwap = 0; // this.volume = 0; // } // // public Vwap(String code, double vwap, double volume) { // this.code = code; // this.vwap = vwap; // this.volume = volume; // } // // public Vwap addTrade(Trade t) { // double volume = this.volume + t.quantity; // double vwap = (this.volume * this.vwap + t.nominal) / volume; // return new Vwap(t.code, vwap, volume); // } // // public static Vwap fromJson(String input) { // return new Gson().fromJson(input, Vwap.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // }
import com.handson.dto.Trade; import com.handson.dto.Vwap; import com.handson.infra.EventStreamClient; import com.handson.infra.HttpRequest; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import rx.observers.TestSubscriber; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import rx.subjects.TestSubject; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package com.handson.rx; public class VwapServerTest { private EventStreamClient tradeEventStreamClient; private TestScheduler scheduler; private VwapServer vwapServer; private TestSubject<String> tradeSourceSubject; @Before public void setUpServer() { tradeEventStreamClient = mock(EventStreamClient.class); scheduler = Schedulers.test(); vwapServer = new VwapServer(42, tradeEventStreamClient, scheduler); tradeSourceSubject = TestSubject.create(scheduler); when(tradeEventStreamClient.readServerSideEvents()).thenReturn(tradeSourceSubject); } /** * Test 10 */ @Test @Ignore public void should_generate_one_google_vwap_event_when_a_google_trade_is_done() { // given TestSubscriber<Vwap> testSubscriber = new TestSubscriber<>();
// Path: marketdata-common/src/main/java/com/handson/dto/Trade.java // public class Trade { // // public final String code; // public final int quantity; // public final double nominal; // // public Trade(String code, int quantity, double nominal) { // this.code = code; // this.quantity = quantity; // this.nominal = nominal; // } // // public static Trade fromJson(String input) { // return new Gson().fromJson(input, Trade.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Vwap.java // public class Vwap { // // public final String code; // public final double vwap; // public final double volume; // // public Vwap(String code) { // this.code = code; // this.vwap = 0; // this.volume = 0; // } // // public Vwap(String code, double vwap, double volume) { // this.code = code; // this.vwap = vwap; // this.volume = volume; // } // // public Vwap addTrade(Trade t) { // double volume = this.volume + t.quantity; // double vwap = (this.volume * this.vwap + t.nominal) / volume; // return new Vwap(t.code, vwap, volume); // } // // public static Vwap fromJson(String input) { // return new Gson().fromJson(input, Vwap.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // } // Path: marketdata-web/src/test/java/com/handson/rx/VwapServerTest.java import com.handson.dto.Trade; import com.handson.dto.Vwap; import com.handson.infra.EventStreamClient; import com.handson.infra.HttpRequest; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import rx.observers.TestSubscriber; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import rx.subjects.TestSubject; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package com.handson.rx; public class VwapServerTest { private EventStreamClient tradeEventStreamClient; private TestScheduler scheduler; private VwapServer vwapServer; private TestSubject<String> tradeSourceSubject; @Before public void setUpServer() { tradeEventStreamClient = mock(EventStreamClient.class); scheduler = Schedulers.test(); vwapServer = new VwapServer(42, tradeEventStreamClient, scheduler); tradeSourceSubject = TestSubject.create(scheduler); when(tradeEventStreamClient.readServerSideEvents()).thenReturn(tradeSourceSubject); } /** * Test 10 */ @Test @Ignore public void should_generate_one_google_vwap_event_when_a_google_trade_is_done() { // given TestSubscriber<Vwap> testSubscriber = new TestSubscriber<>();
HttpRequest request = createRequest("code", "GOOGL");
RxHandsOn/MarketData
marketdata-web/src/test/java/com/handson/rx/VwapServerTest.java
// Path: marketdata-common/src/main/java/com/handson/dto/Trade.java // public class Trade { // // public final String code; // public final int quantity; // public final double nominal; // // public Trade(String code, int quantity, double nominal) { // this.code = code; // this.quantity = quantity; // this.nominal = nominal; // } // // public static Trade fromJson(String input) { // return new Gson().fromJson(input, Trade.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Vwap.java // public class Vwap { // // public final String code; // public final double vwap; // public final double volume; // // public Vwap(String code) { // this.code = code; // this.vwap = 0; // this.volume = 0; // } // // public Vwap(String code, double vwap, double volume) { // this.code = code; // this.vwap = vwap; // this.volume = volume; // } // // public Vwap addTrade(Trade t) { // double volume = this.volume + t.quantity; // double vwap = (this.volume * this.vwap + t.nominal) / volume; // return new Vwap(t.code, vwap, volume); // } // // public static Vwap fromJson(String input) { // return new Gson().fromJson(input, Vwap.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // }
import com.handson.dto.Trade; import com.handson.dto.Vwap; import com.handson.infra.EventStreamClient; import com.handson.infra.HttpRequest; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import rx.observers.TestSubscriber; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import rx.subjects.TestSubject; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package com.handson.rx; public class VwapServerTest { private EventStreamClient tradeEventStreamClient; private TestScheduler scheduler; private VwapServer vwapServer; private TestSubject<String> tradeSourceSubject; @Before public void setUpServer() { tradeEventStreamClient = mock(EventStreamClient.class); scheduler = Schedulers.test(); vwapServer = new VwapServer(42, tradeEventStreamClient, scheduler); tradeSourceSubject = TestSubject.create(scheduler); when(tradeEventStreamClient.readServerSideEvents()).thenReturn(tradeSourceSubject); } /** * Test 10 */ @Test @Ignore public void should_generate_one_google_vwap_event_when_a_google_trade_is_done() { // given TestSubscriber<Vwap> testSubscriber = new TestSubscriber<>(); HttpRequest request = createRequest("code", "GOOGL"); vwapServer.getEvents(request).subscribe(testSubscriber); // when
// Path: marketdata-common/src/main/java/com/handson/dto/Trade.java // public class Trade { // // public final String code; // public final int quantity; // public final double nominal; // // public Trade(String code, int quantity, double nominal) { // this.code = code; // this.quantity = quantity; // this.nominal = nominal; // } // // public static Trade fromJson(String input) { // return new Gson().fromJson(input, Trade.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Vwap.java // public class Vwap { // // public final String code; // public final double vwap; // public final double volume; // // public Vwap(String code) { // this.code = code; // this.vwap = 0; // this.volume = 0; // } // // public Vwap(String code, double vwap, double volume) { // this.code = code; // this.vwap = vwap; // this.volume = volume; // } // // public Vwap addTrade(Trade t) { // double volume = this.volume + t.quantity; // double vwap = (this.volume * this.vwap + t.nominal) / volume; // return new Vwap(t.code, vwap, volume); // } // // public static Vwap fromJson(String input) { // return new Gson().fromJson(input, Vwap.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // } // Path: marketdata-web/src/test/java/com/handson/rx/VwapServerTest.java import com.handson.dto.Trade; import com.handson.dto.Vwap; import com.handson.infra.EventStreamClient; import com.handson.infra.HttpRequest; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import rx.observers.TestSubscriber; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import rx.subjects.TestSubject; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package com.handson.rx; public class VwapServerTest { private EventStreamClient tradeEventStreamClient; private TestScheduler scheduler; private VwapServer vwapServer; private TestSubject<String> tradeSourceSubject; @Before public void setUpServer() { tradeEventStreamClient = mock(EventStreamClient.class); scheduler = Schedulers.test(); vwapServer = new VwapServer(42, tradeEventStreamClient, scheduler); tradeSourceSubject = TestSubject.create(scheduler); when(tradeEventStreamClient.readServerSideEvents()).thenReturn(tradeSourceSubject); } /** * Test 10 */ @Test @Ignore public void should_generate_one_google_vwap_event_when_a_google_trade_is_done() { // given TestSubscriber<Vwap> testSubscriber = new TestSubscriber<>(); HttpRequest request = createRequest("code", "GOOGL"); vwapServer.getEvents(request).subscribe(testSubscriber); // when
tradeSourceSubject.onNext(new Trade("GOOGL", 10, 7058.673).toJson());
RxHandsOn/MarketData
marketdata-web/src/test/java/com/handson/rx/StockServerTest.java
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Stock.java // public class Stock { // // public final String code; // // public final String companyName; // // public final String market; // // public Stock(String code, String companyName, String market) { // this.code = code; // this.companyName = companyName; // this.market = market; // } // // public static Stock fromJson(String input) { // return new Gson().fromJson(input, Stock.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/RequestReplyClient.java // public interface RequestReplyClient { // // Observable<String> request(String parameter); // }
import com.handson.dto.Quote; import com.handson.dto.Stock; import com.handson.infra.EventStreamClient; import com.handson.infra.RequestReplyClient; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import rx.Observable; import rx.marble.junit.MarbleRule; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static rx.marble.MapHelper.of; import static rx.marble.junit.MarbleRule.expectObservable; import static rx.marble.junit.MarbleRule.hot;
package com.handson.rx; public class StockServerTest { @Rule public MarbleRule marble = new MarbleRule(1000); /** * Test 7 */ @Test @Ignore public void should_send_a_stock_message_when_receiving_a_quote() { // given Observable<String> quoteSource
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Stock.java // public class Stock { // // public final String code; // // public final String companyName; // // public final String market; // // public Stock(String code, String companyName, String market) { // this.code = code; // this.companyName = companyName; // this.market = market; // } // // public static Stock fromJson(String input) { // return new Gson().fromJson(input, Stock.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/RequestReplyClient.java // public interface RequestReplyClient { // // Observable<String> request(String parameter); // } // Path: marketdata-web/src/test/java/com/handson/rx/StockServerTest.java import com.handson.dto.Quote; import com.handson.dto.Stock; import com.handson.infra.EventStreamClient; import com.handson.infra.RequestReplyClient; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import rx.Observable; import rx.marble.junit.MarbleRule; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static rx.marble.MapHelper.of; import static rx.marble.junit.MarbleRule.expectObservable; import static rx.marble.junit.MarbleRule.hot; package com.handson.rx; public class StockServerTest { @Rule public MarbleRule marble = new MarbleRule(1000); /** * Test 7 */ @Test @Ignore public void should_send_a_stock_message_when_receiving_a_quote() { // given Observable<String> quoteSource
= hot("--q--", of("q", new Quote("GOOGL", 705.8673).toJson()));
RxHandsOn/MarketData
marketdata-web/src/test/java/com/handson/rx/StockServerTest.java
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Stock.java // public class Stock { // // public final String code; // // public final String companyName; // // public final String market; // // public Stock(String code, String companyName, String market) { // this.code = code; // this.companyName = companyName; // this.market = market; // } // // public static Stock fromJson(String input) { // return new Gson().fromJson(input, Stock.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/RequestReplyClient.java // public interface RequestReplyClient { // // Observable<String> request(String parameter); // }
import com.handson.dto.Quote; import com.handson.dto.Stock; import com.handson.infra.EventStreamClient; import com.handson.infra.RequestReplyClient; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import rx.Observable; import rx.marble.junit.MarbleRule; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static rx.marble.MapHelper.of; import static rx.marble.junit.MarbleRule.expectObservable; import static rx.marble.junit.MarbleRule.hot;
public void should_send_a_stock_message_only_once_when_receiving_two_quotes_for_the_same_stock() { // given Observable<String> quoteSource = hot("--f-s-t--", of("f", new Quote("GOOGL", 705.8673).toJson(), "s", new Quote("GOOGL", 705.8912).toJson(), "t", new Quote("IBM", 106.344).toJson() )); // when StockServer server = createServer(quoteSource); // then expectObservable(server.getEvents(null).map(s -> s.companyName).concatWith(Observable.never())) .toBe("--g---i--", of("g", "Alphabet Inc", "i", "International Business Machines Corp.")); } /** * Test 9 */ @Test @Ignore public void should_stop_stream_after_10_seconds() { // given Observable<String> quoteSource = Observable.never(); // when StockServer server = createServer(quoteSource); // then expectObservable(server.getEvents(null)).toBe("----------|"); } public StockServer createServer(Observable<String> quoteSource) {
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Stock.java // public class Stock { // // public final String code; // // public final String companyName; // // public final String market; // // public Stock(String code, String companyName, String market) { // this.code = code; // this.companyName = companyName; // this.market = market; // } // // public static Stock fromJson(String input) { // return new Gson().fromJson(input, Stock.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/RequestReplyClient.java // public interface RequestReplyClient { // // Observable<String> request(String parameter); // } // Path: marketdata-web/src/test/java/com/handson/rx/StockServerTest.java import com.handson.dto.Quote; import com.handson.dto.Stock; import com.handson.infra.EventStreamClient; import com.handson.infra.RequestReplyClient; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import rx.Observable; import rx.marble.junit.MarbleRule; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static rx.marble.MapHelper.of; import static rx.marble.junit.MarbleRule.expectObservable; import static rx.marble.junit.MarbleRule.hot; public void should_send_a_stock_message_only_once_when_receiving_two_quotes_for_the_same_stock() { // given Observable<String> quoteSource = hot("--f-s-t--", of("f", new Quote("GOOGL", 705.8673).toJson(), "s", new Quote("GOOGL", 705.8912).toJson(), "t", new Quote("IBM", 106.344).toJson() )); // when StockServer server = createServer(quoteSource); // then expectObservable(server.getEvents(null).map(s -> s.companyName).concatWith(Observable.never())) .toBe("--g---i--", of("g", "Alphabet Inc", "i", "International Business Machines Corp.")); } /** * Test 9 */ @Test @Ignore public void should_stop_stream_after_10_seconds() { // given Observable<String> quoteSource = Observable.never(); // when StockServer server = createServer(quoteSource); // then expectObservable(server.getEvents(null)).toBe("----------|"); } public StockServer createServer(Observable<String> quoteSource) {
RequestReplyClient stockClient = mock(RequestReplyClient.class);
RxHandsOn/MarketData
marketdata-web/src/test/java/com/handson/rx/StockServerTest.java
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Stock.java // public class Stock { // // public final String code; // // public final String companyName; // // public final String market; // // public Stock(String code, String companyName, String market) { // this.code = code; // this.companyName = companyName; // this.market = market; // } // // public static Stock fromJson(String input) { // return new Gson().fromJson(input, Stock.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/RequestReplyClient.java // public interface RequestReplyClient { // // Observable<String> request(String parameter); // }
import com.handson.dto.Quote; import com.handson.dto.Stock; import com.handson.infra.EventStreamClient; import com.handson.infra.RequestReplyClient; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import rx.Observable; import rx.marble.junit.MarbleRule; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static rx.marble.MapHelper.of; import static rx.marble.junit.MarbleRule.expectObservable; import static rx.marble.junit.MarbleRule.hot;
// given Observable<String> quoteSource = hot("--f-s-t--", of("f", new Quote("GOOGL", 705.8673).toJson(), "s", new Quote("GOOGL", 705.8912).toJson(), "t", new Quote("IBM", 106.344).toJson() )); // when StockServer server = createServer(quoteSource); // then expectObservable(server.getEvents(null).map(s -> s.companyName).concatWith(Observable.never())) .toBe("--g---i--", of("g", "Alphabet Inc", "i", "International Business Machines Corp.")); } /** * Test 9 */ @Test @Ignore public void should_stop_stream_after_10_seconds() { // given Observable<String> quoteSource = Observable.never(); // when StockServer server = createServer(quoteSource); // then expectObservable(server.getEvents(null)).toBe("----------|"); } public StockServer createServer(Observable<String> quoteSource) { RequestReplyClient stockClient = mock(RequestReplyClient.class);
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Stock.java // public class Stock { // // public final String code; // // public final String companyName; // // public final String market; // // public Stock(String code, String companyName, String market) { // this.code = code; // this.companyName = companyName; // this.market = market; // } // // public static Stock fromJson(String input) { // return new Gson().fromJson(input, Stock.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/RequestReplyClient.java // public interface RequestReplyClient { // // Observable<String> request(String parameter); // } // Path: marketdata-web/src/test/java/com/handson/rx/StockServerTest.java import com.handson.dto.Quote; import com.handson.dto.Stock; import com.handson.infra.EventStreamClient; import com.handson.infra.RequestReplyClient; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import rx.Observable; import rx.marble.junit.MarbleRule; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static rx.marble.MapHelper.of; import static rx.marble.junit.MarbleRule.expectObservable; import static rx.marble.junit.MarbleRule.hot; // given Observable<String> quoteSource = hot("--f-s-t--", of("f", new Quote("GOOGL", 705.8673).toJson(), "s", new Quote("GOOGL", 705.8912).toJson(), "t", new Quote("IBM", 106.344).toJson() )); // when StockServer server = createServer(quoteSource); // then expectObservable(server.getEvents(null).map(s -> s.companyName).concatWith(Observable.never())) .toBe("--g---i--", of("g", "Alphabet Inc", "i", "International Business Machines Corp.")); } /** * Test 9 */ @Test @Ignore public void should_stop_stream_after_10_seconds() { // given Observable<String> quoteSource = Observable.never(); // when StockServer server = createServer(quoteSource); // then expectObservable(server.getEvents(null)).toBe("----------|"); } public StockServer createServer(Observable<String> quoteSource) { RequestReplyClient stockClient = mock(RequestReplyClient.class);
EventStreamClient stockQuoteClient = mock(EventStreamClient.class);
RxHandsOn/MarketData
marketdata-web/src/test/java/com/handson/rx/StockServerTest.java
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Stock.java // public class Stock { // // public final String code; // // public final String companyName; // // public final String market; // // public Stock(String code, String companyName, String market) { // this.code = code; // this.companyName = companyName; // this.market = market; // } // // public static Stock fromJson(String input) { // return new Gson().fromJson(input, Stock.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/RequestReplyClient.java // public interface RequestReplyClient { // // Observable<String> request(String parameter); // }
import com.handson.dto.Quote; import com.handson.dto.Stock; import com.handson.infra.EventStreamClient; import com.handson.infra.RequestReplyClient; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import rx.Observable; import rx.marble.junit.MarbleRule; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static rx.marble.MapHelper.of; import static rx.marble.junit.MarbleRule.expectObservable; import static rx.marble.junit.MarbleRule.hot;
StockServer server = createServer(quoteSource); // then expectObservable(server.getEvents(null).map(s -> s.companyName).concatWith(Observable.never())) .toBe("--g---i--", of("g", "Alphabet Inc", "i", "International Business Machines Corp.")); } /** * Test 9 */ @Test @Ignore public void should_stop_stream_after_10_seconds() { // given Observable<String> quoteSource = Observable.never(); // when StockServer server = createServer(quoteSource); // then expectObservable(server.getEvents(null)).toBe("----------|"); } public StockServer createServer(Observable<String> quoteSource) { RequestReplyClient stockClient = mock(RequestReplyClient.class); EventStreamClient stockQuoteClient = mock(EventStreamClient.class); StockServer stockServer = new StockServer(42, stockClient, stockQuoteClient, marble.scheduler); when(stockQuoteClient.readServerSideEvents()).thenReturn(quoteSource); when(stockClient.request(eq("GOOGL"))) .then( code -> Observable.just(
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Stock.java // public class Stock { // // public final String code; // // public final String companyName; // // public final String market; // // public Stock(String code, String companyName, String market) { // this.code = code; // this.companyName = companyName; // this.market = market; // } // // public static Stock fromJson(String input) { // return new Gson().fromJson(input, Stock.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/RequestReplyClient.java // public interface RequestReplyClient { // // Observable<String> request(String parameter); // } // Path: marketdata-web/src/test/java/com/handson/rx/StockServerTest.java import com.handson.dto.Quote; import com.handson.dto.Stock; import com.handson.infra.EventStreamClient; import com.handson.infra.RequestReplyClient; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import rx.Observable; import rx.marble.junit.MarbleRule; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static rx.marble.MapHelper.of; import static rx.marble.junit.MarbleRule.expectObservable; import static rx.marble.junit.MarbleRule.hot; StockServer server = createServer(quoteSource); // then expectObservable(server.getEvents(null).map(s -> s.companyName).concatWith(Observable.never())) .toBe("--g---i--", of("g", "Alphabet Inc", "i", "International Business Machines Corp.")); } /** * Test 9 */ @Test @Ignore public void should_stop_stream_after_10_seconds() { // given Observable<String> quoteSource = Observable.never(); // when StockServer server = createServer(quoteSource); // then expectObservable(server.getEvents(null)).toBe("----------|"); } public StockServer createServer(Observable<String> quoteSource) { RequestReplyClient stockClient = mock(RequestReplyClient.class); EventStreamClient stockQuoteClient = mock(EventStreamClient.class); StockServer stockServer = new StockServer(42, stockClient, stockQuoteClient, marble.scheduler); when(stockQuoteClient.readServerSideEvents()).thenReturn(quoteSource); when(stockClient.request(eq("GOOGL"))) .then( code -> Observable.just(
new Stock("GOOGL", "Alphabet Inc", "NASDAQ").toJson()
RxHandsOn/MarketData
marketdata-web/src/main/java/com/handson/rx/StockQuoteServer.java
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/RxNettyEventServer.java // public abstract class RxNettyEventServer<T> { // // // private final int port; // // public RxNettyEventServer(int port) { // this.port = port; // } // // public HttpServer<ByteBuf, ServerSentEvent> createServer() { // HttpServer<ByteBuf, ServerSentEvent> server = RxNetty.createHttpServer(port, // (request, response) -> { // response.getHeaders().set(ACCESS_CONTROL_ALLOW_ORIGIN, "*"); // response.getHeaders().set(CACHE_CONTROL, "no-cache"); // response.getHeaders().set(CONNECTION, "keep-alive"); // response.getHeaders().set(CONTENT_TYPE, "text/event-stream"); // return getIntervalObservable(request, response); // }, PipelineConfigurators.<ByteBuf>serveSseConfigurator()); // System.out.println("HTTP Server Sent Events server started..."); // return server; // } // // private Observable<Void> getIntervalObservable(HttpServerRequest<?> request, final HttpServerResponse<ServerSentEvent> response) { // HttpRequest simpleRequest = new HttpRequest(request.getQueryParameters()); // return getEvents(simpleRequest) // .flatMap(event -> { // System.out.println("Writing SSE event: " + event); // ByteBuf data = response.getAllocator().buffer().writeBytes(( event + "\n").getBytes()); // ServerSentEvent sse = new ServerSentEvent(data); // return response.writeAndFlush(sse); // }).materialize() // .takeWhile(notification -> { // if (notification.isOnError()) { // System.out.println("Write to client failed, stopping response sending."); // notification.getThrowable().printStackTrace(System.err); // } // return !notification.isOnError(); // }) // .map((Func1<Notification<Void>, Void>) notification -> null); // } // // // protected abstract Observable<T> getEvents(HttpRequest request); // // // }
import com.handson.dto.Quote; import com.handson.infra.EventStreamClient; import com.handson.infra.HttpRequest; import com.handson.infra.RxNettyEventServer; import rx.Observable; import rx.Scheduler; import rx.Subscription; import rx.subjects.BehaviorSubject; import java.util.concurrent.TimeUnit;
package com.handson.rx; public class StockQuoteServer extends RxNettyEventServer<Quote> { private final EventStreamClient stockQuoteEventStreamClient; private final EventStreamClient forexEventStreamClient; private final Scheduler scheduler; public StockQuoteServer(int port, EventStreamClient stockQuoteEventStreamClient, EventStreamClient forexEventStreamClient, Scheduler scheduler) { super(port); this.stockQuoteEventStreamClient = stockQuoteEventStreamClient; this.forexEventStreamClient = forexEventStreamClient; this.scheduler = scheduler; } @Override
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // // Path: marketdata-common/src/main/java/com/handson/infra/HttpRequest.java // public class HttpRequest { // // private final Map<String, List<String>> parameters; // // public HttpRequest(Map<String, List<String>> parameters) { // this.parameters = parameters; // } // // public String getParameter(String name) { // if (parameters.get(name) == null) { // return null; // } // return parameters.get(name).get(0); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/RxNettyEventServer.java // public abstract class RxNettyEventServer<T> { // // // private final int port; // // public RxNettyEventServer(int port) { // this.port = port; // } // // public HttpServer<ByteBuf, ServerSentEvent> createServer() { // HttpServer<ByteBuf, ServerSentEvent> server = RxNetty.createHttpServer(port, // (request, response) -> { // response.getHeaders().set(ACCESS_CONTROL_ALLOW_ORIGIN, "*"); // response.getHeaders().set(CACHE_CONTROL, "no-cache"); // response.getHeaders().set(CONNECTION, "keep-alive"); // response.getHeaders().set(CONTENT_TYPE, "text/event-stream"); // return getIntervalObservable(request, response); // }, PipelineConfigurators.<ByteBuf>serveSseConfigurator()); // System.out.println("HTTP Server Sent Events server started..."); // return server; // } // // private Observable<Void> getIntervalObservable(HttpServerRequest<?> request, final HttpServerResponse<ServerSentEvent> response) { // HttpRequest simpleRequest = new HttpRequest(request.getQueryParameters()); // return getEvents(simpleRequest) // .flatMap(event -> { // System.out.println("Writing SSE event: " + event); // ByteBuf data = response.getAllocator().buffer().writeBytes(( event + "\n").getBytes()); // ServerSentEvent sse = new ServerSentEvent(data); // return response.writeAndFlush(sse); // }).materialize() // .takeWhile(notification -> { // if (notification.isOnError()) { // System.out.println("Write to client failed, stopping response sending."); // notification.getThrowable().printStackTrace(System.err); // } // return !notification.isOnError(); // }) // .map((Func1<Notification<Void>, Void>) notification -> null); // } // // // protected abstract Observable<T> getEvents(HttpRequest request); // // // } // Path: marketdata-web/src/main/java/com/handson/rx/StockQuoteServer.java import com.handson.dto.Quote; import com.handson.infra.EventStreamClient; import com.handson.infra.HttpRequest; import com.handson.infra.RxNettyEventServer; import rx.Observable; import rx.Scheduler; import rx.Subscription; import rx.subjects.BehaviorSubject; import java.util.concurrent.TimeUnit; package com.handson.rx; public class StockQuoteServer extends RxNettyEventServer<Quote> { private final EventStreamClient stockQuoteEventStreamClient; private final EventStreamClient forexEventStreamClient; private final Scheduler scheduler; public StockQuoteServer(int port, EventStreamClient stockQuoteEventStreamClient, EventStreamClient forexEventStreamClient, Scheduler scheduler) { super(port); this.stockQuoteEventStreamClient = stockQuoteEventStreamClient; this.forexEventStreamClient = forexEventStreamClient; this.scheduler = scheduler; } @Override
protected Observable<Quote> getEvents(HttpRequest request) {
RxHandsOn/MarketData
marketdata-web/src/test/java/com/handson/rx/ForexServerTest.java
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // }
import com.handson.dto.Quote; import com.handson.infra.EventStreamClient; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import rx.Observable; import rx.marble.junit.MarbleRule; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static rx.marble.MapHelper.of; import static rx.marble.junit.MarbleRule.expectObservable; import static rx.marble.junit.MarbleRule.hot;
package com.handson.rx; public class ForexServerTest { @Rule public MarbleRule marble = new MarbleRule(); /** * Test 1 */ @Test @Ignore public void should_forward_forex_data() { // given Observable<String> forexSource
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // Path: marketdata-web/src/test/java/com/handson/rx/ForexServerTest.java import com.handson.dto.Quote; import com.handson.infra.EventStreamClient; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import rx.Observable; import rx.marble.junit.MarbleRule; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static rx.marble.MapHelper.of; import static rx.marble.junit.MarbleRule.expectObservable; import static rx.marble.junit.MarbleRule.hot; package com.handson.rx; public class ForexServerTest { @Rule public MarbleRule marble = new MarbleRule(); /** * Test 1 */ @Test @Ignore public void should_forward_forex_data() { // given Observable<String> forexSource
= hot("--f--", of("f", new Quote("EUR/USD", 1.4).toJson()));
RxHandsOn/MarketData
marketdata-web/src/test/java/com/handson/rx/ForexServerTest.java
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // }
import com.handson.dto.Quote; import com.handson.infra.EventStreamClient; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import rx.Observable; import rx.marble.junit.MarbleRule; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static rx.marble.MapHelper.of; import static rx.marble.junit.MarbleRule.expectObservable; import static rx.marble.junit.MarbleRule.hot;
package com.handson.rx; public class ForexServerTest { @Rule public MarbleRule marble = new MarbleRule(); /** * Test 1 */ @Test @Ignore public void should_forward_forex_data() { // given Observable<String> forexSource = hot("--f--", of("f", new Quote("EUR/USD", 1.4).toJson())); // when ForexServer forexServer = create(forexSource); // then expectObservable(forexServer.getEvents(null).take(1)) .toBe("--(v|)", of("v", 1.4)); } /** * Test 2 */ @Test @Ignore public void should_forward_only_one_forex_data() { // given Observable<String> forexSource = hot("--f-x-", of("f", new Quote("EUR/USD", 1.4).toJson(), "x", new Quote("EUR/USD", 1.5).toJson())); // when ForexServer forexServer = create(forexSource); // then expectObservable(forexServer.getEvents(null)) .toBe("--(v|)", of("v", 1.4)); } public ForexServer create(Observable<String> forexSource) {
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/EventStreamClient.java // public interface EventStreamClient { // // Observable<String> readServerSideEvents(); // } // Path: marketdata-web/src/test/java/com/handson/rx/ForexServerTest.java import com.handson.dto.Quote; import com.handson.infra.EventStreamClient; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import rx.Observable; import rx.marble.junit.MarbleRule; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static rx.marble.MapHelper.of; import static rx.marble.junit.MarbleRule.expectObservable; import static rx.marble.junit.MarbleRule.hot; package com.handson.rx; public class ForexServerTest { @Rule public MarbleRule marble = new MarbleRule(); /** * Test 1 */ @Test @Ignore public void should_forward_forex_data() { // given Observable<String> forexSource = hot("--f--", of("f", new Quote("EUR/USD", 1.4).toJson())); // when ForexServer forexServer = create(forexSource); // then expectObservable(forexServer.getEvents(null).take(1)) .toBe("--(v|)", of("v", 1.4)); } /** * Test 2 */ @Test @Ignore public void should_forward_only_one_forex_data() { // given Observable<String> forexSource = hot("--f-x-", of("f", new Quote("EUR/USD", 1.4).toJson(), "x", new Quote("EUR/USD", 1.5).toJson())); // when ForexServer forexServer = create(forexSource); // then expectObservable(forexServer.getEvents(null)) .toBe("--(v|)", of("v", 1.4)); } public ForexServer create(Observable<String> forexSource) {
EventStreamClient eventStreamClient = mock(EventStreamClient.class);
RxHandsOn/MarketData
marketdata-external/src/main/java/com/handson/market/TradeProvider.java
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Trade.java // public class Trade { // // public final String code; // public final int quantity; // public final double nominal; // // public Trade(String code, int quantity, double nominal) { // this.code = code; // this.quantity = quantity; // this.nominal = nominal; // } // // public static Trade fromJson(String input) { // return new Gson().fromJson(input, Trade.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/RandomSequenceGenerator.java // public class RandomSequenceGenerator { // // private final double min; // private final double max; // private final Random random; // private double bias = 0.3; // // public RandomSequenceGenerator(double min, double max) { // this.min = min; // this.max = max; // this.random = new Random(); // } // // public Observable<Double> create(long interval, TimeUnit timeUnit) { // double init = (min + max) /2; // return Observable // .interval(interval, timeUnit) // .scan(init, (previous, i) -> computeNextNumber(previous)); // } // // public Observable<Integer> createIntegerSequence(long interval, TimeUnit timeUnit) { // double range = max - min; // return Observable // .interval(interval, timeUnit) // .map(i -> ((Double)(random.nextDouble() * range + min)).intValue()); // } // // public double computeNextNumber(double previous) { // double range = (max - min) / 20; // double scaled = (random.nextDouble() - 0.5 + bias) * range; // double shifted = previous + scaled; // if (shifted < min || shifted > max) { // shifted = previous - scaled; // bias = -bias; // } // // shifted = ((Long)Math.round(shifted * 10000)).doubleValue() /10000; // // return shifted; // } // // } // // Path: marketdata-common/src/main/java/com/handson/infra/RxNettyEventBroadcaster.java // public abstract class RxNettyEventBroadcaster<T> extends RxNettyEventServer { // // // private final boolean flaky; // private Observable<T> events; // // public RxNettyEventBroadcaster(int port, boolean flaky) { // super(port); // this.flaky = flaky; // } // // public HttpServer<ByteBuf, ServerSentEvent> createServer() { // if (flaky) { // events = SubscriptionLimiter // .limitSubscriptions(1,initializeEventStream()); // } else { // events = initializeEventStream(); // } // return super.createServer(); // } // // protected abstract Observable<T> initializeEventStream(); // // public Observable<T> getEvents(HttpRequest request) { // return events; // } // // }
import com.handson.dto.Quote; import com.handson.dto.Trade; import com.handson.infra.RandomSequenceGenerator; import com.handson.infra.RxNettyEventBroadcaster; import rx.Observable; import java.util.concurrent.TimeUnit;
package com.handson.market; public class TradeProvider extends RxNettyEventBroadcaster<Trade> { private static final int INTERVAL = 50; private final StockQuoteProvider stockQuoteProvider; public TradeProvider(int port, boolean flaky, StockQuoteProvider stockQuoteProvider) { super(port, flaky); this.stockQuoteProvider = stockQuoteProvider; } @Override protected Observable<Trade> initializeEventStream() {
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Trade.java // public class Trade { // // public final String code; // public final int quantity; // public final double nominal; // // public Trade(String code, int quantity, double nominal) { // this.code = code; // this.quantity = quantity; // this.nominal = nominal; // } // // public static Trade fromJson(String input) { // return new Gson().fromJson(input, Trade.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/RandomSequenceGenerator.java // public class RandomSequenceGenerator { // // private final double min; // private final double max; // private final Random random; // private double bias = 0.3; // // public RandomSequenceGenerator(double min, double max) { // this.min = min; // this.max = max; // this.random = new Random(); // } // // public Observable<Double> create(long interval, TimeUnit timeUnit) { // double init = (min + max) /2; // return Observable // .interval(interval, timeUnit) // .scan(init, (previous, i) -> computeNextNumber(previous)); // } // // public Observable<Integer> createIntegerSequence(long interval, TimeUnit timeUnit) { // double range = max - min; // return Observable // .interval(interval, timeUnit) // .map(i -> ((Double)(random.nextDouble() * range + min)).intValue()); // } // // public double computeNextNumber(double previous) { // double range = (max - min) / 20; // double scaled = (random.nextDouble() - 0.5 + bias) * range; // double shifted = previous + scaled; // if (shifted < min || shifted > max) { // shifted = previous - scaled; // bias = -bias; // } // // shifted = ((Long)Math.round(shifted * 10000)).doubleValue() /10000; // // return shifted; // } // // } // // Path: marketdata-common/src/main/java/com/handson/infra/RxNettyEventBroadcaster.java // public abstract class RxNettyEventBroadcaster<T> extends RxNettyEventServer { // // // private final boolean flaky; // private Observable<T> events; // // public RxNettyEventBroadcaster(int port, boolean flaky) { // super(port); // this.flaky = flaky; // } // // public HttpServer<ByteBuf, ServerSentEvent> createServer() { // if (flaky) { // events = SubscriptionLimiter // .limitSubscriptions(1,initializeEventStream()); // } else { // events = initializeEventStream(); // } // return super.createServer(); // } // // protected abstract Observable<T> initializeEventStream(); // // public Observable<T> getEvents(HttpRequest request) { // return events; // } // // } // Path: marketdata-external/src/main/java/com/handson/market/TradeProvider.java import com.handson.dto.Quote; import com.handson.dto.Trade; import com.handson.infra.RandomSequenceGenerator; import com.handson.infra.RxNettyEventBroadcaster; import rx.Observable; import java.util.concurrent.TimeUnit; package com.handson.market; public class TradeProvider extends RxNettyEventBroadcaster<Trade> { private static final int INTERVAL = 50; private final StockQuoteProvider stockQuoteProvider; public TradeProvider(int port, boolean flaky, StockQuoteProvider stockQuoteProvider) { super(port, flaky); this.stockQuoteProvider = stockQuoteProvider; } @Override protected Observable<Trade> initializeEventStream() {
Observable<Quote> quotes
RxHandsOn/MarketData
marketdata-external/src/main/java/com/handson/market/TradeProvider.java
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Trade.java // public class Trade { // // public final String code; // public final int quantity; // public final double nominal; // // public Trade(String code, int quantity, double nominal) { // this.code = code; // this.quantity = quantity; // this.nominal = nominal; // } // // public static Trade fromJson(String input) { // return new Gson().fromJson(input, Trade.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/RandomSequenceGenerator.java // public class RandomSequenceGenerator { // // private final double min; // private final double max; // private final Random random; // private double bias = 0.3; // // public RandomSequenceGenerator(double min, double max) { // this.min = min; // this.max = max; // this.random = new Random(); // } // // public Observable<Double> create(long interval, TimeUnit timeUnit) { // double init = (min + max) /2; // return Observable // .interval(interval, timeUnit) // .scan(init, (previous, i) -> computeNextNumber(previous)); // } // // public Observable<Integer> createIntegerSequence(long interval, TimeUnit timeUnit) { // double range = max - min; // return Observable // .interval(interval, timeUnit) // .map(i -> ((Double)(random.nextDouble() * range + min)).intValue()); // } // // public double computeNextNumber(double previous) { // double range = (max - min) / 20; // double scaled = (random.nextDouble() - 0.5 + bias) * range; // double shifted = previous + scaled; // if (shifted < min || shifted > max) { // shifted = previous - scaled; // bias = -bias; // } // // shifted = ((Long)Math.round(shifted * 10000)).doubleValue() /10000; // // return shifted; // } // // } // // Path: marketdata-common/src/main/java/com/handson/infra/RxNettyEventBroadcaster.java // public abstract class RxNettyEventBroadcaster<T> extends RxNettyEventServer { // // // private final boolean flaky; // private Observable<T> events; // // public RxNettyEventBroadcaster(int port, boolean flaky) { // super(port); // this.flaky = flaky; // } // // public HttpServer<ByteBuf, ServerSentEvent> createServer() { // if (flaky) { // events = SubscriptionLimiter // .limitSubscriptions(1,initializeEventStream()); // } else { // events = initializeEventStream(); // } // return super.createServer(); // } // // protected abstract Observable<T> initializeEventStream(); // // public Observable<T> getEvents(HttpRequest request) { // return events; // } // // }
import com.handson.dto.Quote; import com.handson.dto.Trade; import com.handson.infra.RandomSequenceGenerator; import com.handson.infra.RxNettyEventBroadcaster; import rx.Observable; import java.util.concurrent.TimeUnit;
package com.handson.market; public class TradeProvider extends RxNettyEventBroadcaster<Trade> { private static final int INTERVAL = 50; private final StockQuoteProvider stockQuoteProvider; public TradeProvider(int port, boolean flaky, StockQuoteProvider stockQuoteProvider) { super(port, flaky); this.stockQuoteProvider = stockQuoteProvider; } @Override protected Observable<Trade> initializeEventStream() { Observable<Quote> quotes = stockQuoteProvider.getEvents(null); Observable<Integer> quantities
// Path: marketdata-common/src/main/java/com/handson/dto/Quote.java // public class Quote { // // public final String code; // public final double quote; // // public Quote(String code, double quote) { // this.code = code; // this.quote = quote; // } // // public static Quote fromJson(String input) { // return new Gson().fromJson(input, Quote.class); // } // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/dto/Trade.java // public class Trade { // // public final String code; // public final int quantity; // public final double nominal; // // public Trade(String code, int quantity, double nominal) { // this.code = code; // this.quantity = quantity; // this.nominal = nominal; // } // // public static Trade fromJson(String input) { // return new Gson().fromJson(input, Trade.class); // } // // // public String toJson() { // return new Gson().toJson(this); // } // // @Override // public String toString() { // return toJson(); // } // } // // Path: marketdata-common/src/main/java/com/handson/infra/RandomSequenceGenerator.java // public class RandomSequenceGenerator { // // private final double min; // private final double max; // private final Random random; // private double bias = 0.3; // // public RandomSequenceGenerator(double min, double max) { // this.min = min; // this.max = max; // this.random = new Random(); // } // // public Observable<Double> create(long interval, TimeUnit timeUnit) { // double init = (min + max) /2; // return Observable // .interval(interval, timeUnit) // .scan(init, (previous, i) -> computeNextNumber(previous)); // } // // public Observable<Integer> createIntegerSequence(long interval, TimeUnit timeUnit) { // double range = max - min; // return Observable // .interval(interval, timeUnit) // .map(i -> ((Double)(random.nextDouble() * range + min)).intValue()); // } // // public double computeNextNumber(double previous) { // double range = (max - min) / 20; // double scaled = (random.nextDouble() - 0.5 + bias) * range; // double shifted = previous + scaled; // if (shifted < min || shifted > max) { // shifted = previous - scaled; // bias = -bias; // } // // shifted = ((Long)Math.round(shifted * 10000)).doubleValue() /10000; // // return shifted; // } // // } // // Path: marketdata-common/src/main/java/com/handson/infra/RxNettyEventBroadcaster.java // public abstract class RxNettyEventBroadcaster<T> extends RxNettyEventServer { // // // private final boolean flaky; // private Observable<T> events; // // public RxNettyEventBroadcaster(int port, boolean flaky) { // super(port); // this.flaky = flaky; // } // // public HttpServer<ByteBuf, ServerSentEvent> createServer() { // if (flaky) { // events = SubscriptionLimiter // .limitSubscriptions(1,initializeEventStream()); // } else { // events = initializeEventStream(); // } // return super.createServer(); // } // // protected abstract Observable<T> initializeEventStream(); // // public Observable<T> getEvents(HttpRequest request) { // return events; // } // // } // Path: marketdata-external/src/main/java/com/handson/market/TradeProvider.java import com.handson.dto.Quote; import com.handson.dto.Trade; import com.handson.infra.RandomSequenceGenerator; import com.handson.infra.RxNettyEventBroadcaster; import rx.Observable; import java.util.concurrent.TimeUnit; package com.handson.market; public class TradeProvider extends RxNettyEventBroadcaster<Trade> { private static final int INTERVAL = 50; private final StockQuoteProvider stockQuoteProvider; public TradeProvider(int port, boolean flaky, StockQuoteProvider stockQuoteProvider) { super(port, flaky); this.stockQuoteProvider = stockQuoteProvider; } @Override protected Observable<Trade> initializeEventStream() { Observable<Quote> quotes = stockQuoteProvider.getEvents(null); Observable<Integer> quantities
= new RandomSequenceGenerator(10, 1000).createIntegerSequence(INTERVAL, TimeUnit.MILLISECONDS).share();
baihui212/tsharding
tsharding-client/src/main/java/com/mogujie/trade/tsharding/route/orm/base/ReadWriteSplittingContextInitializer.java
// Path: tsharding-client/src/main/java/com/mogujie/trade/db/DataSourceType.java // public enum DataSourceType { // master, slave // } // // Path: tsharding-client/src/main/java/com/mogujie/trade/db/ReadWriteSplittingContext.java // public class ReadWriteSplittingContext { // // private static final ThreadLocal<DataSourceType> curDataSourceType = new ThreadLocal<DataSourceType>(); // // public static void set(DataSourceType dataSourceType) { // curDataSourceType.set(dataSourceType); // } // // public static void setMaster() { // curDataSourceType.set(DataSourceType.master); // } // // public static void clear() { // curDataSourceType.remove(); // } // // public static boolean isMaster() { // return DataSourceType.master == curDataSourceType.get(); // } // // }
import com.mogujie.trade.db.DataSourceType; import com.mogujie.trade.db.ReadWriteSplitting; import com.mogujie.trade.db.ReadWriteSplittingContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
package com.mogujie.trade.tsharding.route.orm.base; /** * 读写分离的上下文初始化和清空 * * @author qigong */ public class ReadWriteSplittingContextInitializer { private final static Logger logger = LoggerFactory.getLogger(ReadWriteSplittingContextInitializer.class); private final static String[] DEFAULT_WRITE_METHOD_NAMES = {"update", "save", "insert", "delete", "add", "batchInsert", "batchUpdate", "batchSave", "batchAdd"};
// Path: tsharding-client/src/main/java/com/mogujie/trade/db/DataSourceType.java // public enum DataSourceType { // master, slave // } // // Path: tsharding-client/src/main/java/com/mogujie/trade/db/ReadWriteSplittingContext.java // public class ReadWriteSplittingContext { // // private static final ThreadLocal<DataSourceType> curDataSourceType = new ThreadLocal<DataSourceType>(); // // public static void set(DataSourceType dataSourceType) { // curDataSourceType.set(dataSourceType); // } // // public static void setMaster() { // curDataSourceType.set(DataSourceType.master); // } // // public static void clear() { // curDataSourceType.remove(); // } // // public static boolean isMaster() { // return DataSourceType.master == curDataSourceType.get(); // } // // } // Path: tsharding-client/src/main/java/com/mogujie/trade/tsharding/route/orm/base/ReadWriteSplittingContextInitializer.java import com.mogujie.trade.db.DataSourceType; import com.mogujie.trade.db.ReadWriteSplitting; import com.mogujie.trade.db.ReadWriteSplittingContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; package com.mogujie.trade.tsharding.route.orm.base; /** * 读写分离的上下文初始化和清空 * * @author qigong */ public class ReadWriteSplittingContextInitializer { private final static Logger logger = LoggerFactory.getLogger(ReadWriteSplittingContextInitializer.class); private final static String[] DEFAULT_WRITE_METHOD_NAMES = {"update", "save", "insert", "delete", "add", "batchInsert", "batchUpdate", "batchSave", "batchAdd"};
private final static Map<Method, DataSourceType> cache = new ConcurrentHashMap<>();
baihui212/tsharding
tsharding-client/src/main/java/com/mogujie/trade/tsharding/route/orm/base/ReadWriteSplittingContextInitializer.java
// Path: tsharding-client/src/main/java/com/mogujie/trade/db/DataSourceType.java // public enum DataSourceType { // master, slave // } // // Path: tsharding-client/src/main/java/com/mogujie/trade/db/ReadWriteSplittingContext.java // public class ReadWriteSplittingContext { // // private static final ThreadLocal<DataSourceType> curDataSourceType = new ThreadLocal<DataSourceType>(); // // public static void set(DataSourceType dataSourceType) { // curDataSourceType.set(dataSourceType); // } // // public static void setMaster() { // curDataSourceType.set(DataSourceType.master); // } // // public static void clear() { // curDataSourceType.remove(); // } // // public static boolean isMaster() { // return DataSourceType.master == curDataSourceType.get(); // } // // }
import com.mogujie.trade.db.DataSourceType; import com.mogujie.trade.db.ReadWriteSplitting; import com.mogujie.trade.db.ReadWriteSplittingContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
package com.mogujie.trade.tsharding.route.orm.base; /** * 读写分离的上下文初始化和清空 * * @author qigong */ public class ReadWriteSplittingContextInitializer { private final static Logger logger = LoggerFactory.getLogger(ReadWriteSplittingContextInitializer.class); private final static String[] DEFAULT_WRITE_METHOD_NAMES = {"update", "save", "insert", "delete", "add", "batchInsert", "batchUpdate", "batchSave", "batchAdd"}; private final static Map<Method, DataSourceType> cache = new ConcurrentHashMap<>(); public static void initReadWriteSplittingContext(Method method) { // 忽略object的方法,只关注Mapper的方法 if (method.getDeclaringClass() != Object.class) { } DataSourceType dataSourceType = getDataSourceType(method); logger.debug("ReadWriteSplitting {} using dataSource of {}", method, dataSourceType);
// Path: tsharding-client/src/main/java/com/mogujie/trade/db/DataSourceType.java // public enum DataSourceType { // master, slave // } // // Path: tsharding-client/src/main/java/com/mogujie/trade/db/ReadWriteSplittingContext.java // public class ReadWriteSplittingContext { // // private static final ThreadLocal<DataSourceType> curDataSourceType = new ThreadLocal<DataSourceType>(); // // public static void set(DataSourceType dataSourceType) { // curDataSourceType.set(dataSourceType); // } // // public static void setMaster() { // curDataSourceType.set(DataSourceType.master); // } // // public static void clear() { // curDataSourceType.remove(); // } // // public static boolean isMaster() { // return DataSourceType.master == curDataSourceType.get(); // } // // } // Path: tsharding-client/src/main/java/com/mogujie/trade/tsharding/route/orm/base/ReadWriteSplittingContextInitializer.java import com.mogujie.trade.db.DataSourceType; import com.mogujie.trade.db.ReadWriteSplitting; import com.mogujie.trade.db.ReadWriteSplittingContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; package com.mogujie.trade.tsharding.route.orm.base; /** * 读写分离的上下文初始化和清空 * * @author qigong */ public class ReadWriteSplittingContextInitializer { private final static Logger logger = LoggerFactory.getLogger(ReadWriteSplittingContextInitializer.class); private final static String[] DEFAULT_WRITE_METHOD_NAMES = {"update", "save", "insert", "delete", "add", "batchInsert", "batchUpdate", "batchSave", "batchAdd"}; private final static Map<Method, DataSourceType> cache = new ConcurrentHashMap<>(); public static void initReadWriteSplittingContext(Method method) { // 忽略object的方法,只关注Mapper的方法 if (method.getDeclaringClass() != Object.class) { } DataSourceType dataSourceType = getDataSourceType(method); logger.debug("ReadWriteSplitting {} using dataSource of {}", method, dataSourceType);
ReadWriteSplittingContext.set(dataSourceType);
baihui212/tsharding
tsharding-client/src/test/java/com/mogujie/service/tsharding/test/TShardingTest.java
// Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/bean/ShopOrder.java // public class ShopOrder extends BaseOrder { // // } // // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/dao/ShopOrderDao.java // public interface ShopOrderDao { // // /** // * 根据店铺级订单ID获取订单信息(同一个买家) // * // * @param listShopOrderIds 店铺级订单ID集合 // * @return List<XdShopOrder> // */ // List<ShopOrder> getShopOrderByShopOrderIds(List<Long> listShopOrderIds); // // } // // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/mapper/ShopOrderMapper.java // @DataSourceRouting(handler = TShardingRoutingHandler.class) // public interface ShopOrderMapper { // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // public ShopOrder getShopOrderByShopOrderId(@ShardingOrderPara Long shopOrderId); // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // public List<ShopOrder> getShopOrderByShopOrderIds(@ShardingOrderPara List<Long> shopOrderIds); // // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // int batchUpdateShopOrderByShopOrderIds(@ShardingOrderPara @Param("shopOrderIds") List<Long> shopOrderIds, @Param("shopOrder") ShopOrder shopOrder); // // }
import com.mogujie.service.tsharding.bean.ShopOrder; import com.mogujie.service.tsharding.dao.ShopOrderDao; import com.mogujie.service.tsharding.mapper.ShopOrderMapper; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.Assert; import java.util.ArrayList; import java.util.List;
package com.mogujie.service.tsharding.test; /** * @author by jiuru on 16/7/14. */ public class TShardingTest extends BaseTest { private final Logger logger = LoggerFactory.getLogger(TShardingTest.class); @Autowired
// Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/bean/ShopOrder.java // public class ShopOrder extends BaseOrder { // // } // // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/dao/ShopOrderDao.java // public interface ShopOrderDao { // // /** // * 根据店铺级订单ID获取订单信息(同一个买家) // * // * @param listShopOrderIds 店铺级订单ID集合 // * @return List<XdShopOrder> // */ // List<ShopOrder> getShopOrderByShopOrderIds(List<Long> listShopOrderIds); // // } // // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/mapper/ShopOrderMapper.java // @DataSourceRouting(handler = TShardingRoutingHandler.class) // public interface ShopOrderMapper { // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // public ShopOrder getShopOrderByShopOrderId(@ShardingOrderPara Long shopOrderId); // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // public List<ShopOrder> getShopOrderByShopOrderIds(@ShardingOrderPara List<Long> shopOrderIds); // // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // int batchUpdateShopOrderByShopOrderIds(@ShardingOrderPara @Param("shopOrderIds") List<Long> shopOrderIds, @Param("shopOrder") ShopOrder shopOrder); // // } // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/test/TShardingTest.java import com.mogujie.service.tsharding.bean.ShopOrder; import com.mogujie.service.tsharding.dao.ShopOrderDao; import com.mogujie.service.tsharding.mapper.ShopOrderMapper; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.Assert; import java.util.ArrayList; import java.util.List; package com.mogujie.service.tsharding.test; /** * @author by jiuru on 16/7/14. */ public class TShardingTest extends BaseTest { private final Logger logger = LoggerFactory.getLogger(TShardingTest.class); @Autowired
private ShopOrderDao shopOrderDao;
baihui212/tsharding
tsharding-client/src/test/java/com/mogujie/service/tsharding/test/TShardingTest.java
// Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/bean/ShopOrder.java // public class ShopOrder extends BaseOrder { // // } // // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/dao/ShopOrderDao.java // public interface ShopOrderDao { // // /** // * 根据店铺级订单ID获取订单信息(同一个买家) // * // * @param listShopOrderIds 店铺级订单ID集合 // * @return List<XdShopOrder> // */ // List<ShopOrder> getShopOrderByShopOrderIds(List<Long> listShopOrderIds); // // } // // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/mapper/ShopOrderMapper.java // @DataSourceRouting(handler = TShardingRoutingHandler.class) // public interface ShopOrderMapper { // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // public ShopOrder getShopOrderByShopOrderId(@ShardingOrderPara Long shopOrderId); // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // public List<ShopOrder> getShopOrderByShopOrderIds(@ShardingOrderPara List<Long> shopOrderIds); // // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // int batchUpdateShopOrderByShopOrderIds(@ShardingOrderPara @Param("shopOrderIds") List<Long> shopOrderIds, @Param("shopOrder") ShopOrder shopOrder); // // }
import com.mogujie.service.tsharding.bean.ShopOrder; import com.mogujie.service.tsharding.dao.ShopOrderDao; import com.mogujie.service.tsharding.mapper.ShopOrderMapper; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.Assert; import java.util.ArrayList; import java.util.List;
package com.mogujie.service.tsharding.test; /** * @author by jiuru on 16/7/14. */ public class TShardingTest extends BaseTest { private final Logger logger = LoggerFactory.getLogger(TShardingTest.class); @Autowired private ShopOrderDao shopOrderDao; @Autowired
// Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/bean/ShopOrder.java // public class ShopOrder extends BaseOrder { // // } // // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/dao/ShopOrderDao.java // public interface ShopOrderDao { // // /** // * 根据店铺级订单ID获取订单信息(同一个买家) // * // * @param listShopOrderIds 店铺级订单ID集合 // * @return List<XdShopOrder> // */ // List<ShopOrder> getShopOrderByShopOrderIds(List<Long> listShopOrderIds); // // } // // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/mapper/ShopOrderMapper.java // @DataSourceRouting(handler = TShardingRoutingHandler.class) // public interface ShopOrderMapper { // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // public ShopOrder getShopOrderByShopOrderId(@ShardingOrderPara Long shopOrderId); // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // public List<ShopOrder> getShopOrderByShopOrderIds(@ShardingOrderPara List<Long> shopOrderIds); // // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // int batchUpdateShopOrderByShopOrderIds(@ShardingOrderPara @Param("shopOrderIds") List<Long> shopOrderIds, @Param("shopOrder") ShopOrder shopOrder); // // } // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/test/TShardingTest.java import com.mogujie.service.tsharding.bean.ShopOrder; import com.mogujie.service.tsharding.dao.ShopOrderDao; import com.mogujie.service.tsharding.mapper.ShopOrderMapper; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.Assert; import java.util.ArrayList; import java.util.List; package com.mogujie.service.tsharding.test; /** * @author by jiuru on 16/7/14. */ public class TShardingTest extends BaseTest { private final Logger logger = LoggerFactory.getLogger(TShardingTest.class); @Autowired private ShopOrderDao shopOrderDao; @Autowired
private ShopOrderMapper shopOrderMapper;
baihui212/tsharding
tsharding-client/src/test/java/com/mogujie/service/tsharding/test/TShardingTest.java
// Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/bean/ShopOrder.java // public class ShopOrder extends BaseOrder { // // } // // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/dao/ShopOrderDao.java // public interface ShopOrderDao { // // /** // * 根据店铺级订单ID获取订单信息(同一个买家) // * // * @param listShopOrderIds 店铺级订单ID集合 // * @return List<XdShopOrder> // */ // List<ShopOrder> getShopOrderByShopOrderIds(List<Long> listShopOrderIds); // // } // // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/mapper/ShopOrderMapper.java // @DataSourceRouting(handler = TShardingRoutingHandler.class) // public interface ShopOrderMapper { // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // public ShopOrder getShopOrderByShopOrderId(@ShardingOrderPara Long shopOrderId); // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // public List<ShopOrder> getShopOrderByShopOrderIds(@ShardingOrderPara List<Long> shopOrderIds); // // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // int batchUpdateShopOrderByShopOrderIds(@ShardingOrderPara @Param("shopOrderIds") List<Long> shopOrderIds, @Param("shopOrder") ShopOrder shopOrder); // // }
import com.mogujie.service.tsharding.bean.ShopOrder; import com.mogujie.service.tsharding.dao.ShopOrderDao; import com.mogujie.service.tsharding.mapper.ShopOrderMapper; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.Assert; import java.util.ArrayList; import java.util.List;
package com.mogujie.service.tsharding.test; /** * @author by jiuru on 16/7/14. */ public class TShardingTest extends BaseTest { private final Logger logger = LoggerFactory.getLogger(TShardingTest.class); @Autowired private ShopOrderDao shopOrderDao; @Autowired private ShopOrderMapper shopOrderMapper; @Test public void testGetShopOrderByShopOrderIdsDao() { List<Long> orderIds = new ArrayList<>(); orderIds.add(50000280834672L);
// Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/bean/ShopOrder.java // public class ShopOrder extends BaseOrder { // // } // // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/dao/ShopOrderDao.java // public interface ShopOrderDao { // // /** // * 根据店铺级订单ID获取订单信息(同一个买家) // * // * @param listShopOrderIds 店铺级订单ID集合 // * @return List<XdShopOrder> // */ // List<ShopOrder> getShopOrderByShopOrderIds(List<Long> listShopOrderIds); // // } // // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/mapper/ShopOrderMapper.java // @DataSourceRouting(handler = TShardingRoutingHandler.class) // public interface ShopOrderMapper { // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // public ShopOrder getShopOrderByShopOrderId(@ShardingOrderPara Long shopOrderId); // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // public List<ShopOrder> getShopOrderByShopOrderIds(@ShardingOrderPara List<Long> shopOrderIds); // // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // int batchUpdateShopOrderByShopOrderIds(@ShardingOrderPara @Param("shopOrderIds") List<Long> shopOrderIds, @Param("shopOrder") ShopOrder shopOrder); // // } // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/test/TShardingTest.java import com.mogujie.service.tsharding.bean.ShopOrder; import com.mogujie.service.tsharding.dao.ShopOrderDao; import com.mogujie.service.tsharding.mapper.ShopOrderMapper; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.Assert; import java.util.ArrayList; import java.util.List; package com.mogujie.service.tsharding.test; /** * @author by jiuru on 16/7/14. */ public class TShardingTest extends BaseTest { private final Logger logger = LoggerFactory.getLogger(TShardingTest.class); @Autowired private ShopOrderDao shopOrderDao; @Autowired private ShopOrderMapper shopOrderMapper; @Test public void testGetShopOrderByShopOrderIdsDao() { List<Long> orderIds = new ArrayList<>(); orderIds.add(50000280834672L);
List<ShopOrder> orders = shopOrderDao.getShopOrderByShopOrderIds(orderIds);
baihui212/tsharding
tsharding-client/src/test/java/com/mogujie/service/tsharding/mapper/ShopOrderMapper.java
// Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/bean/ShopOrder.java // public class ShopOrder extends BaseOrder { // // } // // Path: tsharding-client/src/main/java/com/mogujie/trade/tsharding/route/TShardingRoutingHandler.java // public class TShardingRoutingHandler implements DataSourceRoutingHandler { // // @Override // public String dynamicRoute(Method method, Object[] args) { // //route逻辑见TShardingRoutingInvokeFactory // return "testschema"; // } // // @Override // public Collection<String> values() { // //暂未使用 // return null; // } // } // // Path: tsharding-client/src/main/java/com/mogujie/trade/tsharding/route/orm/MapperResourceEnhancer.java // public class MapperResourceEnhancer extends MapperEnhancer{ // // Logger logger = LoggerFactory.getLogger(MapperResourceEnhancer.class); // // public MapperResourceEnhancer(Class<?> mapperClass) { // super(mapperClass); // } // // public SqlSource enhancedShardingSQL(MappedStatement ms, Configuration configuration, Long shardingPara) { // // String tableName = ShardingCaculator.caculateTableName(shardingPara); // SqlSource result = null; // // try { // if (ms.getSqlSource() instanceof DynamicSqlSource) { // // DynamicSqlSource sqlSource = (DynamicSqlSource) ms.getSqlSource(); // // Class sqlSourceClass = sqlSource.getClass(); // // Field sqlNodeField = sqlSourceClass.getDeclaredField("rootSqlNode"); // sqlNodeField.setAccessible(true); // // MixedSqlNode rootSqlNode = (MixedSqlNode) sqlNodeField.get(sqlSource); // // Class mixedSqlNodeClass = rootSqlNode.getClass(); // Field contentsField = mixedSqlNodeClass.getDeclaredField("contents"); // contentsField.setAccessible(true); // List<SqlNode> textSqlNodes = (List<SqlNode>) contentsField.get(rootSqlNode); // List<SqlNode> newSqlNodesList = new ArrayList(); // // //StaticTextSqlNode // Class textSqlNodeClass = textSqlNodes.get(0).getClass(); // Field textField = textSqlNodeClass.getDeclaredField("text"); // textField.setAccessible(true); // for (SqlNode node : textSqlNodes) { // if (node instanceof StaticTextSqlNode) { // StaticTextSqlNode textSqlNode = (StaticTextSqlNode) node; // String text = (String) textField.get(textSqlNode); // if(!text.contains("TradeOrder")){ // newSqlNodesList.add(node); // }else { // newSqlNodesList.add(new StaticTextSqlNode(replaceWithShardingTableName(text, tableName, shardingPara))); // } // }else{ // newSqlNodesList.add(node); // } // } // // MixedSqlNode newrootSqlNode = new MixedSqlNode(newSqlNodesList); // result = new DynamicSqlSource(configuration, newrootSqlNode); // return result; // // } else if (ms.getSqlSource() instanceof RawSqlSource) { // // RawSqlSource sqlSource = (RawSqlSource) ms.getSqlSource(); // Class sqlSourceClass = sqlSource.getClass(); // Field sqlSourceField = sqlSourceClass.getDeclaredField("sqlSource"); // sqlSourceField.setAccessible(true); // StaticSqlSource staticSqlSource = (StaticSqlSource) sqlSourceField.get(sqlSource); // Field sqlField = staticSqlSource.getClass().getDeclaredField("sql"); // Field parameterMappingsField = staticSqlSource.getClass().getDeclaredField("parameterMappings"); // sqlField.setAccessible(true); // parameterMappingsField.setAccessible(true); // // //sql处理 // String sql = (String) sqlField.get(staticSqlSource); // // if(!sql.contains("TradeOrder")){ // result = sqlSource; // }else { // sql = replaceWithShardingTableName(sql, tableName, shardingPara); // result = new RawSqlSource(configuration, sql, null); // //为sqlSource对象设置mappering参数 // StaticSqlSource newStaticSqlSource = (StaticSqlSource) sqlSourceField.get(result); // List<ParameterMapping> parameterMappings = (List<ParameterMapping>)parameterMappingsField.get(staticSqlSource); // parameterMappingsField.set(newStaticSqlSource, parameterMappings); // } // return result; // } else { // throw new RuntimeException("wrong sqlSource type!" + ms.getResource()); // } // // } catch (Exception e) { // logger.error("reflect error!, ms resources:" + ms.getResource(), e); // } // return result; // } // // // private String replaceWithShardingTableName(String text, String tableName, Long shardingPara){ // if(text.contains(" TradeOrderPressureTest")){ // return text.replace(" TradeOrderPressureTest", " TradeOrderPressureTest" + ShardingCaculator.getNumberWithZeroSuffix(shardingPara)); // } // return text.replace(" TradeOrder", " " + tableName); // } // }
import com.mogujie.service.tsharding.bean.ShopOrder; import com.mogujie.trade.db.DataSourceRouting; import com.mogujie.trade.tsharding.annotation.ShardingExtensionMethod; import com.mogujie.trade.tsharding.annotation.parameter.ShardingOrderPara; import com.mogujie.trade.tsharding.route.TShardingRoutingHandler; import com.mogujie.trade.tsharding.route.orm.MapperResourceEnhancer; import org.apache.ibatis.annotations.Param; import java.util.List;
package com.mogujie.service.tsharding.mapper; @DataSourceRouting(handler = TShardingRoutingHandler.class) public interface ShopOrderMapper {
// Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/bean/ShopOrder.java // public class ShopOrder extends BaseOrder { // // } // // Path: tsharding-client/src/main/java/com/mogujie/trade/tsharding/route/TShardingRoutingHandler.java // public class TShardingRoutingHandler implements DataSourceRoutingHandler { // // @Override // public String dynamicRoute(Method method, Object[] args) { // //route逻辑见TShardingRoutingInvokeFactory // return "testschema"; // } // // @Override // public Collection<String> values() { // //暂未使用 // return null; // } // } // // Path: tsharding-client/src/main/java/com/mogujie/trade/tsharding/route/orm/MapperResourceEnhancer.java // public class MapperResourceEnhancer extends MapperEnhancer{ // // Logger logger = LoggerFactory.getLogger(MapperResourceEnhancer.class); // // public MapperResourceEnhancer(Class<?> mapperClass) { // super(mapperClass); // } // // public SqlSource enhancedShardingSQL(MappedStatement ms, Configuration configuration, Long shardingPara) { // // String tableName = ShardingCaculator.caculateTableName(shardingPara); // SqlSource result = null; // // try { // if (ms.getSqlSource() instanceof DynamicSqlSource) { // // DynamicSqlSource sqlSource = (DynamicSqlSource) ms.getSqlSource(); // // Class sqlSourceClass = sqlSource.getClass(); // // Field sqlNodeField = sqlSourceClass.getDeclaredField("rootSqlNode"); // sqlNodeField.setAccessible(true); // // MixedSqlNode rootSqlNode = (MixedSqlNode) sqlNodeField.get(sqlSource); // // Class mixedSqlNodeClass = rootSqlNode.getClass(); // Field contentsField = mixedSqlNodeClass.getDeclaredField("contents"); // contentsField.setAccessible(true); // List<SqlNode> textSqlNodes = (List<SqlNode>) contentsField.get(rootSqlNode); // List<SqlNode> newSqlNodesList = new ArrayList(); // // //StaticTextSqlNode // Class textSqlNodeClass = textSqlNodes.get(0).getClass(); // Field textField = textSqlNodeClass.getDeclaredField("text"); // textField.setAccessible(true); // for (SqlNode node : textSqlNodes) { // if (node instanceof StaticTextSqlNode) { // StaticTextSqlNode textSqlNode = (StaticTextSqlNode) node; // String text = (String) textField.get(textSqlNode); // if(!text.contains("TradeOrder")){ // newSqlNodesList.add(node); // }else { // newSqlNodesList.add(new StaticTextSqlNode(replaceWithShardingTableName(text, tableName, shardingPara))); // } // }else{ // newSqlNodesList.add(node); // } // } // // MixedSqlNode newrootSqlNode = new MixedSqlNode(newSqlNodesList); // result = new DynamicSqlSource(configuration, newrootSqlNode); // return result; // // } else if (ms.getSqlSource() instanceof RawSqlSource) { // // RawSqlSource sqlSource = (RawSqlSource) ms.getSqlSource(); // Class sqlSourceClass = sqlSource.getClass(); // Field sqlSourceField = sqlSourceClass.getDeclaredField("sqlSource"); // sqlSourceField.setAccessible(true); // StaticSqlSource staticSqlSource = (StaticSqlSource) sqlSourceField.get(sqlSource); // Field sqlField = staticSqlSource.getClass().getDeclaredField("sql"); // Field parameterMappingsField = staticSqlSource.getClass().getDeclaredField("parameterMappings"); // sqlField.setAccessible(true); // parameterMappingsField.setAccessible(true); // // //sql处理 // String sql = (String) sqlField.get(staticSqlSource); // // if(!sql.contains("TradeOrder")){ // result = sqlSource; // }else { // sql = replaceWithShardingTableName(sql, tableName, shardingPara); // result = new RawSqlSource(configuration, sql, null); // //为sqlSource对象设置mappering参数 // StaticSqlSource newStaticSqlSource = (StaticSqlSource) sqlSourceField.get(result); // List<ParameterMapping> parameterMappings = (List<ParameterMapping>)parameterMappingsField.get(staticSqlSource); // parameterMappingsField.set(newStaticSqlSource, parameterMappings); // } // return result; // } else { // throw new RuntimeException("wrong sqlSource type!" + ms.getResource()); // } // // } catch (Exception e) { // logger.error("reflect error!, ms resources:" + ms.getResource(), e); // } // return result; // } // // // private String replaceWithShardingTableName(String text, String tableName, Long shardingPara){ // if(text.contains(" TradeOrderPressureTest")){ // return text.replace(" TradeOrderPressureTest", " TradeOrderPressureTest" + ShardingCaculator.getNumberWithZeroSuffix(shardingPara)); // } // return text.replace(" TradeOrder", " " + tableName); // } // } // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/mapper/ShopOrderMapper.java import com.mogujie.service.tsharding.bean.ShopOrder; import com.mogujie.trade.db.DataSourceRouting; import com.mogujie.trade.tsharding.annotation.ShardingExtensionMethod; import com.mogujie.trade.tsharding.annotation.parameter.ShardingOrderPara; import com.mogujie.trade.tsharding.route.TShardingRoutingHandler; import com.mogujie.trade.tsharding.route.orm.MapperResourceEnhancer; import org.apache.ibatis.annotations.Param; import java.util.List; package com.mogujie.service.tsharding.mapper; @DataSourceRouting(handler = TShardingRoutingHandler.class) public interface ShopOrderMapper {
@ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL")
baihui212/tsharding
tsharding-client/src/test/java/com/mogujie/service/tsharding/mapper/ShopOrderMapper.java
// Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/bean/ShopOrder.java // public class ShopOrder extends BaseOrder { // // } // // Path: tsharding-client/src/main/java/com/mogujie/trade/tsharding/route/TShardingRoutingHandler.java // public class TShardingRoutingHandler implements DataSourceRoutingHandler { // // @Override // public String dynamicRoute(Method method, Object[] args) { // //route逻辑见TShardingRoutingInvokeFactory // return "testschema"; // } // // @Override // public Collection<String> values() { // //暂未使用 // return null; // } // } // // Path: tsharding-client/src/main/java/com/mogujie/trade/tsharding/route/orm/MapperResourceEnhancer.java // public class MapperResourceEnhancer extends MapperEnhancer{ // // Logger logger = LoggerFactory.getLogger(MapperResourceEnhancer.class); // // public MapperResourceEnhancer(Class<?> mapperClass) { // super(mapperClass); // } // // public SqlSource enhancedShardingSQL(MappedStatement ms, Configuration configuration, Long shardingPara) { // // String tableName = ShardingCaculator.caculateTableName(shardingPara); // SqlSource result = null; // // try { // if (ms.getSqlSource() instanceof DynamicSqlSource) { // // DynamicSqlSource sqlSource = (DynamicSqlSource) ms.getSqlSource(); // // Class sqlSourceClass = sqlSource.getClass(); // // Field sqlNodeField = sqlSourceClass.getDeclaredField("rootSqlNode"); // sqlNodeField.setAccessible(true); // // MixedSqlNode rootSqlNode = (MixedSqlNode) sqlNodeField.get(sqlSource); // // Class mixedSqlNodeClass = rootSqlNode.getClass(); // Field contentsField = mixedSqlNodeClass.getDeclaredField("contents"); // contentsField.setAccessible(true); // List<SqlNode> textSqlNodes = (List<SqlNode>) contentsField.get(rootSqlNode); // List<SqlNode> newSqlNodesList = new ArrayList(); // // //StaticTextSqlNode // Class textSqlNodeClass = textSqlNodes.get(0).getClass(); // Field textField = textSqlNodeClass.getDeclaredField("text"); // textField.setAccessible(true); // for (SqlNode node : textSqlNodes) { // if (node instanceof StaticTextSqlNode) { // StaticTextSqlNode textSqlNode = (StaticTextSqlNode) node; // String text = (String) textField.get(textSqlNode); // if(!text.contains("TradeOrder")){ // newSqlNodesList.add(node); // }else { // newSqlNodesList.add(new StaticTextSqlNode(replaceWithShardingTableName(text, tableName, shardingPara))); // } // }else{ // newSqlNodesList.add(node); // } // } // // MixedSqlNode newrootSqlNode = new MixedSqlNode(newSqlNodesList); // result = new DynamicSqlSource(configuration, newrootSqlNode); // return result; // // } else if (ms.getSqlSource() instanceof RawSqlSource) { // // RawSqlSource sqlSource = (RawSqlSource) ms.getSqlSource(); // Class sqlSourceClass = sqlSource.getClass(); // Field sqlSourceField = sqlSourceClass.getDeclaredField("sqlSource"); // sqlSourceField.setAccessible(true); // StaticSqlSource staticSqlSource = (StaticSqlSource) sqlSourceField.get(sqlSource); // Field sqlField = staticSqlSource.getClass().getDeclaredField("sql"); // Field parameterMappingsField = staticSqlSource.getClass().getDeclaredField("parameterMappings"); // sqlField.setAccessible(true); // parameterMappingsField.setAccessible(true); // // //sql处理 // String sql = (String) sqlField.get(staticSqlSource); // // if(!sql.contains("TradeOrder")){ // result = sqlSource; // }else { // sql = replaceWithShardingTableName(sql, tableName, shardingPara); // result = new RawSqlSource(configuration, sql, null); // //为sqlSource对象设置mappering参数 // StaticSqlSource newStaticSqlSource = (StaticSqlSource) sqlSourceField.get(result); // List<ParameterMapping> parameterMappings = (List<ParameterMapping>)parameterMappingsField.get(staticSqlSource); // parameterMappingsField.set(newStaticSqlSource, parameterMappings); // } // return result; // } else { // throw new RuntimeException("wrong sqlSource type!" + ms.getResource()); // } // // } catch (Exception e) { // logger.error("reflect error!, ms resources:" + ms.getResource(), e); // } // return result; // } // // // private String replaceWithShardingTableName(String text, String tableName, Long shardingPara){ // if(text.contains(" TradeOrderPressureTest")){ // return text.replace(" TradeOrderPressureTest", " TradeOrderPressureTest" + ShardingCaculator.getNumberWithZeroSuffix(shardingPara)); // } // return text.replace(" TradeOrder", " " + tableName); // } // }
import com.mogujie.service.tsharding.bean.ShopOrder; import com.mogujie.trade.db.DataSourceRouting; import com.mogujie.trade.tsharding.annotation.ShardingExtensionMethod; import com.mogujie.trade.tsharding.annotation.parameter.ShardingOrderPara; import com.mogujie.trade.tsharding.route.TShardingRoutingHandler; import com.mogujie.trade.tsharding.route.orm.MapperResourceEnhancer; import org.apache.ibatis.annotations.Param; import java.util.List;
package com.mogujie.service.tsharding.mapper; @DataSourceRouting(handler = TShardingRoutingHandler.class) public interface ShopOrderMapper { @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL")
// Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/bean/ShopOrder.java // public class ShopOrder extends BaseOrder { // // } // // Path: tsharding-client/src/main/java/com/mogujie/trade/tsharding/route/TShardingRoutingHandler.java // public class TShardingRoutingHandler implements DataSourceRoutingHandler { // // @Override // public String dynamicRoute(Method method, Object[] args) { // //route逻辑见TShardingRoutingInvokeFactory // return "testschema"; // } // // @Override // public Collection<String> values() { // //暂未使用 // return null; // } // } // // Path: tsharding-client/src/main/java/com/mogujie/trade/tsharding/route/orm/MapperResourceEnhancer.java // public class MapperResourceEnhancer extends MapperEnhancer{ // // Logger logger = LoggerFactory.getLogger(MapperResourceEnhancer.class); // // public MapperResourceEnhancer(Class<?> mapperClass) { // super(mapperClass); // } // // public SqlSource enhancedShardingSQL(MappedStatement ms, Configuration configuration, Long shardingPara) { // // String tableName = ShardingCaculator.caculateTableName(shardingPara); // SqlSource result = null; // // try { // if (ms.getSqlSource() instanceof DynamicSqlSource) { // // DynamicSqlSource sqlSource = (DynamicSqlSource) ms.getSqlSource(); // // Class sqlSourceClass = sqlSource.getClass(); // // Field sqlNodeField = sqlSourceClass.getDeclaredField("rootSqlNode"); // sqlNodeField.setAccessible(true); // // MixedSqlNode rootSqlNode = (MixedSqlNode) sqlNodeField.get(sqlSource); // // Class mixedSqlNodeClass = rootSqlNode.getClass(); // Field contentsField = mixedSqlNodeClass.getDeclaredField("contents"); // contentsField.setAccessible(true); // List<SqlNode> textSqlNodes = (List<SqlNode>) contentsField.get(rootSqlNode); // List<SqlNode> newSqlNodesList = new ArrayList(); // // //StaticTextSqlNode // Class textSqlNodeClass = textSqlNodes.get(0).getClass(); // Field textField = textSqlNodeClass.getDeclaredField("text"); // textField.setAccessible(true); // for (SqlNode node : textSqlNodes) { // if (node instanceof StaticTextSqlNode) { // StaticTextSqlNode textSqlNode = (StaticTextSqlNode) node; // String text = (String) textField.get(textSqlNode); // if(!text.contains("TradeOrder")){ // newSqlNodesList.add(node); // }else { // newSqlNodesList.add(new StaticTextSqlNode(replaceWithShardingTableName(text, tableName, shardingPara))); // } // }else{ // newSqlNodesList.add(node); // } // } // // MixedSqlNode newrootSqlNode = new MixedSqlNode(newSqlNodesList); // result = new DynamicSqlSource(configuration, newrootSqlNode); // return result; // // } else if (ms.getSqlSource() instanceof RawSqlSource) { // // RawSqlSource sqlSource = (RawSqlSource) ms.getSqlSource(); // Class sqlSourceClass = sqlSource.getClass(); // Field sqlSourceField = sqlSourceClass.getDeclaredField("sqlSource"); // sqlSourceField.setAccessible(true); // StaticSqlSource staticSqlSource = (StaticSqlSource) sqlSourceField.get(sqlSource); // Field sqlField = staticSqlSource.getClass().getDeclaredField("sql"); // Field parameterMappingsField = staticSqlSource.getClass().getDeclaredField("parameterMappings"); // sqlField.setAccessible(true); // parameterMappingsField.setAccessible(true); // // //sql处理 // String sql = (String) sqlField.get(staticSqlSource); // // if(!sql.contains("TradeOrder")){ // result = sqlSource; // }else { // sql = replaceWithShardingTableName(sql, tableName, shardingPara); // result = new RawSqlSource(configuration, sql, null); // //为sqlSource对象设置mappering参数 // StaticSqlSource newStaticSqlSource = (StaticSqlSource) sqlSourceField.get(result); // List<ParameterMapping> parameterMappings = (List<ParameterMapping>)parameterMappingsField.get(staticSqlSource); // parameterMappingsField.set(newStaticSqlSource, parameterMappings); // } // return result; // } else { // throw new RuntimeException("wrong sqlSource type!" + ms.getResource()); // } // // } catch (Exception e) { // logger.error("reflect error!, ms resources:" + ms.getResource(), e); // } // return result; // } // // // private String replaceWithShardingTableName(String text, String tableName, Long shardingPara){ // if(text.contains(" TradeOrderPressureTest")){ // return text.replace(" TradeOrderPressureTest", " TradeOrderPressureTest" + ShardingCaculator.getNumberWithZeroSuffix(shardingPara)); // } // return text.replace(" TradeOrder", " " + tableName); // } // } // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/mapper/ShopOrderMapper.java import com.mogujie.service.tsharding.bean.ShopOrder; import com.mogujie.trade.db.DataSourceRouting; import com.mogujie.trade.tsharding.annotation.ShardingExtensionMethod; import com.mogujie.trade.tsharding.annotation.parameter.ShardingOrderPara; import com.mogujie.trade.tsharding.route.TShardingRoutingHandler; import com.mogujie.trade.tsharding.route.orm.MapperResourceEnhancer; import org.apache.ibatis.annotations.Param; import java.util.List; package com.mogujie.service.tsharding.mapper; @DataSourceRouting(handler = TShardingRoutingHandler.class) public interface ShopOrderMapper { @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL")
public ShopOrder getShopOrderByShopOrderId(@ShardingOrderPara Long shopOrderId);
baihui212/tsharding
tsharding-client/src/main/java/com/mogujie/trade/tsharding/annotation/ShardingExtensionMethod.java
// Path: tsharding-client/src/main/java/com/mogujie/trade/tsharding/route/orm/MapperResourceEnhancer.java // public class MapperResourceEnhancer extends MapperEnhancer{ // // Logger logger = LoggerFactory.getLogger(MapperResourceEnhancer.class); // // public MapperResourceEnhancer(Class<?> mapperClass) { // super(mapperClass); // } // // public SqlSource enhancedShardingSQL(MappedStatement ms, Configuration configuration, Long shardingPara) { // // String tableName = ShardingCaculator.caculateTableName(shardingPara); // SqlSource result = null; // // try { // if (ms.getSqlSource() instanceof DynamicSqlSource) { // // DynamicSqlSource sqlSource = (DynamicSqlSource) ms.getSqlSource(); // // Class sqlSourceClass = sqlSource.getClass(); // // Field sqlNodeField = sqlSourceClass.getDeclaredField("rootSqlNode"); // sqlNodeField.setAccessible(true); // // MixedSqlNode rootSqlNode = (MixedSqlNode) sqlNodeField.get(sqlSource); // // Class mixedSqlNodeClass = rootSqlNode.getClass(); // Field contentsField = mixedSqlNodeClass.getDeclaredField("contents"); // contentsField.setAccessible(true); // List<SqlNode> textSqlNodes = (List<SqlNode>) contentsField.get(rootSqlNode); // List<SqlNode> newSqlNodesList = new ArrayList(); // // //StaticTextSqlNode // Class textSqlNodeClass = textSqlNodes.get(0).getClass(); // Field textField = textSqlNodeClass.getDeclaredField("text"); // textField.setAccessible(true); // for (SqlNode node : textSqlNodes) { // if (node instanceof StaticTextSqlNode) { // StaticTextSqlNode textSqlNode = (StaticTextSqlNode) node; // String text = (String) textField.get(textSqlNode); // if(!text.contains("TradeOrder")){ // newSqlNodesList.add(node); // }else { // newSqlNodesList.add(new StaticTextSqlNode(replaceWithShardingTableName(text, tableName, shardingPara))); // } // }else{ // newSqlNodesList.add(node); // } // } // // MixedSqlNode newrootSqlNode = new MixedSqlNode(newSqlNodesList); // result = new DynamicSqlSource(configuration, newrootSqlNode); // return result; // // } else if (ms.getSqlSource() instanceof RawSqlSource) { // // RawSqlSource sqlSource = (RawSqlSource) ms.getSqlSource(); // Class sqlSourceClass = sqlSource.getClass(); // Field sqlSourceField = sqlSourceClass.getDeclaredField("sqlSource"); // sqlSourceField.setAccessible(true); // StaticSqlSource staticSqlSource = (StaticSqlSource) sqlSourceField.get(sqlSource); // Field sqlField = staticSqlSource.getClass().getDeclaredField("sql"); // Field parameterMappingsField = staticSqlSource.getClass().getDeclaredField("parameterMappings"); // sqlField.setAccessible(true); // parameterMappingsField.setAccessible(true); // // //sql处理 // String sql = (String) sqlField.get(staticSqlSource); // // if(!sql.contains("TradeOrder")){ // result = sqlSource; // }else { // sql = replaceWithShardingTableName(sql, tableName, shardingPara); // result = new RawSqlSource(configuration, sql, null); // //为sqlSource对象设置mappering参数 // StaticSqlSource newStaticSqlSource = (StaticSqlSource) sqlSourceField.get(result); // List<ParameterMapping> parameterMappings = (List<ParameterMapping>)parameterMappingsField.get(staticSqlSource); // parameterMappingsField.set(newStaticSqlSource, parameterMappings); // } // return result; // } else { // throw new RuntimeException("wrong sqlSource type!" + ms.getResource()); // } // // } catch (Exception e) { // logger.error("reflect error!, ms resources:" + ms.getResource(), e); // } // return result; // } // // // private String replaceWithShardingTableName(String text, String tableName, Long shardingPara){ // if(text.contains(" TradeOrderPressureTest")){ // return text.replace(" TradeOrderPressureTest", " TradeOrderPressureTest" + ShardingCaculator.getNumberWithZeroSuffix(shardingPara)); // } // return text.replace(" TradeOrder", " " + tableName); // } // }
import com.mogujie.trade.tsharding.route.orm.MapperResourceEnhancer; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
package com.mogujie.trade.tsharding.annotation; /** * 需要sharding扩展的dao层方法 * @auther qigong on 6/4/15 11:02 AM. */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ShardingExtensionMethod {
// Path: tsharding-client/src/main/java/com/mogujie/trade/tsharding/route/orm/MapperResourceEnhancer.java // public class MapperResourceEnhancer extends MapperEnhancer{ // // Logger logger = LoggerFactory.getLogger(MapperResourceEnhancer.class); // // public MapperResourceEnhancer(Class<?> mapperClass) { // super(mapperClass); // } // // public SqlSource enhancedShardingSQL(MappedStatement ms, Configuration configuration, Long shardingPara) { // // String tableName = ShardingCaculator.caculateTableName(shardingPara); // SqlSource result = null; // // try { // if (ms.getSqlSource() instanceof DynamicSqlSource) { // // DynamicSqlSource sqlSource = (DynamicSqlSource) ms.getSqlSource(); // // Class sqlSourceClass = sqlSource.getClass(); // // Field sqlNodeField = sqlSourceClass.getDeclaredField("rootSqlNode"); // sqlNodeField.setAccessible(true); // // MixedSqlNode rootSqlNode = (MixedSqlNode) sqlNodeField.get(sqlSource); // // Class mixedSqlNodeClass = rootSqlNode.getClass(); // Field contentsField = mixedSqlNodeClass.getDeclaredField("contents"); // contentsField.setAccessible(true); // List<SqlNode> textSqlNodes = (List<SqlNode>) contentsField.get(rootSqlNode); // List<SqlNode> newSqlNodesList = new ArrayList(); // // //StaticTextSqlNode // Class textSqlNodeClass = textSqlNodes.get(0).getClass(); // Field textField = textSqlNodeClass.getDeclaredField("text"); // textField.setAccessible(true); // for (SqlNode node : textSqlNodes) { // if (node instanceof StaticTextSqlNode) { // StaticTextSqlNode textSqlNode = (StaticTextSqlNode) node; // String text = (String) textField.get(textSqlNode); // if(!text.contains("TradeOrder")){ // newSqlNodesList.add(node); // }else { // newSqlNodesList.add(new StaticTextSqlNode(replaceWithShardingTableName(text, tableName, shardingPara))); // } // }else{ // newSqlNodesList.add(node); // } // } // // MixedSqlNode newrootSqlNode = new MixedSqlNode(newSqlNodesList); // result = new DynamicSqlSource(configuration, newrootSqlNode); // return result; // // } else if (ms.getSqlSource() instanceof RawSqlSource) { // // RawSqlSource sqlSource = (RawSqlSource) ms.getSqlSource(); // Class sqlSourceClass = sqlSource.getClass(); // Field sqlSourceField = sqlSourceClass.getDeclaredField("sqlSource"); // sqlSourceField.setAccessible(true); // StaticSqlSource staticSqlSource = (StaticSqlSource) sqlSourceField.get(sqlSource); // Field sqlField = staticSqlSource.getClass().getDeclaredField("sql"); // Field parameterMappingsField = staticSqlSource.getClass().getDeclaredField("parameterMappings"); // sqlField.setAccessible(true); // parameterMappingsField.setAccessible(true); // // //sql处理 // String sql = (String) sqlField.get(staticSqlSource); // // if(!sql.contains("TradeOrder")){ // result = sqlSource; // }else { // sql = replaceWithShardingTableName(sql, tableName, shardingPara); // result = new RawSqlSource(configuration, sql, null); // //为sqlSource对象设置mappering参数 // StaticSqlSource newStaticSqlSource = (StaticSqlSource) sqlSourceField.get(result); // List<ParameterMapping> parameterMappings = (List<ParameterMapping>)parameterMappingsField.get(staticSqlSource); // parameterMappingsField.set(newStaticSqlSource, parameterMappings); // } // return result; // } else { // throw new RuntimeException("wrong sqlSource type!" + ms.getResource()); // } // // } catch (Exception e) { // logger.error("reflect error!, ms resources:" + ms.getResource(), e); // } // return result; // } // // // private String replaceWithShardingTableName(String text, String tableName, Long shardingPara){ // if(text.contains(" TradeOrderPressureTest")){ // return text.replace(" TradeOrderPressureTest", " TradeOrderPressureTest" + ShardingCaculator.getNumberWithZeroSuffix(shardingPara)); // } // return text.replace(" TradeOrder", " " + tableName); // } // } // Path: tsharding-client/src/main/java/com/mogujie/trade/tsharding/annotation/ShardingExtensionMethod.java import com.mogujie.trade.tsharding.route.orm.MapperResourceEnhancer; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; package com.mogujie.trade.tsharding.annotation; /** * 需要sharding扩展的dao层方法 * @auther qigong on 6/4/15 11:02 AM. */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ShardingExtensionMethod {
Class<?> type() default MapperResourceEnhancer.class;
baihui212/tsharding
tsharding-client/src/main/java/com/mogujie/trade/tsharding/route/orm/MapperResourceEnhancer.java
// Path: tsharding-client/src/main/java/com/mogujie/trade/tsharding/client/ShardingCaculator.java // public class ShardingCaculator { // // /** // * 根据分片参数值计算分表名 // * // * @param shardingPara // * @return 分表名0xxx // */ // public static String caculateTableName(Long shardingPara) { // if (shardingPara >= 0) { // return "TradeOrder" + getNumberWithZeroSuffix((shardingPara % 10000) % 512); // } // return null; // } // // /** // * 根据分片参数值计算分表名 // * // * @param shardingPara // * @return 分表名0xxx // */ // public static Integer caculateTableIndex(Long shardingPara) { // if (shardingPara >= 0) { // return new Long(shardingPara % 10000 % 512).intValue(); // } // return null; // } // // // /** // * 根据分片参数值计算分库名(逻辑库) // * // * @param shardingPara // * @return 分库名000x // */ // public static String caculateSchemaName(String fieldName, Long shardingPara) { // if (shardingPara >= 0) { // // if ("sellerUserId".equals(fieldName)) { // return "sellertrade" + getNumberWithZeroSuffix(((shardingPara % 10000) % 512) / 64); // } else { // return "trade" + getNumberWithZeroSuffix(((shardingPara % 10000) % 512) / 64); // } // } // return null; // } // // /** // * 根据分片参数值计算数据源名 // * // * @param shardingPara // * @return DatasourceName 见数据源配置文件 // */ // public static String caculateDatasourceName(String fieldName, Long shardingPara) { // if (shardingPara >= 0) { // if ("sellerUserId".equals(fieldName)) { // return "seller_ds_" + ((shardingPara % 10000) % 512) / 256; // } else { // return "buyer_ds_" + ((shardingPara % 10000) % 512) / 256; // } // } // return null; // } // // public static String getNumberWithZeroSuffix(long number) { // if (number >= 100) { // return "0" + number; // } else if (number >= 10) { // return "00" + number; // } else if (number >= 0) { // return "000" + number; // } // return null; // } // // /** // * 按订单号批量查询:跨表查,先按分表做分组 // * // * @param listShopOrderIds // * @return tableNo -> orderIds // */ // public static Map<Integer, List<Long>> getTableNoAndOrderIdsMap(List<Long> listShopOrderIds) { // // HashMap<Integer, List<Long>> shopOrderIdsMap = new HashMap(); // if (listShopOrderIds == null || listShopOrderIds.size() == 0) { // return shopOrderIdsMap; // } // for (Long shopOrderId : listShopOrderIds) { // Integer tableNo = ShardingCaculator.caculateTableIndex(shopOrderId); // List<Long> orderIds = shopOrderIdsMap.get(tableNo); // if (orderIds == null) { // orderIds = new ArrayList<>(); // } // orderIds.add(shopOrderId); // shopOrderIdsMap.put(tableNo, orderIds); // } // return shopOrderIdsMap; // } // // public static void main(String args[]) { // System.out.println(caculateTableName(6000004386417L)); // System.out.println(caculateSchemaName("buyerUserId", 6000004386417L)); // // System.out.println(caculateTableName(35586213L)); // System.out.println(caculateSchemaName("sellerUserId", 35586213L)); // } // }
import com.mogujie.trade.tsharding.client.ShardingCaculator; import org.apache.ibatis.builder.StaticSqlSource; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.ParameterMapping; import org.apache.ibatis.mapping.SqlSource; import org.apache.ibatis.scripting.defaults.RawSqlSource; import org.apache.ibatis.scripting.xmltags.*; import org.apache.ibatis.session.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List;
package com.mogujie.trade.tsharding.route.orm; /** * Mappper sql增强 * * @author qigong on 5/1/15 */ public class MapperResourceEnhancer extends MapperEnhancer{ Logger logger = LoggerFactory.getLogger(MapperResourceEnhancer.class); public MapperResourceEnhancer(Class<?> mapperClass) { super(mapperClass); } public SqlSource enhancedShardingSQL(MappedStatement ms, Configuration configuration, Long shardingPara) {
// Path: tsharding-client/src/main/java/com/mogujie/trade/tsharding/client/ShardingCaculator.java // public class ShardingCaculator { // // /** // * 根据分片参数值计算分表名 // * // * @param shardingPara // * @return 分表名0xxx // */ // public static String caculateTableName(Long shardingPara) { // if (shardingPara >= 0) { // return "TradeOrder" + getNumberWithZeroSuffix((shardingPara % 10000) % 512); // } // return null; // } // // /** // * 根据分片参数值计算分表名 // * // * @param shardingPara // * @return 分表名0xxx // */ // public static Integer caculateTableIndex(Long shardingPara) { // if (shardingPara >= 0) { // return new Long(shardingPara % 10000 % 512).intValue(); // } // return null; // } // // // /** // * 根据分片参数值计算分库名(逻辑库) // * // * @param shardingPara // * @return 分库名000x // */ // public static String caculateSchemaName(String fieldName, Long shardingPara) { // if (shardingPara >= 0) { // // if ("sellerUserId".equals(fieldName)) { // return "sellertrade" + getNumberWithZeroSuffix(((shardingPara % 10000) % 512) / 64); // } else { // return "trade" + getNumberWithZeroSuffix(((shardingPara % 10000) % 512) / 64); // } // } // return null; // } // // /** // * 根据分片参数值计算数据源名 // * // * @param shardingPara // * @return DatasourceName 见数据源配置文件 // */ // public static String caculateDatasourceName(String fieldName, Long shardingPara) { // if (shardingPara >= 0) { // if ("sellerUserId".equals(fieldName)) { // return "seller_ds_" + ((shardingPara % 10000) % 512) / 256; // } else { // return "buyer_ds_" + ((shardingPara % 10000) % 512) / 256; // } // } // return null; // } // // public static String getNumberWithZeroSuffix(long number) { // if (number >= 100) { // return "0" + number; // } else if (number >= 10) { // return "00" + number; // } else if (number >= 0) { // return "000" + number; // } // return null; // } // // /** // * 按订单号批量查询:跨表查,先按分表做分组 // * // * @param listShopOrderIds // * @return tableNo -> orderIds // */ // public static Map<Integer, List<Long>> getTableNoAndOrderIdsMap(List<Long> listShopOrderIds) { // // HashMap<Integer, List<Long>> shopOrderIdsMap = new HashMap(); // if (listShopOrderIds == null || listShopOrderIds.size() == 0) { // return shopOrderIdsMap; // } // for (Long shopOrderId : listShopOrderIds) { // Integer tableNo = ShardingCaculator.caculateTableIndex(shopOrderId); // List<Long> orderIds = shopOrderIdsMap.get(tableNo); // if (orderIds == null) { // orderIds = new ArrayList<>(); // } // orderIds.add(shopOrderId); // shopOrderIdsMap.put(tableNo, orderIds); // } // return shopOrderIdsMap; // } // // public static void main(String args[]) { // System.out.println(caculateTableName(6000004386417L)); // System.out.println(caculateSchemaName("buyerUserId", 6000004386417L)); // // System.out.println(caculateTableName(35586213L)); // System.out.println(caculateSchemaName("sellerUserId", 35586213L)); // } // } // Path: tsharding-client/src/main/java/com/mogujie/trade/tsharding/route/orm/MapperResourceEnhancer.java import com.mogujie.trade.tsharding.client.ShardingCaculator; import org.apache.ibatis.builder.StaticSqlSource; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.ParameterMapping; import org.apache.ibatis.mapping.SqlSource; import org.apache.ibatis.scripting.defaults.RawSqlSource; import org.apache.ibatis.scripting.xmltags.*; import org.apache.ibatis.session.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; package com.mogujie.trade.tsharding.route.orm; /** * Mappper sql增强 * * @author qigong on 5/1/15 */ public class MapperResourceEnhancer extends MapperEnhancer{ Logger logger = LoggerFactory.getLogger(MapperResourceEnhancer.class); public MapperResourceEnhancer(Class<?> mapperClass) { super(mapperClass); } public SqlSource enhancedShardingSQL(MappedStatement ms, Configuration configuration, Long shardingPara) {
String tableName = ShardingCaculator.caculateTableName(shardingPara);
baihui212/tsharding
tsharding-client/src/test/java/com/mogujie/service/tsharding/dao/ShopOrderDaoImpl.java
// Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/bean/ShopOrder.java // public class ShopOrder extends BaseOrder { // // } // // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/mapper/ShopOrderMapper.java // @DataSourceRouting(handler = TShardingRoutingHandler.class) // public interface ShopOrderMapper { // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // public ShopOrder getShopOrderByShopOrderId(@ShardingOrderPara Long shopOrderId); // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // public List<ShopOrder> getShopOrderByShopOrderIds(@ShardingOrderPara List<Long> shopOrderIds); // // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // int batchUpdateShopOrderByShopOrderIds(@ShardingOrderPara @Param("shopOrderIds") List<Long> shopOrderIds, @Param("shopOrder") ShopOrder shopOrder); // // }
import com.mogujie.service.tsharding.bean.ShopOrder; import com.mogujie.service.tsharding.mapper.ShopOrderMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set;
package com.mogujie.service.tsharding.dao; /** * @auther qigong on 6/5/15 8:52 PM. */ @Service("shopOrderDao") public class ShopOrderDaoImpl implements ShopOrderDao { @Autowired
// Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/bean/ShopOrder.java // public class ShopOrder extends BaseOrder { // // } // // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/mapper/ShopOrderMapper.java // @DataSourceRouting(handler = TShardingRoutingHandler.class) // public interface ShopOrderMapper { // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // public ShopOrder getShopOrderByShopOrderId(@ShardingOrderPara Long shopOrderId); // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // public List<ShopOrder> getShopOrderByShopOrderIds(@ShardingOrderPara List<Long> shopOrderIds); // // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // int batchUpdateShopOrderByShopOrderIds(@ShardingOrderPara @Param("shopOrderIds") List<Long> shopOrderIds, @Param("shopOrder") ShopOrder shopOrder); // // } // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/dao/ShopOrderDaoImpl.java import com.mogujie.service.tsharding.bean.ShopOrder; import com.mogujie.service.tsharding.mapper.ShopOrderMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; package com.mogujie.service.tsharding.dao; /** * @auther qigong on 6/5/15 8:52 PM. */ @Service("shopOrderDao") public class ShopOrderDaoImpl implements ShopOrderDao { @Autowired
private ShopOrderMapper shopOrderMapper;
baihui212/tsharding
tsharding-client/src/test/java/com/mogujie/service/tsharding/dao/ShopOrderDaoImpl.java
// Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/bean/ShopOrder.java // public class ShopOrder extends BaseOrder { // // } // // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/mapper/ShopOrderMapper.java // @DataSourceRouting(handler = TShardingRoutingHandler.class) // public interface ShopOrderMapper { // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // public ShopOrder getShopOrderByShopOrderId(@ShardingOrderPara Long shopOrderId); // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // public List<ShopOrder> getShopOrderByShopOrderIds(@ShardingOrderPara List<Long> shopOrderIds); // // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // int batchUpdateShopOrderByShopOrderIds(@ShardingOrderPara @Param("shopOrderIds") List<Long> shopOrderIds, @Param("shopOrder") ShopOrder shopOrder); // // }
import com.mogujie.service.tsharding.bean.ShopOrder; import com.mogujie.service.tsharding.mapper.ShopOrderMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set;
package com.mogujie.service.tsharding.dao; /** * @auther qigong on 6/5/15 8:52 PM. */ @Service("shopOrderDao") public class ShopOrderDaoImpl implements ShopOrderDao { @Autowired private ShopOrderMapper shopOrderMapper; @Override
// Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/bean/ShopOrder.java // public class ShopOrder extends BaseOrder { // // } // // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/mapper/ShopOrderMapper.java // @DataSourceRouting(handler = TShardingRoutingHandler.class) // public interface ShopOrderMapper { // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // public ShopOrder getShopOrderByShopOrderId(@ShardingOrderPara Long shopOrderId); // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // public List<ShopOrder> getShopOrderByShopOrderIds(@ShardingOrderPara List<Long> shopOrderIds); // // // @ShardingExtensionMethod(type = MapperResourceEnhancer.class, method = "enhancedShardingSQL") // int batchUpdateShopOrderByShopOrderIds(@ShardingOrderPara @Param("shopOrderIds") List<Long> shopOrderIds, @Param("shopOrder") ShopOrder shopOrder); // // } // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/dao/ShopOrderDaoImpl.java import com.mogujie.service.tsharding.bean.ShopOrder; import com.mogujie.service.tsharding.mapper.ShopOrderMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; package com.mogujie.service.tsharding.dao; /** * @auther qigong on 6/5/15 8:52 PM. */ @Service("shopOrderDao") public class ShopOrderDaoImpl implements ShopOrderDao { @Autowired private ShopOrderMapper shopOrderMapper; @Override
public List<ShopOrder> getShopOrderByShopOrderIds(List<Long> listShopOrderIds) {
baihui212/tsharding
tsharding-client/src/test/java/com/mogujie/service/tsharding/test/client/ShardingCaculatorTest.java
// Path: tsharding-client/src/main/java/com/mogujie/trade/tsharding/client/ShardingCaculator.java // public class ShardingCaculator { // // /** // * 根据分片参数值计算分表名 // * // * @param shardingPara // * @return 分表名0xxx // */ // public static String caculateTableName(Long shardingPara) { // if (shardingPara >= 0) { // return "TradeOrder" + getNumberWithZeroSuffix((shardingPara % 10000) % 512); // } // return null; // } // // /** // * 根据分片参数值计算分表名 // * // * @param shardingPara // * @return 分表名0xxx // */ // public static Integer caculateTableIndex(Long shardingPara) { // if (shardingPara >= 0) { // return new Long(shardingPara % 10000 % 512).intValue(); // } // return null; // } // // // /** // * 根据分片参数值计算分库名(逻辑库) // * // * @param shardingPara // * @return 分库名000x // */ // public static String caculateSchemaName(String fieldName, Long shardingPara) { // if (shardingPara >= 0) { // // if ("sellerUserId".equals(fieldName)) { // return "sellertrade" + getNumberWithZeroSuffix(((shardingPara % 10000) % 512) / 64); // } else { // return "trade" + getNumberWithZeroSuffix(((shardingPara % 10000) % 512) / 64); // } // } // return null; // } // // /** // * 根据分片参数值计算数据源名 // * // * @param shardingPara // * @return DatasourceName 见数据源配置文件 // */ // public static String caculateDatasourceName(String fieldName, Long shardingPara) { // if (shardingPara >= 0) { // if ("sellerUserId".equals(fieldName)) { // return "seller_ds_" + ((shardingPara % 10000) % 512) / 256; // } else { // return "buyer_ds_" + ((shardingPara % 10000) % 512) / 256; // } // } // return null; // } // // public static String getNumberWithZeroSuffix(long number) { // if (number >= 100) { // return "0" + number; // } else if (number >= 10) { // return "00" + number; // } else if (number >= 0) { // return "000" + number; // } // return null; // } // // /** // * 按订单号批量查询:跨表查,先按分表做分组 // * // * @param listShopOrderIds // * @return tableNo -> orderIds // */ // public static Map<Integer, List<Long>> getTableNoAndOrderIdsMap(List<Long> listShopOrderIds) { // // HashMap<Integer, List<Long>> shopOrderIdsMap = new HashMap(); // if (listShopOrderIds == null || listShopOrderIds.size() == 0) { // return shopOrderIdsMap; // } // for (Long shopOrderId : listShopOrderIds) { // Integer tableNo = ShardingCaculator.caculateTableIndex(shopOrderId); // List<Long> orderIds = shopOrderIdsMap.get(tableNo); // if (orderIds == null) { // orderIds = new ArrayList<>(); // } // orderIds.add(shopOrderId); // shopOrderIdsMap.put(tableNo, orderIds); // } // return shopOrderIdsMap; // } // // public static void main(String args[]) { // System.out.println(caculateTableName(6000004386417L)); // System.out.println(caculateSchemaName("buyerUserId", 6000004386417L)); // // System.out.println(caculateTableName(35586213L)); // System.out.println(caculateSchemaName("sellerUserId", 35586213L)); // } // }
import com.mogujie.trade.tsharding.client.ShardingCaculator; import org.junit.Assert; import org.junit.Test;
package com.mogujie.service.tsharding.test.client; /** * @auther qigong on 5/29/15 8:28 AM. */ public class ShardingCaculatorTest { @Test public void testCaculateTableName() { ShardingparaObj para = new ShardingparaObj(); para.setName("buyerId"); para.setValue(100000000L);
// Path: tsharding-client/src/main/java/com/mogujie/trade/tsharding/client/ShardingCaculator.java // public class ShardingCaculator { // // /** // * 根据分片参数值计算分表名 // * // * @param shardingPara // * @return 分表名0xxx // */ // public static String caculateTableName(Long shardingPara) { // if (shardingPara >= 0) { // return "TradeOrder" + getNumberWithZeroSuffix((shardingPara % 10000) % 512); // } // return null; // } // // /** // * 根据分片参数值计算分表名 // * // * @param shardingPara // * @return 分表名0xxx // */ // public static Integer caculateTableIndex(Long shardingPara) { // if (shardingPara >= 0) { // return new Long(shardingPara % 10000 % 512).intValue(); // } // return null; // } // // // /** // * 根据分片参数值计算分库名(逻辑库) // * // * @param shardingPara // * @return 分库名000x // */ // public static String caculateSchemaName(String fieldName, Long shardingPara) { // if (shardingPara >= 0) { // // if ("sellerUserId".equals(fieldName)) { // return "sellertrade" + getNumberWithZeroSuffix(((shardingPara % 10000) % 512) / 64); // } else { // return "trade" + getNumberWithZeroSuffix(((shardingPara % 10000) % 512) / 64); // } // } // return null; // } // // /** // * 根据分片参数值计算数据源名 // * // * @param shardingPara // * @return DatasourceName 见数据源配置文件 // */ // public static String caculateDatasourceName(String fieldName, Long shardingPara) { // if (shardingPara >= 0) { // if ("sellerUserId".equals(fieldName)) { // return "seller_ds_" + ((shardingPara % 10000) % 512) / 256; // } else { // return "buyer_ds_" + ((shardingPara % 10000) % 512) / 256; // } // } // return null; // } // // public static String getNumberWithZeroSuffix(long number) { // if (number >= 100) { // return "0" + number; // } else if (number >= 10) { // return "00" + number; // } else if (number >= 0) { // return "000" + number; // } // return null; // } // // /** // * 按订单号批量查询:跨表查,先按分表做分组 // * // * @param listShopOrderIds // * @return tableNo -> orderIds // */ // public static Map<Integer, List<Long>> getTableNoAndOrderIdsMap(List<Long> listShopOrderIds) { // // HashMap<Integer, List<Long>> shopOrderIdsMap = new HashMap(); // if (listShopOrderIds == null || listShopOrderIds.size() == 0) { // return shopOrderIdsMap; // } // for (Long shopOrderId : listShopOrderIds) { // Integer tableNo = ShardingCaculator.caculateTableIndex(shopOrderId); // List<Long> orderIds = shopOrderIdsMap.get(tableNo); // if (orderIds == null) { // orderIds = new ArrayList<>(); // } // orderIds.add(shopOrderId); // shopOrderIdsMap.put(tableNo, orderIds); // } // return shopOrderIdsMap; // } // // public static void main(String args[]) { // System.out.println(caculateTableName(6000004386417L)); // System.out.println(caculateSchemaName("buyerUserId", 6000004386417L)); // // System.out.println(caculateTableName(35586213L)); // System.out.println(caculateSchemaName("sellerUserId", 35586213L)); // } // } // Path: tsharding-client/src/test/java/com/mogujie/service/tsharding/test/client/ShardingCaculatorTest.java import com.mogujie.trade.tsharding.client.ShardingCaculator; import org.junit.Assert; import org.junit.Test; package com.mogujie.service.tsharding.test.client; /** * @auther qigong on 5/29/15 8:28 AM. */ public class ShardingCaculatorTest { @Test public void testCaculateTableName() { ShardingparaObj para = new ShardingparaObj(); para.setName("buyerId"); para.setValue(100000000L);
Assert.assertEquals("TestTable0000", ShardingCaculator.caculateTableName(para.getValue()));
baihui212/tsharding
tsharding-client/src/main/java/com/mogujie/trade/tsharding/route/orm/MapperScannerWithSharding.java
// Path: tsharding-client/src/main/java/com/mogujie/trade/db/DataSourceLookup.java // public class DataSourceLookup implements Closeable { // // private final Map<String, ReadWriteSplittingDataSource> dataSources; // // public DataSourceLookup(Map<String, ReadWriteSplittingDataSource> dataSources) { // this.dataSources = Collections.unmodifiableMap(dataSources); // } // // /** // * @param name // * @return // */ // public ReadWriteSplittingDataSource get(String name) { // return this.dataSources.get(name); // } // // public Map<String, ReadWriteSplittingDataSource> getMapping() { // return this.dataSources; // } // // @Override // public void close() throws IOException { // for (ReadWriteSplittingDataSource dataSource : dataSources.values()) { // dataSource.close(); // } // } // } // // Path: tsharding-client/src/main/java/com/mogujie/trade/db/ReadWriteSplittingDataSource.java // public class ReadWriteSplittingDataSource extends AbstractDataSource implements DataSource, Closeable { // // private final String name; // // private final DataSource masterDataSource; // // private final DataSource slaveDataSource; // // public ReadWriteSplittingDataSource(String name, DataSource masterDataSource, DataSource slaveDataSource) { // this.name = name; // this.masterDataSource = masterDataSource; // this.slaveDataSource = slaveDataSource; // Assert.isTrue(masterDataSource != slaveDataSource || masterDataSource != null, // "masterDataSource and slaveDataSource can't be both null!"); // } // // @Override // public Connection getConnection() throws SQLException { // return this.determineTargetDataSource().getConnection(); // } // // public DataSource getSlaveDataSource() { // return slaveDataSource; // } // // private DataSource determineTargetDataSource() { // if (slaveDataSource == null) { // return masterDataSource; // } // // if (this.isInTransaction()) { // return masterDataSource; // } // // return ReadWriteSplittingContext.isMaster() ? masterDataSource : slaveDataSource; // } // // private boolean isInTransaction() { // return RoutingDataSourceTransactionContext.getCurTransactionDataSource() != null; // } // // @Override // public Connection getConnection(String username, String password) throws SQLException { // return this.determineTargetDataSource().getConnection(username, password); // } // // public String getName() { // return this.name; // } // // @Override // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append("ReadWriteSplittingDataSource ["); // if (name != null) { // builder.append("name=").append(name).append(", "); // } // if (masterDataSource != null) { // builder.append("masterDataSource=").append(masterDataSource).append(", "); // } // if (slaveDataSource != null) { // builder.append("slaveDataSource=").append(slaveDataSource); // } // builder.append("]"); // return builder.toString(); // } // // @Override // public void close() throws IOException { // if (this.masterDataSource != null) { // if (masterDataSource instanceof AutoCloseable) { // try { // ((AutoCloseable) masterDataSource).close(); // } catch (Exception ignore) { // } // } // } // // if (this.slaveDataSource != null) { // if (slaveDataSource instanceof AutoCloseable) { // try { // ((AutoCloseable) slaveDataSource).close(); // } catch (Exception ignore) { // } // } // } // } // // }
import com.mogujie.trade.db.DataSourceLookup; import com.mogujie.trade.db.ReadWriteSplittingDataSource; import com.mogujie.trade.tsharding.route.orm.base.*; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.beans.BeansException; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.core.io.Resource; import java.io.IOException; import java.lang.reflect.*; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set;
} @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { this.dataSourceLookup = beanFactory.getBean(DataSourceLookup.class); try { this.initSqlSessionFactories(beanFactory); } catch (Exception e) { throw new RuntimeException(e); } ClassPathScanHandler scanner = new ClassPathScanHandler(); Set<Class<?>> mapperClasses = new HashSet<>(); for (String mapperPackage : this.mapperPacakages) { Set<Class<?>> classes = scanner.getPackageAllClasses(mapperPackage.trim(), false); mapperClasses.addAll(classes); } for (Class<?> clazz : mapperClasses) { if (isMapper(clazz)) { Object mapper = this.newMapper(clazz); beanFactory.registerSingleton(Character.toLowerCase(clazz.getSimpleName().charAt(0)) + clazz.getSimpleName().substring(1), mapper); } } } private void initSqlSessionFactories(ConfigurableListableBeanFactory beanFactory) throws Exception { Map<String, SqlSessionFactory> sqlSessionFactories = new HashMap<>(this.dataSourceLookup.getMapping().size());
// Path: tsharding-client/src/main/java/com/mogujie/trade/db/DataSourceLookup.java // public class DataSourceLookup implements Closeable { // // private final Map<String, ReadWriteSplittingDataSource> dataSources; // // public DataSourceLookup(Map<String, ReadWriteSplittingDataSource> dataSources) { // this.dataSources = Collections.unmodifiableMap(dataSources); // } // // /** // * @param name // * @return // */ // public ReadWriteSplittingDataSource get(String name) { // return this.dataSources.get(name); // } // // public Map<String, ReadWriteSplittingDataSource> getMapping() { // return this.dataSources; // } // // @Override // public void close() throws IOException { // for (ReadWriteSplittingDataSource dataSource : dataSources.values()) { // dataSource.close(); // } // } // } // // Path: tsharding-client/src/main/java/com/mogujie/trade/db/ReadWriteSplittingDataSource.java // public class ReadWriteSplittingDataSource extends AbstractDataSource implements DataSource, Closeable { // // private final String name; // // private final DataSource masterDataSource; // // private final DataSource slaveDataSource; // // public ReadWriteSplittingDataSource(String name, DataSource masterDataSource, DataSource slaveDataSource) { // this.name = name; // this.masterDataSource = masterDataSource; // this.slaveDataSource = slaveDataSource; // Assert.isTrue(masterDataSource != slaveDataSource || masterDataSource != null, // "masterDataSource and slaveDataSource can't be both null!"); // } // // @Override // public Connection getConnection() throws SQLException { // return this.determineTargetDataSource().getConnection(); // } // // public DataSource getSlaveDataSource() { // return slaveDataSource; // } // // private DataSource determineTargetDataSource() { // if (slaveDataSource == null) { // return masterDataSource; // } // // if (this.isInTransaction()) { // return masterDataSource; // } // // return ReadWriteSplittingContext.isMaster() ? masterDataSource : slaveDataSource; // } // // private boolean isInTransaction() { // return RoutingDataSourceTransactionContext.getCurTransactionDataSource() != null; // } // // @Override // public Connection getConnection(String username, String password) throws SQLException { // return this.determineTargetDataSource().getConnection(username, password); // } // // public String getName() { // return this.name; // } // // @Override // public String toString() { // StringBuilder builder = new StringBuilder(); // builder.append("ReadWriteSplittingDataSource ["); // if (name != null) { // builder.append("name=").append(name).append(", "); // } // if (masterDataSource != null) { // builder.append("masterDataSource=").append(masterDataSource).append(", "); // } // if (slaveDataSource != null) { // builder.append("slaveDataSource=").append(slaveDataSource); // } // builder.append("]"); // return builder.toString(); // } // // @Override // public void close() throws IOException { // if (this.masterDataSource != null) { // if (masterDataSource instanceof AutoCloseable) { // try { // ((AutoCloseable) masterDataSource).close(); // } catch (Exception ignore) { // } // } // } // // if (this.slaveDataSource != null) { // if (slaveDataSource instanceof AutoCloseable) { // try { // ((AutoCloseable) slaveDataSource).close(); // } catch (Exception ignore) { // } // } // } // } // // } // Path: tsharding-client/src/main/java/com/mogujie/trade/tsharding/route/orm/MapperScannerWithSharding.java import com.mogujie.trade.db.DataSourceLookup; import com.mogujie.trade.db.ReadWriteSplittingDataSource; import com.mogujie.trade.tsharding.route.orm.base.*; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.beans.BeansException; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.core.io.Resource; import java.io.IOException; import java.lang.reflect.*; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { this.dataSourceLookup = beanFactory.getBean(DataSourceLookup.class); try { this.initSqlSessionFactories(beanFactory); } catch (Exception e) { throw new RuntimeException(e); } ClassPathScanHandler scanner = new ClassPathScanHandler(); Set<Class<?>> mapperClasses = new HashSet<>(); for (String mapperPackage : this.mapperPacakages) { Set<Class<?>> classes = scanner.getPackageAllClasses(mapperPackage.trim(), false); mapperClasses.addAll(classes); } for (Class<?> clazz : mapperClasses) { if (isMapper(clazz)) { Object mapper = this.newMapper(clazz); beanFactory.registerSingleton(Character.toLowerCase(clazz.getSimpleName().charAt(0)) + clazz.getSimpleName().substring(1), mapper); } } } private void initSqlSessionFactories(ConfigurableListableBeanFactory beanFactory) throws Exception { Map<String, SqlSessionFactory> sqlSessionFactories = new HashMap<>(this.dataSourceLookup.getMapping().size());
ReadWriteSplittingDataSource defaultDataSource = null;
xvik/generics-resolver
src/main/java/ru/vyarus/java/generics/resolver/util/map/PrintableGenericsMap.java
// Path: src/main/java/ru/vyarus/java/generics/resolver/context/container/ExplicitTypeVariable.java // public class ExplicitTypeVariable implements Type { // // private final String name; // private final TypeVariable declarationSource; // private final Type[] bounds; // // public ExplicitTypeVariable(final TypeVariable variable) { // this.name = variable.getName(); // this.declarationSource = variable; // this.bounds = variable.getBounds(); // } // // public ExplicitTypeVariable(final String name) { // this.name = name; // this.declarationSource = null; // this.bounds = new Type[]{Object.class}; // } // // /** // * @return variable name // */ // public String getName() { // return name; // } // // /** // * @return original (source) type variable or null // */ // public TypeVariable getDeclarationSource() { // return declarationSource; // } // // /** // * @return variable bound (Object when no known bound) // */ // public Type[] getBounds() { // return Arrays.copyOf(bounds, bounds.length); // } // // @Override // public String toString() { // return name; // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // if (!(o instanceof ExplicitTypeVariable)) { // return false; // } // // final ExplicitTypeVariable that = (ExplicitTypeVariable) o; // // if (!name.equals(that.name)) { // return false; // } // if (declarationSource != null // ? !declarationSource.equals(that.declarationSource) : that.declarationSource != null) { // return false; // } // return Arrays.equals(bounds, that.bounds); // } // // @Override // public int hashCode() { // int result = name.hashCode(); // result = 31 * result + (declarationSource != null ? declarationSource.hashCode() : 0); // result = 31 * result + Arrays.hashCode(bounds); // return result; // } // }
import ru.vyarus.java.generics.resolver.context.container.ExplicitTypeVariable; import java.lang.reflect.Type; import java.util.LinkedHashMap; import java.util.Map;
package ru.vyarus.java.generics.resolver.util.map; /** * Special map to use with {@link ru.vyarus.java.generics.resolver.util.TypeToStringUtils} in order to see generic * name in the resulted string. For example, {@code List<T> instead of List<Object>}. * * @author Vyacheslav Rusakov * @since 13.05.2018 */ public class PrintableGenericsMap extends LinkedHashMap<String, Type> { public PrintableGenericsMap() { // default } public PrintableGenericsMap(final Map<? extends String, ? extends Type> m) { super(m); } @Override public Type get(final Object key) { // always Object for unknown generic name final Type res = super.get(key);
// Path: src/main/java/ru/vyarus/java/generics/resolver/context/container/ExplicitTypeVariable.java // public class ExplicitTypeVariable implements Type { // // private final String name; // private final TypeVariable declarationSource; // private final Type[] bounds; // // public ExplicitTypeVariable(final TypeVariable variable) { // this.name = variable.getName(); // this.declarationSource = variable; // this.bounds = variable.getBounds(); // } // // public ExplicitTypeVariable(final String name) { // this.name = name; // this.declarationSource = null; // this.bounds = new Type[]{Object.class}; // } // // /** // * @return variable name // */ // public String getName() { // return name; // } // // /** // * @return original (source) type variable or null // */ // public TypeVariable getDeclarationSource() { // return declarationSource; // } // // /** // * @return variable bound (Object when no known bound) // */ // public Type[] getBounds() { // return Arrays.copyOf(bounds, bounds.length); // } // // @Override // public String toString() { // return name; // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // if (!(o instanceof ExplicitTypeVariable)) { // return false; // } // // final ExplicitTypeVariable that = (ExplicitTypeVariable) o; // // if (!name.equals(that.name)) { // return false; // } // if (declarationSource != null // ? !declarationSource.equals(that.declarationSource) : that.declarationSource != null) { // return false; // } // return Arrays.equals(bounds, that.bounds); // } // // @Override // public int hashCode() { // int result = name.hashCode(); // result = 31 * result + (declarationSource != null ? declarationSource.hashCode() : 0); // result = 31 * result + Arrays.hashCode(bounds); // return result; // } // } // Path: src/main/java/ru/vyarus/java/generics/resolver/util/map/PrintableGenericsMap.java import ru.vyarus.java.generics.resolver.context.container.ExplicitTypeVariable; import java.lang.reflect.Type; import java.util.LinkedHashMap; import java.util.Map; package ru.vyarus.java.generics.resolver.util.map; /** * Special map to use with {@link ru.vyarus.java.generics.resolver.util.TypeToStringUtils} in order to see generic * name in the resulted string. For example, {@code List<T> instead of List<Object>}. * * @author Vyacheslav Rusakov * @since 13.05.2018 */ public class PrintableGenericsMap extends LinkedHashMap<String, Type> { public PrintableGenericsMap() { // default } public PrintableGenericsMap(final Map<? extends String, ? extends Type> m) { super(m); } @Override public Type get(final Object key) { // always Object for unknown generic name final Type res = super.get(key);
return res == null ? new ExplicitTypeVariable((String) key) : res;
xvik/generics-resolver
src/main/java/ru/vyarus/java/generics/resolver/util/walk/MatchVariablesVisitor.java
// Path: src/main/java/ru/vyarus/java/generics/resolver/context/container/ExplicitTypeVariable.java // public class ExplicitTypeVariable implements Type { // // private final String name; // private final TypeVariable declarationSource; // private final Type[] bounds; // // public ExplicitTypeVariable(final TypeVariable variable) { // this.name = variable.getName(); // this.declarationSource = variable; // this.bounds = variable.getBounds(); // } // // public ExplicitTypeVariable(final String name) { // this.name = name; // this.declarationSource = null; // this.bounds = new Type[]{Object.class}; // } // // /** // * @return variable name // */ // public String getName() { // return name; // } // // /** // * @return original (source) type variable or null // */ // public TypeVariable getDeclarationSource() { // return declarationSource; // } // // /** // * @return variable bound (Object when no known bound) // */ // public Type[] getBounds() { // return Arrays.copyOf(bounds, bounds.length); // } // // @Override // public String toString() { // return name; // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // if (!(o instanceof ExplicitTypeVariable)) { // return false; // } // // final ExplicitTypeVariable that = (ExplicitTypeVariable) o; // // if (!name.equals(that.name)) { // return false; // } // if (declarationSource != null // ? !declarationSource.equals(that.declarationSource) : that.declarationSource != null) { // return false; // } // return Arrays.equals(bounds, that.bounds); // } // // @Override // public int hashCode() { // int result = name.hashCode(); // result = 31 * result + (declarationSource != null ? declarationSource.hashCode() : 0); // result = 31 * result + Arrays.hashCode(bounds); // return result; // } // }
import ru.vyarus.java.generics.resolver.context.container.ExplicitTypeVariable; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.HashMap; import java.util.Map;
package ru.vyarus.java.generics.resolver.util.walk; /** * Match {@link ExplicitTypeVariable} in one type with real types from other type. * * @author Vyacheslav Rusakov * @since 14.12.2018 */ public class MatchVariablesVisitor implements TypesVisitor { private final Map<TypeVariable, Type> matched = new HashMap<TypeVariable, Type>(); private final Map<String, Type> matchedMap = new HashMap<String, Type>(); private boolean hierarchyError; @Override public boolean next(final Type one, final Type two) { TypeVariable var = null;
// Path: src/main/java/ru/vyarus/java/generics/resolver/context/container/ExplicitTypeVariable.java // public class ExplicitTypeVariable implements Type { // // private final String name; // private final TypeVariable declarationSource; // private final Type[] bounds; // // public ExplicitTypeVariable(final TypeVariable variable) { // this.name = variable.getName(); // this.declarationSource = variable; // this.bounds = variable.getBounds(); // } // // public ExplicitTypeVariable(final String name) { // this.name = name; // this.declarationSource = null; // this.bounds = new Type[]{Object.class}; // } // // /** // * @return variable name // */ // public String getName() { // return name; // } // // /** // * @return original (source) type variable or null // */ // public TypeVariable getDeclarationSource() { // return declarationSource; // } // // /** // * @return variable bound (Object when no known bound) // */ // public Type[] getBounds() { // return Arrays.copyOf(bounds, bounds.length); // } // // @Override // public String toString() { // return name; // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // if (!(o instanceof ExplicitTypeVariable)) { // return false; // } // // final ExplicitTypeVariable that = (ExplicitTypeVariable) o; // // if (!name.equals(that.name)) { // return false; // } // if (declarationSource != null // ? !declarationSource.equals(that.declarationSource) : that.declarationSource != null) { // return false; // } // return Arrays.equals(bounds, that.bounds); // } // // @Override // public int hashCode() { // int result = name.hashCode(); // result = 31 * result + (declarationSource != null ? declarationSource.hashCode() : 0); // result = 31 * result + Arrays.hashCode(bounds); // return result; // } // } // Path: src/main/java/ru/vyarus/java/generics/resolver/util/walk/MatchVariablesVisitor.java import ru.vyarus.java.generics.resolver.context.container.ExplicitTypeVariable; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.HashMap; import java.util.Map; package ru.vyarus.java.generics.resolver.util.walk; /** * Match {@link ExplicitTypeVariable} in one type with real types from other type. * * @author Vyacheslav Rusakov * @since 14.12.2018 */ public class MatchVariablesVisitor implements TypesVisitor { private final Map<TypeVariable, Type> matched = new HashMap<TypeVariable, Type>(); private final Map<String, Type> matchedMap = new HashMap<String, Type>(); private boolean hierarchyError; @Override public boolean next(final Type one, final Type two) { TypeVariable var = null;
if (one instanceof ExplicitTypeVariable) {
xvik/generics-resolver
src/main/java/ru/vyarus/java/generics/resolver/util/ArrayTypeUtils.java
// Path: src/main/java/ru/vyarus/java/generics/resolver/context/container/GenericArrayTypeImpl.java // public class GenericArrayTypeImpl implements GenericArrayType { // // private final Type componentType; // // public GenericArrayTypeImpl(final Type componentType) { // this.componentType = componentType; // if (componentType == null) { // throw new IllegalArgumentException("Null component type is not allowed"); // } // } // // @Override // public Type getGenericComponentType() { // return componentType; // } // // @Override // public boolean equals(final Object o) { // boolean res = this == o; // if (!res && o instanceof GenericArrayType) { // final Type thatComponentType = ((GenericArrayType) o).getGenericComponentType(); // res = componentType.equals(thatComponentType); // } // return res; // } // // @Override // public int hashCode() { // return componentType.hashCode(); // } // // @Override // public String toString() { // return TypeToStringUtils.toStringType(this); // } // }
import ru.vyarus.java.generics.resolver.context.container.GenericArrayTypeImpl; import java.lang.reflect.GenericArrayType; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map;
final String name = type.getName(); final String typeName; if (type.isArray()) { typeName = ARRAY_TYPE_SIMPLE_PREFIX + name; } else if (type.isPrimitive()) { typeName = ARRAY_TYPE_SIMPLE_PREFIX + PRIMITIVE_ARRAY_LETTER.get(type); } else { typeName = ARRAY_TYPE_OBJECT_PREFIX + name + ";"; } return (Class<T[]>) Class.forName(typeName); } catch (ClassNotFoundException e) { throw new IllegalStateException("Failed to create array class for " + TypeToStringUtils.toStringType(type), e); } } /** * There are two possible cases: * <ul> * <li>Type is pure class - then arrays is simple class (e.g. {@code int[].class} or {@code List[].class}) </li> * <li>Type is generified - then {@link GenericArrayType} must be used (e.g. for parameterized type * {@code List<String>})</li> * </ul> * * @param type type to get array of * @return array type * @see #toArrayClass(Class) for pure class case */ public static Type toArrayType(final Type type) { return type instanceof Class ? toArrayClass((Class<?>) type)
// Path: src/main/java/ru/vyarus/java/generics/resolver/context/container/GenericArrayTypeImpl.java // public class GenericArrayTypeImpl implements GenericArrayType { // // private final Type componentType; // // public GenericArrayTypeImpl(final Type componentType) { // this.componentType = componentType; // if (componentType == null) { // throw new IllegalArgumentException("Null component type is not allowed"); // } // } // // @Override // public Type getGenericComponentType() { // return componentType; // } // // @Override // public boolean equals(final Object o) { // boolean res = this == o; // if (!res && o instanceof GenericArrayType) { // final Type thatComponentType = ((GenericArrayType) o).getGenericComponentType(); // res = componentType.equals(thatComponentType); // } // return res; // } // // @Override // public int hashCode() { // return componentType.hashCode(); // } // // @Override // public String toString() { // return TypeToStringUtils.toStringType(this); // } // } // Path: src/main/java/ru/vyarus/java/generics/resolver/util/ArrayTypeUtils.java import ru.vyarus.java.generics.resolver.context.container.GenericArrayTypeImpl; import java.lang.reflect.GenericArrayType; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; final String name = type.getName(); final String typeName; if (type.isArray()) { typeName = ARRAY_TYPE_SIMPLE_PREFIX + name; } else if (type.isPrimitive()) { typeName = ARRAY_TYPE_SIMPLE_PREFIX + PRIMITIVE_ARRAY_LETTER.get(type); } else { typeName = ARRAY_TYPE_OBJECT_PREFIX + name + ";"; } return (Class<T[]>) Class.forName(typeName); } catch (ClassNotFoundException e) { throw new IllegalStateException("Failed to create array class for " + TypeToStringUtils.toStringType(type), e); } } /** * There are two possible cases: * <ul> * <li>Type is pure class - then arrays is simple class (e.g. {@code int[].class} or {@code List[].class}) </li> * <li>Type is generified - then {@link GenericArrayType} must be used (e.g. for parameterized type * {@code List<String>})</li> * </ul> * * @param type type to get array of * @return array type * @see #toArrayClass(Class) for pure class case */ public static Type toArrayType(final Type type) { return type instanceof Class ? toArrayClass((Class<?>) type)
: new GenericArrayTypeImpl(type);
koterpillar/android-sasl
classpath-0.98/javax/security/sasl/SaslException.java
// Path: src/gnu/java/lang/CPStringBuilder.java // public class CPStringBuilder { // private StringBuilder that; // // public CPStringBuilder() { // that = new StringBuilder(); // } // // public CPStringBuilder(int i){ // that = new StringBuilder(i); // } // // public CPStringBuilder(String string) { // that = new StringBuilder(string); // } // // public CPStringBuilder append(char c) { // that.append(c); // return this; // } // // @Override // public String toString() { // return that.toString(); // } // // public CPStringBuilder append(String string) { // that.append(string); // return this; // } // // public CPStringBuilder append(int length) { // that.append(length); // return this; // } // // public CPStringBuilder append(char[] cs) { // that.append(cs); // return this; // } // }
import gnu.java.lang.CPStringBuilder; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.io.Serializable;
if (_exception != null) _exception.printStackTrace(ps); } /** * Prints this exception's stack trace to a print writer. If this exception * has a root exception; the stack trace of the root exception is also * printed to the print writer. * * @param pw the non-null print writer to use for output. */ public void printStackTrace(PrintWriter pw) { super.printStackTrace(pw); if (_exception != null) _exception.printStackTrace(pw); } /** * Returns the string representation of this exception. The string * representation contains this exception's class name, its detailed * messsage, and if it has a root exception, the string representation of the * root exception. This string representation is meant for debugging and not * meant to be interpreted programmatically. * * @return the non-null string representation of this exception. * @see Throwable#getMessage() */ public String toString() {
// Path: src/gnu/java/lang/CPStringBuilder.java // public class CPStringBuilder { // private StringBuilder that; // // public CPStringBuilder() { // that = new StringBuilder(); // } // // public CPStringBuilder(int i){ // that = new StringBuilder(i); // } // // public CPStringBuilder(String string) { // that = new StringBuilder(string); // } // // public CPStringBuilder append(char c) { // that.append(c); // return this; // } // // @Override // public String toString() { // return that.toString(); // } // // public CPStringBuilder append(String string) { // that.append(string); // return this; // } // // public CPStringBuilder append(int length) { // that.append(length); // return this; // } // // public CPStringBuilder append(char[] cs) { // that.append(cs); // return this; // } // } // Path: classpath-0.98/javax/security/sasl/SaslException.java import gnu.java.lang.CPStringBuilder; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.io.Serializable; if (_exception != null) _exception.printStackTrace(ps); } /** * Prints this exception's stack trace to a print writer. If this exception * has a root exception; the stack trace of the root exception is also * printed to the print writer. * * @param pw the non-null print writer to use for output. */ public void printStackTrace(PrintWriter pw) { super.printStackTrace(pw); if (_exception != null) _exception.printStackTrace(pw); } /** * Returns the string representation of this exception. The string * representation contains this exception's class name, its detailed * messsage, and if it has a root exception, the string representation of the * root exception. This string representation is meant for debugging and not * meant to be interpreted programmatically. * * @return the non-null string representation of this exception. * @see Throwable#getMessage() */ public String toString() {
CPStringBuilder sb = new CPStringBuilder(this.getClass().getName())
koterpillar/android-sasl
classpath-0.98/gnu/javax/crypto/sasl/crammd5/CramMD5AuthInfoProvider.java
// Path: classpath-0.98/gnu/javax/crypto/sasl/IAuthInfoProvider.java // public interface IAuthInfoProvider // { // /** // * Activates (initialises) this provider instance. SHOULD be the first method // * invoked on the provider. // * // * @param context a collection of name-value bindings describing the // * activation context. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // void activate(Map context) throws AuthenticationException; // // /** // * Passivates (releases) this provider instance. SHOULD be the last method // * invoked on the provider. Once it is done, no other method may be invoked on // * the same instance before it is <i>activated</i> agains. // * // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // void passivate() throws AuthenticationException; // // /** // * Checks if a user with a designated name is known to this provider. // * // * @param userName the name of a user to check. // * @return <code>true</code> if the user with the designated name is known // * to this provider; <code>false</code> otherwise. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // boolean contains(String userName) throws AuthenticationException; // // /** // * Returns a collection of information about a designated user. The contents // * of the returned map is provider-specific of name-to-value mappings. // * // * @param userID a map of name-to-value bindings that fully describe a user. // * @return a collection of information about the designated user. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // Map lookup(Map userID) throws AuthenticationException; // // /** // * Updates the credentials of a designated user. // * // * @param userCredentials a map of name-to-value bindings that fully describe // * a user, including per new credentials. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // void update(Map userCredentials) throws AuthenticationException; // // /** // * A provider may operate in more than mode; e.g. SRP-II caters for user // * credentials computed in more than one message digest algorithm. This method // * returns the set of name-to-value bindings describing the mode of the // * provider. // * // * @param mode a unique identifier describing the operational mode. // * @return a collection of name-to-value bindings describing the designated // * mode. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // Map getConfiguration(String mode) throws AuthenticationException; // } // // Path: classpath-0.98/gnu/javax/crypto/sasl/NoSuchUserException.java // public class NoSuchUserException // extends AuthenticationException // { // /** Constructs a <code>NoSuchUserException</code> with no detail message. */ // public NoSuchUserException() // { // super(); // } // // /** // * Constructs a <code>NoSuchUserException</code> with the specified detail // * message. In the case of this exception, the detail message designates the // * offending username. // * // * @param arg the detail message, which in this case is the username. // */ // public NoSuchUserException(String arg) // { // super(arg); // } // } // // Path: classpath-0.98/javax/security/sasl/AuthenticationException.java // public class AuthenticationException extends SaslException // { // // // Constants and variables // // ------------------------------------------------------------------------- // // // Constructor(s) // // ------------------------------------------------------------------------- // // /** // * Constructs a new instance of <code>AuthenticationException</code>. The // * root exception and the detailed message are <code>null</code>. // */ // public AuthenticationException() // { // super(); // } // // /** // * Constructs a new instance of <code>AuthenticationException</code> with a // * detailed message. The root exception is <code>null</code>. // * // * @param detail a possibly <code>null</code> string containing details of // * the exception. // * @see Throwable#getMessage() // */ // public AuthenticationException(String detail) // { // super(detail); // } // // /** // * Constructs a new instance of <code>AuthenticationException</code> with a // * detailed message and a root exception. // * // * @param detail a possibly <code>null</code> string containing details of // * the exception. // * @param ex a possibly <code>null</code> root exception that caused this // * exception. // * @see Throwable#getMessage() // * @see SaslException#getCause() // */ // public AuthenticationException(String detail, Throwable ex) // { // super(detail, ex); // } // // // Class methods // // ------------------------------------------------------------------------- // // // Instance methods // // ------------------------------------------------------------------------- // }
import gnu.java.security.Registry; import gnu.javax.crypto.sasl.IAuthInfoProvider; import gnu.javax.crypto.sasl.NoSuchUserException; import java.io.IOException; import java.util.HashMap; import java.util.Map; import gnusasl.javax.security.sasl.AuthenticationException;
{ passwordFile = null; } public boolean contains(String userName) throws AuthenticationException { if (passwordFile == null) throw new AuthenticationException("contains()", new IllegalStateException()); boolean result = false; try { result = passwordFile.contains(userName); } catch (IOException x) { throw new AuthenticationException("contains()", x); } return result; } public Map lookup(Map userID) throws AuthenticationException { if (passwordFile == null) throw new AuthenticationException("lookup()", new IllegalStateException()); Map result = new HashMap(); try { String userName = (String) userID.get(Registry.SASL_USERNAME); if (userName == null)
// Path: classpath-0.98/gnu/javax/crypto/sasl/IAuthInfoProvider.java // public interface IAuthInfoProvider // { // /** // * Activates (initialises) this provider instance. SHOULD be the first method // * invoked on the provider. // * // * @param context a collection of name-value bindings describing the // * activation context. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // void activate(Map context) throws AuthenticationException; // // /** // * Passivates (releases) this provider instance. SHOULD be the last method // * invoked on the provider. Once it is done, no other method may be invoked on // * the same instance before it is <i>activated</i> agains. // * // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // void passivate() throws AuthenticationException; // // /** // * Checks if a user with a designated name is known to this provider. // * // * @param userName the name of a user to check. // * @return <code>true</code> if the user with the designated name is known // * to this provider; <code>false</code> otherwise. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // boolean contains(String userName) throws AuthenticationException; // // /** // * Returns a collection of information about a designated user. The contents // * of the returned map is provider-specific of name-to-value mappings. // * // * @param userID a map of name-to-value bindings that fully describe a user. // * @return a collection of information about the designated user. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // Map lookup(Map userID) throws AuthenticationException; // // /** // * Updates the credentials of a designated user. // * // * @param userCredentials a map of name-to-value bindings that fully describe // * a user, including per new credentials. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // void update(Map userCredentials) throws AuthenticationException; // // /** // * A provider may operate in more than mode; e.g. SRP-II caters for user // * credentials computed in more than one message digest algorithm. This method // * returns the set of name-to-value bindings describing the mode of the // * provider. // * // * @param mode a unique identifier describing the operational mode. // * @return a collection of name-to-value bindings describing the designated // * mode. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // Map getConfiguration(String mode) throws AuthenticationException; // } // // Path: classpath-0.98/gnu/javax/crypto/sasl/NoSuchUserException.java // public class NoSuchUserException // extends AuthenticationException // { // /** Constructs a <code>NoSuchUserException</code> with no detail message. */ // public NoSuchUserException() // { // super(); // } // // /** // * Constructs a <code>NoSuchUserException</code> with the specified detail // * message. In the case of this exception, the detail message designates the // * offending username. // * // * @param arg the detail message, which in this case is the username. // */ // public NoSuchUserException(String arg) // { // super(arg); // } // } // // Path: classpath-0.98/javax/security/sasl/AuthenticationException.java // public class AuthenticationException extends SaslException // { // // // Constants and variables // // ------------------------------------------------------------------------- // // // Constructor(s) // // ------------------------------------------------------------------------- // // /** // * Constructs a new instance of <code>AuthenticationException</code>. The // * root exception and the detailed message are <code>null</code>. // */ // public AuthenticationException() // { // super(); // } // // /** // * Constructs a new instance of <code>AuthenticationException</code> with a // * detailed message. The root exception is <code>null</code>. // * // * @param detail a possibly <code>null</code> string containing details of // * the exception. // * @see Throwable#getMessage() // */ // public AuthenticationException(String detail) // { // super(detail); // } // // /** // * Constructs a new instance of <code>AuthenticationException</code> with a // * detailed message and a root exception. // * // * @param detail a possibly <code>null</code> string containing details of // * the exception. // * @param ex a possibly <code>null</code> root exception that caused this // * exception. // * @see Throwable#getMessage() // * @see SaslException#getCause() // */ // public AuthenticationException(String detail, Throwable ex) // { // super(detail, ex); // } // // // Class methods // // ------------------------------------------------------------------------- // // // Instance methods // // ------------------------------------------------------------------------- // } // Path: classpath-0.98/gnu/javax/crypto/sasl/crammd5/CramMD5AuthInfoProvider.java import gnu.java.security.Registry; import gnu.javax.crypto.sasl.IAuthInfoProvider; import gnu.javax.crypto.sasl.NoSuchUserException; import java.io.IOException; import java.util.HashMap; import java.util.Map; import gnusasl.javax.security.sasl.AuthenticationException; { passwordFile = null; } public boolean contains(String userName) throws AuthenticationException { if (passwordFile == null) throw new AuthenticationException("contains()", new IllegalStateException()); boolean result = false; try { result = passwordFile.contains(userName); } catch (IOException x) { throw new AuthenticationException("contains()", x); } return result; } public Map lookup(Map userID) throws AuthenticationException { if (passwordFile == null) throw new AuthenticationException("lookup()", new IllegalStateException()); Map result = new HashMap(); try { String userName = (String) userID.get(Registry.SASL_USERNAME); if (userName == null)
throw new NoSuchUserException("");
koterpillar/android-sasl
classpath-0.98/gnu/javax/crypto/sasl/plain/PlainAuthInfoProvider.java
// Path: classpath-0.98/gnu/javax/crypto/sasl/IAuthInfoProvider.java // public interface IAuthInfoProvider // { // /** // * Activates (initialises) this provider instance. SHOULD be the first method // * invoked on the provider. // * // * @param context a collection of name-value bindings describing the // * activation context. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // void activate(Map context) throws AuthenticationException; // // /** // * Passivates (releases) this provider instance. SHOULD be the last method // * invoked on the provider. Once it is done, no other method may be invoked on // * the same instance before it is <i>activated</i> agains. // * // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // void passivate() throws AuthenticationException; // // /** // * Checks if a user with a designated name is known to this provider. // * // * @param userName the name of a user to check. // * @return <code>true</code> if the user with the designated name is known // * to this provider; <code>false</code> otherwise. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // boolean contains(String userName) throws AuthenticationException; // // /** // * Returns a collection of information about a designated user. The contents // * of the returned map is provider-specific of name-to-value mappings. // * // * @param userID a map of name-to-value bindings that fully describe a user. // * @return a collection of information about the designated user. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // Map lookup(Map userID) throws AuthenticationException; // // /** // * Updates the credentials of a designated user. // * // * @param userCredentials a map of name-to-value bindings that fully describe // * a user, including per new credentials. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // void update(Map userCredentials) throws AuthenticationException; // // /** // * A provider may operate in more than mode; e.g. SRP-II caters for user // * credentials computed in more than one message digest algorithm. This method // * returns the set of name-to-value bindings describing the mode of the // * provider. // * // * @param mode a unique identifier describing the operational mode. // * @return a collection of name-to-value bindings describing the designated // * mode. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // Map getConfiguration(String mode) throws AuthenticationException; // } // // Path: classpath-0.98/gnu/javax/crypto/sasl/NoSuchUserException.java // public class NoSuchUserException // extends AuthenticationException // { // /** Constructs a <code>NoSuchUserException</code> with no detail message. */ // public NoSuchUserException() // { // super(); // } // // /** // * Constructs a <code>NoSuchUserException</code> with the specified detail // * message. In the case of this exception, the detail message designates the // * offending username. // * // * @param arg the detail message, which in this case is the username. // */ // public NoSuchUserException(String arg) // { // super(arg); // } // } // // Path: classpath-0.98/javax/security/sasl/AuthenticationException.java // public class AuthenticationException extends SaslException // { // // // Constants and variables // // ------------------------------------------------------------------------- // // // Constructor(s) // // ------------------------------------------------------------------------- // // /** // * Constructs a new instance of <code>AuthenticationException</code>. The // * root exception and the detailed message are <code>null</code>. // */ // public AuthenticationException() // { // super(); // } // // /** // * Constructs a new instance of <code>AuthenticationException</code> with a // * detailed message. The root exception is <code>null</code>. // * // * @param detail a possibly <code>null</code> string containing details of // * the exception. // * @see Throwable#getMessage() // */ // public AuthenticationException(String detail) // { // super(detail); // } // // /** // * Constructs a new instance of <code>AuthenticationException</code> with a // * detailed message and a root exception. // * // * @param detail a possibly <code>null</code> string containing details of // * the exception. // * @param ex a possibly <code>null</code> root exception that caused this // * exception. // * @see Throwable#getMessage() // * @see SaslException#getCause() // */ // public AuthenticationException(String detail, Throwable ex) // { // super(detail, ex); // } // // // Class methods // // ------------------------------------------------------------------------- // // // Instance methods // // ------------------------------------------------------------------------- // }
import gnu.java.security.Registry; import gnu.javax.crypto.sasl.IAuthInfoProvider; import gnu.javax.crypto.sasl.NoSuchUserException; import java.io.IOException; import java.util.HashMap; import java.util.Map; import gnusasl.javax.security.sasl.AuthenticationException;
{ passwordFile = null; } public boolean contains(String userName) throws AuthenticationException { if (passwordFile == null) throw new AuthenticationException("contains()", new IllegalStateException()); boolean result = false; try { result = passwordFile.contains(userName); } catch (IOException x) { throw new AuthenticationException("contains()", x); } return result; } public Map lookup(Map userID) throws AuthenticationException { if (passwordFile == null) throw new AuthenticationException("lookup()", new IllegalStateException()); Map result = new HashMap(); try { String userName = (String) userID.get(Registry.SASL_USERNAME); if (userName == null)
// Path: classpath-0.98/gnu/javax/crypto/sasl/IAuthInfoProvider.java // public interface IAuthInfoProvider // { // /** // * Activates (initialises) this provider instance. SHOULD be the first method // * invoked on the provider. // * // * @param context a collection of name-value bindings describing the // * activation context. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // void activate(Map context) throws AuthenticationException; // // /** // * Passivates (releases) this provider instance. SHOULD be the last method // * invoked on the provider. Once it is done, no other method may be invoked on // * the same instance before it is <i>activated</i> agains. // * // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // void passivate() throws AuthenticationException; // // /** // * Checks if a user with a designated name is known to this provider. // * // * @param userName the name of a user to check. // * @return <code>true</code> if the user with the designated name is known // * to this provider; <code>false</code> otherwise. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // boolean contains(String userName) throws AuthenticationException; // // /** // * Returns a collection of information about a designated user. The contents // * of the returned map is provider-specific of name-to-value mappings. // * // * @param userID a map of name-to-value bindings that fully describe a user. // * @return a collection of information about the designated user. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // Map lookup(Map userID) throws AuthenticationException; // // /** // * Updates the credentials of a designated user. // * // * @param userCredentials a map of name-to-value bindings that fully describe // * a user, including per new credentials. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // void update(Map userCredentials) throws AuthenticationException; // // /** // * A provider may operate in more than mode; e.g. SRP-II caters for user // * credentials computed in more than one message digest algorithm. This method // * returns the set of name-to-value bindings describing the mode of the // * provider. // * // * @param mode a unique identifier describing the operational mode. // * @return a collection of name-to-value bindings describing the designated // * mode. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // Map getConfiguration(String mode) throws AuthenticationException; // } // // Path: classpath-0.98/gnu/javax/crypto/sasl/NoSuchUserException.java // public class NoSuchUserException // extends AuthenticationException // { // /** Constructs a <code>NoSuchUserException</code> with no detail message. */ // public NoSuchUserException() // { // super(); // } // // /** // * Constructs a <code>NoSuchUserException</code> with the specified detail // * message. In the case of this exception, the detail message designates the // * offending username. // * // * @param arg the detail message, which in this case is the username. // */ // public NoSuchUserException(String arg) // { // super(arg); // } // } // // Path: classpath-0.98/javax/security/sasl/AuthenticationException.java // public class AuthenticationException extends SaslException // { // // // Constants and variables // // ------------------------------------------------------------------------- // // // Constructor(s) // // ------------------------------------------------------------------------- // // /** // * Constructs a new instance of <code>AuthenticationException</code>. The // * root exception and the detailed message are <code>null</code>. // */ // public AuthenticationException() // { // super(); // } // // /** // * Constructs a new instance of <code>AuthenticationException</code> with a // * detailed message. The root exception is <code>null</code>. // * // * @param detail a possibly <code>null</code> string containing details of // * the exception. // * @see Throwable#getMessage() // */ // public AuthenticationException(String detail) // { // super(detail); // } // // /** // * Constructs a new instance of <code>AuthenticationException</code> with a // * detailed message and a root exception. // * // * @param detail a possibly <code>null</code> string containing details of // * the exception. // * @param ex a possibly <code>null</code> root exception that caused this // * exception. // * @see Throwable#getMessage() // * @see SaslException#getCause() // */ // public AuthenticationException(String detail, Throwable ex) // { // super(detail, ex); // } // // // Class methods // // ------------------------------------------------------------------------- // // // Instance methods // // ------------------------------------------------------------------------- // } // Path: classpath-0.98/gnu/javax/crypto/sasl/plain/PlainAuthInfoProvider.java import gnu.java.security.Registry; import gnu.javax.crypto.sasl.IAuthInfoProvider; import gnu.javax.crypto.sasl.NoSuchUserException; import java.io.IOException; import java.util.HashMap; import java.util.Map; import gnusasl.javax.security.sasl.AuthenticationException; { passwordFile = null; } public boolean contains(String userName) throws AuthenticationException { if (passwordFile == null) throw new AuthenticationException("contains()", new IllegalStateException()); boolean result = false; try { result = passwordFile.contains(userName); } catch (IOException x) { throw new AuthenticationException("contains()", x); } return result; } public Map lookup(Map userID) throws AuthenticationException { if (passwordFile == null) throw new AuthenticationException("lookup()", new IllegalStateException()); Map result = new HashMap(); try { String userName = (String) userID.get(Registry.SASL_USERNAME); if (userName == null)
throw new NoSuchUserException("");
koterpillar/android-sasl
classpath-0.98/gnu/javax/crypto/sasl/IAuthInfoProvider.java
// Path: classpath-0.98/javax/security/sasl/AuthenticationException.java // public class AuthenticationException extends SaslException // { // // // Constants and variables // // ------------------------------------------------------------------------- // // // Constructor(s) // // ------------------------------------------------------------------------- // // /** // * Constructs a new instance of <code>AuthenticationException</code>. The // * root exception and the detailed message are <code>null</code>. // */ // public AuthenticationException() // { // super(); // } // // /** // * Constructs a new instance of <code>AuthenticationException</code> with a // * detailed message. The root exception is <code>null</code>. // * // * @param detail a possibly <code>null</code> string containing details of // * the exception. // * @see Throwable#getMessage() // */ // public AuthenticationException(String detail) // { // super(detail); // } // // /** // * Constructs a new instance of <code>AuthenticationException</code> with a // * detailed message and a root exception. // * // * @param detail a possibly <code>null</code> string containing details of // * the exception. // * @param ex a possibly <code>null</code> root exception that caused this // * exception. // * @see Throwable#getMessage() // * @see SaslException#getCause() // */ // public AuthenticationException(String detail, Throwable ex) // { // super(detail, ex); // } // // // Class methods // // ------------------------------------------------------------------------- // // // Instance methods // // ------------------------------------------------------------------------- // }
import java.util.Map; import gnusasl.javax.security.sasl.AuthenticationException;
/* IAuthInfoProvider.java -- Copyright (C) 2003, 2006 Free Software Foundation, Inc. Modified for Android (C) 2009, 2010 by Alexey Kotlyarov This file is a part of GNU Classpath. GNU Classpath 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 2 of the License, or (at your option) any later version. GNU Classpath 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 GNU Classpath; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package gnu.javax.crypto.sasl; /** * The visible methods of any authentication information provider. */ public interface IAuthInfoProvider { /** * Activates (initialises) this provider instance. SHOULD be the first method * invoked on the provider. * * @param context a collection of name-value bindings describing the * activation context. * @throws AuthenticationException if an exception occurs during the * operation. */
// Path: classpath-0.98/javax/security/sasl/AuthenticationException.java // public class AuthenticationException extends SaslException // { // // // Constants and variables // // ------------------------------------------------------------------------- // // // Constructor(s) // // ------------------------------------------------------------------------- // // /** // * Constructs a new instance of <code>AuthenticationException</code>. The // * root exception and the detailed message are <code>null</code>. // */ // public AuthenticationException() // { // super(); // } // // /** // * Constructs a new instance of <code>AuthenticationException</code> with a // * detailed message. The root exception is <code>null</code>. // * // * @param detail a possibly <code>null</code> string containing details of // * the exception. // * @see Throwable#getMessage() // */ // public AuthenticationException(String detail) // { // super(detail); // } // // /** // * Constructs a new instance of <code>AuthenticationException</code> with a // * detailed message and a root exception. // * // * @param detail a possibly <code>null</code> string containing details of // * the exception. // * @param ex a possibly <code>null</code> root exception that caused this // * exception. // * @see Throwable#getMessage() // * @see SaslException#getCause() // */ // public AuthenticationException(String detail, Throwable ex) // { // super(detail, ex); // } // // // Class methods // // ------------------------------------------------------------------------- // // // Instance methods // // ------------------------------------------------------------------------- // } // Path: classpath-0.98/gnu/javax/crypto/sasl/IAuthInfoProvider.java import java.util.Map; import gnusasl.javax.security.sasl.AuthenticationException; /* IAuthInfoProvider.java -- Copyright (C) 2003, 2006 Free Software Foundation, Inc. Modified for Android (C) 2009, 2010 by Alexey Kotlyarov This file is a part of GNU Classpath. GNU Classpath 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 2 of the License, or (at your option) any later version. GNU Classpath 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 GNU Classpath; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package gnu.javax.crypto.sasl; /** * The visible methods of any authentication information provider. */ public interface IAuthInfoProvider { /** * Activates (initialises) this provider instance. SHOULD be the first method * invoked on the provider. * * @param context a collection of name-value bindings describing the * activation context. * @throws AuthenticationException if an exception occurs during the * operation. */
void activate(Map context) throws AuthenticationException;
koterpillar/android-sasl
classpath-0.98/gnu/javax/crypto/sasl/srp/SRPAuthInfoProvider.java
// Path: classpath-0.98/gnu/javax/crypto/sasl/IAuthInfoProvider.java // public interface IAuthInfoProvider // { // /** // * Activates (initialises) this provider instance. SHOULD be the first method // * invoked on the provider. // * // * @param context a collection of name-value bindings describing the // * activation context. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // void activate(Map context) throws AuthenticationException; // // /** // * Passivates (releases) this provider instance. SHOULD be the last method // * invoked on the provider. Once it is done, no other method may be invoked on // * the same instance before it is <i>activated</i> agains. // * // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // void passivate() throws AuthenticationException; // // /** // * Checks if a user with a designated name is known to this provider. // * // * @param userName the name of a user to check. // * @return <code>true</code> if the user with the designated name is known // * to this provider; <code>false</code> otherwise. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // boolean contains(String userName) throws AuthenticationException; // // /** // * Returns a collection of information about a designated user. The contents // * of the returned map is provider-specific of name-to-value mappings. // * // * @param userID a map of name-to-value bindings that fully describe a user. // * @return a collection of information about the designated user. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // Map lookup(Map userID) throws AuthenticationException; // // /** // * Updates the credentials of a designated user. // * // * @param userCredentials a map of name-to-value bindings that fully describe // * a user, including per new credentials. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // void update(Map userCredentials) throws AuthenticationException; // // /** // * A provider may operate in more than mode; e.g. SRP-II caters for user // * credentials computed in more than one message digest algorithm. This method // * returns the set of name-to-value bindings describing the mode of the // * provider. // * // * @param mode a unique identifier describing the operational mode. // * @return a collection of name-to-value bindings describing the designated // * mode. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // Map getConfiguration(String mode) throws AuthenticationException; // } // // Path: classpath-0.98/gnu/javax/crypto/sasl/NoSuchUserException.java // public class NoSuchUserException // extends AuthenticationException // { // /** Constructs a <code>NoSuchUserException</code> with no detail message. */ // public NoSuchUserException() // { // super(); // } // // /** // * Constructs a <code>NoSuchUserException</code> with the specified detail // * message. In the case of this exception, the detail message designates the // * offending username. // * // * @param arg the detail message, which in this case is the username. // */ // public NoSuchUserException(String arg) // { // super(arg); // } // } // // Path: classpath-0.98/javax/security/sasl/AuthenticationException.java // public class AuthenticationException extends SaslException // { // // // Constants and variables // // ------------------------------------------------------------------------- // // // Constructor(s) // // ------------------------------------------------------------------------- // // /** // * Constructs a new instance of <code>AuthenticationException</code>. The // * root exception and the detailed message are <code>null</code>. // */ // public AuthenticationException() // { // super(); // } // // /** // * Constructs a new instance of <code>AuthenticationException</code> with a // * detailed message. The root exception is <code>null</code>. // * // * @param detail a possibly <code>null</code> string containing details of // * the exception. // * @see Throwable#getMessage() // */ // public AuthenticationException(String detail) // { // super(detail); // } // // /** // * Constructs a new instance of <code>AuthenticationException</code> with a // * detailed message and a root exception. // * // * @param detail a possibly <code>null</code> string containing details of // * the exception. // * @param ex a possibly <code>null</code> root exception that caused this // * exception. // * @see Throwable#getMessage() // * @see SaslException#getCause() // */ // public AuthenticationException(String detail, Throwable ex) // { // super(detail, ex); // } // // // Class methods // // ------------------------------------------------------------------------- // // // Instance methods // // ------------------------------------------------------------------------- // }
import gnu.java.security.Registry; import gnu.java.security.util.Util; import gnu.javax.crypto.sasl.IAuthInfoProvider; import gnu.javax.crypto.sasl.NoSuchUserException; import java.io.IOException; import java.util.HashMap; import java.util.Map; import gnusasl.javax.security.sasl.AuthenticationException;
{ passwordFile = null; } public boolean contains(String userName) throws AuthenticationException { if (passwordFile == null) throw new AuthenticationException("contains()", new IllegalStateException()); boolean result = false; try { result = passwordFile.contains(userName); } catch (IOException x) { throw new AuthenticationException("contains()", x); } return result; } public Map lookup(Map userID) throws AuthenticationException { if (passwordFile == null) throw new AuthenticationException("lookup()", new IllegalStateException()); Map result = new HashMap(); try { String userName = (String) userID.get(Registry.SASL_USERNAME); if (userName == null)
// Path: classpath-0.98/gnu/javax/crypto/sasl/IAuthInfoProvider.java // public interface IAuthInfoProvider // { // /** // * Activates (initialises) this provider instance. SHOULD be the first method // * invoked on the provider. // * // * @param context a collection of name-value bindings describing the // * activation context. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // void activate(Map context) throws AuthenticationException; // // /** // * Passivates (releases) this provider instance. SHOULD be the last method // * invoked on the provider. Once it is done, no other method may be invoked on // * the same instance before it is <i>activated</i> agains. // * // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // void passivate() throws AuthenticationException; // // /** // * Checks if a user with a designated name is known to this provider. // * // * @param userName the name of a user to check. // * @return <code>true</code> if the user with the designated name is known // * to this provider; <code>false</code> otherwise. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // boolean contains(String userName) throws AuthenticationException; // // /** // * Returns a collection of information about a designated user. The contents // * of the returned map is provider-specific of name-to-value mappings. // * // * @param userID a map of name-to-value bindings that fully describe a user. // * @return a collection of information about the designated user. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // Map lookup(Map userID) throws AuthenticationException; // // /** // * Updates the credentials of a designated user. // * // * @param userCredentials a map of name-to-value bindings that fully describe // * a user, including per new credentials. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // void update(Map userCredentials) throws AuthenticationException; // // /** // * A provider may operate in more than mode; e.g. SRP-II caters for user // * credentials computed in more than one message digest algorithm. This method // * returns the set of name-to-value bindings describing the mode of the // * provider. // * // * @param mode a unique identifier describing the operational mode. // * @return a collection of name-to-value bindings describing the designated // * mode. // * @throws AuthenticationException if an exception occurs during the // * operation. // */ // Map getConfiguration(String mode) throws AuthenticationException; // } // // Path: classpath-0.98/gnu/javax/crypto/sasl/NoSuchUserException.java // public class NoSuchUserException // extends AuthenticationException // { // /** Constructs a <code>NoSuchUserException</code> with no detail message. */ // public NoSuchUserException() // { // super(); // } // // /** // * Constructs a <code>NoSuchUserException</code> with the specified detail // * message. In the case of this exception, the detail message designates the // * offending username. // * // * @param arg the detail message, which in this case is the username. // */ // public NoSuchUserException(String arg) // { // super(arg); // } // } // // Path: classpath-0.98/javax/security/sasl/AuthenticationException.java // public class AuthenticationException extends SaslException // { // // // Constants and variables // // ------------------------------------------------------------------------- // // // Constructor(s) // // ------------------------------------------------------------------------- // // /** // * Constructs a new instance of <code>AuthenticationException</code>. The // * root exception and the detailed message are <code>null</code>. // */ // public AuthenticationException() // { // super(); // } // // /** // * Constructs a new instance of <code>AuthenticationException</code> with a // * detailed message. The root exception is <code>null</code>. // * // * @param detail a possibly <code>null</code> string containing details of // * the exception. // * @see Throwable#getMessage() // */ // public AuthenticationException(String detail) // { // super(detail); // } // // /** // * Constructs a new instance of <code>AuthenticationException</code> with a // * detailed message and a root exception. // * // * @param detail a possibly <code>null</code> string containing details of // * the exception. // * @param ex a possibly <code>null</code> root exception that caused this // * exception. // * @see Throwable#getMessage() // * @see SaslException#getCause() // */ // public AuthenticationException(String detail, Throwable ex) // { // super(detail, ex); // } // // // Class methods // // ------------------------------------------------------------------------- // // // Instance methods // // ------------------------------------------------------------------------- // } // Path: classpath-0.98/gnu/javax/crypto/sasl/srp/SRPAuthInfoProvider.java import gnu.java.security.Registry; import gnu.java.security.util.Util; import gnu.javax.crypto.sasl.IAuthInfoProvider; import gnu.javax.crypto.sasl.NoSuchUserException; import java.io.IOException; import java.util.HashMap; import java.util.Map; import gnusasl.javax.security.sasl.AuthenticationException; { passwordFile = null; } public boolean contains(String userName) throws AuthenticationException { if (passwordFile == null) throw new AuthenticationException("contains()", new IllegalStateException()); boolean result = false; try { result = passwordFile.contains(userName); } catch (IOException x) { throw new AuthenticationException("contains()", x); } return result; } public Map lookup(Map userID) throws AuthenticationException { if (passwordFile == null) throw new AuthenticationException("lookup()", new IllegalStateException()); Map result = new HashMap(); try { String userName = (String) userID.get(Registry.SASL_USERNAME); if (userName == null)
throw new NoSuchUserException("");
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/StringTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException;
public short getAsShort() { return Short.parseShort(value); } @Override public int getAsInt() { return Integer.parseInt(value); } @Override public long getAsLong() { return Long.parseLong(value); } @Override public float getAsFloat() { return Float.parseFloat(value); } @Override public double getAsDouble() { return Double.parseDouble(value); } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/StringTag.java import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; public short getAsShort() { return Short.parseShort(value); } @Override public int getAsInt() { return Integer.parseInt(value); } @Override public long getAsLong() { return Long.parseLong(value); } @Override public float getAsFloat() { return Float.parseFloat(value); } @Override public double getAsDouble() { return Double.parseDouble(value); } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override
public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/StringTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException;
} @Override public long getAsLong() { return Long.parseLong(value); } @Override public float getAsFloat() { return Float.parseFloat(value); } @Override public double getAsDouble() { return Double.parseDouble(value); } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { byte[] bytes = new byte[in.readShort()]; in.readFully(bytes); value = new String(bytes, NBTInputStream.UTF_8); } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/StringTag.java import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; } @Override public long getAsLong() { return Long.parseLong(value); } @Override public float getAsFloat() { return Float.parseFloat(value); } @Override public double getAsDouble() { return Double.parseDouble(value); } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { byte[] bytes = new byte[in.readShort()]; in.readFully(bytes); value = new String(bytes, NBTInputStream.UTF_8); } @Override
public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/LongTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException;
package org.inventivetalent.nbt; public class LongTag extends NumberTag<Long> { private long value; public LongTag() { this(0); } public LongTag(long value) { super(""); this.value = value; } public LongTag(String name) { super(name); } public LongTag(String name, long value) { super(name); this.value = value; } @Override public Long getValue() { return value; } @Override public void setValue(Long aLong) { this.value = aLong; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/LongTag.java import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; package org.inventivetalent.nbt; public class LongTag extends NumberTag<Long> { private long value; public LongTag() { this(0); } public LongTag(long value) { super(""); this.value = value; } public LongTag(String name) { super(name); } public LongTag(String name, long value) { super(name); this.value = value; } @Override public Long getValue() { return value; } @Override public void setValue(Long aLong) { this.value = aLong; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override
public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/LongTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException;
public LongTag(String name) { super(name); } public LongTag(String name, long value) { super(name); this.value = value; } @Override public Long getValue() { return value; } @Override public void setValue(Long aLong) { this.value = aLong; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { value = in.readLong(); } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/LongTag.java import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; public LongTag(String name) { super(name); } public LongTag(String name, long value) { super(name); this.value = value; } @Override public Long getValue() { return value; } @Override public void setValue(Long aLong) { this.value = aLong; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { value = in.readLong(); } @Override
public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/IntArrayTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.common.primitives.Ints; import com.google.gson.JsonArray; import com.google.gson.JsonPrimitive; import org.apache.commons.lang.ArrayUtils; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.List;
public IntArrayTag(String name, int[] value) { super(name); this.value = value; } public IntArrayTag(String name, List<Integer> list) { super(name); this.value = ArrayUtils.toPrimitive(list.toArray(new Integer[list.size()])); } @Override public int[] getValue() { return value; } @Override public void setValue(int[] value) { this.value = value; } @Override public JsonArray asJson() { JsonArray jsonArray = new JsonArray(); for (int i : value) { jsonArray.add(new JsonPrimitive(i)); } return jsonArray; } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/IntArrayTag.java import com.google.common.primitives.Ints; import com.google.gson.JsonArray; import com.google.gson.JsonPrimitive; import org.apache.commons.lang.ArrayUtils; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.List; public IntArrayTag(String name, int[] value) { super(name); this.value = value; } public IntArrayTag(String name, List<Integer> list) { super(name); this.value = ArrayUtils.toPrimitive(list.toArray(new Integer[list.size()])); } @Override public int[] getValue() { return value; } @Override public void setValue(int[] value) { this.value = value; } @Override public JsonArray asJson() { JsonArray jsonArray = new JsonArray(); for (int i : value) { jsonArray.add(new JsonPrimitive(i)); } return jsonArray; } @Override
public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/IntArrayTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.common.primitives.Ints; import com.google.gson.JsonArray; import com.google.gson.JsonPrimitive; import org.apache.commons.lang.ArrayUtils; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.List;
@Override public int[] getValue() { return value; } @Override public void setValue(int[] value) { this.value = value; } @Override public JsonArray asJson() { JsonArray jsonArray = new JsonArray(); for (int i : value) { jsonArray.add(new JsonPrimitive(i)); } return jsonArray; } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { int[] ints = new int[in.readInt()]; for (int i = 0; i < ints.length; i++) { ints[i] = in.readInt(); } value = ints; } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/IntArrayTag.java import com.google.common.primitives.Ints; import com.google.gson.JsonArray; import com.google.gson.JsonPrimitive; import org.apache.commons.lang.ArrayUtils; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.List; @Override public int[] getValue() { return value; } @Override public void setValue(int[] value) { this.value = value; } @Override public JsonArray asJson() { JsonArray jsonArray = new JsonArray(); for (int i : value) { jsonArray.add(new JsonPrimitive(i)); } return jsonArray; } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { int[] ints = new int[in.readInt()]; for (int i = 0; i < ints.length; i++) { ints[i] = in.readInt(); } value = ints; } @Override
public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/ByteTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException;
package org.inventivetalent.nbt; public class ByteTag extends NumberTag<Byte> { private byte value; public ByteTag() { this((byte) 0); } public ByteTag(byte value) { super(""); this.value = value; } public ByteTag(String name) { super(name); } public ByteTag(String name, byte value) { super(name); this.value = value; } @Override public Byte getValue() { return value; } @Override public void setValue(Byte aByte) { this.value = aByte; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/ByteTag.java import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; package org.inventivetalent.nbt; public class ByteTag extends NumberTag<Byte> { private byte value; public ByteTag() { this((byte) 0); } public ByteTag(byte value) { super(""); this.value = value; } public ByteTag(String name) { super(name); } public ByteTag(String name, byte value) { super(name); this.value = value; } @Override public Byte getValue() { return value; } @Override public void setValue(Byte aByte) { this.value = aByte; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override
public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/ByteTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException;
public ByteTag(String name) { super(name); } public ByteTag(String name, byte value) { super(name); this.value = value; } @Override public Byte getValue() { return value; } @Override public void setValue(Byte aByte) { this.value = aByte; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { value = in.readByte(); } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/ByteTag.java import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; public ByteTag(String name) { super(name); } public ByteTag(String name, byte value) { super(name); this.value = value; } @Override public Byte getValue() { return value; } @Override public void setValue(Byte aByte) { this.value = aByte; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { value = in.readByte(); } @Override
public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/annotation/NBTField.java
// Path: src/main/java/org/inventivetalent/nbt/NBTTag.java // public abstract class NBTTag<V> { // // public static NMSClassResolver NMS_CLASS_RESOLVER = new NMSClassResolver(); // // private final String name; // // public NBTTag(String name) { // this.name = name; // } // // public NBTTag(String name, Object nmsTag) { // this.name = name; // // } // // public static NBTTag createType(int type) throws IllegalAccessException, InstantiationException { // return forType(type).newInstance(); // } // // public static NBTTag createType(int type, String name) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { // return forType(type).getConstructor(String.class).newInstance(name); // } // // public static Class<? extends NBTTag> forType(int type) { // switch (type) { // case TAG_BYTE_ARRAY: // return ByteArrayTag.class; // case TAG_BYTE: // return ByteTag.class; // case TAG_COMPOUND: // return CompoundTag.class; // case TAG_DOUBLE: // return DoubleTag.class; // case TAG_END: // return EndTag.class; // case TAG_FLOAT: // return FloatTag.class; // case TAG_INT_ARRAY: // return IntArrayTag.class; // case TAG_INT: // return IntTag.class; // case TAG_LIST: // return ListTag.class; // case TAG_LONG: // return LongTag.class; // case TAG_SHORT: // return ShortTag.class; // case TAG_STRING: // return StringTag.class; // case TAG_LONG_ARRAY: // return LongArrayTag.class; // default: // throw new IllegalArgumentException("Invalid NBTTag type " + type); // } // } // // public String getName() { // return name; // } // // public abstract V getValue(); // // public abstract void setValue(V v); // // // getAs methods // // public Number getAsNumber() { // return 0; // } // // public byte getAsByte() { // return getAsNumber().byteValue(); // } // // public short getAsShort() { // return getAsNumber().shortValue(); // } // // public int getAsInt() { // return getAsNumber().intValue(); // } // // public long getAsLong() { // return getAsNumber().longValue(); // } // // public float getAsFloat() { // return getAsNumber().floatValue(); // } // // public double getAsDouble() { // return getAsNumber().doubleValue(); // } // // public String getAsString() { // return String.valueOf(getValue()); // } // // // /getAs methods // // public abstract JsonElement asJson(); // // public abstract int getTypeId(); // // public abstract String getTypeName(); // // public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { // } // // public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException { // } // // public String getNMSClass() { // return "NBTBase"; // } // // public NBTTag fromNMS(Object nms) throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Field field = clazz.getDeclaredField("data"); // field.setAccessible(true); // setValue((V) field.get(nms)); // return this; // } // // public Object toNMS() throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Constructor constructor = null; // for (Constructor constr : clazz.getConstructors()) { // if (constr.getParameterTypes().length == 1) { // constructor = constr; // break; // } // } // if (constructor == null) { return null; } // return constructor.newInstance(getValue()); // } // // @Override // public String toString() { // return getTypeName() + "(" + getName() + "): " + getValue(); // } // }
import org.inventivetalent.nbt.NBTTag; import java.lang.reflect.Field;
package org.inventivetalent.nbt.annotation; public class NBTField extends NBTMember { private final Field field; public NBTField(String[] key, int type, boolean read, boolean write, NBTPriority priority, Object obj, Field field) { super(key, type, read, write, priority, obj); this.field = field; } @Override
// Path: src/main/java/org/inventivetalent/nbt/NBTTag.java // public abstract class NBTTag<V> { // // public static NMSClassResolver NMS_CLASS_RESOLVER = new NMSClassResolver(); // // private final String name; // // public NBTTag(String name) { // this.name = name; // } // // public NBTTag(String name, Object nmsTag) { // this.name = name; // // } // // public static NBTTag createType(int type) throws IllegalAccessException, InstantiationException { // return forType(type).newInstance(); // } // // public static NBTTag createType(int type, String name) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { // return forType(type).getConstructor(String.class).newInstance(name); // } // // public static Class<? extends NBTTag> forType(int type) { // switch (type) { // case TAG_BYTE_ARRAY: // return ByteArrayTag.class; // case TAG_BYTE: // return ByteTag.class; // case TAG_COMPOUND: // return CompoundTag.class; // case TAG_DOUBLE: // return DoubleTag.class; // case TAG_END: // return EndTag.class; // case TAG_FLOAT: // return FloatTag.class; // case TAG_INT_ARRAY: // return IntArrayTag.class; // case TAG_INT: // return IntTag.class; // case TAG_LIST: // return ListTag.class; // case TAG_LONG: // return LongTag.class; // case TAG_SHORT: // return ShortTag.class; // case TAG_STRING: // return StringTag.class; // case TAG_LONG_ARRAY: // return LongArrayTag.class; // default: // throw new IllegalArgumentException("Invalid NBTTag type " + type); // } // } // // public String getName() { // return name; // } // // public abstract V getValue(); // // public abstract void setValue(V v); // // // getAs methods // // public Number getAsNumber() { // return 0; // } // // public byte getAsByte() { // return getAsNumber().byteValue(); // } // // public short getAsShort() { // return getAsNumber().shortValue(); // } // // public int getAsInt() { // return getAsNumber().intValue(); // } // // public long getAsLong() { // return getAsNumber().longValue(); // } // // public float getAsFloat() { // return getAsNumber().floatValue(); // } // // public double getAsDouble() { // return getAsNumber().doubleValue(); // } // // public String getAsString() { // return String.valueOf(getValue()); // } // // // /getAs methods // // public abstract JsonElement asJson(); // // public abstract int getTypeId(); // // public abstract String getTypeName(); // // public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { // } // // public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException { // } // // public String getNMSClass() { // return "NBTBase"; // } // // public NBTTag fromNMS(Object nms) throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Field field = clazz.getDeclaredField("data"); // field.setAccessible(true); // setValue((V) field.get(nms)); // return this; // } // // public Object toNMS() throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Constructor constructor = null; // for (Constructor constr : clazz.getConstructors()) { // if (constr.getParameterTypes().length == 1) { // constructor = constr; // break; // } // } // if (constructor == null) { return null; } // return constructor.newInstance(getValue()); // } // // @Override // public String toString() { // return getTypeName() + "(" + getName() + "): " + getValue(); // } // } // Path: src/main/java/org/inventivetalent/nbt/annotation/NBTField.java import org.inventivetalent.nbt.NBTTag; import java.lang.reflect.Field; package org.inventivetalent.nbt.annotation; public class NBTField extends NBTMember { private final Field field; public NBTField(String[] key, int type, boolean read, boolean write, NBTPriority priority, Object obj, Field field) { super(key, type, read, write, priority, obj); this.field = field; } @Override
public void read(NBTTag tag) {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/LongArrayTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.common.primitives.Longs; import com.google.gson.JsonArray; import com.google.gson.JsonPrimitive; import org.apache.commons.lang.ArrayUtils; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.List;
public LongArrayTag(String name, long[] value) { super(name); this.value = value; } public LongArrayTag(String name, List<Long> list) { super(name); this.value = ArrayUtils.toPrimitive(list.toArray(new Long[list.size()])); } @Override public long[] getValue() { return value; } @Override public void setValue(long[] value) { this.value = value; } @Override public JsonArray asJson() { JsonArray jsonArray = new JsonArray(); for (long l : value) { jsonArray.add(new JsonPrimitive(l)); } return jsonArray; } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/LongArrayTag.java import com.google.common.primitives.Longs; import com.google.gson.JsonArray; import com.google.gson.JsonPrimitive; import org.apache.commons.lang.ArrayUtils; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.List; public LongArrayTag(String name, long[] value) { super(name); this.value = value; } public LongArrayTag(String name, List<Long> list) { super(name); this.value = ArrayUtils.toPrimitive(list.toArray(new Long[list.size()])); } @Override public long[] getValue() { return value; } @Override public void setValue(long[] value) { this.value = value; } @Override public JsonArray asJson() { JsonArray jsonArray = new JsonArray(); for (long l : value) { jsonArray.add(new JsonPrimitive(l)); } return jsonArray; } @Override
public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/LongArrayTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.common.primitives.Longs; import com.google.gson.JsonArray; import com.google.gson.JsonPrimitive; import org.apache.commons.lang.ArrayUtils; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.List;
@Override public long[] getValue() { return value; } @Override public void setValue(long[] value) { this.value = value; } @Override public JsonArray asJson() { JsonArray jsonArray = new JsonArray(); for (long l : value) { jsonArray.add(new JsonPrimitive(l)); } return jsonArray; } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { long[] longs = new long[in.readInt()]; for (int i = 0; i < longs.length; i++) { longs[i] = in.readLong(); } value = longs; } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/LongArrayTag.java import com.google.common.primitives.Longs; import com.google.gson.JsonArray; import com.google.gson.JsonPrimitive; import org.apache.commons.lang.ArrayUtils; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.List; @Override public long[] getValue() { return value; } @Override public void setValue(long[] value) { this.value = value; } @Override public JsonArray asJson() { JsonArray jsonArray = new JsonArray(); for (long l : value) { jsonArray.add(new JsonPrimitive(l)); } return jsonArray; } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { long[] longs = new long[in.readInt()]; for (int i = 0; i < longs.length; i++) { longs[i] = in.readLong(); } value = longs; } @Override
public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/ByteArrayTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.common.primitives.Bytes; import com.google.gson.JsonArray; import com.google.gson.JsonPrimitive; import org.apache.commons.lang.ArrayUtils; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Iterator;
public ByteArrayTag(String name, byte[] value) { super(name); this.value = value; } public ByteArrayTag(String name, Collection<Byte> list) { super(name); this.value = ArrayUtils.toPrimitive(list.toArray(new Byte[list.size()])); } @Override public byte[] getValue() { return value; } @Override public void setValue(byte[] value) { this.value = value; } @Override public JsonArray asJson() { JsonArray jsonArray = new JsonArray(); for (byte b : value) { jsonArray.add(new JsonPrimitive(b)); } return jsonArray; } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/ByteArrayTag.java import com.google.common.primitives.Bytes; import com.google.gson.JsonArray; import com.google.gson.JsonPrimitive; import org.apache.commons.lang.ArrayUtils; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; public ByteArrayTag(String name, byte[] value) { super(name); this.value = value; } public ByteArrayTag(String name, Collection<Byte> list) { super(name); this.value = ArrayUtils.toPrimitive(list.toArray(new Byte[list.size()])); } @Override public byte[] getValue() { return value; } @Override public void setValue(byte[] value) { this.value = value; } @Override public JsonArray asJson() { JsonArray jsonArray = new JsonArray(); for (byte b : value) { jsonArray.add(new JsonPrimitive(b)); } return jsonArray; } @Override
public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/ByteArrayTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.common.primitives.Bytes; import com.google.gson.JsonArray; import com.google.gson.JsonPrimitive; import org.apache.commons.lang.ArrayUtils; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Iterator;
this.value = ArrayUtils.toPrimitive(list.toArray(new Byte[list.size()])); } @Override public byte[] getValue() { return value; } @Override public void setValue(byte[] value) { this.value = value; } @Override public JsonArray asJson() { JsonArray jsonArray = new JsonArray(); for (byte b : value) { jsonArray.add(new JsonPrimitive(b)); } return jsonArray; } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { byte[] bytes = new byte[in.readInt()]; in.readFully(bytes); value = bytes; } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/ByteArrayTag.java import com.google.common.primitives.Bytes; import com.google.gson.JsonArray; import com.google.gson.JsonPrimitive; import org.apache.commons.lang.ArrayUtils; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; this.value = ArrayUtils.toPrimitive(list.toArray(new Byte[list.size()])); } @Override public byte[] getValue() { return value; } @Override public void setValue(byte[] value) { this.value = value; } @Override public JsonArray asJson() { JsonArray jsonArray = new JsonArray(); for (byte b : value) { jsonArray.add(new JsonPrimitive(b)); } return jsonArray; } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { byte[] bytes = new byte[in.readInt()]; in.readFully(bytes); value = bytes; } @Override
public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/ListTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/TagID.java // public static final int TAG_END = 0;
import com.google.gson.JsonArray; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import static org.inventivetalent.nbt.TagID.TAG_END;
public void add(V tag) { if (tag.getTypeId() != getTagType()) { throw new IllegalArgumentException("Invalid Tag type (List: " + getTagType() + ", Tag: " + tag.getTypeId() + ")"); } value.add(tag); } public void add(int index, V tag) { if (tag.getTypeId() != getTagType()) { throw new IllegalArgumentException("Invalid Tag type (List: " + getTagType() + ", Tag: " + tag.getTypeId() + ")"); } value.add(index, tag); } public void set(int index, V tag) { if (tag.getTypeId() != getTagType()) { throw new IllegalArgumentException("Invalid Tag type (List: " + getTagType() + ", Tag: " + tag.getTypeId() + ")"); } value.set(index, tag); } public int size() { return value.size(); } @Override public JsonArray asJson() { JsonArray jsonArray = new JsonArray(); for (NBTTag tag : value) { jsonArray.add(tag.asJson()); } return jsonArray; } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/TagID.java // public static final int TAG_END = 0; // Path: src/main/java/org/inventivetalent/nbt/ListTag.java import com.google.gson.JsonArray; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import static org.inventivetalent.nbt.TagID.TAG_END; public void add(V tag) { if (tag.getTypeId() != getTagType()) { throw new IllegalArgumentException("Invalid Tag type (List: " + getTagType() + ", Tag: " + tag.getTypeId() + ")"); } value.add(tag); } public void add(int index, V tag) { if (tag.getTypeId() != getTagType()) { throw new IllegalArgumentException("Invalid Tag type (List: " + getTagType() + ", Tag: " + tag.getTypeId() + ")"); } value.add(index, tag); } public void set(int index, V tag) { if (tag.getTypeId() != getTagType()) { throw new IllegalArgumentException("Invalid Tag type (List: " + getTagType() + ", Tag: " + tag.getTypeId() + ")"); } value.set(index, tag); } public int size() { return value.size(); } @Override public JsonArray asJson() { JsonArray jsonArray = new JsonArray(); for (NBTTag tag : value) { jsonArray.add(tag.asJson()); } return jsonArray; } @Override
public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/ListTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/TagID.java // public static final int TAG_END = 0;
import com.google.gson.JsonArray; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import static org.inventivetalent.nbt.TagID.TAG_END;
public void add(int index, V tag) { if (tag.getTypeId() != getTagType()) { throw new IllegalArgumentException("Invalid Tag type (List: " + getTagType() + ", Tag: " + tag.getTypeId() + ")"); } value.add(index, tag); } public void set(int index, V tag) { if (tag.getTypeId() != getTagType()) { throw new IllegalArgumentException("Invalid Tag type (List: " + getTagType() + ", Tag: " + tag.getTypeId() + ")"); } value.set(index, tag); } public int size() { return value.size(); } @Override public JsonArray asJson() { JsonArray jsonArray = new JsonArray(); for (NBTTag tag : value) { jsonArray.add(tag.asJson()); } return jsonArray; } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { int type = in.readByte(); int length = in.readInt(); setTagType(type); for (int i = 0; i < length; i++) { NBTTag tag = nbtIn.readTagContent(type, "", depth + 1);
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/TagID.java // public static final int TAG_END = 0; // Path: src/main/java/org/inventivetalent/nbt/ListTag.java import com.google.gson.JsonArray; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import static org.inventivetalent.nbt.TagID.TAG_END; public void add(int index, V tag) { if (tag.getTypeId() != getTagType()) { throw new IllegalArgumentException("Invalid Tag type (List: " + getTagType() + ", Tag: " + tag.getTypeId() + ")"); } value.add(index, tag); } public void set(int index, V tag) { if (tag.getTypeId() != getTagType()) { throw new IllegalArgumentException("Invalid Tag type (List: " + getTagType() + ", Tag: " + tag.getTypeId() + ")"); } value.set(index, tag); } public int size() { return value.size(); } @Override public JsonArray asJson() { JsonArray jsonArray = new JsonArray(); for (NBTTag tag : value) { jsonArray.add(tag.asJson()); } return jsonArray; } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { int type = in.readByte(); int length = in.readInt(); setTagType(type); for (int i = 0; i < length; i++) { NBTTag tag = nbtIn.readTagContent(type, "", depth + 1);
if (tag.getTypeId() == TAG_END) {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/ListTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/TagID.java // public static final int TAG_END = 0;
import com.google.gson.JsonArray; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import static org.inventivetalent.nbt.TagID.TAG_END;
} public int size() { return value.size(); } @Override public JsonArray asJson() { JsonArray jsonArray = new JsonArray(); for (NBTTag tag : value) { jsonArray.add(tag.asJson()); } return jsonArray; } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { int type = in.readByte(); int length = in.readInt(); setTagType(type); for (int i = 0; i < length; i++) { NBTTag tag = nbtIn.readTagContent(type, "", depth + 1); if (tag.getTypeId() == TAG_END) { throw new IOException("Invalid TAG_End in TAG_List (not allowed)"); } add((V) tag); } } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/TagID.java // public static final int TAG_END = 0; // Path: src/main/java/org/inventivetalent/nbt/ListTag.java import com.google.gson.JsonArray; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import static org.inventivetalent.nbt.TagID.TAG_END; } public int size() { return value.size(); } @Override public JsonArray asJson() { JsonArray jsonArray = new JsonArray(); for (NBTTag tag : value) { jsonArray.add(tag.asJson()); } return jsonArray; } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { int type = in.readByte(); int length = in.readInt(); setTagType(type); for (int i = 0; i < length; i++) { NBTTag tag = nbtIn.readTagContent(type, "", depth + 1); if (tag.getTypeId() == TAG_END) { throw new IOException("Invalid TAG_End in TAG_List (not allowed)"); } add((V) tag); } } @Override
public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/FloatTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException;
package org.inventivetalent.nbt; public class FloatTag extends NumberTag<Float> { private float value; public FloatTag() { this(0); } public FloatTag(float value) { super(""); this.value = value; } public FloatTag(String name) { super(name); } public FloatTag(String name, float value) { super(name); this.value = value; } @Override public Float getValue() { return value; } @Override public void setValue(Float aFloat) { this.value = aFloat; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/FloatTag.java import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; package org.inventivetalent.nbt; public class FloatTag extends NumberTag<Float> { private float value; public FloatTag() { this(0); } public FloatTag(float value) { super(""); this.value = value; } public FloatTag(String name) { super(name); } public FloatTag(String name, float value) { super(name); this.value = value; } @Override public Float getValue() { return value; } @Override public void setValue(Float aFloat) { this.value = aFloat; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override
public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/FloatTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException;
public FloatTag(String name) { super(name); } public FloatTag(String name, float value) { super(name); this.value = value; } @Override public Float getValue() { return value; } @Override public void setValue(Float aFloat) { this.value = aFloat; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { value = in.readFloat(); } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/FloatTag.java import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; public FloatTag(String name) { super(name); } public FloatTag(String name, float value) { super(name); this.value = value; } @Override public Float getValue() { return value; } @Override public void setValue(Float aFloat) { this.value = aFloat; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { value = in.readFloat(); } @Override
public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/annotation/NBTParameter.java
// Path: src/main/java/org/inventivetalent/nbt/NBTTag.java // public abstract class NBTTag<V> { // // public static NMSClassResolver NMS_CLASS_RESOLVER = new NMSClassResolver(); // // private final String name; // // public NBTTag(String name) { // this.name = name; // } // // public NBTTag(String name, Object nmsTag) { // this.name = name; // // } // // public static NBTTag createType(int type) throws IllegalAccessException, InstantiationException { // return forType(type).newInstance(); // } // // public static NBTTag createType(int type, String name) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { // return forType(type).getConstructor(String.class).newInstance(name); // } // // public static Class<? extends NBTTag> forType(int type) { // switch (type) { // case TAG_BYTE_ARRAY: // return ByteArrayTag.class; // case TAG_BYTE: // return ByteTag.class; // case TAG_COMPOUND: // return CompoundTag.class; // case TAG_DOUBLE: // return DoubleTag.class; // case TAG_END: // return EndTag.class; // case TAG_FLOAT: // return FloatTag.class; // case TAG_INT_ARRAY: // return IntArrayTag.class; // case TAG_INT: // return IntTag.class; // case TAG_LIST: // return ListTag.class; // case TAG_LONG: // return LongTag.class; // case TAG_SHORT: // return ShortTag.class; // case TAG_STRING: // return StringTag.class; // case TAG_LONG_ARRAY: // return LongArrayTag.class; // default: // throw new IllegalArgumentException("Invalid NBTTag type " + type); // } // } // // public String getName() { // return name; // } // // public abstract V getValue(); // // public abstract void setValue(V v); // // // getAs methods // // public Number getAsNumber() { // return 0; // } // // public byte getAsByte() { // return getAsNumber().byteValue(); // } // // public short getAsShort() { // return getAsNumber().shortValue(); // } // // public int getAsInt() { // return getAsNumber().intValue(); // } // // public long getAsLong() { // return getAsNumber().longValue(); // } // // public float getAsFloat() { // return getAsNumber().floatValue(); // } // // public double getAsDouble() { // return getAsNumber().doubleValue(); // } // // public String getAsString() { // return String.valueOf(getValue()); // } // // // /getAs methods // // public abstract JsonElement asJson(); // // public abstract int getTypeId(); // // public abstract String getTypeName(); // // public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { // } // // public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException { // } // // public String getNMSClass() { // return "NBTBase"; // } // // public NBTTag fromNMS(Object nms) throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Field field = clazz.getDeclaredField("data"); // field.setAccessible(true); // setValue((V) field.get(nms)); // return this; // } // // public Object toNMS() throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Constructor constructor = null; // for (Constructor constr : clazz.getConstructors()) { // if (constr.getParameterTypes().length == 1) { // constructor = constr; // break; // } // } // if (constructor == null) { return null; } // return constructor.newInstance(getValue()); // } // // @Override // public String toString() { // return getTypeName() + "(" + getName() + "): " + getValue(); // } // }
import org.inventivetalent.nbt.NBTTag; import java.lang.reflect.Method; import java.lang.reflect.Parameter;
package org.inventivetalent.nbt.annotation; public class NBTParameter extends NBTMember { protected final Parameter parameter; public NBTParameter(String[] key, int type, boolean read, boolean write, NBTPriority priority, Method method, Parameter parameter) { super(key, type, read, write, priority, method); this.parameter = parameter; } @Override
// Path: src/main/java/org/inventivetalent/nbt/NBTTag.java // public abstract class NBTTag<V> { // // public static NMSClassResolver NMS_CLASS_RESOLVER = new NMSClassResolver(); // // private final String name; // // public NBTTag(String name) { // this.name = name; // } // // public NBTTag(String name, Object nmsTag) { // this.name = name; // // } // // public static NBTTag createType(int type) throws IllegalAccessException, InstantiationException { // return forType(type).newInstance(); // } // // public static NBTTag createType(int type, String name) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { // return forType(type).getConstructor(String.class).newInstance(name); // } // // public static Class<? extends NBTTag> forType(int type) { // switch (type) { // case TAG_BYTE_ARRAY: // return ByteArrayTag.class; // case TAG_BYTE: // return ByteTag.class; // case TAG_COMPOUND: // return CompoundTag.class; // case TAG_DOUBLE: // return DoubleTag.class; // case TAG_END: // return EndTag.class; // case TAG_FLOAT: // return FloatTag.class; // case TAG_INT_ARRAY: // return IntArrayTag.class; // case TAG_INT: // return IntTag.class; // case TAG_LIST: // return ListTag.class; // case TAG_LONG: // return LongTag.class; // case TAG_SHORT: // return ShortTag.class; // case TAG_STRING: // return StringTag.class; // case TAG_LONG_ARRAY: // return LongArrayTag.class; // default: // throw new IllegalArgumentException("Invalid NBTTag type " + type); // } // } // // public String getName() { // return name; // } // // public abstract V getValue(); // // public abstract void setValue(V v); // // // getAs methods // // public Number getAsNumber() { // return 0; // } // // public byte getAsByte() { // return getAsNumber().byteValue(); // } // // public short getAsShort() { // return getAsNumber().shortValue(); // } // // public int getAsInt() { // return getAsNumber().intValue(); // } // // public long getAsLong() { // return getAsNumber().longValue(); // } // // public float getAsFloat() { // return getAsNumber().floatValue(); // } // // public double getAsDouble() { // return getAsNumber().doubleValue(); // } // // public String getAsString() { // return String.valueOf(getValue()); // } // // // /getAs methods // // public abstract JsonElement asJson(); // // public abstract int getTypeId(); // // public abstract String getTypeName(); // // public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { // } // // public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException { // } // // public String getNMSClass() { // return "NBTBase"; // } // // public NBTTag fromNMS(Object nms) throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Field field = clazz.getDeclaredField("data"); // field.setAccessible(true); // setValue((V) field.get(nms)); // return this; // } // // public Object toNMS() throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Constructor constructor = null; // for (Constructor constr : clazz.getConstructors()) { // if (constr.getParameterTypes().length == 1) { // constructor = constr; // break; // } // } // if (constructor == null) { return null; } // return constructor.newInstance(getValue()); // } // // @Override // public String toString() { // return getTypeName() + "(" + getName() + "): " + getValue(); // } // } // Path: src/main/java/org/inventivetalent/nbt/annotation/NBTParameter.java import org.inventivetalent.nbt.NBTTag; import java.lang.reflect.Method; import java.lang.reflect.Parameter; package org.inventivetalent.nbt.annotation; public class NBTParameter extends NBTMember { protected final Parameter parameter; public NBTParameter(String[] key, int type, boolean read, boolean write, NBTPriority priority, Method method, Parameter parameter) { super(key, type, read, write, priority, method); this.parameter = parameter; } @Override
public void read(NBTTag tag) {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/EndTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.gson.JsonElement; import com.google.gson.JsonNull; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException;
package org.inventivetalent.nbt; public class EndTag extends NBTTag<Void> { public EndTag() { this(""); } public EndTag(String name) { super(name); } @Override public Void getValue() { return null; } @Override public void setValue(Void aVoid) { } @Override public JsonElement asJson() { return JsonNull.INSTANCE; } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/EndTag.java import com.google.gson.JsonElement; import com.google.gson.JsonNull; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; package org.inventivetalent.nbt; public class EndTag extends NBTTag<Void> { public EndTag() { this(""); } public EndTag(String name) { super(name); } @Override public Void getValue() { return null; } @Override public void setValue(Void aVoid) { } @Override public JsonElement asJson() { return JsonNull.INSTANCE; } @Override
public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/EndTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.gson.JsonElement; import com.google.gson.JsonNull; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException;
package org.inventivetalent.nbt; public class EndTag extends NBTTag<Void> { public EndTag() { this(""); } public EndTag(String name) { super(name); } @Override public Void getValue() { return null; } @Override public void setValue(Void aVoid) { } @Override public JsonElement asJson() { return JsonNull.INSTANCE; } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/EndTag.java import com.google.gson.JsonElement; import com.google.gson.JsonNull; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; package org.inventivetalent.nbt; public class EndTag extends NBTTag<Void> { public EndTag() { this(""); } public EndTag(String name) { super(name); } @Override public Void getValue() { return null; } @Override public void setValue(Void aVoid) { } @Override public JsonElement asJson() { return JsonNull.INSTANCE; } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { } @Override
public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java
// Path: src/main/java/org/inventivetalent/nbt/NBTTag.java // public abstract class NBTTag<V> { // // public static NMSClassResolver NMS_CLASS_RESOLVER = new NMSClassResolver(); // // private final String name; // // public NBTTag(String name) { // this.name = name; // } // // public NBTTag(String name, Object nmsTag) { // this.name = name; // // } // // public static NBTTag createType(int type) throws IllegalAccessException, InstantiationException { // return forType(type).newInstance(); // } // // public static NBTTag createType(int type, String name) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { // return forType(type).getConstructor(String.class).newInstance(name); // } // // public static Class<? extends NBTTag> forType(int type) { // switch (type) { // case TAG_BYTE_ARRAY: // return ByteArrayTag.class; // case TAG_BYTE: // return ByteTag.class; // case TAG_COMPOUND: // return CompoundTag.class; // case TAG_DOUBLE: // return DoubleTag.class; // case TAG_END: // return EndTag.class; // case TAG_FLOAT: // return FloatTag.class; // case TAG_INT_ARRAY: // return IntArrayTag.class; // case TAG_INT: // return IntTag.class; // case TAG_LIST: // return ListTag.class; // case TAG_LONG: // return LongTag.class; // case TAG_SHORT: // return ShortTag.class; // case TAG_STRING: // return StringTag.class; // case TAG_LONG_ARRAY: // return LongArrayTag.class; // default: // throw new IllegalArgumentException("Invalid NBTTag type " + type); // } // } // // public String getName() { // return name; // } // // public abstract V getValue(); // // public abstract void setValue(V v); // // // getAs methods // // public Number getAsNumber() { // return 0; // } // // public byte getAsByte() { // return getAsNumber().byteValue(); // } // // public short getAsShort() { // return getAsNumber().shortValue(); // } // // public int getAsInt() { // return getAsNumber().intValue(); // } // // public long getAsLong() { // return getAsNumber().longValue(); // } // // public float getAsFloat() { // return getAsNumber().floatValue(); // } // // public double getAsDouble() { // return getAsNumber().doubleValue(); // } // // public String getAsString() { // return String.valueOf(getValue()); // } // // // /getAs methods // // public abstract JsonElement asJson(); // // public abstract int getTypeId(); // // public abstract String getTypeName(); // // public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { // } // // public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException { // } // // public String getNMSClass() { // return "NBTBase"; // } // // public NBTTag fromNMS(Object nms) throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Field field = clazz.getDeclaredField("data"); // field.setAccessible(true); // setValue((V) field.get(nms)); // return this; // } // // public Object toNMS() throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Constructor constructor = null; // for (Constructor constr : clazz.getConstructors()) { // if (constr.getParameterTypes().length == 1) { // constructor = constr; // break; // } // } // if (constructor == null) { return null; } // return constructor.newInstance(getValue()); // } // // @Override // public String toString() { // return getTypeName() + "(" + getName() + "): " + getValue(); // } // }
import org.inventivetalent.nbt.NBTTag; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.zip.GZIPOutputStream;
package org.inventivetalent.nbt.stream; public class NBTOutputStream implements AutoCloseable { public static final Charset UTF_8 = Charset.forName("UTF-8"); private final DataOutputStream out; public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { if (gzip) { this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); } else { this.out = new DataOutputStream(outputStream); } } public NBTOutputStream(OutputStream outputStream) throws IOException { this.out = new DataOutputStream(outputStream); } public NBTOutputStream(DataOutputStream dataOutputStream) { this.out = dataOutputStream; }
// Path: src/main/java/org/inventivetalent/nbt/NBTTag.java // public abstract class NBTTag<V> { // // public static NMSClassResolver NMS_CLASS_RESOLVER = new NMSClassResolver(); // // private final String name; // // public NBTTag(String name) { // this.name = name; // } // // public NBTTag(String name, Object nmsTag) { // this.name = name; // // } // // public static NBTTag createType(int type) throws IllegalAccessException, InstantiationException { // return forType(type).newInstance(); // } // // public static NBTTag createType(int type, String name) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { // return forType(type).getConstructor(String.class).newInstance(name); // } // // public static Class<? extends NBTTag> forType(int type) { // switch (type) { // case TAG_BYTE_ARRAY: // return ByteArrayTag.class; // case TAG_BYTE: // return ByteTag.class; // case TAG_COMPOUND: // return CompoundTag.class; // case TAG_DOUBLE: // return DoubleTag.class; // case TAG_END: // return EndTag.class; // case TAG_FLOAT: // return FloatTag.class; // case TAG_INT_ARRAY: // return IntArrayTag.class; // case TAG_INT: // return IntTag.class; // case TAG_LIST: // return ListTag.class; // case TAG_LONG: // return LongTag.class; // case TAG_SHORT: // return ShortTag.class; // case TAG_STRING: // return StringTag.class; // case TAG_LONG_ARRAY: // return LongArrayTag.class; // default: // throw new IllegalArgumentException("Invalid NBTTag type " + type); // } // } // // public String getName() { // return name; // } // // public abstract V getValue(); // // public abstract void setValue(V v); // // // getAs methods // // public Number getAsNumber() { // return 0; // } // // public byte getAsByte() { // return getAsNumber().byteValue(); // } // // public short getAsShort() { // return getAsNumber().shortValue(); // } // // public int getAsInt() { // return getAsNumber().intValue(); // } // // public long getAsLong() { // return getAsNumber().longValue(); // } // // public float getAsFloat() { // return getAsNumber().floatValue(); // } // // public double getAsDouble() { // return getAsNumber().doubleValue(); // } // // public String getAsString() { // return String.valueOf(getValue()); // } // // // /getAs methods // // public abstract JsonElement asJson(); // // public abstract int getTypeId(); // // public abstract String getTypeName(); // // public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { // } // // public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException { // } // // public String getNMSClass() { // return "NBTBase"; // } // // public NBTTag fromNMS(Object nms) throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Field field = clazz.getDeclaredField("data"); // field.setAccessible(true); // setValue((V) field.get(nms)); // return this; // } // // public Object toNMS() throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Constructor constructor = null; // for (Constructor constr : clazz.getConstructors()) { // if (constr.getParameterTypes().length == 1) { // constructor = constr; // break; // } // } // if (constructor == null) { return null; } // return constructor.newInstance(getValue()); // } // // @Override // public String toString() { // return getTypeName() + "(" + getName() + "): " + getValue(); // } // } // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java import org.inventivetalent.nbt.NBTTag; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.zip.GZIPOutputStream; package org.inventivetalent.nbt.stream; public class NBTOutputStream implements AutoCloseable { public static final Charset UTF_8 = Charset.forName("UTF-8"); private final DataOutputStream out; public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { if (gzip) { this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); } else { this.out = new DataOutputStream(outputStream); } } public NBTOutputStream(OutputStream outputStream) throws IOException { this.out = new DataOutputStream(outputStream); } public NBTOutputStream(DataOutputStream dataOutputStream) { this.out = dataOutputStream; }
public void writeTag(NBTTag tag) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/CompoundTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.gson.JsonObject; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map;
throw new IllegalArgumentException("ListTag(" + name + ") is not of type " + type.getSimpleName()); } return (ListTag<V>) list; } public <V extends NBTTag> ListTag<V> getOrCreateList(String name, Class<V> type) { if (has(name)) { return getList(name, type); } ListTag<V> listTag = new ListTag<>(name, TagID.forClass(type), new ArrayList<V>()); set(name, listTag); return listTag; } public <T extends Enum<T>> T getEnum(String name, Class<T> clazz) { String string = getString(name); if (string == null) { return null; } return Enum.valueOf(clazz, string); } @Override public JsonObject asJson() { JsonObject jsonObject = new JsonObject(); for (Map.Entry<String, NBTTag> entry : value.entrySet()) { jsonObject.add(entry.getKey(), entry.getValue().asJson()); } return jsonObject; } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/CompoundTag.java import com.google.gson.JsonObject; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; throw new IllegalArgumentException("ListTag(" + name + ") is not of type " + type.getSimpleName()); } return (ListTag<V>) list; } public <V extends NBTTag> ListTag<V> getOrCreateList(String name, Class<V> type) { if (has(name)) { return getList(name, type); } ListTag<V> listTag = new ListTag<>(name, TagID.forClass(type), new ArrayList<V>()); set(name, listTag); return listTag; } public <T extends Enum<T>> T getEnum(String name, Class<T> clazz) { String string = getString(name); if (string == null) { return null; } return Enum.valueOf(clazz, string); } @Override public JsonObject asJson() { JsonObject jsonObject = new JsonObject(); for (Map.Entry<String, NBTTag> entry : value.entrySet()) { jsonObject.add(entry.getKey(), entry.getValue().asJson()); } return jsonObject; } @Override
public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/CompoundTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.gson.JsonObject; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map;
} public <T extends Enum<T>> T getEnum(String name, Class<T> clazz) { String string = getString(name); if (string == null) { return null; } return Enum.valueOf(clazz, string); } @Override public JsonObject asJson() { JsonObject jsonObject = new JsonObject(); for (Map.Entry<String, NBTTag> entry : value.entrySet()) { jsonObject.add(entry.getKey(), entry.getValue().asJson()); } return jsonObject; } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { while (true) { NBTTag tag = nbtIn.readNBTTag(depth + 1); if (tag.getTypeId() == TagID.TAG_END) { break; } else { set(tag.getName(), tag); } } } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/CompoundTag.java import com.google.gson.JsonObject; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; } public <T extends Enum<T>> T getEnum(String name, Class<T> clazz) { String string = getString(name); if (string == null) { return null; } return Enum.valueOf(clazz, string); } @Override public JsonObject asJson() { JsonObject jsonObject = new JsonObject(); for (Map.Entry<String, NBTTag> entry : value.entrySet()) { jsonObject.add(entry.getKey(), entry.getValue().asJson()); } return jsonObject; } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { while (true) { NBTTag tag = nbtIn.readNBTTag(depth + 1); if (tag.getTypeId() == TagID.TAG_END) { break; } else { set(tag.getName(), tag); } } } @Override
public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/IntTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException;
package org.inventivetalent.nbt; public class IntTag extends NumberTag<Integer> { private int value; public IntTag() { this(0); } public IntTag(int value) { super(""); this.value = value; } public IntTag(String name) { super(name); } public IntTag(String name, int value) { super(name); this.value = value; } @Override public Integer getValue() { return value; } @Override public void setValue(Integer integer) { this.value = integer; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/IntTag.java import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; package org.inventivetalent.nbt; public class IntTag extends NumberTag<Integer> { private int value; public IntTag() { this(0); } public IntTag(int value) { super(""); this.value = value; } public IntTag(String name) { super(name); } public IntTag(String name, int value) { super(name); this.value = value; } @Override public Integer getValue() { return value; } @Override public void setValue(Integer integer) { this.value = integer; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override
public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/IntTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException;
public IntTag(String name) { super(name); } public IntTag(String name, int value) { super(name); this.value = value; } @Override public Integer getValue() { return value; } @Override public void setValue(Integer integer) { this.value = integer; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { value = in.readInt(); } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/IntTag.java import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; public IntTag(String name) { super(name); } public IntTag(String name, int value) { super(name); this.value = value; } @Override public Integer getValue() { return value; } @Override public void setValue(Integer integer) { this.value = integer; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { value = in.readInt(); } @Override
public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/DoubleTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException;
package org.inventivetalent.nbt; public class DoubleTag extends NumberTag<Double> { private double value; public DoubleTag() { this(0); } public DoubleTag(double value) { super(""); this.value = value; } public DoubleTag(String name) { super(name); } public DoubleTag(String name, double value) { super(name); this.value = value; } @Override public Double getValue() { return value; } @Override public void setValue(Double aDouble) { this.value = aDouble; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/DoubleTag.java import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; package org.inventivetalent.nbt; public class DoubleTag extends NumberTag<Double> { private double value; public DoubleTag() { this(0); } public DoubleTag(double value) { super(""); this.value = value; } public DoubleTag(String name) { super(name); } public DoubleTag(String name, double value) { super(name); this.value = value; } @Override public Double getValue() { return value; } @Override public void setValue(Double aDouble) { this.value = aDouble; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override
public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/DoubleTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException;
public DoubleTag(String name) { super(name); } public DoubleTag(String name, double value) { super(name); this.value = value; } @Override public Double getValue() { return value; } @Override public void setValue(Double aDouble) { this.value = aDouble; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { value = in.readDouble(); } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/DoubleTag.java import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; public DoubleTag(String name) { super(name); } public DoubleTag(String name, double value) { super(name); this.value = value; } @Override public Double getValue() { return value; } @Override public void setValue(Double aDouble) { this.value = aDouble; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { value = in.readDouble(); } @Override
public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException {
InventivetalentDev/NBTLibrary
src/test/java/org/inventivetalent/nbt/test/StreamTest.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import org.inventivetalent.nbt.*; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import org.junit.Test; import java.io.FileOutputStream; import java.util.HashMap; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
package org.inventivetalent.nbt.test; public class StreamTest { @Test public void uncompressedInputTest() throws Exception {
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/test/java/org/inventivetalent/nbt/test/StreamTest.java import org.inventivetalent.nbt.*; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import org.junit.Test; import java.io.FileOutputStream; import java.util.HashMap; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; package org.inventivetalent.nbt.test; public class StreamTest { @Test public void uncompressedInputTest() throws Exception {
try (NBTInputStream in = new NBTInputStream(StreamTest.class.getResourceAsStream("/hello_world.nbt"))) {
InventivetalentDev/NBTLibrary
src/test/java/org/inventivetalent/nbt/test/StreamTest.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import org.inventivetalent.nbt.*; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import org.junit.Test; import java.io.FileOutputStream; import java.util.HashMap; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
package org.inventivetalent.nbt.test; public class StreamTest { @Test public void uncompressedInputTest() throws Exception { try (NBTInputStream in = new NBTInputStream(StreamTest.class.getResourceAsStream("/hello_world.nbt"))) { NBTTag nbtTag = in.readNBTTag(); System.out.println(nbtTag); assertEquals(TagID.TAG_COMPOUND, nbtTag.getTypeId()); assertEquals("hello world", nbtTag.getName()); CompoundTag compoundTag = (CompoundTag) nbtTag; assertEquals(1, compoundTag.getValue().size()); assertTrue(compoundTag.getValue().containsKey("name")); assertEquals(TagID.TAG_STRING, compoundTag.getValue().get("name").getTypeId()); assertEquals("Bananrama", compoundTag.getValue().get("name").getValue()); } } @Test public void compressedInputTest() throws Exception { try (NBTInputStream in = new NBTInputStream(StreamTest.class.getResourceAsStream("/bigtest.nbt"), true)) { NBTTag nbtTag = in.readNBTTag(); System.out.println(nbtTag); assertEquals(TagID.TAG_COMPOUND, nbtTag.getTypeId()); assertEquals("Level", nbtTag.getName()); //TODO: extend the test } } @Test public void uncompressedOutputTest() throws Exception {
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/test/java/org/inventivetalent/nbt/test/StreamTest.java import org.inventivetalent.nbt.*; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import org.junit.Test; import java.io.FileOutputStream; import java.util.HashMap; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; package org.inventivetalent.nbt.test; public class StreamTest { @Test public void uncompressedInputTest() throws Exception { try (NBTInputStream in = new NBTInputStream(StreamTest.class.getResourceAsStream("/hello_world.nbt"))) { NBTTag nbtTag = in.readNBTTag(); System.out.println(nbtTag); assertEquals(TagID.TAG_COMPOUND, nbtTag.getTypeId()); assertEquals("hello world", nbtTag.getName()); CompoundTag compoundTag = (CompoundTag) nbtTag; assertEquals(1, compoundTag.getValue().size()); assertTrue(compoundTag.getValue().containsKey("name")); assertEquals(TagID.TAG_STRING, compoundTag.getValue().get("name").getTypeId()); assertEquals("Bananrama", compoundTag.getValue().get("name").getValue()); } } @Test public void compressedInputTest() throws Exception { try (NBTInputStream in = new NBTInputStream(StreamTest.class.getResourceAsStream("/bigtest.nbt"), true)) { NBTTag nbtTag = in.readNBTTag(); System.out.println(nbtTag); assertEquals(TagID.TAG_COMPOUND, nbtTag.getTypeId()); assertEquals("Level", nbtTag.getName()); //TODO: extend the test } } @Test public void uncompressedOutputTest() throws Exception {
try (NBTOutputStream out = new NBTOutputStream(new FileOutputStream("uncompressed_test.nbt"))) {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java
// Path: src/main/java/org/inventivetalent/nbt/NBTTag.java // public abstract class NBTTag<V> { // // public static NMSClassResolver NMS_CLASS_RESOLVER = new NMSClassResolver(); // // private final String name; // // public NBTTag(String name) { // this.name = name; // } // // public NBTTag(String name, Object nmsTag) { // this.name = name; // // } // // public static NBTTag createType(int type) throws IllegalAccessException, InstantiationException { // return forType(type).newInstance(); // } // // public static NBTTag createType(int type, String name) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { // return forType(type).getConstructor(String.class).newInstance(name); // } // // public static Class<? extends NBTTag> forType(int type) { // switch (type) { // case TAG_BYTE_ARRAY: // return ByteArrayTag.class; // case TAG_BYTE: // return ByteTag.class; // case TAG_COMPOUND: // return CompoundTag.class; // case TAG_DOUBLE: // return DoubleTag.class; // case TAG_END: // return EndTag.class; // case TAG_FLOAT: // return FloatTag.class; // case TAG_INT_ARRAY: // return IntArrayTag.class; // case TAG_INT: // return IntTag.class; // case TAG_LIST: // return ListTag.class; // case TAG_LONG: // return LongTag.class; // case TAG_SHORT: // return ShortTag.class; // case TAG_STRING: // return StringTag.class; // case TAG_LONG_ARRAY: // return LongArrayTag.class; // default: // throw new IllegalArgumentException("Invalid NBTTag type " + type); // } // } // // public String getName() { // return name; // } // // public abstract V getValue(); // // public abstract void setValue(V v); // // // getAs methods // // public Number getAsNumber() { // return 0; // } // // public byte getAsByte() { // return getAsNumber().byteValue(); // } // // public short getAsShort() { // return getAsNumber().shortValue(); // } // // public int getAsInt() { // return getAsNumber().intValue(); // } // // public long getAsLong() { // return getAsNumber().longValue(); // } // // public float getAsFloat() { // return getAsNumber().floatValue(); // } // // public double getAsDouble() { // return getAsNumber().doubleValue(); // } // // public String getAsString() { // return String.valueOf(getValue()); // } // // // /getAs methods // // public abstract JsonElement asJson(); // // public abstract int getTypeId(); // // public abstract String getTypeName(); // // public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { // } // // public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException { // } // // public String getNMSClass() { // return "NBTBase"; // } // // public NBTTag fromNMS(Object nms) throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Field field = clazz.getDeclaredField("data"); // field.setAccessible(true); // setValue((V) field.get(nms)); // return this; // } // // public Object toNMS() throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Constructor constructor = null; // for (Constructor constr : clazz.getConstructors()) { // if (constr.getParameterTypes().length == 1) { // constructor = constr; // break; // } // } // if (constructor == null) { return null; } // return constructor.newInstance(getValue()); // } // // @Override // public String toString() { // return getTypeName() + "(" + getName() + "): " + getValue(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/TagID.java // public static final int TAG_END = 0;
import org.inventivetalent.nbt.NBTTag; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.zip.GZIPInputStream; import java.util.zip.ZipException; import static org.inventivetalent.nbt.TagID.TAG_END;
package org.inventivetalent.nbt.stream; public class NBTInputStream implements AutoCloseable { public static final Charset UTF_8 = Charset.forName("UTF-8"); private final DataInputStream in; public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { if (gzip) { this.in = new DataInputStream(new GZIPInputStream(inputStream)); } else { this.in = new DataInputStream(inputStream); } } public NBTInputStream(InputStream inputStream) throws IOException { this.in = new DataInputStream(inputStream); } public NBTInputStream(DataInputStream dataInputStream) { this.in = dataInputStream; } public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { try { return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); } catch (ZipException e) { return new NBTInputStream(new DataInputStream(inputStream)); } }
// Path: src/main/java/org/inventivetalent/nbt/NBTTag.java // public abstract class NBTTag<V> { // // public static NMSClassResolver NMS_CLASS_RESOLVER = new NMSClassResolver(); // // private final String name; // // public NBTTag(String name) { // this.name = name; // } // // public NBTTag(String name, Object nmsTag) { // this.name = name; // // } // // public static NBTTag createType(int type) throws IllegalAccessException, InstantiationException { // return forType(type).newInstance(); // } // // public static NBTTag createType(int type, String name) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { // return forType(type).getConstructor(String.class).newInstance(name); // } // // public static Class<? extends NBTTag> forType(int type) { // switch (type) { // case TAG_BYTE_ARRAY: // return ByteArrayTag.class; // case TAG_BYTE: // return ByteTag.class; // case TAG_COMPOUND: // return CompoundTag.class; // case TAG_DOUBLE: // return DoubleTag.class; // case TAG_END: // return EndTag.class; // case TAG_FLOAT: // return FloatTag.class; // case TAG_INT_ARRAY: // return IntArrayTag.class; // case TAG_INT: // return IntTag.class; // case TAG_LIST: // return ListTag.class; // case TAG_LONG: // return LongTag.class; // case TAG_SHORT: // return ShortTag.class; // case TAG_STRING: // return StringTag.class; // case TAG_LONG_ARRAY: // return LongArrayTag.class; // default: // throw new IllegalArgumentException("Invalid NBTTag type " + type); // } // } // // public String getName() { // return name; // } // // public abstract V getValue(); // // public abstract void setValue(V v); // // // getAs methods // // public Number getAsNumber() { // return 0; // } // // public byte getAsByte() { // return getAsNumber().byteValue(); // } // // public short getAsShort() { // return getAsNumber().shortValue(); // } // // public int getAsInt() { // return getAsNumber().intValue(); // } // // public long getAsLong() { // return getAsNumber().longValue(); // } // // public float getAsFloat() { // return getAsNumber().floatValue(); // } // // public double getAsDouble() { // return getAsNumber().doubleValue(); // } // // public String getAsString() { // return String.valueOf(getValue()); // } // // // /getAs methods // // public abstract JsonElement asJson(); // // public abstract int getTypeId(); // // public abstract String getTypeName(); // // public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { // } // // public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException { // } // // public String getNMSClass() { // return "NBTBase"; // } // // public NBTTag fromNMS(Object nms) throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Field field = clazz.getDeclaredField("data"); // field.setAccessible(true); // setValue((V) field.get(nms)); // return this; // } // // public Object toNMS() throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Constructor constructor = null; // for (Constructor constr : clazz.getConstructors()) { // if (constr.getParameterTypes().length == 1) { // constructor = constr; // break; // } // } // if (constructor == null) { return null; } // return constructor.newInstance(getValue()); // } // // @Override // public String toString() { // return getTypeName() + "(" + getName() + "): " + getValue(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/TagID.java // public static final int TAG_END = 0; // Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java import org.inventivetalent.nbt.NBTTag; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.zip.GZIPInputStream; import java.util.zip.ZipException; import static org.inventivetalent.nbt.TagID.TAG_END; package org.inventivetalent.nbt.stream; public class NBTInputStream implements AutoCloseable { public static final Charset UTF_8 = Charset.forName("UTF-8"); private final DataInputStream in; public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { if (gzip) { this.in = new DataInputStream(new GZIPInputStream(inputStream)); } else { this.in = new DataInputStream(inputStream); } } public NBTInputStream(InputStream inputStream) throws IOException { this.in = new DataInputStream(inputStream); } public NBTInputStream(DataInputStream dataInputStream) { this.in = dataInputStream; } public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { try { return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); } catch (ZipException e) { return new NBTInputStream(new DataInputStream(inputStream)); } }
public NBTTag readNBTTag() throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java
// Path: src/main/java/org/inventivetalent/nbt/NBTTag.java // public abstract class NBTTag<V> { // // public static NMSClassResolver NMS_CLASS_RESOLVER = new NMSClassResolver(); // // private final String name; // // public NBTTag(String name) { // this.name = name; // } // // public NBTTag(String name, Object nmsTag) { // this.name = name; // // } // // public static NBTTag createType(int type) throws IllegalAccessException, InstantiationException { // return forType(type).newInstance(); // } // // public static NBTTag createType(int type, String name) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { // return forType(type).getConstructor(String.class).newInstance(name); // } // // public static Class<? extends NBTTag> forType(int type) { // switch (type) { // case TAG_BYTE_ARRAY: // return ByteArrayTag.class; // case TAG_BYTE: // return ByteTag.class; // case TAG_COMPOUND: // return CompoundTag.class; // case TAG_DOUBLE: // return DoubleTag.class; // case TAG_END: // return EndTag.class; // case TAG_FLOAT: // return FloatTag.class; // case TAG_INT_ARRAY: // return IntArrayTag.class; // case TAG_INT: // return IntTag.class; // case TAG_LIST: // return ListTag.class; // case TAG_LONG: // return LongTag.class; // case TAG_SHORT: // return ShortTag.class; // case TAG_STRING: // return StringTag.class; // case TAG_LONG_ARRAY: // return LongArrayTag.class; // default: // throw new IllegalArgumentException("Invalid NBTTag type " + type); // } // } // // public String getName() { // return name; // } // // public abstract V getValue(); // // public abstract void setValue(V v); // // // getAs methods // // public Number getAsNumber() { // return 0; // } // // public byte getAsByte() { // return getAsNumber().byteValue(); // } // // public short getAsShort() { // return getAsNumber().shortValue(); // } // // public int getAsInt() { // return getAsNumber().intValue(); // } // // public long getAsLong() { // return getAsNumber().longValue(); // } // // public float getAsFloat() { // return getAsNumber().floatValue(); // } // // public double getAsDouble() { // return getAsNumber().doubleValue(); // } // // public String getAsString() { // return String.valueOf(getValue()); // } // // // /getAs methods // // public abstract JsonElement asJson(); // // public abstract int getTypeId(); // // public abstract String getTypeName(); // // public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { // } // // public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException { // } // // public String getNMSClass() { // return "NBTBase"; // } // // public NBTTag fromNMS(Object nms) throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Field field = clazz.getDeclaredField("data"); // field.setAccessible(true); // setValue((V) field.get(nms)); // return this; // } // // public Object toNMS() throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Constructor constructor = null; // for (Constructor constr : clazz.getConstructors()) { // if (constr.getParameterTypes().length == 1) { // constructor = constr; // break; // } // } // if (constructor == null) { return null; } // return constructor.newInstance(getValue()); // } // // @Override // public String toString() { // return getTypeName() + "(" + getName() + "): " + getValue(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/TagID.java // public static final int TAG_END = 0;
import org.inventivetalent.nbt.NBTTag; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.zip.GZIPInputStream; import java.util.zip.ZipException; import static org.inventivetalent.nbt.TagID.TAG_END;
package org.inventivetalent.nbt.stream; public class NBTInputStream implements AutoCloseable { public static final Charset UTF_8 = Charset.forName("UTF-8"); private final DataInputStream in; public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { if (gzip) { this.in = new DataInputStream(new GZIPInputStream(inputStream)); } else { this.in = new DataInputStream(inputStream); } } public NBTInputStream(InputStream inputStream) throws IOException { this.in = new DataInputStream(inputStream); } public NBTInputStream(DataInputStream dataInputStream) { this.in = dataInputStream; } public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { try { return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); } catch (ZipException e) { return new NBTInputStream(new DataInputStream(inputStream)); } } public NBTTag readNBTTag() throws IOException { return readNBTTag(0); } public NBTTag readNBTTag(int depth) throws IOException { int tagType = in.readByte() & 0xFF; String tagName = "";
// Path: src/main/java/org/inventivetalent/nbt/NBTTag.java // public abstract class NBTTag<V> { // // public static NMSClassResolver NMS_CLASS_RESOLVER = new NMSClassResolver(); // // private final String name; // // public NBTTag(String name) { // this.name = name; // } // // public NBTTag(String name, Object nmsTag) { // this.name = name; // // } // // public static NBTTag createType(int type) throws IllegalAccessException, InstantiationException { // return forType(type).newInstance(); // } // // public static NBTTag createType(int type, String name) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { // return forType(type).getConstructor(String.class).newInstance(name); // } // // public static Class<? extends NBTTag> forType(int type) { // switch (type) { // case TAG_BYTE_ARRAY: // return ByteArrayTag.class; // case TAG_BYTE: // return ByteTag.class; // case TAG_COMPOUND: // return CompoundTag.class; // case TAG_DOUBLE: // return DoubleTag.class; // case TAG_END: // return EndTag.class; // case TAG_FLOAT: // return FloatTag.class; // case TAG_INT_ARRAY: // return IntArrayTag.class; // case TAG_INT: // return IntTag.class; // case TAG_LIST: // return ListTag.class; // case TAG_LONG: // return LongTag.class; // case TAG_SHORT: // return ShortTag.class; // case TAG_STRING: // return StringTag.class; // case TAG_LONG_ARRAY: // return LongArrayTag.class; // default: // throw new IllegalArgumentException("Invalid NBTTag type " + type); // } // } // // public String getName() { // return name; // } // // public abstract V getValue(); // // public abstract void setValue(V v); // // // getAs methods // // public Number getAsNumber() { // return 0; // } // // public byte getAsByte() { // return getAsNumber().byteValue(); // } // // public short getAsShort() { // return getAsNumber().shortValue(); // } // // public int getAsInt() { // return getAsNumber().intValue(); // } // // public long getAsLong() { // return getAsNumber().longValue(); // } // // public float getAsFloat() { // return getAsNumber().floatValue(); // } // // public double getAsDouble() { // return getAsNumber().doubleValue(); // } // // public String getAsString() { // return String.valueOf(getValue()); // } // // // /getAs methods // // public abstract JsonElement asJson(); // // public abstract int getTypeId(); // // public abstract String getTypeName(); // // public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { // } // // public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException { // } // // public String getNMSClass() { // return "NBTBase"; // } // // public NBTTag fromNMS(Object nms) throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Field field = clazz.getDeclaredField("data"); // field.setAccessible(true); // setValue((V) field.get(nms)); // return this; // } // // public Object toNMS() throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Constructor constructor = null; // for (Constructor constr : clazz.getConstructors()) { // if (constr.getParameterTypes().length == 1) { // constructor = constr; // break; // } // } // if (constructor == null) { return null; } // return constructor.newInstance(getValue()); // } // // @Override // public String toString() { // return getTypeName() + "(" + getName() + "): " + getValue(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/TagID.java // public static final int TAG_END = 0; // Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java import org.inventivetalent.nbt.NBTTag; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.zip.GZIPInputStream; import java.util.zip.ZipException; import static org.inventivetalent.nbt.TagID.TAG_END; package org.inventivetalent.nbt.stream; public class NBTInputStream implements AutoCloseable { public static final Charset UTF_8 = Charset.forName("UTF-8"); private final DataInputStream in; public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { if (gzip) { this.in = new DataInputStream(new GZIPInputStream(inputStream)); } else { this.in = new DataInputStream(inputStream); } } public NBTInputStream(InputStream inputStream) throws IOException { this.in = new DataInputStream(inputStream); } public NBTInputStream(DataInputStream dataInputStream) { this.in = dataInputStream; } public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { try { return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); } catch (ZipException e) { return new NBTInputStream(new DataInputStream(inputStream)); } } public NBTTag readNBTTag() throws IOException { return readNBTTag(0); } public NBTTag readNBTTag(int depth) throws IOException { int tagType = in.readByte() & 0xFF; String tagName = "";
if (tagType != TAG_END) {
InventivetalentDev/NBTLibrary
src/test/java/org/inventivetalent/nbt/test/WrapperTest.java
// Path: src/main/java/org/inventivetalent/nbt/wrapper/BooleanTag.java // public class BooleanTag extends ByteTag { // // public BooleanTag() { // this(false); // } // // public BooleanTag(boolean value) { // super((byte) (value ? 1 : 0)); // } // // public BooleanTag(String name) { // super(name); // } // // public BooleanTag(String name, boolean value) { // super(name, (byte) (value ? 1 : 0)); // } // // public boolean getBoolean() { // return getValue() == 1; // } // // public void setBoolean(boolean value) { // setValue((byte) (value ? 1 : 0)); // } // // }
import org.inventivetalent.nbt.wrapper.BooleanTag; import org.junit.Test; import static org.junit.Assert.assertEquals;
package org.inventivetalent.nbt.test; public class WrapperTest { @Test public void booleanWrapperTest() {
// Path: src/main/java/org/inventivetalent/nbt/wrapper/BooleanTag.java // public class BooleanTag extends ByteTag { // // public BooleanTag() { // this(false); // } // // public BooleanTag(boolean value) { // super((byte) (value ? 1 : 0)); // } // // public BooleanTag(String name) { // super(name); // } // // public BooleanTag(String name, boolean value) { // super(name, (byte) (value ? 1 : 0)); // } // // public boolean getBoolean() { // return getValue() == 1; // } // // public void setBoolean(boolean value) { // setValue((byte) (value ? 1 : 0)); // } // // } // Path: src/test/java/org/inventivetalent/nbt/test/WrapperTest.java import org.inventivetalent.nbt.wrapper.BooleanTag; import org.junit.Test; import static org.junit.Assert.assertEquals; package org.inventivetalent.nbt.test; public class WrapperTest { @Test public void booleanWrapperTest() {
BooleanTag tag1 = new BooleanTag(true);
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/annotation/NBTMember.java
// Path: src/main/java/org/inventivetalent/nbt/NBTTag.java // public abstract class NBTTag<V> { // // public static NMSClassResolver NMS_CLASS_RESOLVER = new NMSClassResolver(); // // private final String name; // // public NBTTag(String name) { // this.name = name; // } // // public NBTTag(String name, Object nmsTag) { // this.name = name; // // } // // public static NBTTag createType(int type) throws IllegalAccessException, InstantiationException { // return forType(type).newInstance(); // } // // public static NBTTag createType(int type, String name) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { // return forType(type).getConstructor(String.class).newInstance(name); // } // // public static Class<? extends NBTTag> forType(int type) { // switch (type) { // case TAG_BYTE_ARRAY: // return ByteArrayTag.class; // case TAG_BYTE: // return ByteTag.class; // case TAG_COMPOUND: // return CompoundTag.class; // case TAG_DOUBLE: // return DoubleTag.class; // case TAG_END: // return EndTag.class; // case TAG_FLOAT: // return FloatTag.class; // case TAG_INT_ARRAY: // return IntArrayTag.class; // case TAG_INT: // return IntTag.class; // case TAG_LIST: // return ListTag.class; // case TAG_LONG: // return LongTag.class; // case TAG_SHORT: // return ShortTag.class; // case TAG_STRING: // return StringTag.class; // case TAG_LONG_ARRAY: // return LongArrayTag.class; // default: // throw new IllegalArgumentException("Invalid NBTTag type " + type); // } // } // // public String getName() { // return name; // } // // public abstract V getValue(); // // public abstract void setValue(V v); // // // getAs methods // // public Number getAsNumber() { // return 0; // } // // public byte getAsByte() { // return getAsNumber().byteValue(); // } // // public short getAsShort() { // return getAsNumber().shortValue(); // } // // public int getAsInt() { // return getAsNumber().intValue(); // } // // public long getAsLong() { // return getAsNumber().longValue(); // } // // public float getAsFloat() { // return getAsNumber().floatValue(); // } // // public double getAsDouble() { // return getAsNumber().doubleValue(); // } // // public String getAsString() { // return String.valueOf(getValue()); // } // // // /getAs methods // // public abstract JsonElement asJson(); // // public abstract int getTypeId(); // // public abstract String getTypeName(); // // public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { // } // // public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException { // } // // public String getNMSClass() { // return "NBTBase"; // } // // public NBTTag fromNMS(Object nms) throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Field field = clazz.getDeclaredField("data"); // field.setAccessible(true); // setValue((V) field.get(nms)); // return this; // } // // public Object toNMS() throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Constructor constructor = null; // for (Constructor constr : clazz.getConstructors()) { // if (constr.getParameterTypes().length == 1) { // constructor = constr; // break; // } // } // if (constructor == null) { return null; } // return constructor.newInstance(getValue()); // } // // @Override // public String toString() { // return getTypeName() + "(" + getName() + "): " + getValue(); // } // }
import org.inventivetalent.nbt.NBTTag;
package org.inventivetalent.nbt.annotation; public abstract class NBTMember extends NBTInfo { protected final Object obj; public NBTMember(String[] key, int type, boolean read, boolean write, NBTPriority priority, Object obj) { super(key, type, read, write, priority); this.obj = obj; }
// Path: src/main/java/org/inventivetalent/nbt/NBTTag.java // public abstract class NBTTag<V> { // // public static NMSClassResolver NMS_CLASS_RESOLVER = new NMSClassResolver(); // // private final String name; // // public NBTTag(String name) { // this.name = name; // } // // public NBTTag(String name, Object nmsTag) { // this.name = name; // // } // // public static NBTTag createType(int type) throws IllegalAccessException, InstantiationException { // return forType(type).newInstance(); // } // // public static NBTTag createType(int type, String name) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { // return forType(type).getConstructor(String.class).newInstance(name); // } // // public static Class<? extends NBTTag> forType(int type) { // switch (type) { // case TAG_BYTE_ARRAY: // return ByteArrayTag.class; // case TAG_BYTE: // return ByteTag.class; // case TAG_COMPOUND: // return CompoundTag.class; // case TAG_DOUBLE: // return DoubleTag.class; // case TAG_END: // return EndTag.class; // case TAG_FLOAT: // return FloatTag.class; // case TAG_INT_ARRAY: // return IntArrayTag.class; // case TAG_INT: // return IntTag.class; // case TAG_LIST: // return ListTag.class; // case TAG_LONG: // return LongTag.class; // case TAG_SHORT: // return ShortTag.class; // case TAG_STRING: // return StringTag.class; // case TAG_LONG_ARRAY: // return LongArrayTag.class; // default: // throw new IllegalArgumentException("Invalid NBTTag type " + type); // } // } // // public String getName() { // return name; // } // // public abstract V getValue(); // // public abstract void setValue(V v); // // // getAs methods // // public Number getAsNumber() { // return 0; // } // // public byte getAsByte() { // return getAsNumber().byteValue(); // } // // public short getAsShort() { // return getAsNumber().shortValue(); // } // // public int getAsInt() { // return getAsNumber().intValue(); // } // // public long getAsLong() { // return getAsNumber().longValue(); // } // // public float getAsFloat() { // return getAsNumber().floatValue(); // } // // public double getAsDouble() { // return getAsNumber().doubleValue(); // } // // public String getAsString() { // return String.valueOf(getValue()); // } // // // /getAs methods // // public abstract JsonElement asJson(); // // public abstract int getTypeId(); // // public abstract String getTypeName(); // // public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { // } // // public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException { // } // // public String getNMSClass() { // return "NBTBase"; // } // // public NBTTag fromNMS(Object nms) throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Field field = clazz.getDeclaredField("data"); // field.setAccessible(true); // setValue((V) field.get(nms)); // return this; // } // // public Object toNMS() throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Constructor constructor = null; // for (Constructor constr : clazz.getConstructors()) { // if (constr.getParameterTypes().length == 1) { // constructor = constr; // break; // } // } // if (constructor == null) { return null; } // return constructor.newInstance(getValue()); // } // // @Override // public String toString() { // return getTypeName() + "(" + getName() + "): " + getValue(); // } // } // Path: src/main/java/org/inventivetalent/nbt/annotation/NBTMember.java import org.inventivetalent.nbt.NBTTag; package org.inventivetalent.nbt.annotation; public abstract class NBTMember extends NBTInfo { protected final Object obj; public NBTMember(String[] key, int type, boolean read, boolean write, NBTPriority priority, Object obj) { super(key, type, read, write, priority); this.obj = obj; }
public abstract void read(NBTTag tag);
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/annotation/NBTWriteMethod.java
// Path: src/main/java/org/inventivetalent/nbt/NBTTag.java // public abstract class NBTTag<V> { // // public static NMSClassResolver NMS_CLASS_RESOLVER = new NMSClassResolver(); // // private final String name; // // public NBTTag(String name) { // this.name = name; // } // // public NBTTag(String name, Object nmsTag) { // this.name = name; // // } // // public static NBTTag createType(int type) throws IllegalAccessException, InstantiationException { // return forType(type).newInstance(); // } // // public static NBTTag createType(int type, String name) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { // return forType(type).getConstructor(String.class).newInstance(name); // } // // public static Class<? extends NBTTag> forType(int type) { // switch (type) { // case TAG_BYTE_ARRAY: // return ByteArrayTag.class; // case TAG_BYTE: // return ByteTag.class; // case TAG_COMPOUND: // return CompoundTag.class; // case TAG_DOUBLE: // return DoubleTag.class; // case TAG_END: // return EndTag.class; // case TAG_FLOAT: // return FloatTag.class; // case TAG_INT_ARRAY: // return IntArrayTag.class; // case TAG_INT: // return IntTag.class; // case TAG_LIST: // return ListTag.class; // case TAG_LONG: // return LongTag.class; // case TAG_SHORT: // return ShortTag.class; // case TAG_STRING: // return StringTag.class; // case TAG_LONG_ARRAY: // return LongArrayTag.class; // default: // throw new IllegalArgumentException("Invalid NBTTag type " + type); // } // } // // public String getName() { // return name; // } // // public abstract V getValue(); // // public abstract void setValue(V v); // // // getAs methods // // public Number getAsNumber() { // return 0; // } // // public byte getAsByte() { // return getAsNumber().byteValue(); // } // // public short getAsShort() { // return getAsNumber().shortValue(); // } // // public int getAsInt() { // return getAsNumber().intValue(); // } // // public long getAsLong() { // return getAsNumber().longValue(); // } // // public float getAsFloat() { // return getAsNumber().floatValue(); // } // // public double getAsDouble() { // return getAsNumber().doubleValue(); // } // // public String getAsString() { // return String.valueOf(getValue()); // } // // // /getAs methods // // public abstract JsonElement asJson(); // // public abstract int getTypeId(); // // public abstract String getTypeName(); // // public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { // } // // public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException { // } // // public String getNMSClass() { // return "NBTBase"; // } // // public NBTTag fromNMS(Object nms) throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Field field = clazz.getDeclaredField("data"); // field.setAccessible(true); // setValue((V) field.get(nms)); // return this; // } // // public Object toNMS() throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Constructor constructor = null; // for (Constructor constr : clazz.getConstructors()) { // if (constr.getParameterTypes().length == 1) { // constructor = constr; // break; // } // } // if (constructor == null) { return null; } // return constructor.newInstance(getValue()); // } // // @Override // public String toString() { // return getTypeName() + "(" + getName() + "): " + getValue(); // } // }
import org.inventivetalent.nbt.NBTTag; import java.lang.reflect.Method;
package org.inventivetalent.nbt.annotation; public class NBTWriteMethod extends NBTMember { protected final Method method; public NBTWriteMethod(String[] key, int type, boolean write, NBTPriority priority, Object obj, Method method) { super(key, type, false, write, priority, obj); this.method = method; } @Override
// Path: src/main/java/org/inventivetalent/nbt/NBTTag.java // public abstract class NBTTag<V> { // // public static NMSClassResolver NMS_CLASS_RESOLVER = new NMSClassResolver(); // // private final String name; // // public NBTTag(String name) { // this.name = name; // } // // public NBTTag(String name, Object nmsTag) { // this.name = name; // // } // // public static NBTTag createType(int type) throws IllegalAccessException, InstantiationException { // return forType(type).newInstance(); // } // // public static NBTTag createType(int type, String name) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { // return forType(type).getConstructor(String.class).newInstance(name); // } // // public static Class<? extends NBTTag> forType(int type) { // switch (type) { // case TAG_BYTE_ARRAY: // return ByteArrayTag.class; // case TAG_BYTE: // return ByteTag.class; // case TAG_COMPOUND: // return CompoundTag.class; // case TAG_DOUBLE: // return DoubleTag.class; // case TAG_END: // return EndTag.class; // case TAG_FLOAT: // return FloatTag.class; // case TAG_INT_ARRAY: // return IntArrayTag.class; // case TAG_INT: // return IntTag.class; // case TAG_LIST: // return ListTag.class; // case TAG_LONG: // return LongTag.class; // case TAG_SHORT: // return ShortTag.class; // case TAG_STRING: // return StringTag.class; // case TAG_LONG_ARRAY: // return LongArrayTag.class; // default: // throw new IllegalArgumentException("Invalid NBTTag type " + type); // } // } // // public String getName() { // return name; // } // // public abstract V getValue(); // // public abstract void setValue(V v); // // // getAs methods // // public Number getAsNumber() { // return 0; // } // // public byte getAsByte() { // return getAsNumber().byteValue(); // } // // public short getAsShort() { // return getAsNumber().shortValue(); // } // // public int getAsInt() { // return getAsNumber().intValue(); // } // // public long getAsLong() { // return getAsNumber().longValue(); // } // // public float getAsFloat() { // return getAsNumber().floatValue(); // } // // public double getAsDouble() { // return getAsNumber().doubleValue(); // } // // public String getAsString() { // return String.valueOf(getValue()); // } // // // /getAs methods // // public abstract JsonElement asJson(); // // public abstract int getTypeId(); // // public abstract String getTypeName(); // // public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { // } // // public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException { // } // // public String getNMSClass() { // return "NBTBase"; // } // // public NBTTag fromNMS(Object nms) throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Field field = clazz.getDeclaredField("data"); // field.setAccessible(true); // setValue((V) field.get(nms)); // return this; // } // // public Object toNMS() throws ReflectiveOperationException { // Class<?> clazz = NMS_CLASS_RESOLVER.resolve(getNMSClass()); // Constructor constructor = null; // for (Constructor constr : clazz.getConstructors()) { // if (constr.getParameterTypes().length == 1) { // constructor = constr; // break; // } // } // if (constructor == null) { return null; } // return constructor.newInstance(getValue()); // } // // @Override // public String toString() { // return getTypeName() + "(" + getName() + "): " + getValue(); // } // } // Path: src/main/java/org/inventivetalent/nbt/annotation/NBTWriteMethod.java import org.inventivetalent.nbt.NBTTag; import java.lang.reflect.Method; package org.inventivetalent.nbt.annotation; public class NBTWriteMethod extends NBTMember { protected final Method method; public NBTWriteMethod(String[] key, int type, boolean write, NBTPriority priority, Object obj, Method method) { super(key, type, false, write, priority, obj); this.method = method; } @Override
public void read(NBTTag tag) {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/ShortTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException;
package org.inventivetalent.nbt; public class ShortTag extends NumberTag<Short> { private short value; public ShortTag() { this((short) 0); } public ShortTag(short value) { super(""); this.value = value; } public ShortTag(String name) { super(name); } public ShortTag(String name, short value) { super(name); this.value = value; } @Override public Short getValue() { return value; } @Override public void setValue(Short aShort) { this.value = aShort; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/ShortTag.java import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; package org.inventivetalent.nbt; public class ShortTag extends NumberTag<Short> { private short value; public ShortTag() { this((short) 0); } public ShortTag(short value) { super(""); this.value = value; } public ShortTag(String name) { super(name); } public ShortTag(String name, short value) { super(name); this.value = value; } @Override public Short getValue() { return value; } @Override public void setValue(Short aShort) { this.value = aShort; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override
public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException {
InventivetalentDev/NBTLibrary
src/main/java/org/inventivetalent/nbt/ShortTag.java
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // }
import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException;
public ShortTag(String name) { super(name); } public ShortTag(String name, short value) { super(name); this.value = value; } @Override public Short getValue() { return value; } @Override public void setValue(Short aShort) { this.value = aShort; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { value = in.readShort(); } @Override
// Path: src/main/java/org/inventivetalent/nbt/stream/NBTInputStream.java // public class NBTInputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataInputStream in; // // public NBTInputStream(InputStream inputStream, boolean gzip) throws IOException { // if (gzip) { // this.in = new DataInputStream(new GZIPInputStream(inputStream)); // } else { // this.in = new DataInputStream(inputStream); // } // } // // public NBTInputStream(InputStream inputStream) throws IOException { // this.in = new DataInputStream(inputStream); // } // // public NBTInputStream(DataInputStream dataInputStream) { // this.in = dataInputStream; // } // // public static NBTInputStream optionalGzip(InputStream inputStream) throws IOException { // try { // return new NBTInputStream(new DataInputStream(new GZIPInputStream(inputStream))); // } catch (ZipException e) { // return new NBTInputStream(new DataInputStream(inputStream)); // } // } // // public NBTTag readNBTTag() throws IOException { // return readNBTTag(0); // } // // public NBTTag readNBTTag(int depth) throws IOException { // int tagType = in.readByte() & 0xFF; // String tagName = ""; // if (tagType != TAG_END) { // int length = in.readShort() & 0xFFFF; // byte[] nameBytes = new byte[length]; // in.readFully(nameBytes); // tagName = new String(nameBytes, UTF_8); // } // // return readTagContent(tagType, tagName, depth); // } // // public NBTTag readTagContent(int tagType, String tagName, int depth) throws IOException { // try { // NBTTag nbtTag = NBTTag.forType(tagType).getConstructor(String.class).newInstance(tagName); // nbtTag.read(this, in, depth); // return nbtTag; // } catch (ReflectiveOperationException e) { // throw new IOException("Could not instantiate NBTTag class for type " + tagType + "'" + tagName + "'", e); // } // } // // @Override // public void close() throws Exception { // in.close(); // } // } // // Path: src/main/java/org/inventivetalent/nbt/stream/NBTOutputStream.java // public class NBTOutputStream implements AutoCloseable { // // public static final Charset UTF_8 = Charset.forName("UTF-8"); // // private final DataOutputStream out; // // public NBTOutputStream(OutputStream outputStream, boolean gzip) throws IOException { // if (gzip) { // this.out = new DataOutputStream(new GZIPOutputStream(outputStream)); // } else { // this.out = new DataOutputStream(outputStream); // } // } // // public NBTOutputStream(OutputStream outputStream) throws IOException { // this.out = new DataOutputStream(outputStream); // } // // public NBTOutputStream(DataOutputStream dataOutputStream) { // this.out = dataOutputStream; // } // // public void writeTag(NBTTag tag) throws IOException { // String name = tag.getName(); // byte[] nameBytes = name.getBytes(UTF_8); // // out.writeByte(tag.getTypeId()); // out.writeShort(nameBytes.length); // out.write(nameBytes); // // writeTagContent(tag); // } // // public void writeTagContent(NBTTag tag) throws IOException { // tag.write(this, out); // } // // @Override // public void close() throws Exception { // out.close(); // } // } // Path: src/main/java/org/inventivetalent/nbt/ShortTag.java import com.google.gson.JsonPrimitive; import org.inventivetalent.nbt.stream.NBTInputStream; import org.inventivetalent.nbt.stream.NBTOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; public ShortTag(String name) { super(name); } public ShortTag(String name, short value) { super(name); this.value = value; } @Override public Short getValue() { return value; } @Override public void setValue(Short aShort) { this.value = aShort; } @Override public JsonPrimitive asJson() { return new JsonPrimitive(value); } @Override public void read(NBTInputStream nbtIn, DataInputStream in, int depth) throws IOException { value = in.readShort(); } @Override
public void write(NBTOutputStream nbtOut, DataOutputStream out) throws IOException {
OsuCelebrity/OsuCelebrity
osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/QueuedPlayer.java
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java // @PersistenceCapable(detachable = "true") // @Getter // @ToString // public class OsuUser { // @PrimaryKey // @UserId // @Getter(onMethod = @__(@UserId)) // private int userId; // // @Index // private String userName; // // private long downloaded; // // @Setter // private Privilege privilege = Privilege.PLAYER; // // @Setter // @Column(defaultValue = "true") // private boolean allowsNotifications = true; // // @Setter // @Column(defaultValue = "true") // @Index // private boolean allowsSpectating = true; // // @Setter(onParam = @__(@GameMode)) // @Getter(onMethod = @__(@GameMode)) // @Column(defaultValue = "0") // @GameMode // private int gameMode = 0; // // @Setter // @Column(defaultValue = "-1") // private long timeOutUntil = -1; // // /** // * Creates a new user object copying all relevant data from the api user object. // * // * @param user downloaded data. // * @param downloaded current time in millis. // */ // public OsuUser(OsuApiUser user, long downloaded) { // this.userId = user.getUserId(); // update(user, downloaded); // } // // /** // * updates this object with the downloaded data. // * // * @param user downloaded data // * @param downloaded current time // */ // public void update(OsuApiUser user, long downloaded) { // this.setUserName(user.getUserName()); // this.setDownloaded(downloaded); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof OsuUser) { // return ((OsuUser) obj).userId == userId; // } // return false; // } // // @Override // public int hashCode() { // return userId; // } // // void setDownloaded(long downloaded) { // this.downloaded = downloaded; // } // // void setUserName(String userName) { // this.userName = userName; // } // }
import lombok.Data; import me.reddev.osucelebrity.osu.OsuUser; import javax.jdo.annotations.Column; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.Index; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey;
package me.reddev.osucelebrity.core; /** * A user who is in the spectating queue. * * @author Redback */ @Data @PersistenceCapable public class QueuedPlayer { public static final int CANCELLED = -2; public static final int DONE = -1; public static final int SPECTATING = 0; public static final int NEXT = 1; public static final int QUEUED = 2; @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.INCREMENT) long id;
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java // @PersistenceCapable(detachable = "true") // @Getter // @ToString // public class OsuUser { // @PrimaryKey // @UserId // @Getter(onMethod = @__(@UserId)) // private int userId; // // @Index // private String userName; // // private long downloaded; // // @Setter // private Privilege privilege = Privilege.PLAYER; // // @Setter // @Column(defaultValue = "true") // private boolean allowsNotifications = true; // // @Setter // @Column(defaultValue = "true") // @Index // private boolean allowsSpectating = true; // // @Setter(onParam = @__(@GameMode)) // @Getter(onMethod = @__(@GameMode)) // @Column(defaultValue = "0") // @GameMode // private int gameMode = 0; // // @Setter // @Column(defaultValue = "-1") // private long timeOutUntil = -1; // // /** // * Creates a new user object copying all relevant data from the api user object. // * // * @param user downloaded data. // * @param downloaded current time in millis. // */ // public OsuUser(OsuApiUser user, long downloaded) { // this.userId = user.getUserId(); // update(user, downloaded); // } // // /** // * updates this object with the downloaded data. // * // * @param user downloaded data // * @param downloaded current time // */ // public void update(OsuApiUser user, long downloaded) { // this.setUserName(user.getUserName()); // this.setDownloaded(downloaded); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof OsuUser) { // return ((OsuUser) obj).userId == userId; // } // return false; // } // // @Override // public int hashCode() { // return userId; // } // // void setDownloaded(long downloaded) { // this.downloaded = downloaded; // } // // void setUserName(String userName) { // this.userName = userName; // } // } // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/QueuedPlayer.java import lombok.Data; import me.reddev.osucelebrity.osu.OsuUser; import javax.jdo.annotations.Column; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.Index; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; package me.reddev.osucelebrity.core; /** * A user who is in the spectating queue. * * @author Redback */ @Data @PersistenceCapable public class QueuedPlayer { public static final int CANCELLED = -2; public static final int DONE = -1; public static final int SPECTATING = 0; public static final int NEXT = 1; public static final int QUEUED = 2; @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.INCREMENT) long id;
OsuUser player;
OsuCelebrity/OsuCelebrity
osuCelebrity-core/src/test/java/me/reddev/osucelebrity/core/SpectatorImplTest.java
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/twitchapi/TwitchApi.java // @PassAndReturnNonnull // public interface TwitchApi { // /** // * Gets a list of moderators currently in a channel. // * // * @return The list of moderator usernames in lowercase // */ // List<String> getOnlineMods(); // // /** // * Determines whether a given user is a moderator of a channel. // * // * @param username The username of the user // * @return True if the user is a moderator // */ // boolean isModerator(String username); // // /** // * Retrieves the user from the API. // * @param username username (all lower case). // * @param maxAge if > 0, cached data up to this age can be returned. // * @param returnCachedOnIoException if true, a cached data is used if a server exception // * occurrs during an update from the api // * @return the user object. // */ // TwitchApiUser getUser(PersistenceManager pm, String username, long maxAge, // boolean returnCachedOnIoException); // // /** // * Retrieves the link to the past broadcast that a play occurred in at the exact time when the // * play started. // * // * @param play any play. // * @return the full URL. if no matching past broadcast can be found, null. // */ // @CheckForNull // URL getReplayLink(QueuedPlayer play) throws IOException; // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/QueuedPlayer.java // public enum QueueSource { // TWITCH, OSU, AUTO // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java // @PersistenceCapable(detachable = "true") // @Getter // @ToString // public class OsuUser { // @PrimaryKey // @UserId // @Getter(onMethod = @__(@UserId)) // private int userId; // // @Index // private String userName; // // private long downloaded; // // @Setter // private Privilege privilege = Privilege.PLAYER; // // @Setter // @Column(defaultValue = "true") // private boolean allowsNotifications = true; // // @Setter // @Column(defaultValue = "true") // @Index // private boolean allowsSpectating = true; // // @Setter(onParam = @__(@GameMode)) // @Getter(onMethod = @__(@GameMode)) // @Column(defaultValue = "0") // @GameMode // private int gameMode = 0; // // @Setter // @Column(defaultValue = "-1") // private long timeOutUntil = -1; // // /** // * Creates a new user object copying all relevant data from the api user object. // * // * @param user downloaded data. // * @param downloaded current time in millis. // */ // public OsuUser(OsuApiUser user, long downloaded) { // this.userId = user.getUserId(); // update(user, downloaded); // } // // /** // * updates this object with the downloaded data. // * // * @param user downloaded data // * @param downloaded current time // */ // public void update(OsuApiUser user, long downloaded) { // this.setUserName(user.getUserName()); // this.setDownloaded(downloaded); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof OsuUser) { // return ((OsuUser) obj).userId == userId; // } // return false; // } // // @Override // public int hashCode() { // return userId; // } // // void setDownloaded(long downloaded) { // this.downloaded = downloaded; // } // // void setUserName(String userName) { // this.userName = userName; // } // }
import me.reddev.osucelebrity.twitchapi.TwitchApi; import me.reddev.osucelebrity.twitch.SceneSwitcher; import me.reddev.osucelebrity.osu.Osu.PollStatusConsumer; import org.mockito.ArgumentCaptor; import me.reddev.osucelebrity.osu.PlayerStatus.PlayerStatusType; import me.reddev.osucelebrity.osu.PlayerStatus; import me.reddev.osucelebrity.core.QueuedPlayer.QueueSource; import me.reddev.osucelebrity.osu.PlayerActivity; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import me.reddev.osucelebrity.AbstractJDOTest; import me.reddev.osucelebrity.osu.Osu; import me.reddev.osucelebrity.osu.OsuStatus; import me.reddev.osucelebrity.osu.OsuStatus.Type; import me.reddev.osucelebrity.osu.OsuUser; import me.reddev.osucelebrity.osuapi.ApiUser; import me.reddev.osucelebrity.osuapi.MockOsuApi; import me.reddev.osucelebrity.osuapi.OsuApi; import me.reddev.osucelebrity.twitch.Twitch; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.tillerino.osuApiModel.GameModes; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import javax.annotation.CheckForNull; import javax.jdo.JDOHelper; import javax.jdo.PersistenceManager;
package me.reddev.osucelebrity.core; public class SpectatorImplTest extends AbstractJDOTest { @Mock private Twitch twitch; @Mock protected Osu osu; @Mock private CoreSettings settings; @Mock private SceneSwitcher sceneSwitcher; @Mock
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/twitchapi/TwitchApi.java // @PassAndReturnNonnull // public interface TwitchApi { // /** // * Gets a list of moderators currently in a channel. // * // * @return The list of moderator usernames in lowercase // */ // List<String> getOnlineMods(); // // /** // * Determines whether a given user is a moderator of a channel. // * // * @param username The username of the user // * @return True if the user is a moderator // */ // boolean isModerator(String username); // // /** // * Retrieves the user from the API. // * @param username username (all lower case). // * @param maxAge if > 0, cached data up to this age can be returned. // * @param returnCachedOnIoException if true, a cached data is used if a server exception // * occurrs during an update from the api // * @return the user object. // */ // TwitchApiUser getUser(PersistenceManager pm, String username, long maxAge, // boolean returnCachedOnIoException); // // /** // * Retrieves the link to the past broadcast that a play occurred in at the exact time when the // * play started. // * // * @param play any play. // * @return the full URL. if no matching past broadcast can be found, null. // */ // @CheckForNull // URL getReplayLink(QueuedPlayer play) throws IOException; // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/QueuedPlayer.java // public enum QueueSource { // TWITCH, OSU, AUTO // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java // @PersistenceCapable(detachable = "true") // @Getter // @ToString // public class OsuUser { // @PrimaryKey // @UserId // @Getter(onMethod = @__(@UserId)) // private int userId; // // @Index // private String userName; // // private long downloaded; // // @Setter // private Privilege privilege = Privilege.PLAYER; // // @Setter // @Column(defaultValue = "true") // private boolean allowsNotifications = true; // // @Setter // @Column(defaultValue = "true") // @Index // private boolean allowsSpectating = true; // // @Setter(onParam = @__(@GameMode)) // @Getter(onMethod = @__(@GameMode)) // @Column(defaultValue = "0") // @GameMode // private int gameMode = 0; // // @Setter // @Column(defaultValue = "-1") // private long timeOutUntil = -1; // // /** // * Creates a new user object copying all relevant data from the api user object. // * // * @param user downloaded data. // * @param downloaded current time in millis. // */ // public OsuUser(OsuApiUser user, long downloaded) { // this.userId = user.getUserId(); // update(user, downloaded); // } // // /** // * updates this object with the downloaded data. // * // * @param user downloaded data // * @param downloaded current time // */ // public void update(OsuApiUser user, long downloaded) { // this.setUserName(user.getUserName()); // this.setDownloaded(downloaded); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof OsuUser) { // return ((OsuUser) obj).userId == userId; // } // return false; // } // // @Override // public int hashCode() { // return userId; // } // // void setDownloaded(long downloaded) { // this.downloaded = downloaded; // } // // void setUserName(String userName) { // this.userName = userName; // } // } // Path: osuCelebrity-core/src/test/java/me/reddev/osucelebrity/core/SpectatorImplTest.java import me.reddev.osucelebrity.twitchapi.TwitchApi; import me.reddev.osucelebrity.twitch.SceneSwitcher; import me.reddev.osucelebrity.osu.Osu.PollStatusConsumer; import org.mockito.ArgumentCaptor; import me.reddev.osucelebrity.osu.PlayerStatus.PlayerStatusType; import me.reddev.osucelebrity.osu.PlayerStatus; import me.reddev.osucelebrity.core.QueuedPlayer.QueueSource; import me.reddev.osucelebrity.osu.PlayerActivity; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import me.reddev.osucelebrity.AbstractJDOTest; import me.reddev.osucelebrity.osu.Osu; import me.reddev.osucelebrity.osu.OsuStatus; import me.reddev.osucelebrity.osu.OsuStatus.Type; import me.reddev.osucelebrity.osu.OsuUser; import me.reddev.osucelebrity.osuapi.ApiUser; import me.reddev.osucelebrity.osuapi.MockOsuApi; import me.reddev.osucelebrity.osuapi.OsuApi; import me.reddev.osucelebrity.twitch.Twitch; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.tillerino.osuApiModel.GameModes; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import javax.annotation.CheckForNull; import javax.jdo.JDOHelper; import javax.jdo.PersistenceManager; package me.reddev.osucelebrity.core; public class SpectatorImplTest extends AbstractJDOTest { @Mock private Twitch twitch; @Mock protected Osu osu; @Mock private CoreSettings settings; @Mock private SceneSwitcher sceneSwitcher; @Mock
private TwitchApi twitchApi;
OsuCelebrity/OsuCelebrity
osuCelebrity-model/src/main/java/me/reddev/osucelebrity/twitchapi/TwitchApi.java
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/QueuedPlayer.java // @Data // @PersistenceCapable // public class QueuedPlayer { // public static final int CANCELLED = -2; // public static final int DONE = -1; // public static final int SPECTATING = 0; // public static final int NEXT = 1; // public static final int QUEUED = 2; // // @PrimaryKey // @Persistent(valueStrategy = IdGeneratorStrategy.INCREMENT) // long id; // // OsuUser player; // // QueueSource queueSource; // // long queuedAt; // // long startedAt; // // long stoppingAt; // // @Column(defaultValue = "0") // long lastRemainingTimeUpdate; // // @Index // int state = 2; // // @Column(defaultValue = "0") // int boost = 0; // // /** // * Creates a new queued player object. This alone won't enqueue this player. // * // * @param queuedPlayer the queued player's user object. // * @param queueSource the user interface via which this player was enqued. // * @param queuedAt current time. // */ // public QueuedPlayer(OsuUser queuedPlayer, QueueSource queueSource, long queuedAt) { // super(); // this.player = queuedPlayer; // this.queueSource = queueSource; // this.queuedAt = queuedAt; // } // // @Override // public boolean equals(Object other) { // if (other instanceof QueuedPlayer) { // QueuedPlayer otherUser = (QueuedPlayer) other; // return otherUser.player.getUserId() == player.getUserId(); // } // return false; // } // // @Override // public int hashCode() { // return player != null ? player.getUserId() : 0; // } // // public enum QueueSource { // TWITCH, OSU, AUTO // } // // public boolean isNotify() { // return queueSource != QueueSource.AUTO && player.isAllowsNotifications(); // } // }
import me.reddev.osucelebrity.PassAndReturnNonnull; import me.reddev.osucelebrity.core.QueuedPlayer; import java.io.IOException; import java.net.URL; import java.util.List; import javax.annotation.CheckForNull; import javax.jdo.PersistenceManager;
package me.reddev.osucelebrity.twitchapi; @PassAndReturnNonnull public interface TwitchApi { /** * Gets a list of moderators currently in a channel. * * @return The list of moderator usernames in lowercase */ List<String> getOnlineMods(); /** * Determines whether a given user is a moderator of a channel. * * @param username The username of the user * @return True if the user is a moderator */ boolean isModerator(String username); /** * Retrieves the user from the API. * @param username username (all lower case). * @param maxAge if > 0, cached data up to this age can be returned. * @param returnCachedOnIoException if true, a cached data is used if a server exception * occurrs during an update from the api * @return the user object. */ TwitchApiUser getUser(PersistenceManager pm, String username, long maxAge, boolean returnCachedOnIoException); /** * Retrieves the link to the past broadcast that a play occurred in at the exact time when the * play started. * * @param play any play. * @return the full URL. if no matching past broadcast can be found, null. */ @CheckForNull
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/QueuedPlayer.java // @Data // @PersistenceCapable // public class QueuedPlayer { // public static final int CANCELLED = -2; // public static final int DONE = -1; // public static final int SPECTATING = 0; // public static final int NEXT = 1; // public static final int QUEUED = 2; // // @PrimaryKey // @Persistent(valueStrategy = IdGeneratorStrategy.INCREMENT) // long id; // // OsuUser player; // // QueueSource queueSource; // // long queuedAt; // // long startedAt; // // long stoppingAt; // // @Column(defaultValue = "0") // long lastRemainingTimeUpdate; // // @Index // int state = 2; // // @Column(defaultValue = "0") // int boost = 0; // // /** // * Creates a new queued player object. This alone won't enqueue this player. // * // * @param queuedPlayer the queued player's user object. // * @param queueSource the user interface via which this player was enqued. // * @param queuedAt current time. // */ // public QueuedPlayer(OsuUser queuedPlayer, QueueSource queueSource, long queuedAt) { // super(); // this.player = queuedPlayer; // this.queueSource = queueSource; // this.queuedAt = queuedAt; // } // // @Override // public boolean equals(Object other) { // if (other instanceof QueuedPlayer) { // QueuedPlayer otherUser = (QueuedPlayer) other; // return otherUser.player.getUserId() == player.getUserId(); // } // return false; // } // // @Override // public int hashCode() { // return player != null ? player.getUserId() : 0; // } // // public enum QueueSource { // TWITCH, OSU, AUTO // } // // public boolean isNotify() { // return queueSource != QueueSource.AUTO && player.isAllowsNotifications(); // } // } // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/twitchapi/TwitchApi.java import me.reddev.osucelebrity.PassAndReturnNonnull; import me.reddev.osucelebrity.core.QueuedPlayer; import java.io.IOException; import java.net.URL; import java.util.List; import javax.annotation.CheckForNull; import javax.jdo.PersistenceManager; package me.reddev.osucelebrity.twitchapi; @PassAndReturnNonnull public interface TwitchApi { /** * Gets a list of moderators currently in a channel. * * @return The list of moderator usernames in lowercase */ List<String> getOnlineMods(); /** * Determines whether a given user is a moderator of a channel. * * @param username The username of the user * @return True if the user is a moderator */ boolean isModerator(String username); /** * Retrieves the user from the API. * @param username username (all lower case). * @param maxAge if > 0, cached data up to this age can be returned. * @param returnCachedOnIoException if true, a cached data is used if a server exception * occurrs during an update from the api * @return the user object. */ TwitchApiUser getUser(PersistenceManager pm, String username, long maxAge, boolean returnCachedOnIoException); /** * Retrieves the link to the past broadcast that a play occurred in at the exact time when the * play started. * * @param play any play. * @return the full URL. if no matching past broadcast can be found, null. */ @CheckForNull
URL getReplayLink(QueuedPlayer play) throws IOException;
OsuCelebrity/OsuCelebrity
osuCelebrity-core/src/main/java/me/reddev/osucelebrity/core/AutoQueue.java
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/QueuedPlayer.java // public enum QueueSource { // TWITCH, OSU, AUTO // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java // @PersistenceCapable(detachable = "true") // @Getter // @ToString // public class OsuUser { // @PrimaryKey // @UserId // @Getter(onMethod = @__(@UserId)) // private int userId; // // @Index // private String userName; // // private long downloaded; // // @Setter // private Privilege privilege = Privilege.PLAYER; // // @Setter // @Column(defaultValue = "true") // private boolean allowsNotifications = true; // // @Setter // @Column(defaultValue = "true") // @Index // private boolean allowsSpectating = true; // // @Setter(onParam = @__(@GameMode)) // @Getter(onMethod = @__(@GameMode)) // @Column(defaultValue = "0") // @GameMode // private int gameMode = 0; // // @Setter // @Column(defaultValue = "-1") // private long timeOutUntil = -1; // // /** // * Creates a new user object copying all relevant data from the api user object. // * // * @param user downloaded data. // * @param downloaded current time in millis. // */ // public OsuUser(OsuApiUser user, long downloaded) { // this.userId = user.getUserId(); // update(user, downloaded); // } // // /** // * updates this object with the downloaded data. // * // * @param user downloaded data // * @param downloaded current time // */ // public void update(OsuApiUser user, long downloaded) { // this.setUserName(user.getUserName()); // this.setDownloaded(downloaded); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof OsuUser) { // return ((OsuUser) obj).userId == userId; // } // return false; // } // // @Override // public int hashCode() { // return userId; // } // // void setDownloaded(long downloaded) { // this.downloaded = downloaded; // } // // void setUserName(String userName) { // this.userName = userName; // } // }
import static me.reddev.osucelebrity.osuapi.QApiUser.apiUser; import com.querydsl.jdo.JDOQuery; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import me.reddev.osucelebrity.core.QueuedPlayer.QueueSource; import me.reddev.osucelebrity.osu.Osu; import me.reddev.osucelebrity.osu.Osu.PollStatusConsumer; import me.reddev.osucelebrity.osu.OsuUser; import me.reddev.osucelebrity.osu.PlayerStatus; import me.reddev.osucelebrity.osu.PlayerStatus.PlayerStatusType; import me.reddev.osucelebrity.osuapi.ApiUser; import me.reddev.osucelebrity.osuapi.OsuApi; import org.tillerino.osuApiModel.GameModes; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.function.ToDoubleFunction; import javax.inject.Inject; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory;
/** * Perform one attempt to auto-queue. Logs exceptions. */ public void loop() { PersistenceManager pm = pmf.getPersistenceManager(); try { loop(pm); } catch (Exception e) { log.error("exception", e); } finally { pm.close(); } } void loop(PersistenceManager pm) throws InterruptedException { if (spectator.getQueueSize(pm) >= settings.getAutoQueueMaxSize()) { return; } if (!semaphore.tryAcquire(10, TimeUnit.SECONDS)) { log.warn("last auto q poll took too long"); semaphore = new Semaphore(1); semaphore.acquire(); } int userId = drawUserId(pm); if (userId < 0) { semaphore.release(); return; }
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/QueuedPlayer.java // public enum QueueSource { // TWITCH, OSU, AUTO // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java // @PersistenceCapable(detachable = "true") // @Getter // @ToString // public class OsuUser { // @PrimaryKey // @UserId // @Getter(onMethod = @__(@UserId)) // private int userId; // // @Index // private String userName; // // private long downloaded; // // @Setter // private Privilege privilege = Privilege.PLAYER; // // @Setter // @Column(defaultValue = "true") // private boolean allowsNotifications = true; // // @Setter // @Column(defaultValue = "true") // @Index // private boolean allowsSpectating = true; // // @Setter(onParam = @__(@GameMode)) // @Getter(onMethod = @__(@GameMode)) // @Column(defaultValue = "0") // @GameMode // private int gameMode = 0; // // @Setter // @Column(defaultValue = "-1") // private long timeOutUntil = -1; // // /** // * Creates a new user object copying all relevant data from the api user object. // * // * @param user downloaded data. // * @param downloaded current time in millis. // */ // public OsuUser(OsuApiUser user, long downloaded) { // this.userId = user.getUserId(); // update(user, downloaded); // } // // /** // * updates this object with the downloaded data. // * // * @param user downloaded data // * @param downloaded current time // */ // public void update(OsuApiUser user, long downloaded) { // this.setUserName(user.getUserName()); // this.setDownloaded(downloaded); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof OsuUser) { // return ((OsuUser) obj).userId == userId; // } // return false; // } // // @Override // public int hashCode() { // return userId; // } // // void setDownloaded(long downloaded) { // this.downloaded = downloaded; // } // // void setUserName(String userName) { // this.userName = userName; // } // } // Path: osuCelebrity-core/src/main/java/me/reddev/osucelebrity/core/AutoQueue.java import static me.reddev.osucelebrity.osuapi.QApiUser.apiUser; import com.querydsl.jdo.JDOQuery; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import me.reddev.osucelebrity.core.QueuedPlayer.QueueSource; import me.reddev.osucelebrity.osu.Osu; import me.reddev.osucelebrity.osu.Osu.PollStatusConsumer; import me.reddev.osucelebrity.osu.OsuUser; import me.reddev.osucelebrity.osu.PlayerStatus; import me.reddev.osucelebrity.osu.PlayerStatus.PlayerStatusType; import me.reddev.osucelebrity.osuapi.ApiUser; import me.reddev.osucelebrity.osuapi.OsuApi; import org.tillerino.osuApiModel.GameModes; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.function.ToDoubleFunction; import javax.inject.Inject; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; /** * Perform one attempt to auto-queue. Logs exceptions. */ public void loop() { PersistenceManager pm = pmf.getPersistenceManager(); try { loop(pm); } catch (Exception e) { log.error("exception", e); } finally { pm.close(); } } void loop(PersistenceManager pm) throws InterruptedException { if (spectator.getQueueSize(pm) >= settings.getAutoQueueMaxSize()) { return; } if (!semaphore.tryAcquire(10, TimeUnit.SECONDS)) { log.warn("last auto q poll took too long"); semaphore = new Semaphore(1); semaphore.acquire(); } int userId = drawUserId(pm); if (userId < 0) { semaphore.release(); return; }
OsuUser user;
OsuCelebrity/OsuCelebrity
osuCelebrity-core/src/main/java/me/reddev/osucelebrity/core/AutoQueue.java
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/QueuedPlayer.java // public enum QueueSource { // TWITCH, OSU, AUTO // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java // @PersistenceCapable(detachable = "true") // @Getter // @ToString // public class OsuUser { // @PrimaryKey // @UserId // @Getter(onMethod = @__(@UserId)) // private int userId; // // @Index // private String userName; // // private long downloaded; // // @Setter // private Privilege privilege = Privilege.PLAYER; // // @Setter // @Column(defaultValue = "true") // private boolean allowsNotifications = true; // // @Setter // @Column(defaultValue = "true") // @Index // private boolean allowsSpectating = true; // // @Setter(onParam = @__(@GameMode)) // @Getter(onMethod = @__(@GameMode)) // @Column(defaultValue = "0") // @GameMode // private int gameMode = 0; // // @Setter // @Column(defaultValue = "-1") // private long timeOutUntil = -1; // // /** // * Creates a new user object copying all relevant data from the api user object. // * // * @param user downloaded data. // * @param downloaded current time in millis. // */ // public OsuUser(OsuApiUser user, long downloaded) { // this.userId = user.getUserId(); // update(user, downloaded); // } // // /** // * updates this object with the downloaded data. // * // * @param user downloaded data // * @param downloaded current time // */ // public void update(OsuApiUser user, long downloaded) { // this.setUserName(user.getUserName()); // this.setDownloaded(downloaded); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof OsuUser) { // return ((OsuUser) obj).userId == userId; // } // return false; // } // // @Override // public int hashCode() { // return userId; // } // // void setDownloaded(long downloaded) { // this.downloaded = downloaded; // } // // void setUserName(String userName) { // this.userName = userName; // } // }
import static me.reddev.osucelebrity.osuapi.QApiUser.apiUser; import com.querydsl.jdo.JDOQuery; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import me.reddev.osucelebrity.core.QueuedPlayer.QueueSource; import me.reddev.osucelebrity.osu.Osu; import me.reddev.osucelebrity.osu.Osu.PollStatusConsumer; import me.reddev.osucelebrity.osu.OsuUser; import me.reddev.osucelebrity.osu.PlayerStatus; import me.reddev.osucelebrity.osu.PlayerStatus.PlayerStatusType; import me.reddev.osucelebrity.osuapi.ApiUser; import me.reddev.osucelebrity.osuapi.OsuApi; import org.tillerino.osuApiModel.GameModes; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.function.ToDoubleFunction; import javax.inject.Inject; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory;
return -1; } double rnd = Math.random() * sum; Entry<Double, ApiUser> floorEntry = distribution.floorEntry(rnd); if (floorEntry == null) { throw new RuntimeException(rnd + " in " + sum); } int userId = floorEntry.getValue().getUserId(); if (lastDraws.size() >= 100) { lastDrawsAsSet.remove(lastDraws.removeFirst()); } lastDraws.add(userId); lastDrawsAsSet.add(userId); return userId; } List<ApiUser> getTopPlayers(PersistenceManager pm) { try (JDOQuery<ApiUser> query = new JDOQuery<>(pm).select(apiUser).from(apiUser)) { return new ArrayList<>(query.where(apiUser.rank.loe(1000), apiUser.rank.goe(1)).fetch()); } } private void pollStatus(OsuUser user) { Semaphore currentSemaphore = semaphore; PollStatusConsumer action = new PollStatusConsumer() { @Override public void accept(PersistenceManager pm, PlayerStatus status) throws IOException { currentSemaphore.release(); if (status.getType() == PlayerStatusType.PLAYING) { QueuedPlayer queueRequest =
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/QueuedPlayer.java // public enum QueueSource { // TWITCH, OSU, AUTO // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java // @PersistenceCapable(detachable = "true") // @Getter // @ToString // public class OsuUser { // @PrimaryKey // @UserId // @Getter(onMethod = @__(@UserId)) // private int userId; // // @Index // private String userName; // // private long downloaded; // // @Setter // private Privilege privilege = Privilege.PLAYER; // // @Setter // @Column(defaultValue = "true") // private boolean allowsNotifications = true; // // @Setter // @Column(defaultValue = "true") // @Index // private boolean allowsSpectating = true; // // @Setter(onParam = @__(@GameMode)) // @Getter(onMethod = @__(@GameMode)) // @Column(defaultValue = "0") // @GameMode // private int gameMode = 0; // // @Setter // @Column(defaultValue = "-1") // private long timeOutUntil = -1; // // /** // * Creates a new user object copying all relevant data from the api user object. // * // * @param user downloaded data. // * @param downloaded current time in millis. // */ // public OsuUser(OsuApiUser user, long downloaded) { // this.userId = user.getUserId(); // update(user, downloaded); // } // // /** // * updates this object with the downloaded data. // * // * @param user downloaded data // * @param downloaded current time // */ // public void update(OsuApiUser user, long downloaded) { // this.setUserName(user.getUserName()); // this.setDownloaded(downloaded); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof OsuUser) { // return ((OsuUser) obj).userId == userId; // } // return false; // } // // @Override // public int hashCode() { // return userId; // } // // void setDownloaded(long downloaded) { // this.downloaded = downloaded; // } // // void setUserName(String userName) { // this.userName = userName; // } // } // Path: osuCelebrity-core/src/main/java/me/reddev/osucelebrity/core/AutoQueue.java import static me.reddev.osucelebrity.osuapi.QApiUser.apiUser; import com.querydsl.jdo.JDOQuery; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import me.reddev.osucelebrity.core.QueuedPlayer.QueueSource; import me.reddev.osucelebrity.osu.Osu; import me.reddev.osucelebrity.osu.Osu.PollStatusConsumer; import me.reddev.osucelebrity.osu.OsuUser; import me.reddev.osucelebrity.osu.PlayerStatus; import me.reddev.osucelebrity.osu.PlayerStatus.PlayerStatusType; import me.reddev.osucelebrity.osuapi.ApiUser; import me.reddev.osucelebrity.osuapi.OsuApi; import org.tillerino.osuApiModel.GameModes; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.function.ToDoubleFunction; import javax.inject.Inject; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; return -1; } double rnd = Math.random() * sum; Entry<Double, ApiUser> floorEntry = distribution.floorEntry(rnd); if (floorEntry == null) { throw new RuntimeException(rnd + " in " + sum); } int userId = floorEntry.getValue().getUserId(); if (lastDraws.size() >= 100) { lastDrawsAsSet.remove(lastDraws.removeFirst()); } lastDraws.add(userId); lastDrawsAsSet.add(userId); return userId; } List<ApiUser> getTopPlayers(PersistenceManager pm) { try (JDOQuery<ApiUser> query = new JDOQuery<>(pm).select(apiUser).from(apiUser)) { return new ArrayList<>(query.where(apiUser.rank.loe(1000), apiUser.rank.goe(1)).fetch()); } } private void pollStatus(OsuUser user) { Semaphore currentSemaphore = semaphore; PollStatusConsumer action = new PollStatusConsumer() { @Override public void accept(PersistenceManager pm, PlayerStatus status) throws IOException { currentSemaphore.release(); if (status.getType() == PlayerStatusType.PLAYING) { QueuedPlayer queueRequest =
new QueuedPlayer(status.getUser(), QueueSource.AUTO, clock.getTime());
OsuCelebrity/OsuCelebrity
osuCelebrity-osu/src/main/java/me/reddev/osucelebrity/osu/OsuApiImpl.java
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/Clock.java // public interface Clock { // long getTime(); // // void sleepUntil(long time) throws InterruptedException; // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuIrcUser.java // @PersistenceCapable // @Data // @AllArgsConstructor // public class OsuIrcUser { // @PrimaryKey // String ircName; // // @CheckForNull // OsuUser user; // // long resolved; // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java // @PersistenceCapable(detachable = "true") // @Getter // @ToString // public class OsuUser { // @PrimaryKey // @UserId // @Getter(onMethod = @__(@UserId)) // private int userId; // // @Index // private String userName; // // private long downloaded; // // @Setter // private Privilege privilege = Privilege.PLAYER; // // @Setter // @Column(defaultValue = "true") // private boolean allowsNotifications = true; // // @Setter // @Column(defaultValue = "true") // @Index // private boolean allowsSpectating = true; // // @Setter(onParam = @__(@GameMode)) // @Getter(onMethod = @__(@GameMode)) // @Column(defaultValue = "0") // @GameMode // private int gameMode = 0; // // @Setter // @Column(defaultValue = "-1") // private long timeOutUntil = -1; // // /** // * Creates a new user object copying all relevant data from the api user object. // * // * @param user downloaded data. // * @param downloaded current time in millis. // */ // public OsuUser(OsuApiUser user, long downloaded) { // this.userId = user.getUserId(); // update(user, downloaded); // } // // /** // * updates this object with the downloaded data. // * // * @param user downloaded data // * @param downloaded current time // */ // public void update(OsuApiUser user, long downloaded) { // this.setUserName(user.getUserName()); // this.setDownloaded(downloaded); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof OsuUser) { // return ((OsuUser) obj).userId == userId; // } // return false; // } // // @Override // public int hashCode() { // return userId; // } // // void setDownloaded(long downloaded) { // this.downloaded = downloaded; // } // // void setUserName(String userName) { // this.userName = userName; // } // }
import static me.reddev.osucelebrity.osu.QOsuIrcUser.osuIrcUser; import static me.reddev.osucelebrity.osu.QOsuUser.osuUser; import static me.reddev.osucelebrity.osu.QPlayerActivity.playerActivity; import static me.reddev.osucelebrity.osuapi.QApiUser.apiUser; import com.querydsl.jdo.JDOQuery; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import lombok.RequiredArgsConstructor; import me.reddev.osucelebrity.core.Clock; import me.reddev.osucelebrity.osu.OsuIrcUser; import me.reddev.osucelebrity.osu.OsuUser; import me.reddev.osucelebrity.osu.PlayerActivity; import me.reddev.osucelebrity.osuapi.ApiUser; import me.reddev.osucelebrity.osuapi.OsuApi; import org.mapstruct.Mapper; import org.mapstruct.MappingTarget; import org.tillerino.osuApiModel.Downloader; import org.tillerino.osuApiModel.GameModes; import org.tillerino.osuApiModel.OsuApiScore; import org.tillerino.osuApiModel.OsuApiUser; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.List; import javax.inject.Inject; import javax.jdo.PersistenceManager;
package me.reddev.osucelebrity.osu; @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class OsuApiImpl implements OsuApi { @Mapper public interface FromApiMapper { void update(OsuApiUser user, @MappingTarget ApiUser target); } private final Downloader downloader;
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/Clock.java // public interface Clock { // long getTime(); // // void sleepUntil(long time) throws InterruptedException; // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuIrcUser.java // @PersistenceCapable // @Data // @AllArgsConstructor // public class OsuIrcUser { // @PrimaryKey // String ircName; // // @CheckForNull // OsuUser user; // // long resolved; // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java // @PersistenceCapable(detachable = "true") // @Getter // @ToString // public class OsuUser { // @PrimaryKey // @UserId // @Getter(onMethod = @__(@UserId)) // private int userId; // // @Index // private String userName; // // private long downloaded; // // @Setter // private Privilege privilege = Privilege.PLAYER; // // @Setter // @Column(defaultValue = "true") // private boolean allowsNotifications = true; // // @Setter // @Column(defaultValue = "true") // @Index // private boolean allowsSpectating = true; // // @Setter(onParam = @__(@GameMode)) // @Getter(onMethod = @__(@GameMode)) // @Column(defaultValue = "0") // @GameMode // private int gameMode = 0; // // @Setter // @Column(defaultValue = "-1") // private long timeOutUntil = -1; // // /** // * Creates a new user object copying all relevant data from the api user object. // * // * @param user downloaded data. // * @param downloaded current time in millis. // */ // public OsuUser(OsuApiUser user, long downloaded) { // this.userId = user.getUserId(); // update(user, downloaded); // } // // /** // * updates this object with the downloaded data. // * // * @param user downloaded data // * @param downloaded current time // */ // public void update(OsuApiUser user, long downloaded) { // this.setUserName(user.getUserName()); // this.setDownloaded(downloaded); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof OsuUser) { // return ((OsuUser) obj).userId == userId; // } // return false; // } // // @Override // public int hashCode() { // return userId; // } // // void setDownloaded(long downloaded) { // this.downloaded = downloaded; // } // // void setUserName(String userName) { // this.userName = userName; // } // } // Path: osuCelebrity-osu/src/main/java/me/reddev/osucelebrity/osu/OsuApiImpl.java import static me.reddev.osucelebrity.osu.QOsuIrcUser.osuIrcUser; import static me.reddev.osucelebrity.osu.QOsuUser.osuUser; import static me.reddev.osucelebrity.osu.QPlayerActivity.playerActivity; import static me.reddev.osucelebrity.osuapi.QApiUser.apiUser; import com.querydsl.jdo.JDOQuery; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import lombok.RequiredArgsConstructor; import me.reddev.osucelebrity.core.Clock; import me.reddev.osucelebrity.osu.OsuIrcUser; import me.reddev.osucelebrity.osu.OsuUser; import me.reddev.osucelebrity.osu.PlayerActivity; import me.reddev.osucelebrity.osuapi.ApiUser; import me.reddev.osucelebrity.osuapi.OsuApi; import org.mapstruct.Mapper; import org.mapstruct.MappingTarget; import org.tillerino.osuApiModel.Downloader; import org.tillerino.osuApiModel.GameModes; import org.tillerino.osuApiModel.OsuApiScore; import org.tillerino.osuApiModel.OsuApiUser; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.List; import javax.inject.Inject; import javax.jdo.PersistenceManager; package me.reddev.osucelebrity.osu; @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class OsuApiImpl implements OsuApi { @Mapper public interface FromApiMapper { void update(OsuApiUser user, @MappingTarget ApiUser target); } private final Downloader downloader;
private final Clock clock;
OsuCelebrity/OsuCelebrity
osuCelebrity-osu/src/main/java/me/reddev/osucelebrity/osu/OsuApiImpl.java
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/Clock.java // public interface Clock { // long getTime(); // // void sleepUntil(long time) throws InterruptedException; // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuIrcUser.java // @PersistenceCapable // @Data // @AllArgsConstructor // public class OsuIrcUser { // @PrimaryKey // String ircName; // // @CheckForNull // OsuUser user; // // long resolved; // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java // @PersistenceCapable(detachable = "true") // @Getter // @ToString // public class OsuUser { // @PrimaryKey // @UserId // @Getter(onMethod = @__(@UserId)) // private int userId; // // @Index // private String userName; // // private long downloaded; // // @Setter // private Privilege privilege = Privilege.PLAYER; // // @Setter // @Column(defaultValue = "true") // private boolean allowsNotifications = true; // // @Setter // @Column(defaultValue = "true") // @Index // private boolean allowsSpectating = true; // // @Setter(onParam = @__(@GameMode)) // @Getter(onMethod = @__(@GameMode)) // @Column(defaultValue = "0") // @GameMode // private int gameMode = 0; // // @Setter // @Column(defaultValue = "-1") // private long timeOutUntil = -1; // // /** // * Creates a new user object copying all relevant data from the api user object. // * // * @param user downloaded data. // * @param downloaded current time in millis. // */ // public OsuUser(OsuApiUser user, long downloaded) { // this.userId = user.getUserId(); // update(user, downloaded); // } // // /** // * updates this object with the downloaded data. // * // * @param user downloaded data // * @param downloaded current time // */ // public void update(OsuApiUser user, long downloaded) { // this.setUserName(user.getUserName()); // this.setDownloaded(downloaded); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof OsuUser) { // return ((OsuUser) obj).userId == userId; // } // return false; // } // // @Override // public int hashCode() { // return userId; // } // // void setDownloaded(long downloaded) { // this.downloaded = downloaded; // } // // void setUserName(String userName) { // this.userName = userName; // } // }
import static me.reddev.osucelebrity.osu.QOsuIrcUser.osuIrcUser; import static me.reddev.osucelebrity.osu.QOsuUser.osuUser; import static me.reddev.osucelebrity.osu.QPlayerActivity.playerActivity; import static me.reddev.osucelebrity.osuapi.QApiUser.apiUser; import com.querydsl.jdo.JDOQuery; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import lombok.RequiredArgsConstructor; import me.reddev.osucelebrity.core.Clock; import me.reddev.osucelebrity.osu.OsuIrcUser; import me.reddev.osucelebrity.osu.OsuUser; import me.reddev.osucelebrity.osu.PlayerActivity; import me.reddev.osucelebrity.osuapi.ApiUser; import me.reddev.osucelebrity.osuapi.OsuApi; import org.mapstruct.Mapper; import org.mapstruct.MappingTarget; import org.tillerino.osuApiModel.Downloader; import org.tillerino.osuApiModel.GameModes; import org.tillerino.osuApiModel.OsuApiScore; import org.tillerino.osuApiModel.OsuApiUser; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.List; import javax.inject.Inject; import javax.jdo.PersistenceManager;
package me.reddev.osucelebrity.osu; @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class OsuApiImpl implements OsuApi { @Mapper public interface FromApiMapper { void update(OsuApiUser user, @MappingTarget ApiUser target); } private final Downloader downloader; private final Clock clock; @Override
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/Clock.java // public interface Clock { // long getTime(); // // void sleepUntil(long time) throws InterruptedException; // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuIrcUser.java // @PersistenceCapable // @Data // @AllArgsConstructor // public class OsuIrcUser { // @PrimaryKey // String ircName; // // @CheckForNull // OsuUser user; // // long resolved; // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java // @PersistenceCapable(detachable = "true") // @Getter // @ToString // public class OsuUser { // @PrimaryKey // @UserId // @Getter(onMethod = @__(@UserId)) // private int userId; // // @Index // private String userName; // // private long downloaded; // // @Setter // private Privilege privilege = Privilege.PLAYER; // // @Setter // @Column(defaultValue = "true") // private boolean allowsNotifications = true; // // @Setter // @Column(defaultValue = "true") // @Index // private boolean allowsSpectating = true; // // @Setter(onParam = @__(@GameMode)) // @Getter(onMethod = @__(@GameMode)) // @Column(defaultValue = "0") // @GameMode // private int gameMode = 0; // // @Setter // @Column(defaultValue = "-1") // private long timeOutUntil = -1; // // /** // * Creates a new user object copying all relevant data from the api user object. // * // * @param user downloaded data. // * @param downloaded current time in millis. // */ // public OsuUser(OsuApiUser user, long downloaded) { // this.userId = user.getUserId(); // update(user, downloaded); // } // // /** // * updates this object with the downloaded data. // * // * @param user downloaded data // * @param downloaded current time // */ // public void update(OsuApiUser user, long downloaded) { // this.setUserName(user.getUserName()); // this.setDownloaded(downloaded); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof OsuUser) { // return ((OsuUser) obj).userId == userId; // } // return false; // } // // @Override // public int hashCode() { // return userId; // } // // void setDownloaded(long downloaded) { // this.downloaded = downloaded; // } // // void setUserName(String userName) { // this.userName = userName; // } // } // Path: osuCelebrity-osu/src/main/java/me/reddev/osucelebrity/osu/OsuApiImpl.java import static me.reddev.osucelebrity.osu.QOsuIrcUser.osuIrcUser; import static me.reddev.osucelebrity.osu.QOsuUser.osuUser; import static me.reddev.osucelebrity.osu.QPlayerActivity.playerActivity; import static me.reddev.osucelebrity.osuapi.QApiUser.apiUser; import com.querydsl.jdo.JDOQuery; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import lombok.RequiredArgsConstructor; import me.reddev.osucelebrity.core.Clock; import me.reddev.osucelebrity.osu.OsuIrcUser; import me.reddev.osucelebrity.osu.OsuUser; import me.reddev.osucelebrity.osu.PlayerActivity; import me.reddev.osucelebrity.osuapi.ApiUser; import me.reddev.osucelebrity.osuapi.OsuApi; import org.mapstruct.Mapper; import org.mapstruct.MappingTarget; import org.tillerino.osuApiModel.Downloader; import org.tillerino.osuApiModel.GameModes; import org.tillerino.osuApiModel.OsuApiScore; import org.tillerino.osuApiModel.OsuApiUser; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.List; import javax.inject.Inject; import javax.jdo.PersistenceManager; package me.reddev.osucelebrity.osu; @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class OsuApiImpl implements OsuApi { @Mapper public interface FromApiMapper { void update(OsuApiUser user, @MappingTarget ApiUser target); } private final Downloader downloader; private final Clock clock; @Override
public OsuUser getUser(int userid, PersistenceManager pm, long maxAge) throws IOException {
OsuCelebrity/OsuCelebrity
osuCelebrity-osu/src/main/java/me/reddev/osucelebrity/osu/OsuApiImpl.java
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/Clock.java // public interface Clock { // long getTime(); // // void sleepUntil(long time) throws InterruptedException; // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuIrcUser.java // @PersistenceCapable // @Data // @AllArgsConstructor // public class OsuIrcUser { // @PrimaryKey // String ircName; // // @CheckForNull // OsuUser user; // // long resolved; // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java // @PersistenceCapable(detachable = "true") // @Getter // @ToString // public class OsuUser { // @PrimaryKey // @UserId // @Getter(onMethod = @__(@UserId)) // private int userId; // // @Index // private String userName; // // private long downloaded; // // @Setter // private Privilege privilege = Privilege.PLAYER; // // @Setter // @Column(defaultValue = "true") // private boolean allowsNotifications = true; // // @Setter // @Column(defaultValue = "true") // @Index // private boolean allowsSpectating = true; // // @Setter(onParam = @__(@GameMode)) // @Getter(onMethod = @__(@GameMode)) // @Column(defaultValue = "0") // @GameMode // private int gameMode = 0; // // @Setter // @Column(defaultValue = "-1") // private long timeOutUntil = -1; // // /** // * Creates a new user object copying all relevant data from the api user object. // * // * @param user downloaded data. // * @param downloaded current time in millis. // */ // public OsuUser(OsuApiUser user, long downloaded) { // this.userId = user.getUserId(); // update(user, downloaded); // } // // /** // * updates this object with the downloaded data. // * // * @param user downloaded data // * @param downloaded current time // */ // public void update(OsuApiUser user, long downloaded) { // this.setUserName(user.getUserName()); // this.setDownloaded(downloaded); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof OsuUser) { // return ((OsuUser) obj).userId == userId; // } // return false; // } // // @Override // public int hashCode() { // return userId; // } // // void setDownloaded(long downloaded) { // this.downloaded = downloaded; // } // // void setUserName(String userName) { // this.userName = userName; // } // }
import static me.reddev.osucelebrity.osu.QOsuIrcUser.osuIrcUser; import static me.reddev.osucelebrity.osu.QOsuUser.osuUser; import static me.reddev.osucelebrity.osu.QPlayerActivity.playerActivity; import static me.reddev.osucelebrity.osuapi.QApiUser.apiUser; import com.querydsl.jdo.JDOQuery; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import lombok.RequiredArgsConstructor; import me.reddev.osucelebrity.core.Clock; import me.reddev.osucelebrity.osu.OsuIrcUser; import me.reddev.osucelebrity.osu.OsuUser; import me.reddev.osucelebrity.osu.PlayerActivity; import me.reddev.osucelebrity.osuapi.ApiUser; import me.reddev.osucelebrity.osuapi.OsuApi; import org.mapstruct.Mapper; import org.mapstruct.MappingTarget; import org.tillerino.osuApiModel.Downloader; import org.tillerino.osuApiModel.GameModes; import org.tillerino.osuApiModel.OsuApiScore; import org.tillerino.osuApiModel.OsuApiUser; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.List; import javax.inject.Inject; import javax.jdo.PersistenceManager;
ApiUser saved = query.where(apiUser.userId.eq(downloaded.getUserId()), apiUser.gameMode.eq(downloaded.getMode())).fetchOne(); if (saved == null) { saved = new ApiUser(downloaded.getUserId(), downloaded.getMode()); new FromApiMapperImpl().update(downloaded, saved); saved.setDownloaded(clock.getTime()); pm.makePersistent(saved); } else { new FromApiMapperImpl().update(downloaded, saved); saved.setDownloaded(clock.getTime()); } } } void saveGeneral(PersistenceManager pm, OsuApiUser downloaded) { try (JDOQuery<OsuUser> query = new JDOQuery<>(pm).select(osuUser).from(osuUser)) { OsuUser saved = query.where(osuUser.userId.eq(downloaded.getUserId())).fetchOne(); if (saved == null) { pm.makePersistent(new OsuUser(downloaded, clock.getTime())); } else { saved.update(downloaded, clock.getTime()); } } } @SuppressFBWarnings("TQ") @Override
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/Clock.java // public interface Clock { // long getTime(); // // void sleepUntil(long time) throws InterruptedException; // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuIrcUser.java // @PersistenceCapable // @Data // @AllArgsConstructor // public class OsuIrcUser { // @PrimaryKey // String ircName; // // @CheckForNull // OsuUser user; // // long resolved; // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java // @PersistenceCapable(detachable = "true") // @Getter // @ToString // public class OsuUser { // @PrimaryKey // @UserId // @Getter(onMethod = @__(@UserId)) // private int userId; // // @Index // private String userName; // // private long downloaded; // // @Setter // private Privilege privilege = Privilege.PLAYER; // // @Setter // @Column(defaultValue = "true") // private boolean allowsNotifications = true; // // @Setter // @Column(defaultValue = "true") // @Index // private boolean allowsSpectating = true; // // @Setter(onParam = @__(@GameMode)) // @Getter(onMethod = @__(@GameMode)) // @Column(defaultValue = "0") // @GameMode // private int gameMode = 0; // // @Setter // @Column(defaultValue = "-1") // private long timeOutUntil = -1; // // /** // * Creates a new user object copying all relevant data from the api user object. // * // * @param user downloaded data. // * @param downloaded current time in millis. // */ // public OsuUser(OsuApiUser user, long downloaded) { // this.userId = user.getUserId(); // update(user, downloaded); // } // // /** // * updates this object with the downloaded data. // * // * @param user downloaded data // * @param downloaded current time // */ // public void update(OsuApiUser user, long downloaded) { // this.setUserName(user.getUserName()); // this.setDownloaded(downloaded); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof OsuUser) { // return ((OsuUser) obj).userId == userId; // } // return false; // } // // @Override // public int hashCode() { // return userId; // } // // void setDownloaded(long downloaded) { // this.downloaded = downloaded; // } // // void setUserName(String userName) { // this.userName = userName; // } // } // Path: osuCelebrity-osu/src/main/java/me/reddev/osucelebrity/osu/OsuApiImpl.java import static me.reddev.osucelebrity.osu.QOsuIrcUser.osuIrcUser; import static me.reddev.osucelebrity.osu.QOsuUser.osuUser; import static me.reddev.osucelebrity.osu.QPlayerActivity.playerActivity; import static me.reddev.osucelebrity.osuapi.QApiUser.apiUser; import com.querydsl.jdo.JDOQuery; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import lombok.RequiredArgsConstructor; import me.reddev.osucelebrity.core.Clock; import me.reddev.osucelebrity.osu.OsuIrcUser; import me.reddev.osucelebrity.osu.OsuUser; import me.reddev.osucelebrity.osu.PlayerActivity; import me.reddev.osucelebrity.osuapi.ApiUser; import me.reddev.osucelebrity.osuapi.OsuApi; import org.mapstruct.Mapper; import org.mapstruct.MappingTarget; import org.tillerino.osuApiModel.Downloader; import org.tillerino.osuApiModel.GameModes; import org.tillerino.osuApiModel.OsuApiScore; import org.tillerino.osuApiModel.OsuApiUser; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.List; import javax.inject.Inject; import javax.jdo.PersistenceManager; ApiUser saved = query.where(apiUser.userId.eq(downloaded.getUserId()), apiUser.gameMode.eq(downloaded.getMode())).fetchOne(); if (saved == null) { saved = new ApiUser(downloaded.getUserId(), downloaded.getMode()); new FromApiMapperImpl().update(downloaded, saved); saved.setDownloaded(clock.getTime()); pm.makePersistent(saved); } else { new FromApiMapperImpl().update(downloaded, saved); saved.setDownloaded(clock.getTime()); } } } void saveGeneral(PersistenceManager pm, OsuApiUser downloaded) { try (JDOQuery<OsuUser> query = new JDOQuery<>(pm).select(osuUser).from(osuUser)) { OsuUser saved = query.where(osuUser.userId.eq(downloaded.getUserId())).fetchOne(); if (saved == null) { pm.makePersistent(new OsuUser(downloaded, clock.getTime())); } else { saved.update(downloaded, clock.getTime()); } } } @SuppressFBWarnings("TQ") @Override
public OsuIrcUser getIrcUser(String ircUserName, PersistenceManager pm, long maxAge)
OsuCelebrity/OsuCelebrity
osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/api/DisplayVote.java
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/VoteType.java // public enum VoteType { // UP, // DOWN; // }
import lombok.Data; import me.reddev.osucelebrity.core.VoteType;
package me.reddev.osucelebrity.core.api; @Data public class DisplayVote { public long id; long voteTime; String twitchUser;
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/VoteType.java // public enum VoteType { // UP, // DOWN; // } // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/api/DisplayVote.java import lombok.Data; import me.reddev.osucelebrity.core.VoteType; package me.reddev.osucelebrity.core.api; @Data public class DisplayVote { public long id; long voteTime; String twitchUser;
VoteType voteType;
OsuCelebrity/OsuCelebrity
osuCelebrity-core/src/main/java/me/reddev/osucelebrity/core/api/VoteService.java
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/QueuedPlayer.java // @Data // @PersistenceCapable // public class QueuedPlayer { // public static final int CANCELLED = -2; // public static final int DONE = -1; // public static final int SPECTATING = 0; // public static final int NEXT = 1; // public static final int QUEUED = 2; // // @PrimaryKey // @Persistent(valueStrategy = IdGeneratorStrategy.INCREMENT) // long id; // // OsuUser player; // // QueueSource queueSource; // // long queuedAt; // // long startedAt; // // long stoppingAt; // // @Column(defaultValue = "0") // long lastRemainingTimeUpdate; // // @Index // int state = 2; // // @Column(defaultValue = "0") // int boost = 0; // // /** // * Creates a new queued player object. This alone won't enqueue this player. // * // * @param queuedPlayer the queued player's user object. // * @param queueSource the user interface via which this player was enqued. // * @param queuedAt current time. // */ // public QueuedPlayer(OsuUser queuedPlayer, QueueSource queueSource, long queuedAt) { // super(); // this.player = queuedPlayer; // this.queueSource = queueSource; // this.queuedAt = queuedAt; // } // // @Override // public boolean equals(Object other) { // if (other instanceof QueuedPlayer) { // QueuedPlayer otherUser = (QueuedPlayer) other; // return otherUser.player.getUserId() == player.getUserId(); // } // return false; // } // // @Override // public int hashCode() { // return player != null ? player.getUserId() : 0; // } // // public enum QueueSource { // TWITCH, OSU, AUTO // } // // public boolean isNotify() { // return queueSource != QueueSource.AUTO && player.isAllowsNotifications(); // } // }
import lombok.RequiredArgsConstructor; import me.reddev.osucelebrity.core.QueuedPlayer; import me.reddev.osucelebrity.core.Spectator; import me.reddev.osucelebrity.core.Vote; import org.mapstruct.Mapper; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Singleton; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType;
package me.reddev.osucelebrity.core.api; @Singleton @Path("/votes") @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class VoteService { @Mapper public interface VoteMapper { public DisplayVote voteToDisplayVote(Vote vote); } private final PersistenceManagerFactory pmf; private final Spectator spectator; /** * Shows the votes for the current player. * @return List of unique votes for the current player */ @GET @Produces(MediaType.APPLICATION_JSON) public List<DisplayVote> votes() { PersistenceManager pm = pmf.getPersistenceManager(); try {
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/QueuedPlayer.java // @Data // @PersistenceCapable // public class QueuedPlayer { // public static final int CANCELLED = -2; // public static final int DONE = -1; // public static final int SPECTATING = 0; // public static final int NEXT = 1; // public static final int QUEUED = 2; // // @PrimaryKey // @Persistent(valueStrategy = IdGeneratorStrategy.INCREMENT) // long id; // // OsuUser player; // // QueueSource queueSource; // // long queuedAt; // // long startedAt; // // long stoppingAt; // // @Column(defaultValue = "0") // long lastRemainingTimeUpdate; // // @Index // int state = 2; // // @Column(defaultValue = "0") // int boost = 0; // // /** // * Creates a new queued player object. This alone won't enqueue this player. // * // * @param queuedPlayer the queued player's user object. // * @param queueSource the user interface via which this player was enqued. // * @param queuedAt current time. // */ // public QueuedPlayer(OsuUser queuedPlayer, QueueSource queueSource, long queuedAt) { // super(); // this.player = queuedPlayer; // this.queueSource = queueSource; // this.queuedAt = queuedAt; // } // // @Override // public boolean equals(Object other) { // if (other instanceof QueuedPlayer) { // QueuedPlayer otherUser = (QueuedPlayer) other; // return otherUser.player.getUserId() == player.getUserId(); // } // return false; // } // // @Override // public int hashCode() { // return player != null ? player.getUserId() : 0; // } // // public enum QueueSource { // TWITCH, OSU, AUTO // } // // public boolean isNotify() { // return queueSource != QueueSource.AUTO && player.isAllowsNotifications(); // } // } // Path: osuCelebrity-core/src/main/java/me/reddev/osucelebrity/core/api/VoteService.java import lombok.RequiredArgsConstructor; import me.reddev.osucelebrity.core.QueuedPlayer; import me.reddev.osucelebrity.core.Spectator; import me.reddev.osucelebrity.core.Vote; import org.mapstruct.Mapper; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Singleton; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; package me.reddev.osucelebrity.core.api; @Singleton @Path("/votes") @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class VoteService { @Mapper public interface VoteMapper { public DisplayVote voteToDisplayVote(Vote vote); } private final PersistenceManagerFactory pmf; private final Spectator spectator; /** * Shows the votes for the current player. * @return List of unique votes for the current player */ @GET @Produces(MediaType.APPLICATION_JSON) public List<DisplayVote> votes() { PersistenceManager pm = pmf.getPersistenceManager(); try {
QueuedPlayer queued = spectator.getCurrentPlayer(pm);
OsuCelebrity/OsuCelebrity
osuCelebrity-twitch/src/main/java/me/reddev/osucelebrity/twitch/TwitchImpl.java
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/SkipReason.java // public enum SkipReason { // IDLE, // OFFLINE, // BANNED_MAP // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java // @PersistenceCapable(detachable = "true") // @Getter // @ToString // public class OsuUser { // @PrimaryKey // @UserId // @Getter(onMethod = @__(@UserId)) // private int userId; // // @Index // private String userName; // // private long downloaded; // // @Setter // private Privilege privilege = Privilege.PLAYER; // // @Setter // @Column(defaultValue = "true") // private boolean allowsNotifications = true; // // @Setter // @Column(defaultValue = "true") // @Index // private boolean allowsSpectating = true; // // @Setter(onParam = @__(@GameMode)) // @Getter(onMethod = @__(@GameMode)) // @Column(defaultValue = "0") // @GameMode // private int gameMode = 0; // // @Setter // @Column(defaultValue = "-1") // private long timeOutUntil = -1; // // /** // * Creates a new user object copying all relevant data from the api user object. // * // * @param user downloaded data. // * @param downloaded current time in millis. // */ // public OsuUser(OsuApiUser user, long downloaded) { // this.userId = user.getUserId(); // update(user, downloaded); // } // // /** // * updates this object with the downloaded data. // * // * @param user downloaded data // * @param downloaded current time // */ // public void update(OsuApiUser user, long downloaded) { // this.setUserName(user.getUserName()); // this.setDownloaded(downloaded); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof OsuUser) { // return ((OsuUser) obj).userId == userId; // } // return false; // } // // @Override // public int hashCode() { // return userId; // } // // void setDownloaded(long downloaded) { // this.downloaded = downloaded; // } // // void setUserName(String userName) { // this.userName = userName; // } // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/twitchapi/TwitchApi.java // @PassAndReturnNonnull // public interface TwitchApi { // /** // * Gets a list of moderators currently in a channel. // * // * @return The list of moderator usernames in lowercase // */ // List<String> getOnlineMods(); // // /** // * Determines whether a given user is a moderator of a channel. // * // * @param username The username of the user // * @return True if the user is a moderator // */ // boolean isModerator(String username); // // /** // * Retrieves the user from the API. // * @param username username (all lower case). // * @param maxAge if > 0, cached data up to this age can be returned. // * @param returnCachedOnIoException if true, a cached data is used if a server exception // * occurrs during an update from the api // * @return the user object. // */ // TwitchApiUser getUser(PersistenceManager pm, String username, long maxAge, // boolean returnCachedOnIoException); // // /** // * Retrieves the link to the past broadcast that a play occurred in at the exact time when the // * play started. // * // * @param play any play. // * @return the full URL. if no matching past broadcast can be found, null. // */ // @CheckForNull // URL getReplayLink(QueuedPlayer play) throws IOException; // }
import static me.reddev.osucelebrity.twitch.QTwitchUser.twitchUser; import com.querydsl.jdo.JDOQuery; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import me.reddev.osucelebrity.TwitchResponses; import me.reddev.osucelebrity.core.SkipReason; import me.reddev.osucelebrity.osu.OsuUser; import me.reddev.osucelebrity.osuapi.OsuApi; import me.reddev.osucelebrity.twitchapi.TwitchApi; import me.reddev.osucelebrity.twitchapi.TwitchApiSettings; import me.reddev.osucelebrity.twitchapi.TwitchApiUser; import java.io.IOException; import javax.inject.Inject; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory;
package me.reddev.osucelebrity.twitch; @Slf4j @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class TwitchImpl implements Twitch { final OsuApi osuApi; final TwitchIrcSettings ircSettings; final TwitchApiSettings apiSettings; final PersistenceManagerFactory pmf; final TwitchIrcBot bot;
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/SkipReason.java // public enum SkipReason { // IDLE, // OFFLINE, // BANNED_MAP // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java // @PersistenceCapable(detachable = "true") // @Getter // @ToString // public class OsuUser { // @PrimaryKey // @UserId // @Getter(onMethod = @__(@UserId)) // private int userId; // // @Index // private String userName; // // private long downloaded; // // @Setter // private Privilege privilege = Privilege.PLAYER; // // @Setter // @Column(defaultValue = "true") // private boolean allowsNotifications = true; // // @Setter // @Column(defaultValue = "true") // @Index // private boolean allowsSpectating = true; // // @Setter(onParam = @__(@GameMode)) // @Getter(onMethod = @__(@GameMode)) // @Column(defaultValue = "0") // @GameMode // private int gameMode = 0; // // @Setter // @Column(defaultValue = "-1") // private long timeOutUntil = -1; // // /** // * Creates a new user object copying all relevant data from the api user object. // * // * @param user downloaded data. // * @param downloaded current time in millis. // */ // public OsuUser(OsuApiUser user, long downloaded) { // this.userId = user.getUserId(); // update(user, downloaded); // } // // /** // * updates this object with the downloaded data. // * // * @param user downloaded data // * @param downloaded current time // */ // public void update(OsuApiUser user, long downloaded) { // this.setUserName(user.getUserName()); // this.setDownloaded(downloaded); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof OsuUser) { // return ((OsuUser) obj).userId == userId; // } // return false; // } // // @Override // public int hashCode() { // return userId; // } // // void setDownloaded(long downloaded) { // this.downloaded = downloaded; // } // // void setUserName(String userName) { // this.userName = userName; // } // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/twitchapi/TwitchApi.java // @PassAndReturnNonnull // public interface TwitchApi { // /** // * Gets a list of moderators currently in a channel. // * // * @return The list of moderator usernames in lowercase // */ // List<String> getOnlineMods(); // // /** // * Determines whether a given user is a moderator of a channel. // * // * @param username The username of the user // * @return True if the user is a moderator // */ // boolean isModerator(String username); // // /** // * Retrieves the user from the API. // * @param username username (all lower case). // * @param maxAge if > 0, cached data up to this age can be returned. // * @param returnCachedOnIoException if true, a cached data is used if a server exception // * occurrs during an update from the api // * @return the user object. // */ // TwitchApiUser getUser(PersistenceManager pm, String username, long maxAge, // boolean returnCachedOnIoException); // // /** // * Retrieves the link to the past broadcast that a play occurred in at the exact time when the // * play started. // * // * @param play any play. // * @return the full URL. if no matching past broadcast can be found, null. // */ // @CheckForNull // URL getReplayLink(QueuedPlayer play) throws IOException; // } // Path: osuCelebrity-twitch/src/main/java/me/reddev/osucelebrity/twitch/TwitchImpl.java import static me.reddev.osucelebrity.twitch.QTwitchUser.twitchUser; import com.querydsl.jdo.JDOQuery; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import me.reddev.osucelebrity.TwitchResponses; import me.reddev.osucelebrity.core.SkipReason; import me.reddev.osucelebrity.osu.OsuUser; import me.reddev.osucelebrity.osuapi.OsuApi; import me.reddev.osucelebrity.twitchapi.TwitchApi; import me.reddev.osucelebrity.twitchapi.TwitchApiSettings; import me.reddev.osucelebrity.twitchapi.TwitchApiUser; import java.io.IOException; import javax.inject.Inject; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; package me.reddev.osucelebrity.twitch; @Slf4j @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class TwitchImpl implements Twitch { final OsuApi osuApi; final TwitchIrcSettings ircSettings; final TwitchApiSettings apiSettings; final PersistenceManagerFactory pmf; final TwitchIrcBot bot;
final TwitchApi api;
OsuCelebrity/OsuCelebrity
osuCelebrity-twitch/src/main/java/me/reddev/osucelebrity/twitch/TwitchImpl.java
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/SkipReason.java // public enum SkipReason { // IDLE, // OFFLINE, // BANNED_MAP // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java // @PersistenceCapable(detachable = "true") // @Getter // @ToString // public class OsuUser { // @PrimaryKey // @UserId // @Getter(onMethod = @__(@UserId)) // private int userId; // // @Index // private String userName; // // private long downloaded; // // @Setter // private Privilege privilege = Privilege.PLAYER; // // @Setter // @Column(defaultValue = "true") // private boolean allowsNotifications = true; // // @Setter // @Column(defaultValue = "true") // @Index // private boolean allowsSpectating = true; // // @Setter(onParam = @__(@GameMode)) // @Getter(onMethod = @__(@GameMode)) // @Column(defaultValue = "0") // @GameMode // private int gameMode = 0; // // @Setter // @Column(defaultValue = "-1") // private long timeOutUntil = -1; // // /** // * Creates a new user object copying all relevant data from the api user object. // * // * @param user downloaded data. // * @param downloaded current time in millis. // */ // public OsuUser(OsuApiUser user, long downloaded) { // this.userId = user.getUserId(); // update(user, downloaded); // } // // /** // * updates this object with the downloaded data. // * // * @param user downloaded data // * @param downloaded current time // */ // public void update(OsuApiUser user, long downloaded) { // this.setUserName(user.getUserName()); // this.setDownloaded(downloaded); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof OsuUser) { // return ((OsuUser) obj).userId == userId; // } // return false; // } // // @Override // public int hashCode() { // return userId; // } // // void setDownloaded(long downloaded) { // this.downloaded = downloaded; // } // // void setUserName(String userName) { // this.userName = userName; // } // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/twitchapi/TwitchApi.java // @PassAndReturnNonnull // public interface TwitchApi { // /** // * Gets a list of moderators currently in a channel. // * // * @return The list of moderator usernames in lowercase // */ // List<String> getOnlineMods(); // // /** // * Determines whether a given user is a moderator of a channel. // * // * @param username The username of the user // * @return True if the user is a moderator // */ // boolean isModerator(String username); // // /** // * Retrieves the user from the API. // * @param username username (all lower case). // * @param maxAge if > 0, cached data up to this age can be returned. // * @param returnCachedOnIoException if true, a cached data is used if a server exception // * occurrs during an update from the api // * @return the user object. // */ // TwitchApiUser getUser(PersistenceManager pm, String username, long maxAge, // boolean returnCachedOnIoException); // // /** // * Retrieves the link to the past broadcast that a play occurred in at the exact time when the // * play started. // * // * @param play any play. // * @return the full URL. if no matching past broadcast can be found, null. // */ // @CheckForNull // URL getReplayLink(QueuedPlayer play) throws IOException; // }
import static me.reddev.osucelebrity.twitch.QTwitchUser.twitchUser; import com.querydsl.jdo.JDOQuery; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import me.reddev.osucelebrity.TwitchResponses; import me.reddev.osucelebrity.core.SkipReason; import me.reddev.osucelebrity.osu.OsuUser; import me.reddev.osucelebrity.osuapi.OsuApi; import me.reddev.osucelebrity.twitchapi.TwitchApi; import me.reddev.osucelebrity.twitchapi.TwitchApiSettings; import me.reddev.osucelebrity.twitchapi.TwitchApiUser; import java.io.IOException; import javax.inject.Inject; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory;
package me.reddev.osucelebrity.twitch; @Slf4j @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class TwitchImpl implements Twitch { final OsuApi osuApi; final TwitchIrcSettings ircSettings; final TwitchApiSettings apiSettings; final PersistenceManagerFactory pmf; final TwitchIrcBot bot; final TwitchApi api; @Override public void whisperUser(String nick, String message) { // TODO Auto-generated method stub } @Override
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/SkipReason.java // public enum SkipReason { // IDLE, // OFFLINE, // BANNED_MAP // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java // @PersistenceCapable(detachable = "true") // @Getter // @ToString // public class OsuUser { // @PrimaryKey // @UserId // @Getter(onMethod = @__(@UserId)) // private int userId; // // @Index // private String userName; // // private long downloaded; // // @Setter // private Privilege privilege = Privilege.PLAYER; // // @Setter // @Column(defaultValue = "true") // private boolean allowsNotifications = true; // // @Setter // @Column(defaultValue = "true") // @Index // private boolean allowsSpectating = true; // // @Setter(onParam = @__(@GameMode)) // @Getter(onMethod = @__(@GameMode)) // @Column(defaultValue = "0") // @GameMode // private int gameMode = 0; // // @Setter // @Column(defaultValue = "-1") // private long timeOutUntil = -1; // // /** // * Creates a new user object copying all relevant data from the api user object. // * // * @param user downloaded data. // * @param downloaded current time in millis. // */ // public OsuUser(OsuApiUser user, long downloaded) { // this.userId = user.getUserId(); // update(user, downloaded); // } // // /** // * updates this object with the downloaded data. // * // * @param user downloaded data // * @param downloaded current time // */ // public void update(OsuApiUser user, long downloaded) { // this.setUserName(user.getUserName()); // this.setDownloaded(downloaded); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof OsuUser) { // return ((OsuUser) obj).userId == userId; // } // return false; // } // // @Override // public int hashCode() { // return userId; // } // // void setDownloaded(long downloaded) { // this.downloaded = downloaded; // } // // void setUserName(String userName) { // this.userName = userName; // } // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/twitchapi/TwitchApi.java // @PassAndReturnNonnull // public interface TwitchApi { // /** // * Gets a list of moderators currently in a channel. // * // * @return The list of moderator usernames in lowercase // */ // List<String> getOnlineMods(); // // /** // * Determines whether a given user is a moderator of a channel. // * // * @param username The username of the user // * @return True if the user is a moderator // */ // boolean isModerator(String username); // // /** // * Retrieves the user from the API. // * @param username username (all lower case). // * @param maxAge if > 0, cached data up to this age can be returned. // * @param returnCachedOnIoException if true, a cached data is used if a server exception // * occurrs during an update from the api // * @return the user object. // */ // TwitchApiUser getUser(PersistenceManager pm, String username, long maxAge, // boolean returnCachedOnIoException); // // /** // * Retrieves the link to the past broadcast that a play occurred in at the exact time when the // * play started. // * // * @param play any play. // * @return the full URL. if no matching past broadcast can be found, null. // */ // @CheckForNull // URL getReplayLink(QueuedPlayer play) throws IOException; // } // Path: osuCelebrity-twitch/src/main/java/me/reddev/osucelebrity/twitch/TwitchImpl.java import static me.reddev.osucelebrity.twitch.QTwitchUser.twitchUser; import com.querydsl.jdo.JDOQuery; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import me.reddev.osucelebrity.TwitchResponses; import me.reddev.osucelebrity.core.SkipReason; import me.reddev.osucelebrity.osu.OsuUser; import me.reddev.osucelebrity.osuapi.OsuApi; import me.reddev.osucelebrity.twitchapi.TwitchApi; import me.reddev.osucelebrity.twitchapi.TwitchApiSettings; import me.reddev.osucelebrity.twitchapi.TwitchApiUser; import java.io.IOException; import javax.inject.Inject; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; package me.reddev.osucelebrity.twitch; @Slf4j @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class TwitchImpl implements Twitch { final OsuApi osuApi; final TwitchIrcSettings ircSettings; final TwitchApiSettings apiSettings; final PersistenceManagerFactory pmf; final TwitchIrcBot bot; final TwitchApi api; @Override public void whisperUser(String nick, String message) { // TODO Auto-generated method stub } @Override
public void announceAdvance(SkipReason reason, OsuUser oldPlayer, OsuUser newPlayer) {
OsuCelebrity/OsuCelebrity
osuCelebrity-twitch/src/main/java/me/reddev/osucelebrity/twitch/TwitchImpl.java
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/SkipReason.java // public enum SkipReason { // IDLE, // OFFLINE, // BANNED_MAP // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java // @PersistenceCapable(detachable = "true") // @Getter // @ToString // public class OsuUser { // @PrimaryKey // @UserId // @Getter(onMethod = @__(@UserId)) // private int userId; // // @Index // private String userName; // // private long downloaded; // // @Setter // private Privilege privilege = Privilege.PLAYER; // // @Setter // @Column(defaultValue = "true") // private boolean allowsNotifications = true; // // @Setter // @Column(defaultValue = "true") // @Index // private boolean allowsSpectating = true; // // @Setter(onParam = @__(@GameMode)) // @Getter(onMethod = @__(@GameMode)) // @Column(defaultValue = "0") // @GameMode // private int gameMode = 0; // // @Setter // @Column(defaultValue = "-1") // private long timeOutUntil = -1; // // /** // * Creates a new user object copying all relevant data from the api user object. // * // * @param user downloaded data. // * @param downloaded current time in millis. // */ // public OsuUser(OsuApiUser user, long downloaded) { // this.userId = user.getUserId(); // update(user, downloaded); // } // // /** // * updates this object with the downloaded data. // * // * @param user downloaded data // * @param downloaded current time // */ // public void update(OsuApiUser user, long downloaded) { // this.setUserName(user.getUserName()); // this.setDownloaded(downloaded); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof OsuUser) { // return ((OsuUser) obj).userId == userId; // } // return false; // } // // @Override // public int hashCode() { // return userId; // } // // void setDownloaded(long downloaded) { // this.downloaded = downloaded; // } // // void setUserName(String userName) { // this.userName = userName; // } // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/twitchapi/TwitchApi.java // @PassAndReturnNonnull // public interface TwitchApi { // /** // * Gets a list of moderators currently in a channel. // * // * @return The list of moderator usernames in lowercase // */ // List<String> getOnlineMods(); // // /** // * Determines whether a given user is a moderator of a channel. // * // * @param username The username of the user // * @return True if the user is a moderator // */ // boolean isModerator(String username); // // /** // * Retrieves the user from the API. // * @param username username (all lower case). // * @param maxAge if > 0, cached data up to this age can be returned. // * @param returnCachedOnIoException if true, a cached data is used if a server exception // * occurrs during an update from the api // * @return the user object. // */ // TwitchApiUser getUser(PersistenceManager pm, String username, long maxAge, // boolean returnCachedOnIoException); // // /** // * Retrieves the link to the past broadcast that a play occurred in at the exact time when the // * play started. // * // * @param play any play. // * @return the full URL. if no matching past broadcast can be found, null. // */ // @CheckForNull // URL getReplayLink(QueuedPlayer play) throws IOException; // }
import static me.reddev.osucelebrity.twitch.QTwitchUser.twitchUser; import com.querydsl.jdo.JDOQuery; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import me.reddev.osucelebrity.TwitchResponses; import me.reddev.osucelebrity.core.SkipReason; import me.reddev.osucelebrity.osu.OsuUser; import me.reddev.osucelebrity.osuapi.OsuApi; import me.reddev.osucelebrity.twitchapi.TwitchApi; import me.reddev.osucelebrity.twitchapi.TwitchApiSettings; import me.reddev.osucelebrity.twitchapi.TwitchApiUser; import java.io.IOException; import javax.inject.Inject; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory;
package me.reddev.osucelebrity.twitch; @Slf4j @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class TwitchImpl implements Twitch { final OsuApi osuApi; final TwitchIrcSettings ircSettings; final TwitchApiSettings apiSettings; final PersistenceManagerFactory pmf; final TwitchIrcBot bot; final TwitchApi api; @Override public void whisperUser(String nick, String message) { // TODO Auto-generated method stub } @Override
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/core/SkipReason.java // public enum SkipReason { // IDLE, // OFFLINE, // BANNED_MAP // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java // @PersistenceCapable(detachable = "true") // @Getter // @ToString // public class OsuUser { // @PrimaryKey // @UserId // @Getter(onMethod = @__(@UserId)) // private int userId; // // @Index // private String userName; // // private long downloaded; // // @Setter // private Privilege privilege = Privilege.PLAYER; // // @Setter // @Column(defaultValue = "true") // private boolean allowsNotifications = true; // // @Setter // @Column(defaultValue = "true") // @Index // private boolean allowsSpectating = true; // // @Setter(onParam = @__(@GameMode)) // @Getter(onMethod = @__(@GameMode)) // @Column(defaultValue = "0") // @GameMode // private int gameMode = 0; // // @Setter // @Column(defaultValue = "-1") // private long timeOutUntil = -1; // // /** // * Creates a new user object copying all relevant data from the api user object. // * // * @param user downloaded data. // * @param downloaded current time in millis. // */ // public OsuUser(OsuApiUser user, long downloaded) { // this.userId = user.getUserId(); // update(user, downloaded); // } // // /** // * updates this object with the downloaded data. // * // * @param user downloaded data // * @param downloaded current time // */ // public void update(OsuApiUser user, long downloaded) { // this.setUserName(user.getUserName()); // this.setDownloaded(downloaded); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof OsuUser) { // return ((OsuUser) obj).userId == userId; // } // return false; // } // // @Override // public int hashCode() { // return userId; // } // // void setDownloaded(long downloaded) { // this.downloaded = downloaded; // } // // void setUserName(String userName) { // this.userName = userName; // } // } // // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/twitchapi/TwitchApi.java // @PassAndReturnNonnull // public interface TwitchApi { // /** // * Gets a list of moderators currently in a channel. // * // * @return The list of moderator usernames in lowercase // */ // List<String> getOnlineMods(); // // /** // * Determines whether a given user is a moderator of a channel. // * // * @param username The username of the user // * @return True if the user is a moderator // */ // boolean isModerator(String username); // // /** // * Retrieves the user from the API. // * @param username username (all lower case). // * @param maxAge if > 0, cached data up to this age can be returned. // * @param returnCachedOnIoException if true, a cached data is used if a server exception // * occurrs during an update from the api // * @return the user object. // */ // TwitchApiUser getUser(PersistenceManager pm, String username, long maxAge, // boolean returnCachedOnIoException); // // /** // * Retrieves the link to the past broadcast that a play occurred in at the exact time when the // * play started. // * // * @param play any play. // * @return the full URL. if no matching past broadcast can be found, null. // */ // @CheckForNull // URL getReplayLink(QueuedPlayer play) throws IOException; // } // Path: osuCelebrity-twitch/src/main/java/me/reddev/osucelebrity/twitch/TwitchImpl.java import static me.reddev.osucelebrity.twitch.QTwitchUser.twitchUser; import com.querydsl.jdo.JDOQuery; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import me.reddev.osucelebrity.TwitchResponses; import me.reddev.osucelebrity.core.SkipReason; import me.reddev.osucelebrity.osu.OsuUser; import me.reddev.osucelebrity.osuapi.OsuApi; import me.reddev.osucelebrity.twitchapi.TwitchApi; import me.reddev.osucelebrity.twitchapi.TwitchApiSettings; import me.reddev.osucelebrity.twitchapi.TwitchApiUser; import java.io.IOException; import javax.inject.Inject; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; package me.reddev.osucelebrity.twitch; @Slf4j @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class TwitchImpl implements Twitch { final OsuApi osuApi; final TwitchIrcSettings ircSettings; final TwitchApiSettings apiSettings; final PersistenceManagerFactory pmf; final TwitchIrcBot bot; final TwitchApi api; @Override public void whisperUser(String nick, String message) { // TODO Auto-generated method stub } @Override
public void announceAdvance(SkipReason reason, OsuUser oldPlayer, OsuUser newPlayer) {
OsuCelebrity/OsuCelebrity
osuCelebrity-model/src/test/java/me/reddev/osucelebrity/util/ExecutorServiceHelperTest.java
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java // @PersistenceCapable(detachable = "true") // @Getter // @ToString // public class OsuUser { // @PrimaryKey // @UserId // @Getter(onMethod = @__(@UserId)) // private int userId; // // @Index // private String userName; // // private long downloaded; // // @Setter // private Privilege privilege = Privilege.PLAYER; // // @Setter // @Column(defaultValue = "true") // private boolean allowsNotifications = true; // // @Setter // @Column(defaultValue = "true") // @Index // private boolean allowsSpectating = true; // // @Setter(onParam = @__(@GameMode)) // @Getter(onMethod = @__(@GameMode)) // @Column(defaultValue = "0") // @GameMode // private int gameMode = 0; // // @Setter // @Column(defaultValue = "-1") // private long timeOutUntil = -1; // // /** // * Creates a new user object copying all relevant data from the api user object. // * // * @param user downloaded data. // * @param downloaded current time in millis. // */ // public OsuUser(OsuApiUser user, long downloaded) { // this.userId = user.getUserId(); // update(user, downloaded); // } // // /** // * updates this object with the downloaded data. // * // * @param user downloaded data // * @param downloaded current time // */ // public void update(OsuApiUser user, long downloaded) { // this.setUserName(user.getUserName()); // this.setDownloaded(downloaded); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof OsuUser) { // return ((OsuUser) obj).userId == userId; // } // return false; // } // // @Override // public int hashCode() { // return userId; // } // // void setDownloaded(long downloaded) { // this.downloaded = downloaded; // } // // void setUserName(String userName) { // this.userName = userName; // } // }
import org.mockito.Mock; import me.reddev.osucelebrity.util.ExecutorServiceHelper.Async; import static org.mockito.Mockito.verify; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import org.slf4j.Logger; import static org.junit.Assert.*; import java.util.concurrent.atomic.AtomicReference; import me.reddev.osucelebrity.osu.OsuUser; import me.reddev.osucelebrity.AbstractJDOTest; import org.junit.Test; import javax.jdo.JDOHelper;
package me.reddev.osucelebrity.util; public class ExecutorServiceHelperTest extends AbstractJDOTest { @Mock Logger log; @Test public void testOneArg() throws Exception {
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java // @PersistenceCapable(detachable = "true") // @Getter // @ToString // public class OsuUser { // @PrimaryKey // @UserId // @Getter(onMethod = @__(@UserId)) // private int userId; // // @Index // private String userName; // // private long downloaded; // // @Setter // private Privilege privilege = Privilege.PLAYER; // // @Setter // @Column(defaultValue = "true") // private boolean allowsNotifications = true; // // @Setter // @Column(defaultValue = "true") // @Index // private boolean allowsSpectating = true; // // @Setter(onParam = @__(@GameMode)) // @Getter(onMethod = @__(@GameMode)) // @Column(defaultValue = "0") // @GameMode // private int gameMode = 0; // // @Setter // @Column(defaultValue = "-1") // private long timeOutUntil = -1; // // /** // * Creates a new user object copying all relevant data from the api user object. // * // * @param user downloaded data. // * @param downloaded current time in millis. // */ // public OsuUser(OsuApiUser user, long downloaded) { // this.userId = user.getUserId(); // update(user, downloaded); // } // // /** // * updates this object with the downloaded data. // * // * @param user downloaded data // * @param downloaded current time // */ // public void update(OsuApiUser user, long downloaded) { // this.setUserName(user.getUserName()); // this.setDownloaded(downloaded); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof OsuUser) { // return ((OsuUser) obj).userId == userId; // } // return false; // } // // @Override // public int hashCode() { // return userId; // } // // void setDownloaded(long downloaded) { // this.downloaded = downloaded; // } // // void setUserName(String userName) { // this.userName = userName; // } // } // Path: osuCelebrity-model/src/test/java/me/reddev/osucelebrity/util/ExecutorServiceHelperTest.java import org.mockito.Mock; import me.reddev.osucelebrity.util.ExecutorServiceHelper.Async; import static org.mockito.Mockito.verify; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import org.slf4j.Logger; import static org.junit.Assert.*; import java.util.concurrent.atomic.AtomicReference; import me.reddev.osucelebrity.osu.OsuUser; import me.reddev.osucelebrity.AbstractJDOTest; import org.junit.Test; import javax.jdo.JDOHelper; package me.reddev.osucelebrity.util; public class ExecutorServiceHelperTest extends AbstractJDOTest { @Mock Logger log; @Test public void testOneArg() throws Exception {
AtomicReference<OsuUser> ref = new AtomicReference<>();
OsuCelebrity/OsuCelebrity
osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/Privilege.java // @RequiredArgsConstructor // public enum Privilege { // ADMIN(true, true, true), // MOD(false, true, true), // PLAYER(false, false, false); // // /** // * Can raise people's level to mod. // */ // public final boolean canMod; // /** // * Can skip a player (see {@link Spectator#advance(javax.jdo.PersistenceManager)}. // */ // public final boolean canSkip; // /** // * Can skip a player (see {@link Spectator#advance(javax.jdo.PersistenceManager)}. // */ // public final boolean canRestartClient; // }
import lombok.Getter; import lombok.Setter; import lombok.ToString; import me.reddev.osucelebrity.Privilege; import org.tillerino.osuApiModel.OsuApiUser; import org.tillerino.osuApiModel.types.GameMode; import org.tillerino.osuApiModel.types.UserId; import javax.jdo.annotations.Column; import javax.jdo.annotations.Index; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.PrimaryKey;
package me.reddev.osucelebrity.osu; @PersistenceCapable(detachable = "true") @Getter @ToString public class OsuUser { @PrimaryKey @UserId @Getter(onMethod = @__(@UserId)) private int userId; @Index private String userName; private long downloaded; @Setter
// Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/Privilege.java // @RequiredArgsConstructor // public enum Privilege { // ADMIN(true, true, true), // MOD(false, true, true), // PLAYER(false, false, false); // // /** // * Can raise people's level to mod. // */ // public final boolean canMod; // /** // * Can skip a player (see {@link Spectator#advance(javax.jdo.PersistenceManager)}. // */ // public final boolean canSkip; // /** // * Can skip a player (see {@link Spectator#advance(javax.jdo.PersistenceManager)}. // */ // public final boolean canRestartClient; // } // Path: osuCelebrity-model/src/main/java/me/reddev/osucelebrity/osu/OsuUser.java import lombok.Getter; import lombok.Setter; import lombok.ToString; import me.reddev.osucelebrity.Privilege; import org.tillerino.osuApiModel.OsuApiUser; import org.tillerino.osuApiModel.types.GameMode; import org.tillerino.osuApiModel.types.UserId; import javax.jdo.annotations.Column; import javax.jdo.annotations.Index; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.PrimaryKey; package me.reddev.osucelebrity.osu; @PersistenceCapable(detachable = "true") @Getter @ToString public class OsuUser { @PrimaryKey @UserId @Getter(onMethod = @__(@UserId)) private int userId; @Index private String userName; private long downloaded; @Setter
private Privilege privilege = Privilege.PLAYER;
akorshak/android-arch-examples
mvvm/app/src/main/java/com/mera/mvvmweatherchecker/interfaces/WeatherView.java
// Path: mvvm/app/src/main/java/com/mera/mvvmweatherchecker/models/WeatherResponse.java // @Parcel // public class WeatherResponse { // // @SerializedName("list") // private List<WeatherData> mWeatherData = new ArrayList<>(); // // public List<WeatherData> getWeatherData() { // return mWeatherData; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherResponse that = (WeatherResponse) o; // // return !(mWeatherData != null ? !mWeatherData.equals(that.mWeatherData) : that.mWeatherData != null); // // } // // @Override // public int hashCode() { // return mWeatherData != null ? mWeatherData.hashCode() : 0; // } // // @Parcel // public static class WeatherData { // // private final static String ICON_ADDR = "http://openweathermap.org/img/w/"; // // @Parcel // private static class Weather { // @SerializedName("description") // String mDescription; // // @SerializedName("icon") // String mIcon; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Weather weather = (Weather) o; // // if (mDescription != null ? !mDescription.equals(weather.mDescription) : weather.mDescription != null) // return false; // return !(mIcon != null ? !mIcon.equals(weather.mIcon) : weather.mIcon != null); // // } // // @Override // public int hashCode() { // int result = mDescription != null ? mDescription.hashCode() : 0; // result = 31 * result + (mIcon != null ? mIcon.hashCode() : 0); // return result; // } // } // // @Parcel // private static class Main { // @SerializedName("temp") // float mTemp; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Main main = (Main) o; // // return Float.compare(main.mTemp, mTemp) == 0; // // } // // @Override // public int hashCode() { // return (mTemp != +0.0f ? Float.floatToIntBits(mTemp) : 0); // } // } // // @SerializedName("main") // private Main mMain = new Main(); // // @SerializedName("weather") // private List<Weather> mWeather = new ArrayList<>(); // // @SerializedName("name") // private String mCity = ""; // // private WeatherData() { // } // // public String getCity() { // return mCity; // } // // public String getTemperatureInCelsius() { // float temp = mMain.mTemp - 273.15f; // return String.format("%.2f \u00b0C", temp); // } // // public String getIconAddress() { // return ICON_ADDR + mWeather.get(0).mIcon + ".png"; // } // // public String getDescription() { // if (mWeather.size() > 0) { // return mWeather.get(0).mDescription; // } // return ""; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherData that = (WeatherData) o; // // if (mMain != null ? !mMain.equals(that.mMain) : that.mMain != null) return false; // if (mWeather != null ? !mWeather.equals(that.mWeather) : that.mWeather != null) // return false; // return !(mCity != null ? !mCity.equals(that.mCity) : that.mCity != null); // // } // // @Override // public int hashCode() { // int result = mMain != null ? mMain.hashCode() : 0; // result = 31 * result + (mWeather != null ? mWeather.hashCode() : 0); // result = 31 * result + (mCity != null ? mCity.hashCode() : 0); // return result; // } // } // }
import android.content.Context; import com.mera.mvvmweatherchecker.models.WeatherResponse; import java.util.List;
package com.mera.mvvmweatherchecker.interfaces; /** * Created by akorshak on 3/22/2016. * Project: MVVM Weather Checker */ public interface WeatherView { Context getContext();
// Path: mvvm/app/src/main/java/com/mera/mvvmweatherchecker/models/WeatherResponse.java // @Parcel // public class WeatherResponse { // // @SerializedName("list") // private List<WeatherData> mWeatherData = new ArrayList<>(); // // public List<WeatherData> getWeatherData() { // return mWeatherData; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherResponse that = (WeatherResponse) o; // // return !(mWeatherData != null ? !mWeatherData.equals(that.mWeatherData) : that.mWeatherData != null); // // } // // @Override // public int hashCode() { // return mWeatherData != null ? mWeatherData.hashCode() : 0; // } // // @Parcel // public static class WeatherData { // // private final static String ICON_ADDR = "http://openweathermap.org/img/w/"; // // @Parcel // private static class Weather { // @SerializedName("description") // String mDescription; // // @SerializedName("icon") // String mIcon; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Weather weather = (Weather) o; // // if (mDescription != null ? !mDescription.equals(weather.mDescription) : weather.mDescription != null) // return false; // return !(mIcon != null ? !mIcon.equals(weather.mIcon) : weather.mIcon != null); // // } // // @Override // public int hashCode() { // int result = mDescription != null ? mDescription.hashCode() : 0; // result = 31 * result + (mIcon != null ? mIcon.hashCode() : 0); // return result; // } // } // // @Parcel // private static class Main { // @SerializedName("temp") // float mTemp; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Main main = (Main) o; // // return Float.compare(main.mTemp, mTemp) == 0; // // } // // @Override // public int hashCode() { // return (mTemp != +0.0f ? Float.floatToIntBits(mTemp) : 0); // } // } // // @SerializedName("main") // private Main mMain = new Main(); // // @SerializedName("weather") // private List<Weather> mWeather = new ArrayList<>(); // // @SerializedName("name") // private String mCity = ""; // // private WeatherData() { // } // // public String getCity() { // return mCity; // } // // public String getTemperatureInCelsius() { // float temp = mMain.mTemp - 273.15f; // return String.format("%.2f \u00b0C", temp); // } // // public String getIconAddress() { // return ICON_ADDR + mWeather.get(0).mIcon + ".png"; // } // // public String getDescription() { // if (mWeather.size() > 0) { // return mWeather.get(0).mDescription; // } // return ""; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherData that = (WeatherData) o; // // if (mMain != null ? !mMain.equals(that.mMain) : that.mMain != null) return false; // if (mWeather != null ? !mWeather.equals(that.mWeather) : that.mWeather != null) // return false; // return !(mCity != null ? !mCity.equals(that.mCity) : that.mCity != null); // // } // // @Override // public int hashCode() { // int result = mMain != null ? mMain.hashCode() : 0; // result = 31 * result + (mWeather != null ? mWeather.hashCode() : 0); // result = 31 * result + (mCity != null ? mCity.hashCode() : 0); // return result; // } // } // } // Path: mvvm/app/src/main/java/com/mera/mvvmweatherchecker/interfaces/WeatherView.java import android.content.Context; import com.mera.mvvmweatherchecker.models.WeatherResponse; import java.util.List; package com.mera.mvvmweatherchecker.interfaces; /** * Created by akorshak on 3/22/2016. * Project: MVVM Weather Checker */ public interface WeatherView { Context getContext();
void showForecast(List<WeatherResponse.WeatherData> data);
akorshak/android-arch-examples
mvvm/app/src/main/java/com/mera/mvvmweatherchecker/viewmodel/WeatherItemViewModel.java
// Path: mvvm/app/src/main/java/com/mera/mvvmweatherchecker/models/WeatherResponse.java // @Parcel // public class WeatherResponse { // // @SerializedName("list") // private List<WeatherData> mWeatherData = new ArrayList<>(); // // public List<WeatherData> getWeatherData() { // return mWeatherData; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherResponse that = (WeatherResponse) o; // // return !(mWeatherData != null ? !mWeatherData.equals(that.mWeatherData) : that.mWeatherData != null); // // } // // @Override // public int hashCode() { // return mWeatherData != null ? mWeatherData.hashCode() : 0; // } // // @Parcel // public static class WeatherData { // // private final static String ICON_ADDR = "http://openweathermap.org/img/w/"; // // @Parcel // private static class Weather { // @SerializedName("description") // String mDescription; // // @SerializedName("icon") // String mIcon; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Weather weather = (Weather) o; // // if (mDescription != null ? !mDescription.equals(weather.mDescription) : weather.mDescription != null) // return false; // return !(mIcon != null ? !mIcon.equals(weather.mIcon) : weather.mIcon != null); // // } // // @Override // public int hashCode() { // int result = mDescription != null ? mDescription.hashCode() : 0; // result = 31 * result + (mIcon != null ? mIcon.hashCode() : 0); // return result; // } // } // // @Parcel // private static class Main { // @SerializedName("temp") // float mTemp; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Main main = (Main) o; // // return Float.compare(main.mTemp, mTemp) == 0; // // } // // @Override // public int hashCode() { // return (mTemp != +0.0f ? Float.floatToIntBits(mTemp) : 0); // } // } // // @SerializedName("main") // private Main mMain = new Main(); // // @SerializedName("weather") // private List<Weather> mWeather = new ArrayList<>(); // // @SerializedName("name") // private String mCity = ""; // // private WeatherData() { // } // // public String getCity() { // return mCity; // } // // public String getTemperatureInCelsius() { // float temp = mMain.mTemp - 273.15f; // return String.format("%.2f \u00b0C", temp); // } // // public String getIconAddress() { // return ICON_ADDR + mWeather.get(0).mIcon + ".png"; // } // // public String getDescription() { // if (mWeather.size() > 0) { // return mWeather.get(0).mDescription; // } // return ""; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherData that = (WeatherData) o; // // if (mMain != null ? !mMain.equals(that.mMain) : that.mMain != null) return false; // if (mWeather != null ? !mWeather.equals(that.mWeather) : that.mWeather != null) // return false; // return !(mCity != null ? !mCity.equals(that.mCity) : that.mCity != null); // // } // // @Override // public int hashCode() { // int result = mMain != null ? mMain.hashCode() : 0; // result = 31 * result + (mWeather != null ? mWeather.hashCode() : 0); // result = 31 * result + (mCity != null ? mCity.hashCode() : 0); // return result; // } // } // }
import android.content.Context; import android.databinding.BaseObservable; import android.databinding.Bindable; import android.databinding.BindingAdapter; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.mera.mvvmweatherchecker.models.WeatherResponse;
package com.mera.mvvmweatherchecker.viewmodel; /** * Created by akorshak on 3/22/2016. * Project: MVVM Weather Checker */ public class WeatherItemViewModel extends BaseObservable { private Context mContext;
// Path: mvvm/app/src/main/java/com/mera/mvvmweatherchecker/models/WeatherResponse.java // @Parcel // public class WeatherResponse { // // @SerializedName("list") // private List<WeatherData> mWeatherData = new ArrayList<>(); // // public List<WeatherData> getWeatherData() { // return mWeatherData; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherResponse that = (WeatherResponse) o; // // return !(mWeatherData != null ? !mWeatherData.equals(that.mWeatherData) : that.mWeatherData != null); // // } // // @Override // public int hashCode() { // return mWeatherData != null ? mWeatherData.hashCode() : 0; // } // // @Parcel // public static class WeatherData { // // private final static String ICON_ADDR = "http://openweathermap.org/img/w/"; // // @Parcel // private static class Weather { // @SerializedName("description") // String mDescription; // // @SerializedName("icon") // String mIcon; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Weather weather = (Weather) o; // // if (mDescription != null ? !mDescription.equals(weather.mDescription) : weather.mDescription != null) // return false; // return !(mIcon != null ? !mIcon.equals(weather.mIcon) : weather.mIcon != null); // // } // // @Override // public int hashCode() { // int result = mDescription != null ? mDescription.hashCode() : 0; // result = 31 * result + (mIcon != null ? mIcon.hashCode() : 0); // return result; // } // } // // @Parcel // private static class Main { // @SerializedName("temp") // float mTemp; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Main main = (Main) o; // // return Float.compare(main.mTemp, mTemp) == 0; // // } // // @Override // public int hashCode() { // return (mTemp != +0.0f ? Float.floatToIntBits(mTemp) : 0); // } // } // // @SerializedName("main") // private Main mMain = new Main(); // // @SerializedName("weather") // private List<Weather> mWeather = new ArrayList<>(); // // @SerializedName("name") // private String mCity = ""; // // private WeatherData() { // } // // public String getCity() { // return mCity; // } // // public String getTemperatureInCelsius() { // float temp = mMain.mTemp - 273.15f; // return String.format("%.2f \u00b0C", temp); // } // // public String getIconAddress() { // return ICON_ADDR + mWeather.get(0).mIcon + ".png"; // } // // public String getDescription() { // if (mWeather.size() > 0) { // return mWeather.get(0).mDescription; // } // return ""; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherData that = (WeatherData) o; // // if (mMain != null ? !mMain.equals(that.mMain) : that.mMain != null) return false; // if (mWeather != null ? !mWeather.equals(that.mWeather) : that.mWeather != null) // return false; // return !(mCity != null ? !mCity.equals(that.mCity) : that.mCity != null); // // } // // @Override // public int hashCode() { // int result = mMain != null ? mMain.hashCode() : 0; // result = 31 * result + (mWeather != null ? mWeather.hashCode() : 0); // result = 31 * result + (mCity != null ? mCity.hashCode() : 0); // return result; // } // } // } // Path: mvvm/app/src/main/java/com/mera/mvvmweatherchecker/viewmodel/WeatherItemViewModel.java import android.content.Context; import android.databinding.BaseObservable; import android.databinding.Bindable; import android.databinding.BindingAdapter; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.mera.mvvmweatherchecker.models.WeatherResponse; package com.mera.mvvmweatherchecker.viewmodel; /** * Created by akorshak on 3/22/2016. * Project: MVVM Weather Checker */ public class WeatherItemViewModel extends BaseObservable { private Context mContext;
private WeatherResponse.WeatherData mWeatherData;
akorshak/android-arch-examples
mvc_example_2/app/src/main/java/com/mera/mvcweatherchecker/components/WeatherAdapter.java
// Path: mvc_example_2/app/src/main/java/com/mera/mvcweatherchecker/network/WeatherResponse.java // @Parcel // public class WeatherResponse { // // @SerializedName("list") // private List<WeatherData> mWeatherData = new ArrayList<>(); // // public List<WeatherData> getWeatherData() { // return mWeatherData; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherResponse that = (WeatherResponse) o; // // return !(mWeatherData != null ? !mWeatherData.equals(that.mWeatherData) : that.mWeatherData != null); // // } // // @Override // public int hashCode() { // return mWeatherData != null ? mWeatherData.hashCode() : 0; // } // // @Parcel // public static class WeatherData { // // private final static String ICON_ADDR = "http://openweathermap.org/img/w/"; // // @Parcel // private static class Weather { // @SerializedName("description") // String mDescription; // // @SerializedName("icon") // String mIcon; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Weather weather = (Weather) o; // // if (mDescription != null ? !mDescription.equals(weather.mDescription) : weather.mDescription != null) // return false; // return !(mIcon != null ? !mIcon.equals(weather.mIcon) : weather.mIcon != null); // // } // // @Override // public int hashCode() { // int result = mDescription != null ? mDescription.hashCode() : 0; // result = 31 * result + (mIcon != null ? mIcon.hashCode() : 0); // return result; // } // } // // @Parcel // private static class Main { // @SerializedName("temp") // float mTemp; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Main main = (Main) o; // // return Float.compare(main.mTemp, mTemp) == 0; // // } // // @Override // public int hashCode() { // return (mTemp != +0.0f ? Float.floatToIntBits(mTemp) : 0); // } // } // // @SerializedName("main") // private Main mMain = new Main(); // // @SerializedName("weather") // private List<Weather> mWeather = new ArrayList<>(); // // @SerializedName("name") // private String mCity = ""; // // private WeatherData() { // } // // public String getCity() { // return mCity; // } // // public String getTemperatureInCelsius() { // float temp = mMain.mTemp - 273.15f; // return String.format("%.2f \u00b0C", temp); // } // // public String getIconAddress() { // return ICON_ADDR + mWeather.get(0).mIcon + ".png"; // } // // public String getDescription() { // if (mWeather.size() > 0) { // return mWeather.get(0).mDescription; // } // return ""; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherData that = (WeatherData) o; // // if (mMain != null ? !mMain.equals(that.mMain) : that.mMain != null) return false; // if (mWeather != null ? !mWeather.equals(that.mWeather) : that.mWeather != null) // return false; // return !(mCity != null ? !mCity.equals(that.mCity) : that.mCity != null); // // } // // @Override // public int hashCode() { // int result = mMain != null ? mMain.hashCode() : 0; // result = 31 * result + (mWeather != null ? mWeather.hashCode() : 0); // result = 31 * result + (mCity != null ? mCity.hashCode() : 0); // return result; // } // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.mera.mvcweatherchecker.R; import com.mera.mvcweatherchecker.network.WeatherResponse; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife;
package com.mera.mvcweatherchecker.components; /** * Created by akorshak on 3/18/2016. * Project: MVC Weather Checker */ public class WeatherAdapter extends RecyclerView.Adapter { private Context mContext;
// Path: mvc_example_2/app/src/main/java/com/mera/mvcweatherchecker/network/WeatherResponse.java // @Parcel // public class WeatherResponse { // // @SerializedName("list") // private List<WeatherData> mWeatherData = new ArrayList<>(); // // public List<WeatherData> getWeatherData() { // return mWeatherData; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherResponse that = (WeatherResponse) o; // // return !(mWeatherData != null ? !mWeatherData.equals(that.mWeatherData) : that.mWeatherData != null); // // } // // @Override // public int hashCode() { // return mWeatherData != null ? mWeatherData.hashCode() : 0; // } // // @Parcel // public static class WeatherData { // // private final static String ICON_ADDR = "http://openweathermap.org/img/w/"; // // @Parcel // private static class Weather { // @SerializedName("description") // String mDescription; // // @SerializedName("icon") // String mIcon; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Weather weather = (Weather) o; // // if (mDescription != null ? !mDescription.equals(weather.mDescription) : weather.mDescription != null) // return false; // return !(mIcon != null ? !mIcon.equals(weather.mIcon) : weather.mIcon != null); // // } // // @Override // public int hashCode() { // int result = mDescription != null ? mDescription.hashCode() : 0; // result = 31 * result + (mIcon != null ? mIcon.hashCode() : 0); // return result; // } // } // // @Parcel // private static class Main { // @SerializedName("temp") // float mTemp; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Main main = (Main) o; // // return Float.compare(main.mTemp, mTemp) == 0; // // } // // @Override // public int hashCode() { // return (mTemp != +0.0f ? Float.floatToIntBits(mTemp) : 0); // } // } // // @SerializedName("main") // private Main mMain = new Main(); // // @SerializedName("weather") // private List<Weather> mWeather = new ArrayList<>(); // // @SerializedName("name") // private String mCity = ""; // // private WeatherData() { // } // // public String getCity() { // return mCity; // } // // public String getTemperatureInCelsius() { // float temp = mMain.mTemp - 273.15f; // return String.format("%.2f \u00b0C", temp); // } // // public String getIconAddress() { // return ICON_ADDR + mWeather.get(0).mIcon + ".png"; // } // // public String getDescription() { // if (mWeather.size() > 0) { // return mWeather.get(0).mDescription; // } // return ""; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherData that = (WeatherData) o; // // if (mMain != null ? !mMain.equals(that.mMain) : that.mMain != null) return false; // if (mWeather != null ? !mWeather.equals(that.mWeather) : that.mWeather != null) // return false; // return !(mCity != null ? !mCity.equals(that.mCity) : that.mCity != null); // // } // // @Override // public int hashCode() { // int result = mMain != null ? mMain.hashCode() : 0; // result = 31 * result + (mWeather != null ? mWeather.hashCode() : 0); // result = 31 * result + (mCity != null ? mCity.hashCode() : 0); // return result; // } // } // } // Path: mvc_example_2/app/src/main/java/com/mera/mvcweatherchecker/components/WeatherAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.mera.mvcweatherchecker.R; import com.mera.mvcweatherchecker.network.WeatherResponse; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; package com.mera.mvcweatherchecker.components; /** * Created by akorshak on 3/18/2016. * Project: MVC Weather Checker */ public class WeatherAdapter extends RecyclerView.Adapter { private Context mContext;
private List<WeatherResponse.WeatherData> mWeatherData = new ArrayList<>();
akorshak/android-arch-examples
mvvm/app/src/main/java/com/mera/mvvmweatherchecker/interfaces/WeatherInteractor.java
// Path: mvvm/app/src/main/java/com/mera/mvvmweatherchecker/models/WeatherResponse.java // @Parcel // public class WeatherResponse { // // @SerializedName("list") // private List<WeatherData> mWeatherData = new ArrayList<>(); // // public List<WeatherData> getWeatherData() { // return mWeatherData; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherResponse that = (WeatherResponse) o; // // return !(mWeatherData != null ? !mWeatherData.equals(that.mWeatherData) : that.mWeatherData != null); // // } // // @Override // public int hashCode() { // return mWeatherData != null ? mWeatherData.hashCode() : 0; // } // // @Parcel // public static class WeatherData { // // private final static String ICON_ADDR = "http://openweathermap.org/img/w/"; // // @Parcel // private static class Weather { // @SerializedName("description") // String mDescription; // // @SerializedName("icon") // String mIcon; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Weather weather = (Weather) o; // // if (mDescription != null ? !mDescription.equals(weather.mDescription) : weather.mDescription != null) // return false; // return !(mIcon != null ? !mIcon.equals(weather.mIcon) : weather.mIcon != null); // // } // // @Override // public int hashCode() { // int result = mDescription != null ? mDescription.hashCode() : 0; // result = 31 * result + (mIcon != null ? mIcon.hashCode() : 0); // return result; // } // } // // @Parcel // private static class Main { // @SerializedName("temp") // float mTemp; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Main main = (Main) o; // // return Float.compare(main.mTemp, mTemp) == 0; // // } // // @Override // public int hashCode() { // return (mTemp != +0.0f ? Float.floatToIntBits(mTemp) : 0); // } // } // // @SerializedName("main") // private Main mMain = new Main(); // // @SerializedName("weather") // private List<Weather> mWeather = new ArrayList<>(); // // @SerializedName("name") // private String mCity = ""; // // private WeatherData() { // } // // public String getCity() { // return mCity; // } // // public String getTemperatureInCelsius() { // float temp = mMain.mTemp - 273.15f; // return String.format("%.2f \u00b0C", temp); // } // // public String getIconAddress() { // return ICON_ADDR + mWeather.get(0).mIcon + ".png"; // } // // public String getDescription() { // if (mWeather.size() > 0) { // return mWeather.get(0).mDescription; // } // return ""; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherData that = (WeatherData) o; // // if (mMain != null ? !mMain.equals(that.mMain) : that.mMain != null) return false; // if (mWeather != null ? !mWeather.equals(that.mWeather) : that.mWeather != null) // return false; // return !(mCity != null ? !mCity.equals(that.mCity) : that.mCity != null); // // } // // @Override // public int hashCode() { // int result = mMain != null ? mMain.hashCode() : 0; // result = 31 * result + (mWeather != null ? mWeather.hashCode() : 0); // result = 31 * result + (mCity != null ? mCity.hashCode() : 0); // return result; // } // } // }
import com.mera.mvvmweatherchecker.models.WeatherResponse; import retrofit2.http.GET; import rx.Observable;
package com.mera.mvvmweatherchecker.interfaces; /** * Created by akorshak on 3/22/2016. * Project: MVVM Weather Checker */ public interface WeatherInteractor { String API_URL = "http://api.openweathermap.org/data/2.5/"; @GET("find?lat=55.5&lon=37.5&cnt=10&appid=6b462378109409573b90b51b8a4b79f5")
// Path: mvvm/app/src/main/java/com/mera/mvvmweatherchecker/models/WeatherResponse.java // @Parcel // public class WeatherResponse { // // @SerializedName("list") // private List<WeatherData> mWeatherData = new ArrayList<>(); // // public List<WeatherData> getWeatherData() { // return mWeatherData; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherResponse that = (WeatherResponse) o; // // return !(mWeatherData != null ? !mWeatherData.equals(that.mWeatherData) : that.mWeatherData != null); // // } // // @Override // public int hashCode() { // return mWeatherData != null ? mWeatherData.hashCode() : 0; // } // // @Parcel // public static class WeatherData { // // private final static String ICON_ADDR = "http://openweathermap.org/img/w/"; // // @Parcel // private static class Weather { // @SerializedName("description") // String mDescription; // // @SerializedName("icon") // String mIcon; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Weather weather = (Weather) o; // // if (mDescription != null ? !mDescription.equals(weather.mDescription) : weather.mDescription != null) // return false; // return !(mIcon != null ? !mIcon.equals(weather.mIcon) : weather.mIcon != null); // // } // // @Override // public int hashCode() { // int result = mDescription != null ? mDescription.hashCode() : 0; // result = 31 * result + (mIcon != null ? mIcon.hashCode() : 0); // return result; // } // } // // @Parcel // private static class Main { // @SerializedName("temp") // float mTemp; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Main main = (Main) o; // // return Float.compare(main.mTemp, mTemp) == 0; // // } // // @Override // public int hashCode() { // return (mTemp != +0.0f ? Float.floatToIntBits(mTemp) : 0); // } // } // // @SerializedName("main") // private Main mMain = new Main(); // // @SerializedName("weather") // private List<Weather> mWeather = new ArrayList<>(); // // @SerializedName("name") // private String mCity = ""; // // private WeatherData() { // } // // public String getCity() { // return mCity; // } // // public String getTemperatureInCelsius() { // float temp = mMain.mTemp - 273.15f; // return String.format("%.2f \u00b0C", temp); // } // // public String getIconAddress() { // return ICON_ADDR + mWeather.get(0).mIcon + ".png"; // } // // public String getDescription() { // if (mWeather.size() > 0) { // return mWeather.get(0).mDescription; // } // return ""; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherData that = (WeatherData) o; // // if (mMain != null ? !mMain.equals(that.mMain) : that.mMain != null) return false; // if (mWeather != null ? !mWeather.equals(that.mWeather) : that.mWeather != null) // return false; // return !(mCity != null ? !mCity.equals(that.mCity) : that.mCity != null); // // } // // @Override // public int hashCode() { // int result = mMain != null ? mMain.hashCode() : 0; // result = 31 * result + (mWeather != null ? mWeather.hashCode() : 0); // result = 31 * result + (mCity != null ? mCity.hashCode() : 0); // return result; // } // } // } // Path: mvvm/app/src/main/java/com/mera/mvvmweatherchecker/interfaces/WeatherInteractor.java import com.mera.mvvmweatherchecker.models.WeatherResponse; import retrofit2.http.GET; import rx.Observable; package com.mera.mvvmweatherchecker.interfaces; /** * Created by akorshak on 3/22/2016. * Project: MVVM Weather Checker */ public interface WeatherInteractor { String API_URL = "http://api.openweathermap.org/data/2.5/"; @GET("find?lat=55.5&lon=37.5&cnt=10&appid=6b462378109409573b90b51b8a4b79f5")
Observable<WeatherResponse> getWeatherList();
akorshak/android-arch-examples
mvc_example_1/app/src/main/java/com/mera/mvcweatherchecker/managers/weather/WeatherManager.java
// Path: mvc_example_1/app/src/main/java/com/mera/mvcweatherchecker/models/WeatherResponse.java // @Parcel // public class WeatherResponse { // // @SerializedName("list") // private List<WeatherData> mWeatherData = new ArrayList<>(); // // public List<WeatherData> getWeatherData() { // return mWeatherData; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherResponse that = (WeatherResponse) o; // // return !(mWeatherData != null ? !mWeatherData.equals(that.mWeatherData) : that.mWeatherData != null); // // } // // @Override // public int hashCode() { // return mWeatherData != null ? mWeatherData.hashCode() : 0; // } // // @Parcel // public static class WeatherData { // // private final static String ICON_ADDR = "http://openweathermap.org/img/w/"; // // @Parcel // private static class Weather { // @SerializedName("description") // String mDescription; // // @SerializedName("icon") // String mIcon; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Weather weather = (Weather) o; // // if (mDescription != null ? !mDescription.equals(weather.mDescription) : weather.mDescription != null) // return false; // return !(mIcon != null ? !mIcon.equals(weather.mIcon) : weather.mIcon != null); // // } // // @Override // public int hashCode() { // int result = mDescription != null ? mDescription.hashCode() : 0; // result = 31 * result + (mIcon != null ? mIcon.hashCode() : 0); // return result; // } // } // // @Parcel // private static class Main { // @SerializedName("temp") // float mTemp; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Main main = (Main) o; // // return Float.compare(main.mTemp, mTemp) == 0; // // } // // @Override // public int hashCode() { // return (mTemp != +0.0f ? Float.floatToIntBits(mTemp) : 0); // } // } // // @SerializedName("main") // private Main mMain = new Main(); // // @SerializedName("weather") // private List<Weather> mWeather = new ArrayList<>(); // // @SerializedName("name") // private String mCity = ""; // // private WeatherData() { // } // // public String getCity() { // return mCity; // } // // public String getTemperatureInCelsius() { // float temp = mMain.mTemp - 273.15f; // return String.format("%.2f \u00b0C", temp); // } // // public String getIconAddress() { // return ICON_ADDR + mWeather.get(0).mIcon + ".png"; // } // // public String getDescription() { // if (mWeather.size() > 0) { // return mWeather.get(0).mDescription; // } // return ""; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherData that = (WeatherData) o; // // if (mMain != null ? !mMain.equals(that.mMain) : that.mMain != null) return false; // if (mWeather != null ? !mWeather.equals(that.mWeather) : that.mWeather != null) // return false; // return !(mCity != null ? !mCity.equals(that.mCity) : that.mCity != null); // // } // // @Override // public int hashCode() { // int result = mMain != null ? mMain.hashCode() : 0; // result = 31 * result + (mWeather != null ? mWeather.hashCode() : 0); // result = 31 * result + (mCity != null ? mCity.hashCode() : 0); // return result; // } // } // }
import com.mera.mvcweatherchecker.models.WeatherResponse;
package com.mera.mvcweatherchecker.managers.weather; /** * Created by akorshak on 3/22/2016. * Project: MVC Weather Checker */ public class WeatherManager { private WeatherInteractor mInteractor; public WeatherManager() { mInteractor = new WeatherInteractor(); }
// Path: mvc_example_1/app/src/main/java/com/mera/mvcweatherchecker/models/WeatherResponse.java // @Parcel // public class WeatherResponse { // // @SerializedName("list") // private List<WeatherData> mWeatherData = new ArrayList<>(); // // public List<WeatherData> getWeatherData() { // return mWeatherData; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherResponse that = (WeatherResponse) o; // // return !(mWeatherData != null ? !mWeatherData.equals(that.mWeatherData) : that.mWeatherData != null); // // } // // @Override // public int hashCode() { // return mWeatherData != null ? mWeatherData.hashCode() : 0; // } // // @Parcel // public static class WeatherData { // // private final static String ICON_ADDR = "http://openweathermap.org/img/w/"; // // @Parcel // private static class Weather { // @SerializedName("description") // String mDescription; // // @SerializedName("icon") // String mIcon; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Weather weather = (Weather) o; // // if (mDescription != null ? !mDescription.equals(weather.mDescription) : weather.mDescription != null) // return false; // return !(mIcon != null ? !mIcon.equals(weather.mIcon) : weather.mIcon != null); // // } // // @Override // public int hashCode() { // int result = mDescription != null ? mDescription.hashCode() : 0; // result = 31 * result + (mIcon != null ? mIcon.hashCode() : 0); // return result; // } // } // // @Parcel // private static class Main { // @SerializedName("temp") // float mTemp; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Main main = (Main) o; // // return Float.compare(main.mTemp, mTemp) == 0; // // } // // @Override // public int hashCode() { // return (mTemp != +0.0f ? Float.floatToIntBits(mTemp) : 0); // } // } // // @SerializedName("main") // private Main mMain = new Main(); // // @SerializedName("weather") // private List<Weather> mWeather = new ArrayList<>(); // // @SerializedName("name") // private String mCity = ""; // // private WeatherData() { // } // // public String getCity() { // return mCity; // } // // public String getTemperatureInCelsius() { // float temp = mMain.mTemp - 273.15f; // return String.format("%.2f \u00b0C", temp); // } // // public String getIconAddress() { // return ICON_ADDR + mWeather.get(0).mIcon + ".png"; // } // // public String getDescription() { // if (mWeather.size() > 0) { // return mWeather.get(0).mDescription; // } // return ""; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherData that = (WeatherData) o; // // if (mMain != null ? !mMain.equals(that.mMain) : that.mMain != null) return false; // if (mWeather != null ? !mWeather.equals(that.mWeather) : that.mWeather != null) // return false; // return !(mCity != null ? !mCity.equals(that.mCity) : that.mCity != null); // // } // // @Override // public int hashCode() { // int result = mMain != null ? mMain.hashCode() : 0; // result = 31 * result + (mWeather != null ? mWeather.hashCode() : 0); // result = 31 * result + (mCity != null ? mCity.hashCode() : 0); // return result; // } // } // } // Path: mvc_example_1/app/src/main/java/com/mera/mvcweatherchecker/managers/weather/WeatherManager.java import com.mera.mvcweatherchecker.models.WeatherResponse; package com.mera.mvcweatherchecker.managers.weather; /** * Created by akorshak on 3/22/2016. * Project: MVC Weather Checker */ public class WeatherManager { private WeatherInteractor mInteractor; public WeatherManager() { mInteractor = new WeatherInteractor(); }
public void requestWeather(rx.Observer<WeatherResponse> view) {
akorshak/android-arch-examples
mvc_example_1/app/src/main/java/com/mera/mvcweatherchecker/managers/weather/WeatherInteractor.java
// Path: mvc_example_1/app/src/main/java/com/mera/mvcweatherchecker/models/WeatherResponse.java // @Parcel // public class WeatherResponse { // // @SerializedName("list") // private List<WeatherData> mWeatherData = new ArrayList<>(); // // public List<WeatherData> getWeatherData() { // return mWeatherData; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherResponse that = (WeatherResponse) o; // // return !(mWeatherData != null ? !mWeatherData.equals(that.mWeatherData) : that.mWeatherData != null); // // } // // @Override // public int hashCode() { // return mWeatherData != null ? mWeatherData.hashCode() : 0; // } // // @Parcel // public static class WeatherData { // // private final static String ICON_ADDR = "http://openweathermap.org/img/w/"; // // @Parcel // private static class Weather { // @SerializedName("description") // String mDescription; // // @SerializedName("icon") // String mIcon; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Weather weather = (Weather) o; // // if (mDescription != null ? !mDescription.equals(weather.mDescription) : weather.mDescription != null) // return false; // return !(mIcon != null ? !mIcon.equals(weather.mIcon) : weather.mIcon != null); // // } // // @Override // public int hashCode() { // int result = mDescription != null ? mDescription.hashCode() : 0; // result = 31 * result + (mIcon != null ? mIcon.hashCode() : 0); // return result; // } // } // // @Parcel // private static class Main { // @SerializedName("temp") // float mTemp; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Main main = (Main) o; // // return Float.compare(main.mTemp, mTemp) == 0; // // } // // @Override // public int hashCode() { // return (mTemp != +0.0f ? Float.floatToIntBits(mTemp) : 0); // } // } // // @SerializedName("main") // private Main mMain = new Main(); // // @SerializedName("weather") // private List<Weather> mWeather = new ArrayList<>(); // // @SerializedName("name") // private String mCity = ""; // // private WeatherData() { // } // // public String getCity() { // return mCity; // } // // public String getTemperatureInCelsius() { // float temp = mMain.mTemp - 273.15f; // return String.format("%.2f \u00b0C", temp); // } // // public String getIconAddress() { // return ICON_ADDR + mWeather.get(0).mIcon + ".png"; // } // // public String getDescription() { // if (mWeather.size() > 0) { // return mWeather.get(0).mDescription; // } // return ""; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherData that = (WeatherData) o; // // if (mMain != null ? !mMain.equals(that.mMain) : that.mMain != null) return false; // if (mWeather != null ? !mWeather.equals(that.mWeather) : that.mWeather != null) // return false; // return !(mCity != null ? !mCity.equals(that.mCity) : that.mCity != null); // // } // // @Override // public int hashCode() { // int result = mMain != null ? mMain.hashCode() : 0; // result = 31 * result + (mWeather != null ? mWeather.hashCode() : 0); // result = 31 * result + (mCity != null ? mCity.hashCode() : 0); // return result; // } // } // }
import com.mera.mvcweatherchecker.models.WeatherResponse; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.GET; import rx.Observable; import rx.Observer; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
package com.mera.mvcweatherchecker.managers.weather; /** * Created by akorshak on 3/18/2016. * Project: MVC Weather Checker */ public class WeatherInteractor { private static final String API_URL = "http://api.openweathermap.org/data/2.5/"; private WeatherService mWeatherService; WeatherInteractor() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(API_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); mWeatherService = retrofit.create(WeatherService.class); }
// Path: mvc_example_1/app/src/main/java/com/mera/mvcweatherchecker/models/WeatherResponse.java // @Parcel // public class WeatherResponse { // // @SerializedName("list") // private List<WeatherData> mWeatherData = new ArrayList<>(); // // public List<WeatherData> getWeatherData() { // return mWeatherData; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherResponse that = (WeatherResponse) o; // // return !(mWeatherData != null ? !mWeatherData.equals(that.mWeatherData) : that.mWeatherData != null); // // } // // @Override // public int hashCode() { // return mWeatherData != null ? mWeatherData.hashCode() : 0; // } // // @Parcel // public static class WeatherData { // // private final static String ICON_ADDR = "http://openweathermap.org/img/w/"; // // @Parcel // private static class Weather { // @SerializedName("description") // String mDescription; // // @SerializedName("icon") // String mIcon; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Weather weather = (Weather) o; // // if (mDescription != null ? !mDescription.equals(weather.mDescription) : weather.mDescription != null) // return false; // return !(mIcon != null ? !mIcon.equals(weather.mIcon) : weather.mIcon != null); // // } // // @Override // public int hashCode() { // int result = mDescription != null ? mDescription.hashCode() : 0; // result = 31 * result + (mIcon != null ? mIcon.hashCode() : 0); // return result; // } // } // // @Parcel // private static class Main { // @SerializedName("temp") // float mTemp; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Main main = (Main) o; // // return Float.compare(main.mTemp, mTemp) == 0; // // } // // @Override // public int hashCode() { // return (mTemp != +0.0f ? Float.floatToIntBits(mTemp) : 0); // } // } // // @SerializedName("main") // private Main mMain = new Main(); // // @SerializedName("weather") // private List<Weather> mWeather = new ArrayList<>(); // // @SerializedName("name") // private String mCity = ""; // // private WeatherData() { // } // // public String getCity() { // return mCity; // } // // public String getTemperatureInCelsius() { // float temp = mMain.mTemp - 273.15f; // return String.format("%.2f \u00b0C", temp); // } // // public String getIconAddress() { // return ICON_ADDR + mWeather.get(0).mIcon + ".png"; // } // // public String getDescription() { // if (mWeather.size() > 0) { // return mWeather.get(0).mDescription; // } // return ""; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherData that = (WeatherData) o; // // if (mMain != null ? !mMain.equals(that.mMain) : that.mMain != null) return false; // if (mWeather != null ? !mWeather.equals(that.mWeather) : that.mWeather != null) // return false; // return !(mCity != null ? !mCity.equals(that.mCity) : that.mCity != null); // // } // // @Override // public int hashCode() { // int result = mMain != null ? mMain.hashCode() : 0; // result = 31 * result + (mWeather != null ? mWeather.hashCode() : 0); // result = 31 * result + (mCity != null ? mCity.hashCode() : 0); // return result; // } // } // } // Path: mvc_example_1/app/src/main/java/com/mera/mvcweatherchecker/managers/weather/WeatherInteractor.java import com.mera.mvcweatherchecker.models.WeatherResponse; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.GET; import rx.Observable; import rx.Observer; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; package com.mera.mvcweatherchecker.managers.weather; /** * Created by akorshak on 3/18/2016. * Project: MVC Weather Checker */ public class WeatherInteractor { private static final String API_URL = "http://api.openweathermap.org/data/2.5/"; private WeatherService mWeatherService; WeatherInteractor() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(API_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); mWeatherService = retrofit.create(WeatherService.class); }
public void fetchWeatherData(Observer<WeatherResponse> view) {
akorshak/android-arch-examples
mvc_example_1/app/src/main/java/com/mera/mvcweatherchecker/components/WeatherAdapter.java
// Path: mvc_example_1/app/src/main/java/com/mera/mvcweatherchecker/models/WeatherResponse.java // @Parcel // public class WeatherResponse { // // @SerializedName("list") // private List<WeatherData> mWeatherData = new ArrayList<>(); // // public List<WeatherData> getWeatherData() { // return mWeatherData; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherResponse that = (WeatherResponse) o; // // return !(mWeatherData != null ? !mWeatherData.equals(that.mWeatherData) : that.mWeatherData != null); // // } // // @Override // public int hashCode() { // return mWeatherData != null ? mWeatherData.hashCode() : 0; // } // // @Parcel // public static class WeatherData { // // private final static String ICON_ADDR = "http://openweathermap.org/img/w/"; // // @Parcel // private static class Weather { // @SerializedName("description") // String mDescription; // // @SerializedName("icon") // String mIcon; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Weather weather = (Weather) o; // // if (mDescription != null ? !mDescription.equals(weather.mDescription) : weather.mDescription != null) // return false; // return !(mIcon != null ? !mIcon.equals(weather.mIcon) : weather.mIcon != null); // // } // // @Override // public int hashCode() { // int result = mDescription != null ? mDescription.hashCode() : 0; // result = 31 * result + (mIcon != null ? mIcon.hashCode() : 0); // return result; // } // } // // @Parcel // private static class Main { // @SerializedName("temp") // float mTemp; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Main main = (Main) o; // // return Float.compare(main.mTemp, mTemp) == 0; // // } // // @Override // public int hashCode() { // return (mTemp != +0.0f ? Float.floatToIntBits(mTemp) : 0); // } // } // // @SerializedName("main") // private Main mMain = new Main(); // // @SerializedName("weather") // private List<Weather> mWeather = new ArrayList<>(); // // @SerializedName("name") // private String mCity = ""; // // private WeatherData() { // } // // public String getCity() { // return mCity; // } // // public String getTemperatureInCelsius() { // float temp = mMain.mTemp - 273.15f; // return String.format("%.2f \u00b0C", temp); // } // // public String getIconAddress() { // return ICON_ADDR + mWeather.get(0).mIcon + ".png"; // } // // public String getDescription() { // if (mWeather.size() > 0) { // return mWeather.get(0).mDescription; // } // return ""; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherData that = (WeatherData) o; // // if (mMain != null ? !mMain.equals(that.mMain) : that.mMain != null) return false; // if (mWeather != null ? !mWeather.equals(that.mWeather) : that.mWeather != null) // return false; // return !(mCity != null ? !mCity.equals(that.mCity) : that.mCity != null); // // } // // @Override // public int hashCode() { // int result = mMain != null ? mMain.hashCode() : 0; // result = 31 * result + (mWeather != null ? mWeather.hashCode() : 0); // result = 31 * result + (mCity != null ? mCity.hashCode() : 0); // return result; // } // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.mera.mvcweatherchecker.R; import com.mera.mvcweatherchecker.models.WeatherResponse; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife;
package com.mera.mvcweatherchecker.components; /** * Created by akorshak on 3/18/2016. * Project: MVC Weather Checker */ public class WeatherAdapter extends RecyclerView.Adapter { private Context mContext;
// Path: mvc_example_1/app/src/main/java/com/mera/mvcweatherchecker/models/WeatherResponse.java // @Parcel // public class WeatherResponse { // // @SerializedName("list") // private List<WeatherData> mWeatherData = new ArrayList<>(); // // public List<WeatherData> getWeatherData() { // return mWeatherData; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherResponse that = (WeatherResponse) o; // // return !(mWeatherData != null ? !mWeatherData.equals(that.mWeatherData) : that.mWeatherData != null); // // } // // @Override // public int hashCode() { // return mWeatherData != null ? mWeatherData.hashCode() : 0; // } // // @Parcel // public static class WeatherData { // // private final static String ICON_ADDR = "http://openweathermap.org/img/w/"; // // @Parcel // private static class Weather { // @SerializedName("description") // String mDescription; // // @SerializedName("icon") // String mIcon; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Weather weather = (Weather) o; // // if (mDescription != null ? !mDescription.equals(weather.mDescription) : weather.mDescription != null) // return false; // return !(mIcon != null ? !mIcon.equals(weather.mIcon) : weather.mIcon != null); // // } // // @Override // public int hashCode() { // int result = mDescription != null ? mDescription.hashCode() : 0; // result = 31 * result + (mIcon != null ? mIcon.hashCode() : 0); // return result; // } // } // // @Parcel // private static class Main { // @SerializedName("temp") // float mTemp; // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Main main = (Main) o; // // return Float.compare(main.mTemp, mTemp) == 0; // // } // // @Override // public int hashCode() { // return (mTemp != +0.0f ? Float.floatToIntBits(mTemp) : 0); // } // } // // @SerializedName("main") // private Main mMain = new Main(); // // @SerializedName("weather") // private List<Weather> mWeather = new ArrayList<>(); // // @SerializedName("name") // private String mCity = ""; // // private WeatherData() { // } // // public String getCity() { // return mCity; // } // // public String getTemperatureInCelsius() { // float temp = mMain.mTemp - 273.15f; // return String.format("%.2f \u00b0C", temp); // } // // public String getIconAddress() { // return ICON_ADDR + mWeather.get(0).mIcon + ".png"; // } // // public String getDescription() { // if (mWeather.size() > 0) { // return mWeather.get(0).mDescription; // } // return ""; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // WeatherData that = (WeatherData) o; // // if (mMain != null ? !mMain.equals(that.mMain) : that.mMain != null) return false; // if (mWeather != null ? !mWeather.equals(that.mWeather) : that.mWeather != null) // return false; // return !(mCity != null ? !mCity.equals(that.mCity) : that.mCity != null); // // } // // @Override // public int hashCode() { // int result = mMain != null ? mMain.hashCode() : 0; // result = 31 * result + (mWeather != null ? mWeather.hashCode() : 0); // result = 31 * result + (mCity != null ? mCity.hashCode() : 0); // return result; // } // } // } // Path: mvc_example_1/app/src/main/java/com/mera/mvcweatherchecker/components/WeatherAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.mera.mvcweatherchecker.R; import com.mera.mvcweatherchecker.models.WeatherResponse; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; package com.mera.mvcweatherchecker.components; /** * Created by akorshak on 3/18/2016. * Project: MVC Weather Checker */ public class WeatherAdapter extends RecyclerView.Adapter { private Context mContext;
private List<WeatherResponse.WeatherData> mWeatherData = new ArrayList<>();
semanticvectors/semanticvectors
src/test/java/pitt/search/semanticvectors/vectors/ComplexVectorTest.java
// Path: src/main/java/pitt/search/semanticvectors/vectors/ComplexVector.java // public static enum Mode { // /** Uses a nonnegative 16 bit short for each phase angle. The value -1 is reserved for // * representing the complex number zero, i.e., there is no entry in this dimension. */ // POLAR_DENSE, // /** Uses a pair of 16 bit shorts for each (offset, phase angle) pair. */ // POLAR_SPARSE, // /** Uses a pair of 32 bit floats for each (real, imaginary) complex coordinate. */ // CARTESIAN, // /** As above, but with normalization to unit length and the hermitian scalar product // * instead of the alternatives proposed by Plate */ // HERMITIAN // }
import java.io.IOException; import java.util.Arrays; import java.util.Random; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.store.RAMDirectory; import org.junit.Test; import static pitt.search.semanticvectors.MyTestUtils.assertFloatArrayEquals; import static pitt.search.semanticvectors.vectors.ComplexVector.Mode; import junit.framework.TestCase; import static org.junit.Assert.assertArrayEquals;
/** Copyright (c) 2011, the SemanticVectors AUTHORS. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Pittsburgh nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ package pitt.search.semanticvectors.vectors; /** * Tests for {@code ComplexVector} class. Many of these tests use {@code ComplexVector#toString} * to check correct results. This is somewhat ad hoc and any change in the debug string * representation will likely cause breakages. Be warned! */ public class ComplexVectorTest extends TestCase { private static final double TOL = 0.001; @Test public void testGenerateRandomVector() { // Generate random vector ComplexVector cv1 = (ComplexVector) VectorFactory.generateRandomVector( VectorType.COMPLEX, 5, 2, new Random(0)); assertArrayEquals(new short[] {0, 13622, 4, 9934}, cv1.getSparseOffsets());
// Path: src/main/java/pitt/search/semanticvectors/vectors/ComplexVector.java // public static enum Mode { // /** Uses a nonnegative 16 bit short for each phase angle. The value -1 is reserved for // * representing the complex number zero, i.e., there is no entry in this dimension. */ // POLAR_DENSE, // /** Uses a pair of 16 bit shorts for each (offset, phase angle) pair. */ // POLAR_SPARSE, // /** Uses a pair of 32 bit floats for each (real, imaginary) complex coordinate. */ // CARTESIAN, // /** As above, but with normalization to unit length and the hermitian scalar product // * instead of the alternatives proposed by Plate */ // HERMITIAN // } // Path: src/test/java/pitt/search/semanticvectors/vectors/ComplexVectorTest.java import java.io.IOException; import java.util.Arrays; import java.util.Random; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.store.RAMDirectory; import org.junit.Test; import static pitt.search.semanticvectors.MyTestUtils.assertFloatArrayEquals; import static pitt.search.semanticvectors.vectors.ComplexVector.Mode; import junit.framework.TestCase; import static org.junit.Assert.assertArrayEquals; /** Copyright (c) 2011, the SemanticVectors AUTHORS. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Pittsburgh nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ package pitt.search.semanticvectors.vectors; /** * Tests for {@code ComplexVector} class. Many of these tests use {@code ComplexVector#toString} * to check correct results. This is somewhat ad hoc and any change in the debug string * representation will likely cause breakages. Be warned! */ public class ComplexVectorTest extends TestCase { private static final double TOL = 0.001; @Test public void testGenerateRandomVector() { // Generate random vector ComplexVector cv1 = (ComplexVector) VectorFactory.generateRandomVector( VectorType.COMPLEX, 5, 2, new Random(0)); assertArrayEquals(new short[] {0, 13622, 4, 9934}, cv1.getSparseOffsets());
assertEquals(Mode.POLAR_SPARSE, cv1.getOpMode());
semanticvectors/semanticvectors
src/main/java/pitt/search/semanticvectors/IncrementalDocVectors.java
// Path: src/main/java/pitt/search/semanticvectors/vectors/VectorFactory.java // public class VectorFactory { // private static final BinaryVector binaryInstance = new BinaryVector(0); // private static final RealVector realInstance = new RealVector(0); // private static final ComplexVector complexInstance = // new ComplexVector(0, ComplexVector.Mode.POLAR_SPARSE); // private static final ComplexVector complexFlatInstance = // new ComplexVector(0, ComplexVector.Mode.CARTESIAN); // // /** // * createZeroVector returns a vector set to zero. It can be used externally, but // * be careful particularly with Complex Vectors to make sure that polar / cartesian / hermitian // * modes are set correctly especially if you try to set coordinates manually after that. // */ // public static Vector createZeroVector(VectorType type, int dimension) { // switch (type) { // case BINARY: // return new BinaryVector(dimension); // case REAL: // return new RealVector(dimension); // case COMPLEX: // return new ComplexVector(dimension, Mode.POLAR_SPARSE); // case COMPLEXFLAT: // return new ComplexVector(dimension, Mode.POLAR_SPARSE); // case PERMUTATION: // return new PermutationVector(dimension); // default: // throw new IllegalArgumentException("Unrecognized VectorType: " + type); // } // } // // /** // * Generates an appropriate random vector. // * // * @param type one of the recognized vector types // * @param dimension number of dimensions in the generated vector // * @param numEntries total number of non-zero entries; must be no greater than half of dimension // * @param random random number generator; passed in to enable deterministic testing // * @return vector generated with appropriate type, dimension and number of nonzero entries // */ // public static Vector generateRandomVector( // VectorType type, int dimension, int numEntries, Random random) { // // if (2 * numEntries > dimension && !type.equals(VectorType.COMPLEX) && !(numEntries == dimension)) { // throw new RuntimeException("Requested " + numEntries + " to be filled in sparse " // + "vector of dimension " + dimension + ". This is not sparse and may cause problems."); // } // switch (type) { // case BINARY: // return binaryInstance.generateRandomVector(dimension, numEntries, random); // case REAL: // return realInstance.generateRandomVector(dimension, numEntries, random); // case COMPLEX: // if (!ComplexVector.getDominantMode().equals(Mode.HERMITIAN)) // ComplexVector.setDominantMode(Mode.POLAR_DENSE); // return complexInstance.generateRandomVector(dimension, numEntries, random); // case COMPLEXFLAT: // ComplexVector.setDominantMode(Mode.CARTESIAN); // return complexInstance.generateRandomVector(dimension, numEntries, random); // default: // throw new IllegalArgumentException("Unrecognized VectorType: " + type); // } // } // // /** // * Returns the size in bytes expected to be taken up by the serialization // * of this vector in Lucene format. // */ // public static int getLuceneByteSize(VectorType vectorType, int dimension) { // switch (vectorType) { // case BINARY: // return 8 * ((dimension / 64) ); // case REAL: // return 4 * dimension; // case COMPLEX: // case COMPLEXFLAT: // return 8 * dimension; // default: // throw new IllegalArgumentException("Unrecognized VectorType: " + vectorType); // } // } // }
import java.io.File; import java.io.IOException; import java.nio.file.FileSystems; import java.util.Arrays; import java.util.logging.Logger; import org.apache.lucene.index.*; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.BytesRef; import pitt.search.semanticvectors.utils.VerbatimLogger; import pitt.search.semanticvectors.vectors.Vector; import pitt.search.semanticvectors.vectors.VectorFactory;
private void trainIncrementalDocVectors() throws IOException { int numdocs = luceneUtils.getNumDocs(); // Open file and write headers. File vectorFile = new File( VectorStoreUtils.getStoreFileName(flagConfig.docvectorsfile(), flagConfig)); String parentPath = vectorFile.getParent(); if (parentPath == null) parentPath = ""; FSDirectory fsDirectory = FSDirectory.open(FileSystems.getDefault().getPath(parentPath)); java.nio.file.Files.deleteIfExists(vectorFile.toPath()); IndexOutput outputStream = fsDirectory.createOutput(vectorFile.getName(), IOContext.DEFAULT); VerbatimLogger.info("Writing vectors incrementally to file " + vectorFile + " ... "); // Write header giving number of dimension for all vectors. outputStream.writeString(VectorStoreWriter.generateHeaderString(flagConfig)); // Iterate through documents. for (int dc = 0; dc < numdocs; dc++) { // Output progress counter. if ((dc > 0) && ((dc % 10000 == 0) || (dc < 10000 && dc % 1000 == 0))) { VerbatimLogger.info("Processed " + dc + " documents ... "); } // Get filename and path to be used as document vector ID, defaulting to doc number only if // docidfield is not populated. String docID = luceneUtils.getExternalDocId(dc);
// Path: src/main/java/pitt/search/semanticvectors/vectors/VectorFactory.java // public class VectorFactory { // private static final BinaryVector binaryInstance = new BinaryVector(0); // private static final RealVector realInstance = new RealVector(0); // private static final ComplexVector complexInstance = // new ComplexVector(0, ComplexVector.Mode.POLAR_SPARSE); // private static final ComplexVector complexFlatInstance = // new ComplexVector(0, ComplexVector.Mode.CARTESIAN); // // /** // * createZeroVector returns a vector set to zero. It can be used externally, but // * be careful particularly with Complex Vectors to make sure that polar / cartesian / hermitian // * modes are set correctly especially if you try to set coordinates manually after that. // */ // public static Vector createZeroVector(VectorType type, int dimension) { // switch (type) { // case BINARY: // return new BinaryVector(dimension); // case REAL: // return new RealVector(dimension); // case COMPLEX: // return new ComplexVector(dimension, Mode.POLAR_SPARSE); // case COMPLEXFLAT: // return new ComplexVector(dimension, Mode.POLAR_SPARSE); // case PERMUTATION: // return new PermutationVector(dimension); // default: // throw new IllegalArgumentException("Unrecognized VectorType: " + type); // } // } // // /** // * Generates an appropriate random vector. // * // * @param type one of the recognized vector types // * @param dimension number of dimensions in the generated vector // * @param numEntries total number of non-zero entries; must be no greater than half of dimension // * @param random random number generator; passed in to enable deterministic testing // * @return vector generated with appropriate type, dimension and number of nonzero entries // */ // public static Vector generateRandomVector( // VectorType type, int dimension, int numEntries, Random random) { // // if (2 * numEntries > dimension && !type.equals(VectorType.COMPLEX) && !(numEntries == dimension)) { // throw new RuntimeException("Requested " + numEntries + " to be filled in sparse " // + "vector of dimension " + dimension + ". This is not sparse and may cause problems."); // } // switch (type) { // case BINARY: // return binaryInstance.generateRandomVector(dimension, numEntries, random); // case REAL: // return realInstance.generateRandomVector(dimension, numEntries, random); // case COMPLEX: // if (!ComplexVector.getDominantMode().equals(Mode.HERMITIAN)) // ComplexVector.setDominantMode(Mode.POLAR_DENSE); // return complexInstance.generateRandomVector(dimension, numEntries, random); // case COMPLEXFLAT: // ComplexVector.setDominantMode(Mode.CARTESIAN); // return complexInstance.generateRandomVector(dimension, numEntries, random); // default: // throw new IllegalArgumentException("Unrecognized VectorType: " + type); // } // } // // /** // * Returns the size in bytes expected to be taken up by the serialization // * of this vector in Lucene format. // */ // public static int getLuceneByteSize(VectorType vectorType, int dimension) { // switch (vectorType) { // case BINARY: // return 8 * ((dimension / 64) ); // case REAL: // return 4 * dimension; // case COMPLEX: // case COMPLEXFLAT: // return 8 * dimension; // default: // throw new IllegalArgumentException("Unrecognized VectorType: " + vectorType); // } // } // } // Path: src/main/java/pitt/search/semanticvectors/IncrementalDocVectors.java import java.io.File; import java.io.IOException; import java.nio.file.FileSystems; import java.util.Arrays; import java.util.logging.Logger; import org.apache.lucene.index.*; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.BytesRef; import pitt.search.semanticvectors.utils.VerbatimLogger; import pitt.search.semanticvectors.vectors.Vector; import pitt.search.semanticvectors.vectors.VectorFactory; private void trainIncrementalDocVectors() throws IOException { int numdocs = luceneUtils.getNumDocs(); // Open file and write headers. File vectorFile = new File( VectorStoreUtils.getStoreFileName(flagConfig.docvectorsfile(), flagConfig)); String parentPath = vectorFile.getParent(); if (parentPath == null) parentPath = ""; FSDirectory fsDirectory = FSDirectory.open(FileSystems.getDefault().getPath(parentPath)); java.nio.file.Files.deleteIfExists(vectorFile.toPath()); IndexOutput outputStream = fsDirectory.createOutput(vectorFile.getName(), IOContext.DEFAULT); VerbatimLogger.info("Writing vectors incrementally to file " + vectorFile + " ... "); // Write header giving number of dimension for all vectors. outputStream.writeString(VectorStoreWriter.generateHeaderString(flagConfig)); // Iterate through documents. for (int dc = 0; dc < numdocs; dc++) { // Output progress counter. if ((dc > 0) && ((dc % 10000 == 0) || (dc < 10000 && dc % 1000 == 0))) { VerbatimLogger.info("Processed " + dc + " documents ... "); } // Get filename and path to be used as document vector ID, defaulting to doc number only if // docidfield is not populated. String docID = luceneUtils.getExternalDocId(dc);
Vector docVector = VectorFactory.createZeroVector(flagConfig.vectortype(), flagConfig.dimension());
semanticvectors/semanticvectors
src/main/java/pitt/search/semanticvectors/DocVectors.java
// Path: src/main/java/pitt/search/semanticvectors/vectors/VectorFactory.java // public class VectorFactory { // private static final BinaryVector binaryInstance = new BinaryVector(0); // private static final RealVector realInstance = new RealVector(0); // private static final ComplexVector complexInstance = // new ComplexVector(0, ComplexVector.Mode.POLAR_SPARSE); // private static final ComplexVector complexFlatInstance = // new ComplexVector(0, ComplexVector.Mode.CARTESIAN); // // /** // * createZeroVector returns a vector set to zero. It can be used externally, but // * be careful particularly with Complex Vectors to make sure that polar / cartesian / hermitian // * modes are set correctly especially if you try to set coordinates manually after that. // */ // public static Vector createZeroVector(VectorType type, int dimension) { // switch (type) { // case BINARY: // return new BinaryVector(dimension); // case REAL: // return new RealVector(dimension); // case COMPLEX: // return new ComplexVector(dimension, Mode.POLAR_SPARSE); // case COMPLEXFLAT: // return new ComplexVector(dimension, Mode.POLAR_SPARSE); // case PERMUTATION: // return new PermutationVector(dimension); // default: // throw new IllegalArgumentException("Unrecognized VectorType: " + type); // } // } // // /** // * Generates an appropriate random vector. // * // * @param type one of the recognized vector types // * @param dimension number of dimensions in the generated vector // * @param numEntries total number of non-zero entries; must be no greater than half of dimension // * @param random random number generator; passed in to enable deterministic testing // * @return vector generated with appropriate type, dimension and number of nonzero entries // */ // public static Vector generateRandomVector( // VectorType type, int dimension, int numEntries, Random random) { // // if (2 * numEntries > dimension && !type.equals(VectorType.COMPLEX) && !(numEntries == dimension)) { // throw new RuntimeException("Requested " + numEntries + " to be filled in sparse " // + "vector of dimension " + dimension + ". This is not sparse and may cause problems."); // } // switch (type) { // case BINARY: // return binaryInstance.generateRandomVector(dimension, numEntries, random); // case REAL: // return realInstance.generateRandomVector(dimension, numEntries, random); // case COMPLEX: // if (!ComplexVector.getDominantMode().equals(Mode.HERMITIAN)) // ComplexVector.setDominantMode(Mode.POLAR_DENSE); // return complexInstance.generateRandomVector(dimension, numEntries, random); // case COMPLEXFLAT: // ComplexVector.setDominantMode(Mode.CARTESIAN); // return complexInstance.generateRandomVector(dimension, numEntries, random); // default: // throw new IllegalArgumentException("Unrecognized VectorType: " + type); // } // } // // /** // * Returns the size in bytes expected to be taken up by the serialization // * of this vector in Lucene format. // */ // public static int getLuceneByteSize(VectorType vectorType, int dimension) { // switch (vectorType) { // case BINARY: // return 8 * ((dimension / 64) ); // case REAL: // return 4 * dimension; // case COMPLEX: // case COMPLEXFLAT: // return 8 * dimension; // default: // throw new IllegalArgumentException("Unrecognized VectorType: " + vectorType); // } // } // } // // Path: src/main/java/pitt/search/semanticvectors/vectors/VectorType.java // public enum VectorType { // /** // * Uses binary-valued vectors. May be slower for some operations, but highly accurate. // */ // BINARY, // /** // * "Standard" real-valued vectors. Performs well for many operations though bind and release // * are (in some cases) either lossy with respect to argument structure and binding, or // * inexact with respect to inverse. // */ // REAL, // /** // * Complex-valued vectors, default "polar" version, normalized to coordinates on the unit circle, // * and compared using angular differences. // */ // COMPLEX, // /** // * Complex-valued vectors, normalized and compared using a hermitian scalar product. // */ // COMPLEXFLAT, // /** // * Vector of integer values, describing a permutation // */ // PERMUTATION // }
import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.Term; import org.apache.lucene.index.TermsEnum; import pitt.search.semanticvectors.utils.VerbatimLogger; import pitt.search.semanticvectors.vectors.Vector; import pitt.search.semanticvectors.vectors.VectorFactory; import pitt.search.semanticvectors.vectors.VectorType; import java.io.IOException; import java.util.Enumeration; import java.util.logging.Logger;
while (terms.next() != null) { numTerms++; } fieldweight = (float) (1/Math.sqrt(numTerms)); } docVector.superpose( termVector, localweight * globalweight * fieldweight, null); } } } } catch (IOException e) { // catches from indexReader. e.printStackTrace(); } VerbatimLogger.info("\nNormalizing doc vectors ...\n"); Enumeration<ObjectVector> docEnum = docVectors.getAllVectors(); while (docEnum.hasMoreElements()) docEnum.nextElement().getVector().normalize(); } /** * Allocate doc vectors to zero vectors. */ private void initializeZeroDocVectors() throws IOException { VerbatimLogger.info("Initializing new document vector store ... \n"); for (int i = 0; i < luceneUtils.getNumDocs(); ++i) { String externalDocId = luceneUtils.getExternalDocId(i);
// Path: src/main/java/pitt/search/semanticvectors/vectors/VectorFactory.java // public class VectorFactory { // private static final BinaryVector binaryInstance = new BinaryVector(0); // private static final RealVector realInstance = new RealVector(0); // private static final ComplexVector complexInstance = // new ComplexVector(0, ComplexVector.Mode.POLAR_SPARSE); // private static final ComplexVector complexFlatInstance = // new ComplexVector(0, ComplexVector.Mode.CARTESIAN); // // /** // * createZeroVector returns a vector set to zero. It can be used externally, but // * be careful particularly with Complex Vectors to make sure that polar / cartesian / hermitian // * modes are set correctly especially if you try to set coordinates manually after that. // */ // public static Vector createZeroVector(VectorType type, int dimension) { // switch (type) { // case BINARY: // return new BinaryVector(dimension); // case REAL: // return new RealVector(dimension); // case COMPLEX: // return new ComplexVector(dimension, Mode.POLAR_SPARSE); // case COMPLEXFLAT: // return new ComplexVector(dimension, Mode.POLAR_SPARSE); // case PERMUTATION: // return new PermutationVector(dimension); // default: // throw new IllegalArgumentException("Unrecognized VectorType: " + type); // } // } // // /** // * Generates an appropriate random vector. // * // * @param type one of the recognized vector types // * @param dimension number of dimensions in the generated vector // * @param numEntries total number of non-zero entries; must be no greater than half of dimension // * @param random random number generator; passed in to enable deterministic testing // * @return vector generated with appropriate type, dimension and number of nonzero entries // */ // public static Vector generateRandomVector( // VectorType type, int dimension, int numEntries, Random random) { // // if (2 * numEntries > dimension && !type.equals(VectorType.COMPLEX) && !(numEntries == dimension)) { // throw new RuntimeException("Requested " + numEntries + " to be filled in sparse " // + "vector of dimension " + dimension + ". This is not sparse and may cause problems."); // } // switch (type) { // case BINARY: // return binaryInstance.generateRandomVector(dimension, numEntries, random); // case REAL: // return realInstance.generateRandomVector(dimension, numEntries, random); // case COMPLEX: // if (!ComplexVector.getDominantMode().equals(Mode.HERMITIAN)) // ComplexVector.setDominantMode(Mode.POLAR_DENSE); // return complexInstance.generateRandomVector(dimension, numEntries, random); // case COMPLEXFLAT: // ComplexVector.setDominantMode(Mode.CARTESIAN); // return complexInstance.generateRandomVector(dimension, numEntries, random); // default: // throw new IllegalArgumentException("Unrecognized VectorType: " + type); // } // } // // /** // * Returns the size in bytes expected to be taken up by the serialization // * of this vector in Lucene format. // */ // public static int getLuceneByteSize(VectorType vectorType, int dimension) { // switch (vectorType) { // case BINARY: // return 8 * ((dimension / 64) ); // case REAL: // return 4 * dimension; // case COMPLEX: // case COMPLEXFLAT: // return 8 * dimension; // default: // throw new IllegalArgumentException("Unrecognized VectorType: " + vectorType); // } // } // } // // Path: src/main/java/pitt/search/semanticvectors/vectors/VectorType.java // public enum VectorType { // /** // * Uses binary-valued vectors. May be slower for some operations, but highly accurate. // */ // BINARY, // /** // * "Standard" real-valued vectors. Performs well for many operations though bind and release // * are (in some cases) either lossy with respect to argument structure and binding, or // * inexact with respect to inverse. // */ // REAL, // /** // * Complex-valued vectors, default "polar" version, normalized to coordinates on the unit circle, // * and compared using angular differences. // */ // COMPLEX, // /** // * Complex-valued vectors, normalized and compared using a hermitian scalar product. // */ // COMPLEXFLAT, // /** // * Vector of integer values, describing a permutation // */ // PERMUTATION // } // Path: src/main/java/pitt/search/semanticvectors/DocVectors.java import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.Term; import org.apache.lucene.index.TermsEnum; import pitt.search.semanticvectors.utils.VerbatimLogger; import pitt.search.semanticvectors.vectors.Vector; import pitt.search.semanticvectors.vectors.VectorFactory; import pitt.search.semanticvectors.vectors.VectorType; import java.io.IOException; import java.util.Enumeration; import java.util.logging.Logger; while (terms.next() != null) { numTerms++; } fieldweight = (float) (1/Math.sqrt(numTerms)); } docVector.superpose( termVector, localweight * globalweight * fieldweight, null); } } } } catch (IOException e) { // catches from indexReader. e.printStackTrace(); } VerbatimLogger.info("\nNormalizing doc vectors ...\n"); Enumeration<ObjectVector> docEnum = docVectors.getAllVectors(); while (docEnum.hasMoreElements()) docEnum.nextElement().getVector().normalize(); } /** * Allocate doc vectors to zero vectors. */ private void initializeZeroDocVectors() throws IOException { VerbatimLogger.info("Initializing new document vector store ... \n"); for (int i = 0; i < luceneUtils.getNumDocs(); ++i) { String externalDocId = luceneUtils.getExternalDocId(i);
Vector docVector = VectorFactory.createZeroVector(flagConfig.vectortype(), flagConfig.dimension());
semanticvectors/semanticvectors
src/main/java/pitt/search/semanticvectors/BuildPositionalIndex.java
// Path: src/main/java/pitt/search/semanticvectors/DocVectors.java // public enum DocIndexingStrategy { // /** // * Index documents in memory, write to disk at the end. Fast but relies on large // * memory footprint. */ // INMEMORY, // // /** // * Index one document at a time, writing to disk during the process. // * Requires less memory. Cannot be used for indexing strategies that rely // * on random access to doc vector store during indexing. // */ // INCREMENTAL, // // /** // * Do not create document vectors at all. Useful if there are many documents // * and you are only interested in exploring term vectors. // */ // NONE, // } // // Path: src/main/java/pitt/search/semanticvectors/TermTermVectorsFromLucene.java // public enum PositionalMethod { // /** Basic "bag-of-words" method using context windows. */ // BASIC, // /** Binds vectors on left or right based on position. */ // DIRECTIONAL, // /** Permutes vectors according to how many places they are from focus term. */ // PERMUTATION, // /** Superposition of basic and permuted vectors. */ // PERMUTATIONPLUSBASIC, // /** Encodes position within sliding window using NumberRepresentation */ // PROXIMITY // } // // Path: src/main/java/pitt/search/semanticvectors/TermTermVectorsFromLucene.java // public enum EncodingMethod { // /** Random indexing */ // RANDOM_INDEXING, // /** Implementation of skipgram with negative sampling (Mikolov 2013) */ // EMBEDDINGS // }
import java.io.IOException; import java.util.Arrays; import java.util.Enumeration; import java.util.logging.Logger; import pitt.search.semanticvectors.DocVectors.DocIndexingStrategy; import pitt.search.semanticvectors.TermTermVectorsFromLucene.PositionalMethod; import pitt.search.semanticvectors.TermTermVectorsFromLucene.EncodingMethod; import pitt.search.semanticvectors.utils.VerbatimLogger;
logger.info("Could not read from vector store " + flagConfig.initialtermvectors()); System.out.println(usageMessage); throw new IllegalArgumentException(); } } String termFile = ""; switch (flagConfig.positionalmethod()) { case BASIC: termFile = flagConfig.termtermvectorsfile(); break; case PROXIMITY: termFile = flagConfig.proximityvectorfile(); break; case PERMUTATION: termFile = flagConfig.permutedvectorfile(); break; case PERMUTATIONPLUSBASIC: termFile = flagConfig.permplustermvectorfile(); break; case DIRECTIONAL: termFile = flagConfig.directionalvectorfile(); break; default: throw new IllegalArgumentException( "Unrecognized -positionalmethod: " + flagConfig.positionalmethod()); }
// Path: src/main/java/pitt/search/semanticvectors/DocVectors.java // public enum DocIndexingStrategy { // /** // * Index documents in memory, write to disk at the end. Fast but relies on large // * memory footprint. */ // INMEMORY, // // /** // * Index one document at a time, writing to disk during the process. // * Requires less memory. Cannot be used for indexing strategies that rely // * on random access to doc vector store during indexing. // */ // INCREMENTAL, // // /** // * Do not create document vectors at all. Useful if there are many documents // * and you are only interested in exploring term vectors. // */ // NONE, // } // // Path: src/main/java/pitt/search/semanticvectors/TermTermVectorsFromLucene.java // public enum PositionalMethod { // /** Basic "bag-of-words" method using context windows. */ // BASIC, // /** Binds vectors on left or right based on position. */ // DIRECTIONAL, // /** Permutes vectors according to how many places they are from focus term. */ // PERMUTATION, // /** Superposition of basic and permuted vectors. */ // PERMUTATIONPLUSBASIC, // /** Encodes position within sliding window using NumberRepresentation */ // PROXIMITY // } // // Path: src/main/java/pitt/search/semanticvectors/TermTermVectorsFromLucene.java // public enum EncodingMethod { // /** Random indexing */ // RANDOM_INDEXING, // /** Implementation of skipgram with negative sampling (Mikolov 2013) */ // EMBEDDINGS // } // Path: src/main/java/pitt/search/semanticvectors/BuildPositionalIndex.java import java.io.IOException; import java.util.Arrays; import java.util.Enumeration; import java.util.logging.Logger; import pitt.search.semanticvectors.DocVectors.DocIndexingStrategy; import pitt.search.semanticvectors.TermTermVectorsFromLucene.PositionalMethod; import pitt.search.semanticvectors.TermTermVectorsFromLucene.EncodingMethod; import pitt.search.semanticvectors.utils.VerbatimLogger; logger.info("Could not read from vector store " + flagConfig.initialtermvectors()); System.out.println(usageMessage); throw new IllegalArgumentException(); } } String termFile = ""; switch (flagConfig.positionalmethod()) { case BASIC: termFile = flagConfig.termtermvectorsfile(); break; case PROXIMITY: termFile = flagConfig.proximityvectorfile(); break; case PERMUTATION: termFile = flagConfig.permutedvectorfile(); break; case PERMUTATIONPLUSBASIC: termFile = flagConfig.permplustermvectorfile(); break; case DIRECTIONAL: termFile = flagConfig.directionalvectorfile(); break; default: throw new IllegalArgumentException( "Unrecognized -positionalmethod: " + flagConfig.positionalmethod()); }
if (flagConfig.encodingmethod().equals(EncodingMethod.EMBEDDINGS))
semanticvectors/semanticvectors
src/main/java/pitt/search/semanticvectors/BuildPositionalIndex.java
// Path: src/main/java/pitt/search/semanticvectors/DocVectors.java // public enum DocIndexingStrategy { // /** // * Index documents in memory, write to disk at the end. Fast but relies on large // * memory footprint. */ // INMEMORY, // // /** // * Index one document at a time, writing to disk during the process. // * Requires less memory. Cannot be used for indexing strategies that rely // * on random access to doc vector store during indexing. // */ // INCREMENTAL, // // /** // * Do not create document vectors at all. Useful if there are many documents // * and you are only interested in exploring term vectors. // */ // NONE, // } // // Path: src/main/java/pitt/search/semanticvectors/TermTermVectorsFromLucene.java // public enum PositionalMethod { // /** Basic "bag-of-words" method using context windows. */ // BASIC, // /** Binds vectors on left or right based on position. */ // DIRECTIONAL, // /** Permutes vectors according to how many places they are from focus term. */ // PERMUTATION, // /** Superposition of basic and permuted vectors. */ // PERMUTATIONPLUSBASIC, // /** Encodes position within sliding window using NumberRepresentation */ // PROXIMITY // } // // Path: src/main/java/pitt/search/semanticvectors/TermTermVectorsFromLucene.java // public enum EncodingMethod { // /** Random indexing */ // RANDOM_INDEXING, // /** Implementation of skipgram with negative sampling (Mikolov 2013) */ // EMBEDDINGS // }
import java.io.IOException; import java.util.Arrays; import java.util.Enumeration; import java.util.logging.Logger; import pitt.search.semanticvectors.DocVectors.DocIndexingStrategy; import pitt.search.semanticvectors.TermTermVectorsFromLucene.PositionalMethod; import pitt.search.semanticvectors.TermTermVectorsFromLucene.EncodingMethod; import pitt.search.semanticvectors.utils.VerbatimLogger;
VerbatimLogger.info("Building positional index, Lucene index: " + luceneIndex + ", Seedlength: " + flagConfig.seedlength() + ", Vector length: " + flagConfig.dimension() + ", Vector type: " + flagConfig.vectortype() + ", Minimum term frequency: " + flagConfig.minfrequency() + ", Maximum term frequency: " + flagConfig.maxfrequency() + ", Number non-alphabet characters: " + flagConfig.maxnonalphabetchars() + ", Window radius: " + flagConfig.windowradius() + ", Fields to index: " + Arrays.toString(flagConfig.contentsfields()) + "\n"); try { TermTermVectorsFromLucene termTermIndexer = new TermTermVectorsFromLucene( flagConfig, newElementalTermVectors); //note - perhaps best to refactor this sometime in the near future - the //issue is that training cycles are represented within TermTermVectorsFromLucene //for embeddings currently if (!flagConfig.encodingmethod().equals(EncodingMethod.EMBEDDINGS)) for (int i = 1; i < flagConfig.trainingcycles(); ++i) { newElementalTermVectors = termTermIndexer.getSemanticTermVectors(); VerbatimLogger.info("\nRetraining with learned term vectors ..."); termTermIndexer = new TermTermVectorsFromLucene( flagConfig, newElementalTermVectors); } // Normalize term vectors - but with embeddings this occurs only after document vectors are generated
// Path: src/main/java/pitt/search/semanticvectors/DocVectors.java // public enum DocIndexingStrategy { // /** // * Index documents in memory, write to disk at the end. Fast but relies on large // * memory footprint. */ // INMEMORY, // // /** // * Index one document at a time, writing to disk during the process. // * Requires less memory. Cannot be used for indexing strategies that rely // * on random access to doc vector store during indexing. // */ // INCREMENTAL, // // /** // * Do not create document vectors at all. Useful if there are many documents // * and you are only interested in exploring term vectors. // */ // NONE, // } // // Path: src/main/java/pitt/search/semanticvectors/TermTermVectorsFromLucene.java // public enum PositionalMethod { // /** Basic "bag-of-words" method using context windows. */ // BASIC, // /** Binds vectors on left or right based on position. */ // DIRECTIONAL, // /** Permutes vectors according to how many places they are from focus term. */ // PERMUTATION, // /** Superposition of basic and permuted vectors. */ // PERMUTATIONPLUSBASIC, // /** Encodes position within sliding window using NumberRepresentation */ // PROXIMITY // } // // Path: src/main/java/pitt/search/semanticvectors/TermTermVectorsFromLucene.java // public enum EncodingMethod { // /** Random indexing */ // RANDOM_INDEXING, // /** Implementation of skipgram with negative sampling (Mikolov 2013) */ // EMBEDDINGS // } // Path: src/main/java/pitt/search/semanticvectors/BuildPositionalIndex.java import java.io.IOException; import java.util.Arrays; import java.util.Enumeration; import java.util.logging.Logger; import pitt.search.semanticvectors.DocVectors.DocIndexingStrategy; import pitt.search.semanticvectors.TermTermVectorsFromLucene.PositionalMethod; import pitt.search.semanticvectors.TermTermVectorsFromLucene.EncodingMethod; import pitt.search.semanticvectors.utils.VerbatimLogger; VerbatimLogger.info("Building positional index, Lucene index: " + luceneIndex + ", Seedlength: " + flagConfig.seedlength() + ", Vector length: " + flagConfig.dimension() + ", Vector type: " + flagConfig.vectortype() + ", Minimum term frequency: " + flagConfig.minfrequency() + ", Maximum term frequency: " + flagConfig.maxfrequency() + ", Number non-alphabet characters: " + flagConfig.maxnonalphabetchars() + ", Window radius: " + flagConfig.windowradius() + ", Fields to index: " + Arrays.toString(flagConfig.contentsfields()) + "\n"); try { TermTermVectorsFromLucene termTermIndexer = new TermTermVectorsFromLucene( flagConfig, newElementalTermVectors); //note - perhaps best to refactor this sometime in the near future - the //issue is that training cycles are represented within TermTermVectorsFromLucene //for embeddings currently if (!flagConfig.encodingmethod().equals(EncodingMethod.EMBEDDINGS)) for (int i = 1; i < flagConfig.trainingcycles(); ++i) { newElementalTermVectors = termTermIndexer.getSemanticTermVectors(); VerbatimLogger.info("\nRetraining with learned term vectors ..."); termTermIndexer = new TermTermVectorsFromLucene( flagConfig, newElementalTermVectors); } // Normalize term vectors - but with embeddings this occurs only after document vectors are generated
if (!flagConfig.encodingmethod().equals(EncodingMethod.EMBEDDINGS) || flagConfig.docindexing().equals(DocIndexingStrategy.NONE))
semanticvectors/semanticvectors
src/main/java/pitt/search/semanticvectors/LSA.java
// Path: src/main/java/pitt/search/semanticvectors/LuceneUtils.java // public enum TermWeight { // /** No term weighting: all terms have weight 1. */ // NONE, // /** Use inverse document frequency: see {@link LuceneUtils#getIDF}. */ // IDF, // /** Use log entropy: see {@link LuceneUtils#getEntropy}. */ // LOGENTROPY, // /** Use term frequency: see {@link LuceneUtils#getGlobalTermFreq} */ // FREQ, // /** Use square root of term frequency. */ // SQRT, // /** Use log of term frequency. */ // LOGFREQ, // } // // Path: src/main/java/pitt/search/semanticvectors/vectors/VectorType.java // public enum VectorType { // /** // * Uses binary-valued vectors. May be slower for some operations, but highly accurate. // */ // BINARY, // /** // * "Standard" real-valued vectors. Performs well for many operations though bind and release // * are (in some cases) either lossy with respect to argument structure and binding, or // * inexact with respect to inverse. // */ // REAL, // /** // * Complex-valued vectors, default "polar" version, normalized to coordinates on the unit circle, // * and compared using angular differences. // */ // COMPLEX, // /** // * Complex-valued vectors, normalized and compared using a hermitian scalar product. // */ // COMPLEXFLAT, // /** // * Vector of integer values, describing a permutation // */ // PERMUTATION // }
import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.Term; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.BytesRef; import pitt.search.semanticvectors.LuceneUtils.TermWeight; import pitt.search.semanticvectors.utils.VerbatimLogger; import pitt.search.semanticvectors.vectors.RealVector; import pitt.search.semanticvectors.vectors.Vector; import pitt.search.semanticvectors.vectors.VectorType; import java.io.IOException; import java.nio.file.FileSystems; import java.util.logging.Logger; import ch.akuhn.edu.mit.tedlab.*;
package pitt.search.semanticvectors; /** * Interface to Adrian Kuhn and David Erni's implementation of SVDLIBJ, a native Java version * of Doug Rhodes' SVDLIBC, which was in turn based on SVDPACK, by Michael Berry, Theresa Do, * Gavin O'Brien, Vijay Krishna and Sowmini Varadhan. * * This class will produce two files, svd_termvectors.bin and svd_docvectors.bin from a Lucene index * Command line arguments are consistent with the rest of the Semantic Vectors Package */ public class LSA { private static final Logger logger = Logger.getLogger(LSA.class.getCanonicalName()); public static String usageMessage = "\nLSA class in package pitt.search.semanticvectors" + "\nUsage: java pitt.search.semanticvectors.LSA [other flags] -luceneindexpath PATH_TO_LUCENE_INDEX" + "Use flags to configure dimension, min term frequency, etc. See online documentation for other available flags"; private FlagConfig flagConfig; /** Stores the list of terms in the same order as rows in the matrix. */ private String[] termList; /** The single contents field in the Lucene index: LSA only supports one. */ private String contentsField; private LuceneUtils luceneUtils; /** * Basic constructor that tries to check up front that resources are available and * configurations are consistent. * * @param luceneIndexDir Relative path to directory containing Lucene index. * @throws IOException */ private LSA(String luceneIndexDir, FlagConfig flagConfig) throws IOException { this.flagConfig = flagConfig; this.luceneUtils = new LuceneUtils(flagConfig); if (flagConfig.contentsfields().length > 1) { logger.warning( "LSA implementation only supports a single -contentsfield. Only '" + flagConfig.contentsfields()[0] + "' will be indexed."); } this.contentsField = flagConfig.contentsfields()[0]; // Find the number of docs, and if greater than dimension, set the dimension // to be this number. if (flagConfig.dimension() > this.luceneUtils.getNumDocs()) { logger.warning("Dimension for SVD cannot be greater than number of documents ... " + "Setting dimension to " + this.luceneUtils.getNumDocs()); flagConfig.setDimension(this.luceneUtils.getNumDocs()); }
// Path: src/main/java/pitt/search/semanticvectors/LuceneUtils.java // public enum TermWeight { // /** No term weighting: all terms have weight 1. */ // NONE, // /** Use inverse document frequency: see {@link LuceneUtils#getIDF}. */ // IDF, // /** Use log entropy: see {@link LuceneUtils#getEntropy}. */ // LOGENTROPY, // /** Use term frequency: see {@link LuceneUtils#getGlobalTermFreq} */ // FREQ, // /** Use square root of term frequency. */ // SQRT, // /** Use log of term frequency. */ // LOGFREQ, // } // // Path: src/main/java/pitt/search/semanticvectors/vectors/VectorType.java // public enum VectorType { // /** // * Uses binary-valued vectors. May be slower for some operations, but highly accurate. // */ // BINARY, // /** // * "Standard" real-valued vectors. Performs well for many operations though bind and release // * are (in some cases) either lossy with respect to argument structure and binding, or // * inexact with respect to inverse. // */ // REAL, // /** // * Complex-valued vectors, default "polar" version, normalized to coordinates on the unit circle, // * and compared using angular differences. // */ // COMPLEX, // /** // * Complex-valued vectors, normalized and compared using a hermitian scalar product. // */ // COMPLEXFLAT, // /** // * Vector of integer values, describing a permutation // */ // PERMUTATION // } // Path: src/main/java/pitt/search/semanticvectors/LSA.java import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.Term; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.BytesRef; import pitt.search.semanticvectors.LuceneUtils.TermWeight; import pitt.search.semanticvectors.utils.VerbatimLogger; import pitt.search.semanticvectors.vectors.RealVector; import pitt.search.semanticvectors.vectors.Vector; import pitt.search.semanticvectors.vectors.VectorType; import java.io.IOException; import java.nio.file.FileSystems; import java.util.logging.Logger; import ch.akuhn.edu.mit.tedlab.*; package pitt.search.semanticvectors; /** * Interface to Adrian Kuhn and David Erni's implementation of SVDLIBJ, a native Java version * of Doug Rhodes' SVDLIBC, which was in turn based on SVDPACK, by Michael Berry, Theresa Do, * Gavin O'Brien, Vijay Krishna and Sowmini Varadhan. * * This class will produce two files, svd_termvectors.bin and svd_docvectors.bin from a Lucene index * Command line arguments are consistent with the rest of the Semantic Vectors Package */ public class LSA { private static final Logger logger = Logger.getLogger(LSA.class.getCanonicalName()); public static String usageMessage = "\nLSA class in package pitt.search.semanticvectors" + "\nUsage: java pitt.search.semanticvectors.LSA [other flags] -luceneindexpath PATH_TO_LUCENE_INDEX" + "Use flags to configure dimension, min term frequency, etc. See online documentation for other available flags"; private FlagConfig flagConfig; /** Stores the list of terms in the same order as rows in the matrix. */ private String[] termList; /** The single contents field in the Lucene index: LSA only supports one. */ private String contentsField; private LuceneUtils luceneUtils; /** * Basic constructor that tries to check up front that resources are available and * configurations are consistent. * * @param luceneIndexDir Relative path to directory containing Lucene index. * @throws IOException */ private LSA(String luceneIndexDir, FlagConfig flagConfig) throws IOException { this.flagConfig = flagConfig; this.luceneUtils = new LuceneUtils(flagConfig); if (flagConfig.contentsfields().length > 1) { logger.warning( "LSA implementation only supports a single -contentsfield. Only '" + flagConfig.contentsfields()[0] + "' will be indexed."); } this.contentsField = flagConfig.contentsfields()[0]; // Find the number of docs, and if greater than dimension, set the dimension // to be this number. if (flagConfig.dimension() > this.luceneUtils.getNumDocs()) { logger.warning("Dimension for SVD cannot be greater than number of documents ... " + "Setting dimension to " + this.luceneUtils.getNumDocs()); flagConfig.setDimension(this.luceneUtils.getNumDocs()); }
if (flagConfig.termweight().equals(TermWeight.LOGENTROPY)) {
semanticvectors/semanticvectors
src/main/java/pitt/search/semanticvectors/LSA.java
// Path: src/main/java/pitt/search/semanticvectors/LuceneUtils.java // public enum TermWeight { // /** No term weighting: all terms have weight 1. */ // NONE, // /** Use inverse document frequency: see {@link LuceneUtils#getIDF}. */ // IDF, // /** Use log entropy: see {@link LuceneUtils#getEntropy}. */ // LOGENTROPY, // /** Use term frequency: see {@link LuceneUtils#getGlobalTermFreq} */ // FREQ, // /** Use square root of term frequency. */ // SQRT, // /** Use log of term frequency. */ // LOGFREQ, // } // // Path: src/main/java/pitt/search/semanticvectors/vectors/VectorType.java // public enum VectorType { // /** // * Uses binary-valued vectors. May be slower for some operations, but highly accurate. // */ // BINARY, // /** // * "Standard" real-valued vectors. Performs well for many operations though bind and release // * are (in some cases) either lossy with respect to argument structure and binding, or // * inexact with respect to inverse. // */ // REAL, // /** // * Complex-valued vectors, default "polar" version, normalized to coordinates on the unit circle, // * and compared using angular differences. // */ // COMPLEX, // /** // * Complex-valued vectors, normalized and compared using a hermitian scalar product. // */ // COMPLEXFLAT, // /** // * Vector of integer values, describing a permutation // */ // PERMUTATION // }
import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.Term; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.BytesRef; import pitt.search.semanticvectors.LuceneUtils.TermWeight; import pitt.search.semanticvectors.utils.VerbatimLogger; import pitt.search.semanticvectors.vectors.RealVector; import pitt.search.semanticvectors.vectors.Vector; import pitt.search.semanticvectors.vectors.VectorType; import java.io.IOException; import java.nio.file.FileSystems; import java.util.logging.Logger; import ch.akuhn.edu.mit.tedlab.*;
// Write header giving number of dimensions for all vectors and make sure type is real. outputStream.writeString(VectorStoreWriter.generateHeaderString(flagConfig)); // Write out document vectors for (cnt = 0; cnt < luceneUtils.getNumDocs(); cnt++) { String thePath = this.luceneUtils.getDoc(cnt).get(flagConfig.docidfield()); outputStream.writeString(thePath); float[] tmp = new float[flagConfig.dimension()]; for (int i = 0; i < flagConfig.dimension(); i++) tmp[i] = (float) uT.value[i][cnt]; RealVector docVector = new RealVector(tmp); docVector.normalize(); docVector.writeToLuceneStream(outputStream); } outputStream.close(); VerbatimLogger.info("Wrote " + cnt + " document vectors incrementally to file " + flagConfig.docvectorsfile() + ". Done.\n"); } public static void main(String[] args) throws IllegalArgumentException, IOException { FlagConfig flagConfig; try { flagConfig = FlagConfig.getFlagConfig(args); args = flagConfig.remainingArgs; } catch (IllegalArgumentException e) { System.out.println(usageMessage); throw e; }
// Path: src/main/java/pitt/search/semanticvectors/LuceneUtils.java // public enum TermWeight { // /** No term weighting: all terms have weight 1. */ // NONE, // /** Use inverse document frequency: see {@link LuceneUtils#getIDF}. */ // IDF, // /** Use log entropy: see {@link LuceneUtils#getEntropy}. */ // LOGENTROPY, // /** Use term frequency: see {@link LuceneUtils#getGlobalTermFreq} */ // FREQ, // /** Use square root of term frequency. */ // SQRT, // /** Use log of term frequency. */ // LOGFREQ, // } // // Path: src/main/java/pitt/search/semanticvectors/vectors/VectorType.java // public enum VectorType { // /** // * Uses binary-valued vectors. May be slower for some operations, but highly accurate. // */ // BINARY, // /** // * "Standard" real-valued vectors. Performs well for many operations though bind and release // * are (in some cases) either lossy with respect to argument structure and binding, or // * inexact with respect to inverse. // */ // REAL, // /** // * Complex-valued vectors, default "polar" version, normalized to coordinates on the unit circle, // * and compared using angular differences. // */ // COMPLEX, // /** // * Complex-valued vectors, normalized and compared using a hermitian scalar product. // */ // COMPLEXFLAT, // /** // * Vector of integer values, describing a permutation // */ // PERMUTATION // } // Path: src/main/java/pitt/search/semanticvectors/LSA.java import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.Term; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.BytesRef; import pitt.search.semanticvectors.LuceneUtils.TermWeight; import pitt.search.semanticvectors.utils.VerbatimLogger; import pitt.search.semanticvectors.vectors.RealVector; import pitt.search.semanticvectors.vectors.Vector; import pitt.search.semanticvectors.vectors.VectorType; import java.io.IOException; import java.nio.file.FileSystems; import java.util.logging.Logger; import ch.akuhn.edu.mit.tedlab.*; // Write header giving number of dimensions for all vectors and make sure type is real. outputStream.writeString(VectorStoreWriter.generateHeaderString(flagConfig)); // Write out document vectors for (cnt = 0; cnt < luceneUtils.getNumDocs(); cnt++) { String thePath = this.luceneUtils.getDoc(cnt).get(flagConfig.docidfield()); outputStream.writeString(thePath); float[] tmp = new float[flagConfig.dimension()]; for (int i = 0; i < flagConfig.dimension(); i++) tmp[i] = (float) uT.value[i][cnt]; RealVector docVector = new RealVector(tmp); docVector.normalize(); docVector.writeToLuceneStream(outputStream); } outputStream.close(); VerbatimLogger.info("Wrote " + cnt + " document vectors incrementally to file " + flagConfig.docvectorsfile() + ". Done.\n"); } public static void main(String[] args) throws IllegalArgumentException, IOException { FlagConfig flagConfig; try { flagConfig = FlagConfig.getFlagConfig(args); args = flagConfig.remainingArgs; } catch (IllegalArgumentException e) { System.out.println(usageMessage); throw e; }
if (flagConfig.vectortype() != VectorType.REAL) {
semanticvectors/semanticvectors
src/main/java/pitt/search/semanticvectors/CompressedVectorStoreRAM.java
// Path: src/main/java/pitt/search/semanticvectors/vectors/VectorFactory.java // public class VectorFactory { // private static final BinaryVector binaryInstance = new BinaryVector(0); // private static final RealVector realInstance = new RealVector(0); // private static final ComplexVector complexInstance = // new ComplexVector(0, ComplexVector.Mode.POLAR_SPARSE); // private static final ComplexVector complexFlatInstance = // new ComplexVector(0, ComplexVector.Mode.CARTESIAN); // // /** // * createZeroVector returns a vector set to zero. It can be used externally, but // * be careful particularly with Complex Vectors to make sure that polar / cartesian / hermitian // * modes are set correctly especially if you try to set coordinates manually after that. // */ // public static Vector createZeroVector(VectorType type, int dimension) { // switch (type) { // case BINARY: // return new BinaryVector(dimension); // case REAL: // return new RealVector(dimension); // case COMPLEX: // return new ComplexVector(dimension, Mode.POLAR_SPARSE); // case COMPLEXFLAT: // return new ComplexVector(dimension, Mode.POLAR_SPARSE); // case PERMUTATION: // return new PermutationVector(dimension); // default: // throw new IllegalArgumentException("Unrecognized VectorType: " + type); // } // } // // /** // * Generates an appropriate random vector. // * // * @param type one of the recognized vector types // * @param dimension number of dimensions in the generated vector // * @param numEntries total number of non-zero entries; must be no greater than half of dimension // * @param random random number generator; passed in to enable deterministic testing // * @return vector generated with appropriate type, dimension and number of nonzero entries // */ // public static Vector generateRandomVector( // VectorType type, int dimension, int numEntries, Random random) { // // if (2 * numEntries > dimension && !type.equals(VectorType.COMPLEX) && !(numEntries == dimension)) { // throw new RuntimeException("Requested " + numEntries + " to be filled in sparse " // + "vector of dimension " + dimension + ". This is not sparse and may cause problems."); // } // switch (type) { // case BINARY: // return binaryInstance.generateRandomVector(dimension, numEntries, random); // case REAL: // return realInstance.generateRandomVector(dimension, numEntries, random); // case COMPLEX: // if (!ComplexVector.getDominantMode().equals(Mode.HERMITIAN)) // ComplexVector.setDominantMode(Mode.POLAR_DENSE); // return complexInstance.generateRandomVector(dimension, numEntries, random); // case COMPLEXFLAT: // ComplexVector.setDominantMode(Mode.CARTESIAN); // return complexInstance.generateRandomVector(dimension, numEntries, random); // default: // throw new IllegalArgumentException("Unrecognized VectorType: " + type); // } // } // // /** // * Returns the size in bytes expected to be taken up by the serialization // * of this vector in Lucene format. // */ // public static int getLuceneByteSize(VectorType vectorType, int dimension) { // switch (vectorType) { // case BINARY: // return 8 * ((dimension / 64) ); // case REAL: // return 4 * dimension; // case COMPLEX: // case COMPLEXFLAT: // return 8 * dimension; // default: // throw new IllegalArgumentException("Unrecognized VectorType: " + vectorType); // } // } // }
import java.util.ArrayList; import java.util.Random; import pitt.search.semanticvectors.vectors.Vector; import pitt.search.semanticvectors.vectors.VectorFactory;
* This implementation only works for string objects so far. * * @param subsSample - if true, this method will return "null" instead of a vector for Strings that * hash to keys that have been encountered with a frequency > .01*flagConfig.samplingthreshold() * In practice this means n-grams are subsampled more aggressively than terms * Subsampling follows the procedure described in Mikolov 2013, 1-sqrt(T/F), with F * being the cumulative count of the observations of the relevant hash code / total observed hash codes * * @param desiredObject - the string you're searching for * @return vector from the VectorStore, or null if not found. */ public Vector getVector(String desiredObject, boolean subSample) { int hashedKey = getHashedKey(desiredObject); observationCounts[hashedKey]++; totalCounts++; //the hashed key has been seen before - a vector exists if (vectorTable[hashedKey] != null) { if (subSample) { double frequency = observationCounts[hashedKey]/ (double) totalCounts; double subsamp = Math.sqrt(flagConfig.samplingthreshold() / frequency); if (subsamp > 0 && random.nextDouble() <= subsamp) return null; } return vectorTable[hashedKey]; } //previously unseen hash (and therefore previously unseen key) else {
// Path: src/main/java/pitt/search/semanticvectors/vectors/VectorFactory.java // public class VectorFactory { // private static final BinaryVector binaryInstance = new BinaryVector(0); // private static final RealVector realInstance = new RealVector(0); // private static final ComplexVector complexInstance = // new ComplexVector(0, ComplexVector.Mode.POLAR_SPARSE); // private static final ComplexVector complexFlatInstance = // new ComplexVector(0, ComplexVector.Mode.CARTESIAN); // // /** // * createZeroVector returns a vector set to zero. It can be used externally, but // * be careful particularly with Complex Vectors to make sure that polar / cartesian / hermitian // * modes are set correctly especially if you try to set coordinates manually after that. // */ // public static Vector createZeroVector(VectorType type, int dimension) { // switch (type) { // case BINARY: // return new BinaryVector(dimension); // case REAL: // return new RealVector(dimension); // case COMPLEX: // return new ComplexVector(dimension, Mode.POLAR_SPARSE); // case COMPLEXFLAT: // return new ComplexVector(dimension, Mode.POLAR_SPARSE); // case PERMUTATION: // return new PermutationVector(dimension); // default: // throw new IllegalArgumentException("Unrecognized VectorType: " + type); // } // } // // /** // * Generates an appropriate random vector. // * // * @param type one of the recognized vector types // * @param dimension number of dimensions in the generated vector // * @param numEntries total number of non-zero entries; must be no greater than half of dimension // * @param random random number generator; passed in to enable deterministic testing // * @return vector generated with appropriate type, dimension and number of nonzero entries // */ // public static Vector generateRandomVector( // VectorType type, int dimension, int numEntries, Random random) { // // if (2 * numEntries > dimension && !type.equals(VectorType.COMPLEX) && !(numEntries == dimension)) { // throw new RuntimeException("Requested " + numEntries + " to be filled in sparse " // + "vector of dimension " + dimension + ". This is not sparse and may cause problems."); // } // switch (type) { // case BINARY: // return binaryInstance.generateRandomVector(dimension, numEntries, random); // case REAL: // return realInstance.generateRandomVector(dimension, numEntries, random); // case COMPLEX: // if (!ComplexVector.getDominantMode().equals(Mode.HERMITIAN)) // ComplexVector.setDominantMode(Mode.POLAR_DENSE); // return complexInstance.generateRandomVector(dimension, numEntries, random); // case COMPLEXFLAT: // ComplexVector.setDominantMode(Mode.CARTESIAN); // return complexInstance.generateRandomVector(dimension, numEntries, random); // default: // throw new IllegalArgumentException("Unrecognized VectorType: " + type); // } // } // // /** // * Returns the size in bytes expected to be taken up by the serialization // * of this vector in Lucene format. // */ // public static int getLuceneByteSize(VectorType vectorType, int dimension) { // switch (vectorType) { // case BINARY: // return 8 * ((dimension / 64) ); // case REAL: // return 4 * dimension; // case COMPLEX: // case COMPLEXFLAT: // return 8 * dimension; // default: // throw new IllegalArgumentException("Unrecognized VectorType: " + vectorType); // } // } // } // Path: src/main/java/pitt/search/semanticvectors/CompressedVectorStoreRAM.java import java.util.ArrayList; import java.util.Random; import pitt.search.semanticvectors.vectors.Vector; import pitt.search.semanticvectors.vectors.VectorFactory; * This implementation only works for string objects so far. * * @param subsSample - if true, this method will return "null" instead of a vector for Strings that * hash to keys that have been encountered with a frequency > .01*flagConfig.samplingthreshold() * In practice this means n-grams are subsampled more aggressively than terms * Subsampling follows the procedure described in Mikolov 2013, 1-sqrt(T/F), with F * being the cumulative count of the observations of the relevant hash code / total observed hash codes * * @param desiredObject - the string you're searching for * @return vector from the VectorStore, or null if not found. */ public Vector getVector(String desiredObject, boolean subSample) { int hashedKey = getHashedKey(desiredObject); observationCounts[hashedKey]++; totalCounts++; //the hashed key has been seen before - a vector exists if (vectorTable[hashedKey] != null) { if (subSample) { double frequency = observationCounts[hashedKey]/ (double) totalCounts; double subsamp = Math.sqrt(flagConfig.samplingthreshold() / frequency); if (subsamp > 0 && random.nextDouble() <= subsamp) return null; } return vectorTable[hashedKey]; } //previously unseen hash (and therefore previously unseen key) else {
Vector toBeAdded = VectorFactory.generateRandomVector(flagConfig.vectortype(), flagConfig.dimension(), flagConfig.seedlength, random);