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
bverbeken/litmus
samples/test/webdriver/SampleWebDriverTest.java
// Path: app/litmus/webdriver/WebDriverTest.java // @Category(value = WEBDRIVER, priority = 20000, slow = true) // public abstract class WebDriverTest extends FestAssertFunctionalTest { // // @BeforeClass // public static void checkPlayConfig() { // String playPool = Play.configuration.getProperty("play.pool"); // if (playPool == null) { // throw new IllegalStateException("'play.pool' property not found. Please set the 'play.pool' property in your application.conf to at least 2"); // } else if (parseInt(playPool) < 2) { // throw new IllegalStateException("Cannot run WebDriver tests when 'play.pool' config value is < 2. Please set the 'play.pool' property in your application.conf to at least 2"); // } // } // // @AfterClass // public static void quitWebDriver() { // WebDriverFactory.quitAndInit(); // } // // protected WebElementAssert assertThat(WebElement element) { // return WebDriverAssertions.assertThat(element); // } // // protected PageAssert assertThat(Page page) { // return WebDriverAssertions.assertThat(page); // } // // } // // Path: samples/test/webdriver/pages/HelloWorldPage.java // public class HelloWorldPage extends Page<HelloWorldPage> { // // @FindBy(id="name") // public WebElement nameInput; // // @FindBy(id="submit") // public WebElement submit; // // @FindBy(className = "error") // public WebElement error; // // // @Override // protected boolean arrivedAt() { // return getTitle().equals("HelloWorld"); // } // // public HelloWorldPage enterName(String name) { // nameInput.sendKeys(name); // return this; // } // // public SayHelloPage clickSubmit() { // submit.click(); // return new SayHelloPage(); // } // // public HelloWorldPage clickSubmitAndExpectValidationErrors() { // submit.click(); // return new HelloWorldPage().assertArrivedAt(); // } // // } // // Path: samples/test/webdriver/pages/SayHelloPage.java // public class SayHelloPage extends Page<SayHelloPage> { // // @FindBy(id = "msg") // public WebElement message; // // @Override // protected boolean arrivedAt() { // return getTitle().equals("SayHello"); // } // // } // // Path: samples/test/webdriver/pages/Pages.java // public static HelloWorldPage goToHelloWorldPage() { // open("/html/helloworld"); // return new HelloWorldPage(); // } // // Path: samples/test/webdriver/pages/Pages.java // public static SayHelloPage goToSayHelloPage(String name){ // open("/html/sayHello?name=" + name); // return new SayHelloPage(); // }
import litmus.webdriver.WebDriverTest; import org.junit.Test; import webdriver.pages.HelloWorldPage; import webdriver.pages.SayHelloPage; import static webdriver.pages.Pages.goToHelloWorldPage; import static webdriver.pages.Pages.goToSayHelloPage;
package webdriver; public class SampleWebDriverTest extends WebDriverTest { @Test public void iShouldBeAbleToSubmitAndSeeTheMessage() {
// Path: app/litmus/webdriver/WebDriverTest.java // @Category(value = WEBDRIVER, priority = 20000, slow = true) // public abstract class WebDriverTest extends FestAssertFunctionalTest { // // @BeforeClass // public static void checkPlayConfig() { // String playPool = Play.configuration.getProperty("play.pool"); // if (playPool == null) { // throw new IllegalStateException("'play.pool' property not found. Please set the 'play.pool' property in your application.conf to at least 2"); // } else if (parseInt(playPool) < 2) { // throw new IllegalStateException("Cannot run WebDriver tests when 'play.pool' config value is < 2. Please set the 'play.pool' property in your application.conf to at least 2"); // } // } // // @AfterClass // public static void quitWebDriver() { // WebDriverFactory.quitAndInit(); // } // // protected WebElementAssert assertThat(WebElement element) { // return WebDriverAssertions.assertThat(element); // } // // protected PageAssert assertThat(Page page) { // return WebDriverAssertions.assertThat(page); // } // // } // // Path: samples/test/webdriver/pages/HelloWorldPage.java // public class HelloWorldPage extends Page<HelloWorldPage> { // // @FindBy(id="name") // public WebElement nameInput; // // @FindBy(id="submit") // public WebElement submit; // // @FindBy(className = "error") // public WebElement error; // // // @Override // protected boolean arrivedAt() { // return getTitle().equals("HelloWorld"); // } // // public HelloWorldPage enterName(String name) { // nameInput.sendKeys(name); // return this; // } // // public SayHelloPage clickSubmit() { // submit.click(); // return new SayHelloPage(); // } // // public HelloWorldPage clickSubmitAndExpectValidationErrors() { // submit.click(); // return new HelloWorldPage().assertArrivedAt(); // } // // } // // Path: samples/test/webdriver/pages/SayHelloPage.java // public class SayHelloPage extends Page<SayHelloPage> { // // @FindBy(id = "msg") // public WebElement message; // // @Override // protected boolean arrivedAt() { // return getTitle().equals("SayHello"); // } // // } // // Path: samples/test/webdriver/pages/Pages.java // public static HelloWorldPage goToHelloWorldPage() { // open("/html/helloworld"); // return new HelloWorldPage(); // } // // Path: samples/test/webdriver/pages/Pages.java // public static SayHelloPage goToSayHelloPage(String name){ // open("/html/sayHello?name=" + name); // return new SayHelloPage(); // } // Path: samples/test/webdriver/SampleWebDriverTest.java import litmus.webdriver.WebDriverTest; import org.junit.Test; import webdriver.pages.HelloWorldPage; import webdriver.pages.SayHelloPage; import static webdriver.pages.Pages.goToHelloWorldPage; import static webdriver.pages.Pages.goToSayHelloPage; package webdriver; public class SampleWebDriverTest extends WebDriverTest { @Test public void iShouldBeAbleToSubmitAndSeeTheMessage() {
SayHelloPage page = goToHelloWorldPage()
bverbeken/litmus
samples/test/webdriver/SampleWebDriverTest.java
// Path: app/litmus/webdriver/WebDriverTest.java // @Category(value = WEBDRIVER, priority = 20000, slow = true) // public abstract class WebDriverTest extends FestAssertFunctionalTest { // // @BeforeClass // public static void checkPlayConfig() { // String playPool = Play.configuration.getProperty("play.pool"); // if (playPool == null) { // throw new IllegalStateException("'play.pool' property not found. Please set the 'play.pool' property in your application.conf to at least 2"); // } else if (parseInt(playPool) < 2) { // throw new IllegalStateException("Cannot run WebDriver tests when 'play.pool' config value is < 2. Please set the 'play.pool' property in your application.conf to at least 2"); // } // } // // @AfterClass // public static void quitWebDriver() { // WebDriverFactory.quitAndInit(); // } // // protected WebElementAssert assertThat(WebElement element) { // return WebDriverAssertions.assertThat(element); // } // // protected PageAssert assertThat(Page page) { // return WebDriverAssertions.assertThat(page); // } // // } // // Path: samples/test/webdriver/pages/HelloWorldPage.java // public class HelloWorldPage extends Page<HelloWorldPage> { // // @FindBy(id="name") // public WebElement nameInput; // // @FindBy(id="submit") // public WebElement submit; // // @FindBy(className = "error") // public WebElement error; // // // @Override // protected boolean arrivedAt() { // return getTitle().equals("HelloWorld"); // } // // public HelloWorldPage enterName(String name) { // nameInput.sendKeys(name); // return this; // } // // public SayHelloPage clickSubmit() { // submit.click(); // return new SayHelloPage(); // } // // public HelloWorldPage clickSubmitAndExpectValidationErrors() { // submit.click(); // return new HelloWorldPage().assertArrivedAt(); // } // // } // // Path: samples/test/webdriver/pages/SayHelloPage.java // public class SayHelloPage extends Page<SayHelloPage> { // // @FindBy(id = "msg") // public WebElement message; // // @Override // protected boolean arrivedAt() { // return getTitle().equals("SayHello"); // } // // } // // Path: samples/test/webdriver/pages/Pages.java // public static HelloWorldPage goToHelloWorldPage() { // open("/html/helloworld"); // return new HelloWorldPage(); // } // // Path: samples/test/webdriver/pages/Pages.java // public static SayHelloPage goToSayHelloPage(String name){ // open("/html/sayHello?name=" + name); // return new SayHelloPage(); // }
import litmus.webdriver.WebDriverTest; import org.junit.Test; import webdriver.pages.HelloWorldPage; import webdriver.pages.SayHelloPage; import static webdriver.pages.Pages.goToHelloWorldPage; import static webdriver.pages.Pages.goToSayHelloPage;
package webdriver; public class SampleWebDriverTest extends WebDriverTest { @Test public void iShouldBeAbleToSubmitAndSeeTheMessage() { SayHelloPage page = goToHelloWorldPage() .enterName("World") .clickSubmit(); assertThat(page.message).containsText("Hello"); assertThat(page.message).containsText("World"); assertThat(page.message).containsText("!"); assertThat(page.message).containsTextExactly("Hello World!"); assertThat(page.message).doesNotContainText("Byebye"); } @Test public void iGetACorrectErrorMessageWhenSubmittingValueThatIsTooSmall() {
// Path: app/litmus/webdriver/WebDriverTest.java // @Category(value = WEBDRIVER, priority = 20000, slow = true) // public abstract class WebDriverTest extends FestAssertFunctionalTest { // // @BeforeClass // public static void checkPlayConfig() { // String playPool = Play.configuration.getProperty("play.pool"); // if (playPool == null) { // throw new IllegalStateException("'play.pool' property not found. Please set the 'play.pool' property in your application.conf to at least 2"); // } else if (parseInt(playPool) < 2) { // throw new IllegalStateException("Cannot run WebDriver tests when 'play.pool' config value is < 2. Please set the 'play.pool' property in your application.conf to at least 2"); // } // } // // @AfterClass // public static void quitWebDriver() { // WebDriverFactory.quitAndInit(); // } // // protected WebElementAssert assertThat(WebElement element) { // return WebDriverAssertions.assertThat(element); // } // // protected PageAssert assertThat(Page page) { // return WebDriverAssertions.assertThat(page); // } // // } // // Path: samples/test/webdriver/pages/HelloWorldPage.java // public class HelloWorldPage extends Page<HelloWorldPage> { // // @FindBy(id="name") // public WebElement nameInput; // // @FindBy(id="submit") // public WebElement submit; // // @FindBy(className = "error") // public WebElement error; // // // @Override // protected boolean arrivedAt() { // return getTitle().equals("HelloWorld"); // } // // public HelloWorldPage enterName(String name) { // nameInput.sendKeys(name); // return this; // } // // public SayHelloPage clickSubmit() { // submit.click(); // return new SayHelloPage(); // } // // public HelloWorldPage clickSubmitAndExpectValidationErrors() { // submit.click(); // return new HelloWorldPage().assertArrivedAt(); // } // // } // // Path: samples/test/webdriver/pages/SayHelloPage.java // public class SayHelloPage extends Page<SayHelloPage> { // // @FindBy(id = "msg") // public WebElement message; // // @Override // protected boolean arrivedAt() { // return getTitle().equals("SayHello"); // } // // } // // Path: samples/test/webdriver/pages/Pages.java // public static HelloWorldPage goToHelloWorldPage() { // open("/html/helloworld"); // return new HelloWorldPage(); // } // // Path: samples/test/webdriver/pages/Pages.java // public static SayHelloPage goToSayHelloPage(String name){ // open("/html/sayHello?name=" + name); // return new SayHelloPage(); // } // Path: samples/test/webdriver/SampleWebDriverTest.java import litmus.webdriver.WebDriverTest; import org.junit.Test; import webdriver.pages.HelloWorldPage; import webdriver.pages.SayHelloPage; import static webdriver.pages.Pages.goToHelloWorldPage; import static webdriver.pages.Pages.goToSayHelloPage; package webdriver; public class SampleWebDriverTest extends WebDriverTest { @Test public void iShouldBeAbleToSubmitAndSeeTheMessage() { SayHelloPage page = goToHelloWorldPage() .enterName("World") .clickSubmit(); assertThat(page.message).containsText("Hello"); assertThat(page.message).containsText("World"); assertThat(page.message).containsText("!"); assertThat(page.message).containsTextExactly("Hello World!"); assertThat(page.message).doesNotContainText("Byebye"); } @Test public void iGetACorrectErrorMessageWhenSubmittingValueThatIsTooSmall() {
HelloWorldPage page = goToHelloWorldPage()
bverbeken/litmus
samples/test/webdriver/SampleWebDriverTest.java
// Path: app/litmus/webdriver/WebDriverTest.java // @Category(value = WEBDRIVER, priority = 20000, slow = true) // public abstract class WebDriverTest extends FestAssertFunctionalTest { // // @BeforeClass // public static void checkPlayConfig() { // String playPool = Play.configuration.getProperty("play.pool"); // if (playPool == null) { // throw new IllegalStateException("'play.pool' property not found. Please set the 'play.pool' property in your application.conf to at least 2"); // } else if (parseInt(playPool) < 2) { // throw new IllegalStateException("Cannot run WebDriver tests when 'play.pool' config value is < 2. Please set the 'play.pool' property in your application.conf to at least 2"); // } // } // // @AfterClass // public static void quitWebDriver() { // WebDriverFactory.quitAndInit(); // } // // protected WebElementAssert assertThat(WebElement element) { // return WebDriverAssertions.assertThat(element); // } // // protected PageAssert assertThat(Page page) { // return WebDriverAssertions.assertThat(page); // } // // } // // Path: samples/test/webdriver/pages/HelloWorldPage.java // public class HelloWorldPage extends Page<HelloWorldPage> { // // @FindBy(id="name") // public WebElement nameInput; // // @FindBy(id="submit") // public WebElement submit; // // @FindBy(className = "error") // public WebElement error; // // // @Override // protected boolean arrivedAt() { // return getTitle().equals("HelloWorld"); // } // // public HelloWorldPage enterName(String name) { // nameInput.sendKeys(name); // return this; // } // // public SayHelloPage clickSubmit() { // submit.click(); // return new SayHelloPage(); // } // // public HelloWorldPage clickSubmitAndExpectValidationErrors() { // submit.click(); // return new HelloWorldPage().assertArrivedAt(); // } // // } // // Path: samples/test/webdriver/pages/SayHelloPage.java // public class SayHelloPage extends Page<SayHelloPage> { // // @FindBy(id = "msg") // public WebElement message; // // @Override // protected boolean arrivedAt() { // return getTitle().equals("SayHello"); // } // // } // // Path: samples/test/webdriver/pages/Pages.java // public static HelloWorldPage goToHelloWorldPage() { // open("/html/helloworld"); // return new HelloWorldPage(); // } // // Path: samples/test/webdriver/pages/Pages.java // public static SayHelloPage goToSayHelloPage(String name){ // open("/html/sayHello?name=" + name); // return new SayHelloPage(); // }
import litmus.webdriver.WebDriverTest; import org.junit.Test; import webdriver.pages.HelloWorldPage; import webdriver.pages.SayHelloPage; import static webdriver.pages.Pages.goToHelloWorldPage; import static webdriver.pages.Pages.goToSayHelloPage;
package webdriver; public class SampleWebDriverTest extends WebDriverTest { @Test public void iShouldBeAbleToSubmitAndSeeTheMessage() { SayHelloPage page = goToHelloWorldPage() .enterName("World") .clickSubmit(); assertThat(page.message).containsText("Hello"); assertThat(page.message).containsText("World"); assertThat(page.message).containsText("!"); assertThat(page.message).containsTextExactly("Hello World!"); assertThat(page.message).doesNotContainText("Byebye"); } @Test public void iGetACorrectErrorMessageWhenSubmittingValueThatIsTooSmall() { HelloWorldPage page = goToHelloWorldPage() .enterName("Ben") .clickSubmitAndExpectValidationErrors(); assertThat(page.error).containsTextExactly("Minimum size is 4"); } @Test public void tagNameAssertExample() { SayHelloPage page = goToHelloWorldPage() .enterName("Caroline") .clickSubmit(); assertThat(page.message).hasTagName("div"); assertThat(page.message).isDiv(); } @Test public void iCanDirectlyAccessTheSayHelloPage(){
// Path: app/litmus/webdriver/WebDriverTest.java // @Category(value = WEBDRIVER, priority = 20000, slow = true) // public abstract class WebDriverTest extends FestAssertFunctionalTest { // // @BeforeClass // public static void checkPlayConfig() { // String playPool = Play.configuration.getProperty("play.pool"); // if (playPool == null) { // throw new IllegalStateException("'play.pool' property not found. Please set the 'play.pool' property in your application.conf to at least 2"); // } else if (parseInt(playPool) < 2) { // throw new IllegalStateException("Cannot run WebDriver tests when 'play.pool' config value is < 2. Please set the 'play.pool' property in your application.conf to at least 2"); // } // } // // @AfterClass // public static void quitWebDriver() { // WebDriverFactory.quitAndInit(); // } // // protected WebElementAssert assertThat(WebElement element) { // return WebDriverAssertions.assertThat(element); // } // // protected PageAssert assertThat(Page page) { // return WebDriverAssertions.assertThat(page); // } // // } // // Path: samples/test/webdriver/pages/HelloWorldPage.java // public class HelloWorldPage extends Page<HelloWorldPage> { // // @FindBy(id="name") // public WebElement nameInput; // // @FindBy(id="submit") // public WebElement submit; // // @FindBy(className = "error") // public WebElement error; // // // @Override // protected boolean arrivedAt() { // return getTitle().equals("HelloWorld"); // } // // public HelloWorldPage enterName(String name) { // nameInput.sendKeys(name); // return this; // } // // public SayHelloPage clickSubmit() { // submit.click(); // return new SayHelloPage(); // } // // public HelloWorldPage clickSubmitAndExpectValidationErrors() { // submit.click(); // return new HelloWorldPage().assertArrivedAt(); // } // // } // // Path: samples/test/webdriver/pages/SayHelloPage.java // public class SayHelloPage extends Page<SayHelloPage> { // // @FindBy(id = "msg") // public WebElement message; // // @Override // protected boolean arrivedAt() { // return getTitle().equals("SayHello"); // } // // } // // Path: samples/test/webdriver/pages/Pages.java // public static HelloWorldPage goToHelloWorldPage() { // open("/html/helloworld"); // return new HelloWorldPage(); // } // // Path: samples/test/webdriver/pages/Pages.java // public static SayHelloPage goToSayHelloPage(String name){ // open("/html/sayHello?name=" + name); // return new SayHelloPage(); // } // Path: samples/test/webdriver/SampleWebDriverTest.java import litmus.webdriver.WebDriverTest; import org.junit.Test; import webdriver.pages.HelloWorldPage; import webdriver.pages.SayHelloPage; import static webdriver.pages.Pages.goToHelloWorldPage; import static webdriver.pages.Pages.goToSayHelloPage; package webdriver; public class SampleWebDriverTest extends WebDriverTest { @Test public void iShouldBeAbleToSubmitAndSeeTheMessage() { SayHelloPage page = goToHelloWorldPage() .enterName("World") .clickSubmit(); assertThat(page.message).containsText("Hello"); assertThat(page.message).containsText("World"); assertThat(page.message).containsText("!"); assertThat(page.message).containsTextExactly("Hello World!"); assertThat(page.message).doesNotContainText("Byebye"); } @Test public void iGetACorrectErrorMessageWhenSubmittingValueThatIsTooSmall() { HelloWorldPage page = goToHelloWorldPage() .enterName("Ben") .clickSubmitAndExpectValidationErrors(); assertThat(page.error).containsTextExactly("Minimum size is 4"); } @Test public void tagNameAssertExample() { SayHelloPage page = goToHelloWorldPage() .enterName("Caroline") .clickSubmit(); assertThat(page.message).hasTagName("div"); assertThat(page.message).isDiv(); } @Test public void iCanDirectlyAccessTheSayHelloPage(){
SayHelloPage page = goToSayHelloPage("Ben Verbeken");
bverbeken/litmus
samples/test/unit/validation/EmailValidationTest.java
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/EmailModel.java // public class EmailModel { // // @Email // public String email; // // public EmailModel(String email) { // this.email = email; // } // }
import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.EmailModel; import org.junit.Test;
package unit.validation; public class EmailValidationTest extends ValidationTest<EmailModel> { @Override
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/EmailModel.java // public class EmailModel { // // @Email // public String email; // // public EmailModel(String email) { // this.email = email; // } // } // Path: samples/test/unit/validation/EmailValidationTest.java import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.EmailModel; import org.junit.Test; package unit.validation; public class EmailValidationTest extends ValidationTest<EmailModel> { @Override
protected Builder<EmailModel> valid() {
bverbeken/litmus
samples/test/unit/validation/ValidValidationTest.java
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/Person.java // public class Person { // // @Required // public String firstName; // // @MinSize(4) // public String lastName; // // @Email // public String email; // // public Person(String firstName) { // this(firstName, null); // } // // public Person(String firstName, String lastName) { // this.firstName = firstName; // this.lastName = lastName; // } // // @Override // public String toString() { // return firstName + " " + lastName + "(" + email + ")"; // } // // @Override // public boolean equals(Object that) { // return reflectionEquals(this, that); // } // // @Override // public int hashCode() { // return reflectionHashCode(this); // } // } // // Path: samples/app/models/ValidModel.java // public class ValidModel { // // @Valid // public Person validPerson; // // // }
import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.Person; import models.ValidModel; import org.junit.Test; import static litmus.unit.validation.BuiltInValidation.VALID;
package unit.validation; public class ValidValidationTest extends ValidationTest<ValidModel> { @Override protected ValidModelBuilder valid() { return new ValidModelBuilder(); } @Test public void validShouldBeValid() {
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/Person.java // public class Person { // // @Required // public String firstName; // // @MinSize(4) // public String lastName; // // @Email // public String email; // // public Person(String firstName) { // this(firstName, null); // } // // public Person(String firstName, String lastName) { // this.firstName = firstName; // this.lastName = lastName; // } // // @Override // public String toString() { // return firstName + " " + lastName + "(" + email + ")"; // } // // @Override // public boolean equals(Object that) { // return reflectionEquals(this, that); // } // // @Override // public int hashCode() { // return reflectionHashCode(this); // } // } // // Path: samples/app/models/ValidModel.java // public class ValidModel { // // @Valid // public Person validPerson; // // // } // Path: samples/test/unit/validation/ValidValidationTest.java import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.Person; import models.ValidModel; import org.junit.Test; import static litmus.unit.validation.BuiltInValidation.VALID; package unit.validation; public class ValidValidationTest extends ValidationTest<ValidModel> { @Override protected ValidModelBuilder valid() { return new ValidModelBuilder(); } @Test public void validShouldBeValid() {
Object invalidPerson = new Person(null, null);
bverbeken/litmus
samples/test/unit/validation/ValidValidationTest.java
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/Person.java // public class Person { // // @Required // public String firstName; // // @MinSize(4) // public String lastName; // // @Email // public String email; // // public Person(String firstName) { // this(firstName, null); // } // // public Person(String firstName, String lastName) { // this.firstName = firstName; // this.lastName = lastName; // } // // @Override // public String toString() { // return firstName + " " + lastName + "(" + email + ")"; // } // // @Override // public boolean equals(Object that) { // return reflectionEquals(this, that); // } // // @Override // public int hashCode() { // return reflectionHashCode(this); // } // } // // Path: samples/app/models/ValidModel.java // public class ValidModel { // // @Valid // public Person validPerson; // // // }
import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.Person; import models.ValidModel; import org.junit.Test; import static litmus.unit.validation.BuiltInValidation.VALID;
package unit.validation; public class ValidValidationTest extends ValidationTest<ValidModel> { @Override protected ValidModelBuilder valid() { return new ValidModelBuilder(); } @Test public void validShouldBeValid() { Object invalidPerson = new Person(null, null); assertThat("validPerson").withValue(invalidPerson).hasValidationError(VALID); assertThat("validPerson").withValue(invalidPerson).hasValidationError("validation.object"); }
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/Person.java // public class Person { // // @Required // public String firstName; // // @MinSize(4) // public String lastName; // // @Email // public String email; // // public Person(String firstName) { // this(firstName, null); // } // // public Person(String firstName, String lastName) { // this.firstName = firstName; // this.lastName = lastName; // } // // @Override // public String toString() { // return firstName + " " + lastName + "(" + email + ")"; // } // // @Override // public boolean equals(Object that) { // return reflectionEquals(this, that); // } // // @Override // public int hashCode() { // return reflectionHashCode(this); // } // } // // Path: samples/app/models/ValidModel.java // public class ValidModel { // // @Valid // public Person validPerson; // // // } // Path: samples/test/unit/validation/ValidValidationTest.java import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.Person; import models.ValidModel; import org.junit.Test; import static litmus.unit.validation.BuiltInValidation.VALID; package unit.validation; public class ValidValidationTest extends ValidationTest<ValidModel> { @Override protected ValidModelBuilder valid() { return new ValidModelBuilder(); } @Test public void validShouldBeValid() { Object invalidPerson = new Person(null, null); assertThat("validPerson").withValue(invalidPerson).hasValidationError(VALID); assertThat("validPerson").withValue(invalidPerson).hasValidationError("validation.object"); }
private class ValidModelBuilder extends Builder<ValidModel> {
bverbeken/litmus
app/litmus/unit/validation/ValidationAssert.java
// Path: app/litmus/unit/validation/Validator.java // public static List<String> getErrorMessagesForField(String field) { // List<String> result = new ArrayList<String>(); // List<play.data.validation.Error> errors = Validation.current().errorsMap().get("." + field); // if (errors != null && !errors.isEmpty()) { // for (Error error : errors) { // result.add(getErrorKey(error)); // } // } // return result; // }
import org.fest.assertions.Assertions; import org.fest.assertions.GenericAssert; import static litmus.unit.validation.Validator.getErrorMessagesForField;
/* * Copyright 2012 Ben Verbeken * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package litmus.unit.validation; public class ValidationAssert<T> extends GenericAssert<ValidationAssert, T> { protected ValidationAssert(T actual) { super(ValidationAssert.class, actual); } public ValidationAssert<T> isValid() { Assertions.assertThat(Validator.isValid(actual)).isTrue(); return this; } public ValidationAssert<T> isInvalid() { Assertions.assertThat(Validator.isValid(actual)).isFalse(); return this; } public ValidationAssert<T> isInvalidBecause(String fieldName, String error) { isInvalid();
// Path: app/litmus/unit/validation/Validator.java // public static List<String> getErrorMessagesForField(String field) { // List<String> result = new ArrayList<String>(); // List<play.data.validation.Error> errors = Validation.current().errorsMap().get("." + field); // if (errors != null && !errors.isEmpty()) { // for (Error error : errors) { // result.add(getErrorKey(error)); // } // } // return result; // } // Path: app/litmus/unit/validation/ValidationAssert.java import org.fest.assertions.Assertions; import org.fest.assertions.GenericAssert; import static litmus.unit.validation.Validator.getErrorMessagesForField; /* * Copyright 2012 Ben Verbeken * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package litmus.unit.validation; public class ValidationAssert<T> extends GenericAssert<ValidationAssert, T> { protected ValidationAssert(T actual) { super(ValidationAssert.class, actual); } public ValidationAssert<T> isValid() { Assertions.assertThat(Validator.isValid(actual)).isTrue(); return this; } public ValidationAssert<T> isInvalid() { Assertions.assertThat(Validator.isValid(actual)).isFalse(); return this; } public ValidationAssert<T> isInvalidBecause(String fieldName, String error) { isInvalid();
Assertions.assertThat(getErrorMessagesForField(fieldName))
bverbeken/litmus
samples/test/unit/validation/MaxValidationTest.java
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/MaxModel.java // public class MaxModel { // // // @Max(10) // public int maxInt; // // @Max(10) // public double maxDouble; // // // @Max(10) // public Long maxLong; // // @Max(10) // public String maxString; // }
import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.MaxModel; import org.junit.Test;
package unit.validation; public class MaxValidationTest extends ValidationTest<MaxModel> { @Override
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/MaxModel.java // public class MaxModel { // // // @Max(10) // public int maxInt; // // @Max(10) // public double maxDouble; // // // @Max(10) // public Long maxLong; // // @Max(10) // public String maxString; // } // Path: samples/test/unit/validation/MaxValidationTest.java import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.MaxModel; import org.junit.Test; package unit.validation; public class MaxValidationTest extends ValidationTest<MaxModel> { @Override
protected Builder<MaxModel> valid() {
bverbeken/litmus
app/litmus/functional/ResponseAssert.java
// Path: app/litmus/unit/validation/BuiltInValidation.java // public enum BuiltInValidation { // // // EMAIL("email"), // EQUALS("equals"), // IN_FUTURE("future"), // AFTER("after"), // IN_PAST("past"), // BEFORE("before"), // IP_V4_ADDRESS("ipv4"), // IP_V6_ADDRESS("ipv6"), // IS_TRUE("isTrue"), // MATCH("match"), // MAX("max"), // MAX_SIZE("maxSize"), // MIN("min"), // MIN_SIZE("minSize"), // PHONE("phone"), // RANGE("range"), // REQUIRED("required"), // UNIQUE("unique"), // URL("url"), // VALID("object"); // // // private final String messageSuffix; // // BuiltInValidation(String messageSuffix) { // this.messageSuffix = messageSuffix; // } // // // public String getMessageKey() { // return "validation." + messageSuffix; // } // // }
import litmus.unit.validation.BuiltInValidation; import org.fest.assertions.Assertions; import org.fest.assertions.GenericAssert; import play.mvc.Http; import static org.fest.assertions.Assertions.assertThat; import static play.mvc.Http.StatusCode.*;
public ResponseAssert isHtml() { return hasContentType("text/html"); } public ResponseAssert isXml() { return hasContentType("text/xml"); } public ResponseAssert isJson() { return hasContentType("application/json"); } public ResponseAssert isText() { return hasContentType("text/plain"); } public ResponseAssert hasContentType(String contentType) { FunctionalAssertions.assertThat(response.getContentType()).isEqualTo(contentType); return this; } public ResponseAssert isEncoded(String encoding) { assertThat(response.getEncoding()).isEqualToIgnoringCase(encoding); return this; } public ResponseAssert isUtf8() { return isEncoded("utf-8"); }
// Path: app/litmus/unit/validation/BuiltInValidation.java // public enum BuiltInValidation { // // // EMAIL("email"), // EQUALS("equals"), // IN_FUTURE("future"), // AFTER("after"), // IN_PAST("past"), // BEFORE("before"), // IP_V4_ADDRESS("ipv4"), // IP_V6_ADDRESS("ipv6"), // IS_TRUE("isTrue"), // MATCH("match"), // MAX("max"), // MAX_SIZE("maxSize"), // MIN("min"), // MIN_SIZE("minSize"), // PHONE("phone"), // RANGE("range"), // REQUIRED("required"), // UNIQUE("unique"), // URL("url"), // VALID("object"); // // // private final String messageSuffix; // // BuiltInValidation(String messageSuffix) { // this.messageSuffix = messageSuffix; // } // // // public String getMessageKey() { // return "validation." + messageSuffix; // } // // } // Path: app/litmus/functional/ResponseAssert.java import litmus.unit.validation.BuiltInValidation; import org.fest.assertions.Assertions; import org.fest.assertions.GenericAssert; import play.mvc.Http; import static org.fest.assertions.Assertions.assertThat; import static play.mvc.Http.StatusCode.*; public ResponseAssert isHtml() { return hasContentType("text/html"); } public ResponseAssert isXml() { return hasContentType("text/xml"); } public ResponseAssert isJson() { return hasContentType("application/json"); } public ResponseAssert isText() { return hasContentType("text/plain"); } public ResponseAssert hasContentType(String contentType) { FunctionalAssertions.assertThat(response.getContentType()).isEqualTo(contentType); return this; } public ResponseAssert isEncoded(String encoding) { assertThat(response.getEncoding()).isEqualToIgnoringCase(encoding); return this; } public ResponseAssert isUtf8() { return isEncoded("utf-8"); }
public ResponseAssert hasValidationError(String fieldName, BuiltInValidation validation) {
bverbeken/litmus
samples/test/unit/validation/IpAddressValidationTest.java
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/IpAddressModel.java // public class IpAddressModel { // // @IPv4Address // public String ipV4Address; // // @IPv6Address // public String ipV6Address; // // }
import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.IpAddressModel; import org.junit.Test;
package unit.validation; public class IpAddressValidationTest extends ValidationTest<IpAddressModel> { @Override
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/IpAddressModel.java // public class IpAddressModel { // // @IPv4Address // public String ipV4Address; // // @IPv6Address // public String ipV6Address; // // } // Path: samples/test/unit/validation/IpAddressValidationTest.java import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.IpAddressModel; import org.junit.Test; package unit.validation; public class IpAddressValidationTest extends ValidationTest<IpAddressModel> { @Override
protected Builder<IpAddressModel> valid() {
bverbeken/litmus
samples/test/unit/validation/MatchValidationTest.java
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/MatchModel.java // public class MatchModel { // // @Match("[0-9]*") // public String matchingString; // // // }
import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.MatchModel; import org.junit.Test; import static litmus.unit.validation.BuiltInValidation.MATCH;
package unit.validation; public class MatchValidationTest extends ValidationTest<MatchModel> { @Override
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/MatchModel.java // public class MatchModel { // // @Match("[0-9]*") // public String matchingString; // // // } // Path: samples/test/unit/validation/MatchValidationTest.java import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.MatchModel; import org.junit.Test; import static litmus.unit.validation.BuiltInValidation.MATCH; package unit.validation; public class MatchValidationTest extends ValidationTest<MatchModel> { @Override
protected Builder<MatchModel> valid() {
bverbeken/litmus
samples/test/unit/validation/PhoneValidationTest.java
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/PhoneModel.java // public class PhoneModel { // // @Phone // public String phone; // // // }
import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.PhoneModel; import org.junit.Test;
package unit.validation; public class PhoneValidationTest extends ValidationTest<PhoneModel> { @Override
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/PhoneModel.java // public class PhoneModel { // // @Phone // public String phone; // // // } // Path: samples/test/unit/validation/PhoneValidationTest.java import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.PhoneModel; import org.junit.Test; package unit.validation; public class PhoneValidationTest extends ValidationTest<PhoneModel> { @Override
protected Builder<PhoneModel> valid() {
bverbeken/litmus
samples/test/functional/text/TextResponseExample.java
// Path: app/litmus/functional/FunctionalTest.java // @Category(value = FUNCTIONAL, priority = 20000) // public abstract class FunctionalTest extends FestAssertFunctionalTest { // // // @Before // public void cleanDb() { // deleteDatabase(); // } // // /** // * Perform a GET on a URL. <br/> // * This is a shortcut method for <pre>new Request(url).get();</pre> // * // * @param url the url to GET // * @return the {@link Response} object // */ // protected static Response get(Object url) { // return new Request(url).get(); // } // // /** // * Perform a POST on a URL. <br/> // * This is a shortcut method for <pre>new Request(url).post(params);</pre> // * // * @param url the url to POST // * @return the {@link Response} object // */ // protected static Response post(Object url, Map<String, String> params) { // return new Request(url).post(params); // } // // // /** // * Shortcut method you can use instead of <pre>get(url).getHtml();</pre> // * // * @param url the url to GET // * @return an {@link Html} object // */ // protected static Html getHtml(Object url) { // return get(url).getHtml(); // } // // // /** // * Shortcut method for logging in. // * <br/> // * This method performs a POST on /login with the provided username and password parameters, like so: // * <pre> // * new Request("/login").with("username", username).with("password", password).post(); // * </pre> // * // * This method will also verify that you actually are logged in, by checking that the PLAY_SESSION cookie has been returned in the response. // * // * @param username the username // * @param password the password // * @return a {@link Response} object // */ // protected Response login(String username, String password) { // Response response = new Request("/login") // .with("username", username) // .with("password", password) // .post(); // assertThat(response.getCookieValue("PLAY_SESSION")).as("play session cookie").isNotEmpty(); // return response; // } // // /** // * Shortcut method for logging out, by calling clearCookies(); // */ // protected void logout() { // clearCookies(); // } // // // } // // Path: app/litmus/functional/WrongContentTypeException.java // public class WrongContentTypeException extends RuntimeException { // // public WrongContentTypeException(String expectedContentType, String actualContentType, HttpMethod method, Object request) { // super(format("Expected to find contentType %s but was %s [Request: %s %s]", expectedContentType, actualContentType, method, request)); // } // // }
import litmus.functional.FunctionalTest; import litmus.functional.WrongContentTypeException; import org.junit.Test;
/* * Copyright 2012 Ben Verbeken * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package functional.text; public class TextResponseExample extends FunctionalTest { @Test public void contains() { assertThat(get("/contentTypes/text").getContent()).contains("Hello World"); assertThat(get("/contentTypes/text").getText()).contains("Hello World"); } @Test public void getTextThrowsExceptionIfContentTypeIsNotOk() { try { get("/contentTypes/html").getText(); fail();
// Path: app/litmus/functional/FunctionalTest.java // @Category(value = FUNCTIONAL, priority = 20000) // public abstract class FunctionalTest extends FestAssertFunctionalTest { // // // @Before // public void cleanDb() { // deleteDatabase(); // } // // /** // * Perform a GET on a URL. <br/> // * This is a shortcut method for <pre>new Request(url).get();</pre> // * // * @param url the url to GET // * @return the {@link Response} object // */ // protected static Response get(Object url) { // return new Request(url).get(); // } // // /** // * Perform a POST on a URL. <br/> // * This is a shortcut method for <pre>new Request(url).post(params);</pre> // * // * @param url the url to POST // * @return the {@link Response} object // */ // protected static Response post(Object url, Map<String, String> params) { // return new Request(url).post(params); // } // // // /** // * Shortcut method you can use instead of <pre>get(url).getHtml();</pre> // * // * @param url the url to GET // * @return an {@link Html} object // */ // protected static Html getHtml(Object url) { // return get(url).getHtml(); // } // // // /** // * Shortcut method for logging in. // * <br/> // * This method performs a POST on /login with the provided username and password parameters, like so: // * <pre> // * new Request("/login").with("username", username).with("password", password).post(); // * </pre> // * // * This method will also verify that you actually are logged in, by checking that the PLAY_SESSION cookie has been returned in the response. // * // * @param username the username // * @param password the password // * @return a {@link Response} object // */ // protected Response login(String username, String password) { // Response response = new Request("/login") // .with("username", username) // .with("password", password) // .post(); // assertThat(response.getCookieValue("PLAY_SESSION")).as("play session cookie").isNotEmpty(); // return response; // } // // /** // * Shortcut method for logging out, by calling clearCookies(); // */ // protected void logout() { // clearCookies(); // } // // // } // // Path: app/litmus/functional/WrongContentTypeException.java // public class WrongContentTypeException extends RuntimeException { // // public WrongContentTypeException(String expectedContentType, String actualContentType, HttpMethod method, Object request) { // super(format("Expected to find contentType %s but was %s [Request: %s %s]", expectedContentType, actualContentType, method, request)); // } // // } // Path: samples/test/functional/text/TextResponseExample.java import litmus.functional.FunctionalTest; import litmus.functional.WrongContentTypeException; import org.junit.Test; /* * Copyright 2012 Ben Verbeken * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package functional.text; public class TextResponseExample extends FunctionalTest { @Test public void contains() { assertThat(get("/contentTypes/text").getContent()).contains("Hello World"); assertThat(get("/contentTypes/text").getText()).contains("Hello World"); } @Test public void getTextThrowsExceptionIfContentTypeIsNotOk() { try { get("/contentTypes/html").getText(); fail();
} catch (WrongContentTypeException e) {
bverbeken/litmus
samples/test/unit/validation/IsTrueValidationTest.java
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/IsTrueModel.java // public class IsTrueModel { // // // @IsTrue // public boolean trueBoolean; // // @IsTrue // public String trueString; // // @IsTrue // public Integer trueInteger; // // @IsTrue // public Long trueLong; // // @IsTrue // public Double trueDouble; // // @IsTrue // public BigDecimal trueBigDecimal; // // @IsTrue // public Float trueFloat; // // // }
import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.IsTrueModel; import org.junit.Test; import java.math.BigDecimal;
@Test public void isTrue_Long() { assertThat("trueLong").isInvalidWhenEqualTo(0L); assertThat("trueLong").isInvalidWhenEqualTo(null); assertThat("trueLong").mustBeTrue(); } @Test public void isTrue_Double() { assertThat("trueDouble").isInvalidWhenEqualTo(0d); assertThat("trueDouble").isInvalidWhenEqualTo(null); assertThat("trueDouble").mustBeTrue(); } @Test public void isTrue_Float() { assertThat("trueFloat").isInvalidWhenEqualTo(0f); assertThat("trueFloat").isInvalidWhenEqualTo(null); assertThat("trueFloat").mustBeTrue(); } @Test public void isTrue_BigDecimal() { assertThat("trueBigDecimal").isInvalidWhenEqualTo(BigDecimal.ZERO); assertThat("trueBigDecimal").isInvalidWhenEqualTo(null); assertThat("trueBigDecimal").mustBeTrue(); }
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/IsTrueModel.java // public class IsTrueModel { // // // @IsTrue // public boolean trueBoolean; // // @IsTrue // public String trueString; // // @IsTrue // public Integer trueInteger; // // @IsTrue // public Long trueLong; // // @IsTrue // public Double trueDouble; // // @IsTrue // public BigDecimal trueBigDecimal; // // @IsTrue // public Float trueFloat; // // // } // Path: samples/test/unit/validation/IsTrueValidationTest.java import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.IsTrueModel; import org.junit.Test; import java.math.BigDecimal; @Test public void isTrue_Long() { assertThat("trueLong").isInvalidWhenEqualTo(0L); assertThat("trueLong").isInvalidWhenEqualTo(null); assertThat("trueLong").mustBeTrue(); } @Test public void isTrue_Double() { assertThat("trueDouble").isInvalidWhenEqualTo(0d); assertThat("trueDouble").isInvalidWhenEqualTo(null); assertThat("trueDouble").mustBeTrue(); } @Test public void isTrue_Float() { assertThat("trueFloat").isInvalidWhenEqualTo(0f); assertThat("trueFloat").isInvalidWhenEqualTo(null); assertThat("trueFloat").mustBeTrue(); } @Test public void isTrue_BigDecimal() { assertThat("trueBigDecimal").isInvalidWhenEqualTo(BigDecimal.ZERO); assertThat("trueBigDecimal").isInvalidWhenEqualTo(null); assertThat("trueBigDecimal").mustBeTrue(); }
private class IsTrueModelBuilder extends Builder<IsTrueModel> {
bverbeken/litmus
app/controllers/LitmusTestRunner.java
// Path: app/litmus/engine/Tests.java // public class Tests { // // private HashMap<CategoryInstance, List<TestClass>> map = new HashMap<CategoryInstance, List<TestClass>>(); // // // public Tests() { // for (Class testClass : getAllTests()) { // if (!isAbstract(testClass.getModifiers())) { // addTest(testClass); // } // } // } // // private List<Class> getAllTests() { // // TODO: don't just pick up Assert subclasses, but all non abstract classes that end with *Test // // Check junit's naming rules // return classloader.getAssignableClasses(Assert.class); // } // // // private void addTest(Class<?> testClass) { // Category annotation = findCategoryAnnotation(testClass); // if (annotation != null) { // addToCategory(testClass, new CategoryInstance(annotation)); // } else { // addToCategory(testClass, NONE); // } // } // // private boolean addToCategory(Class<?> testClass, CategoryInstance category) { // return getOrCreateCategoryList(category).add(new TestClass(testClass)); // } // // private Category findCategoryAnnotation(Class<?> testClass) { // if (testClass.equals(Object.class)) { // return null; // } else { // Category annotation = testClass.getAnnotation(Category.class); // return annotation == null ? findCategoryAnnotation(testClass.getSuperclass()) : annotation; // } // } // // private List<TestClass> getOrCreateCategoryList(CategoryInstance category) { // if (map.get(category) == null) { // map.put(category, new ArrayList<TestClass>()); // } // return map.get(category); // } // // public List<CategoryInstance> getCategories() { // ArrayList<CategoryInstance> categories = newArrayList(map.keySet()); // Collections.sort(categories, new CategoryInstanceComparator()); // return categories; // } // // // public List<TestClass> get(CategoryInstance o) { // List<TestClass> classes = map.get(o); // sort(classes); // return classes; // } // // // }
import litmus.engine.Tests; import play.Logger; import play.mvc.Controller; import play.test.TestEngine; import java.io.File; import java.util.HashMap; import java.util.Map; import static play.Play.getFile; import static play.libs.IO.writeContent; import static play.templates.TemplateLoader.load; import static play.test.TestEngine.TestResults;
package controllers; @SuppressWarnings({"UnusedDeclaration", "ConstantConditions"}) public class LitmusTestRunner extends Controller { public static void testList() {
// Path: app/litmus/engine/Tests.java // public class Tests { // // private HashMap<CategoryInstance, List<TestClass>> map = new HashMap<CategoryInstance, List<TestClass>>(); // // // public Tests() { // for (Class testClass : getAllTests()) { // if (!isAbstract(testClass.getModifiers())) { // addTest(testClass); // } // } // } // // private List<Class> getAllTests() { // // TODO: don't just pick up Assert subclasses, but all non abstract classes that end with *Test // // Check junit's naming rules // return classloader.getAssignableClasses(Assert.class); // } // // // private void addTest(Class<?> testClass) { // Category annotation = findCategoryAnnotation(testClass); // if (annotation != null) { // addToCategory(testClass, new CategoryInstance(annotation)); // } else { // addToCategory(testClass, NONE); // } // } // // private boolean addToCategory(Class<?> testClass, CategoryInstance category) { // return getOrCreateCategoryList(category).add(new TestClass(testClass)); // } // // private Category findCategoryAnnotation(Class<?> testClass) { // if (testClass.equals(Object.class)) { // return null; // } else { // Category annotation = testClass.getAnnotation(Category.class); // return annotation == null ? findCategoryAnnotation(testClass.getSuperclass()) : annotation; // } // } // // private List<TestClass> getOrCreateCategoryList(CategoryInstance category) { // if (map.get(category) == null) { // map.put(category, new ArrayList<TestClass>()); // } // return map.get(category); // } // // public List<CategoryInstance> getCategories() { // ArrayList<CategoryInstance> categories = newArrayList(map.keySet()); // Collections.sort(categories, new CategoryInstanceComparator()); // return categories; // } // // // public List<TestClass> get(CategoryInstance o) { // List<TestClass> classes = map.get(o); // sort(classes); // return classes; // } // // // } // Path: app/controllers/LitmusTestRunner.java import litmus.engine.Tests; import play.Logger; import play.mvc.Controller; import play.test.TestEngine; import java.io.File; import java.util.HashMap; import java.util.Map; import static play.Play.getFile; import static play.libs.IO.writeContent; import static play.templates.TemplateLoader.load; import static play.test.TestEngine.TestResults; package controllers; @SuppressWarnings({"UnusedDeclaration", "ConstantConditions"}) public class LitmusTestRunner extends Controller { public static void testList() {
Tests tests = new Tests();
bverbeken/litmus
samples/test/functional/html/HtmlElementExample.java
// Path: app/litmus/functional/FunctionalTest.java // @Category(value = FUNCTIONAL, priority = 20000) // public abstract class FunctionalTest extends FestAssertFunctionalTest { // // // @Before // public void cleanDb() { // deleteDatabase(); // } // // /** // * Perform a GET on a URL. <br/> // * This is a shortcut method for <pre>new Request(url).get();</pre> // * // * @param url the url to GET // * @return the {@link Response} object // */ // protected static Response get(Object url) { // return new Request(url).get(); // } // // /** // * Perform a POST on a URL. <br/> // * This is a shortcut method for <pre>new Request(url).post(params);</pre> // * // * @param url the url to POST // * @return the {@link Response} object // */ // protected static Response post(Object url, Map<String, String> params) { // return new Request(url).post(params); // } // // // /** // * Shortcut method you can use instead of <pre>get(url).getHtml();</pre> // * // * @param url the url to GET // * @return an {@link Html} object // */ // protected static Html getHtml(Object url) { // return get(url).getHtml(); // } // // // /** // * Shortcut method for logging in. // * <br/> // * This method performs a POST on /login with the provided username and password parameters, like so: // * <pre> // * new Request("/login").with("username", username).with("password", password).post(); // * </pre> // * // * This method will also verify that you actually are logged in, by checking that the PLAY_SESSION cookie has been returned in the response. // * // * @param username the username // * @param password the password // * @return a {@link Response} object // */ // protected Response login(String username, String password) { // Response response = new Request("/login") // .with("username", username) // .with("password", password) // .post(); // assertThat(response.getCookieValue("PLAY_SESSION")).as("play session cookie").isNotEmpty(); // return response; // } // // /** // * Shortcut method for logging out, by calling clearCookies(); // */ // protected void logout() { // clearCookies(); // } // // // } // // Path: app/litmus/functional/WrongContentTypeException.java // public class WrongContentTypeException extends RuntimeException { // // public WrongContentTypeException(String expectedContentType, String actualContentType, HttpMethod method, Object request) { // super(format("Expected to find contentType %s but was %s [Request: %s %s]", expectedContentType, actualContentType, method, request)); // } // // }
import litmus.functional.FunctionalTest; import litmus.functional.WrongContentTypeException; import org.jsoup.nodes.Element; import org.junit.Test;
@Test public void hasAttributeValue() { Element actual = getHtml(PATH).selectSingle("#myDiv"); assertThat(actual).hasAttributeValue("title", "myDiv title"); } @Test public void hasNoAttribute() { Element actual = getHtml(PATH).selectSingle("#myDiv"); assertThat(actual).hasNoAttribute("unexistingAttr"); } @Test public void containsMessage(){ Element actual = getHtml(PATH).selectSingle("#divWithMessage"); assertThat(actual).containsMessage("this.is.a.message.key"); } @Test public void containsMessageWithArgs(){ Element actual = getHtml(PATH).selectSingle("#divWithMessageWithArgs"); assertThat(actual).containsMessage("this.is.a.message.key.with.args", "argValue1", "argValue2"); } @Test public void getHtmlThrowsExceptionIfContentTypeIsNotOk() { try { getHtml("/contentTypes/text"); fail();
// Path: app/litmus/functional/FunctionalTest.java // @Category(value = FUNCTIONAL, priority = 20000) // public abstract class FunctionalTest extends FestAssertFunctionalTest { // // // @Before // public void cleanDb() { // deleteDatabase(); // } // // /** // * Perform a GET on a URL. <br/> // * This is a shortcut method for <pre>new Request(url).get();</pre> // * // * @param url the url to GET // * @return the {@link Response} object // */ // protected static Response get(Object url) { // return new Request(url).get(); // } // // /** // * Perform a POST on a URL. <br/> // * This is a shortcut method for <pre>new Request(url).post(params);</pre> // * // * @param url the url to POST // * @return the {@link Response} object // */ // protected static Response post(Object url, Map<String, String> params) { // return new Request(url).post(params); // } // // // /** // * Shortcut method you can use instead of <pre>get(url).getHtml();</pre> // * // * @param url the url to GET // * @return an {@link Html} object // */ // protected static Html getHtml(Object url) { // return get(url).getHtml(); // } // // // /** // * Shortcut method for logging in. // * <br/> // * This method performs a POST on /login with the provided username and password parameters, like so: // * <pre> // * new Request("/login").with("username", username).with("password", password).post(); // * </pre> // * // * This method will also verify that you actually are logged in, by checking that the PLAY_SESSION cookie has been returned in the response. // * // * @param username the username // * @param password the password // * @return a {@link Response} object // */ // protected Response login(String username, String password) { // Response response = new Request("/login") // .with("username", username) // .with("password", password) // .post(); // assertThat(response.getCookieValue("PLAY_SESSION")).as("play session cookie").isNotEmpty(); // return response; // } // // /** // * Shortcut method for logging out, by calling clearCookies(); // */ // protected void logout() { // clearCookies(); // } // // // } // // Path: app/litmus/functional/WrongContentTypeException.java // public class WrongContentTypeException extends RuntimeException { // // public WrongContentTypeException(String expectedContentType, String actualContentType, HttpMethod method, Object request) { // super(format("Expected to find contentType %s but was %s [Request: %s %s]", expectedContentType, actualContentType, method, request)); // } // // } // Path: samples/test/functional/html/HtmlElementExample.java import litmus.functional.FunctionalTest; import litmus.functional.WrongContentTypeException; import org.jsoup.nodes.Element; import org.junit.Test; @Test public void hasAttributeValue() { Element actual = getHtml(PATH).selectSingle("#myDiv"); assertThat(actual).hasAttributeValue("title", "myDiv title"); } @Test public void hasNoAttribute() { Element actual = getHtml(PATH).selectSingle("#myDiv"); assertThat(actual).hasNoAttribute("unexistingAttr"); } @Test public void containsMessage(){ Element actual = getHtml(PATH).selectSingle("#divWithMessage"); assertThat(actual).containsMessage("this.is.a.message.key"); } @Test public void containsMessageWithArgs(){ Element actual = getHtml(PATH).selectSingle("#divWithMessageWithArgs"); assertThat(actual).containsMessage("this.is.a.message.key.with.args", "argValue1", "argValue2"); } @Test public void getHtmlThrowsExceptionIfContentTypeIsNotOk() { try { getHtml("/contentTypes/text"); fail();
} catch (WrongContentTypeException e) {
bverbeken/litmus
samples/test/unit/validation/SampleFieldValidationTest.java
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/Person.java // public class Person { // // @Required // public String firstName; // // @MinSize(4) // public String lastName; // // @Email // public String email; // // public Person(String firstName) { // this(firstName, null); // } // // public Person(String firstName, String lastName) { // this.firstName = firstName; // this.lastName = lastName; // } // // @Override // public String toString() { // return firstName + " " + lastName + "(" + email + ")"; // } // // @Override // public boolean equals(Object that) { // return reflectionEquals(this, that); // } // // @Override // public int hashCode() { // return reflectionHashCode(this); // } // }
import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.Person; import org.junit.Test;
/* * Copyright 2012 Ben Verbeken * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package unit.validation; public class SampleFieldValidationTest extends ValidationTest<Person> { @Override
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/Person.java // public class Person { // // @Required // public String firstName; // // @MinSize(4) // public String lastName; // // @Email // public String email; // // public Person(String firstName) { // this(firstName, null); // } // // public Person(String firstName, String lastName) { // this.firstName = firstName; // this.lastName = lastName; // } // // @Override // public String toString() { // return firstName + " " + lastName + "(" + email + ")"; // } // // @Override // public boolean equals(Object that) { // return reflectionEquals(this, that); // } // // @Override // public int hashCode() { // return reflectionHashCode(this); // } // } // Path: samples/test/unit/validation/SampleFieldValidationTest.java import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.Person; import org.junit.Test; /* * Copyright 2012 Ben Verbeken * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package unit.validation; public class SampleFieldValidationTest extends ValidationTest<Person> { @Override
protected Builder<Person> valid() {
bverbeken/litmus
samples/test/functional/response/RenderArgsTest.java
// Path: app/litmus/functional/FunctionalTest.java // @Category(value = FUNCTIONAL, priority = 20000) // public abstract class FunctionalTest extends FestAssertFunctionalTest { // // // @Before // public void cleanDb() { // deleteDatabase(); // } // // /** // * Perform a GET on a URL. <br/> // * This is a shortcut method for <pre>new Request(url).get();</pre> // * // * @param url the url to GET // * @return the {@link Response} object // */ // protected static Response get(Object url) { // return new Request(url).get(); // } // // /** // * Perform a POST on a URL. <br/> // * This is a shortcut method for <pre>new Request(url).post(params);</pre> // * // * @param url the url to POST // * @return the {@link Response} object // */ // protected static Response post(Object url, Map<String, String> params) { // return new Request(url).post(params); // } // // // /** // * Shortcut method you can use instead of <pre>get(url).getHtml();</pre> // * // * @param url the url to GET // * @return an {@link Html} object // */ // protected static Html getHtml(Object url) { // return get(url).getHtml(); // } // // // /** // * Shortcut method for logging in. // * <br/> // * This method performs a POST on /login with the provided username and password parameters, like so: // * <pre> // * new Request("/login").with("username", username).with("password", password).post(); // * </pre> // * // * This method will also verify that you actually are logged in, by checking that the PLAY_SESSION cookie has been returned in the response. // * // * @param username the username // * @param password the password // * @return a {@link Response} object // */ // protected Response login(String username, String password) { // Response response = new Request("/login") // .with("username", username) // .with("password", password) // .post(); // assertThat(response.getCookieValue("PLAY_SESSION")).as("play session cookie").isNotEmpty(); // return response; // } // // /** // * Shortcut method for logging out, by calling clearCookies(); // */ // protected void logout() { // clearCookies(); // } // // // } // // Path: samples/app/models/Person.java // public class Person { // // @Required // public String firstName; // // @MinSize(4) // public String lastName; // // @Email // public String email; // // public Person(String firstName) { // this(firstName, null); // } // // public Person(String firstName, String lastName) { // this.firstName = firstName; // this.lastName = lastName; // } // // @Override // public String toString() { // return firstName + " " + lastName + "(" + email + ")"; // } // // @Override // public boolean equals(Object that) { // return reflectionEquals(this, that); // } // // @Override // public int hashCode() { // return reflectionHashCode(this); // } // }
import litmus.functional.FunctionalTest; import models.Person; import org.junit.Test; import java.util.List; import static com.google.common.collect.Lists.newArrayList;
/* * Copyright 2012 Ben Verbeken * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package functional.response; public class RenderArgsTest extends FunctionalTest { @Test public void simpleExample() { assertThat(get("/renderargs/arg1")).hasRenderArg("arg1"); } @Test public void worksWithTwoRequestsToo() { assertThat(get("/renderargs/arg1")).hasRenderArg("arg1"); assertThat(get("/renderargs/arg2")).hasRenderArg("arg2"); } @Test public void hasNoRenderArg() { assertThat(get("/renderargs/people")).hasNoRenderArg("unexisting"); } @Test public void collectionAsContent() {
// Path: app/litmus/functional/FunctionalTest.java // @Category(value = FUNCTIONAL, priority = 20000) // public abstract class FunctionalTest extends FestAssertFunctionalTest { // // // @Before // public void cleanDb() { // deleteDatabase(); // } // // /** // * Perform a GET on a URL. <br/> // * This is a shortcut method for <pre>new Request(url).get();</pre> // * // * @param url the url to GET // * @return the {@link Response} object // */ // protected static Response get(Object url) { // return new Request(url).get(); // } // // /** // * Perform a POST on a URL. <br/> // * This is a shortcut method for <pre>new Request(url).post(params);</pre> // * // * @param url the url to POST // * @return the {@link Response} object // */ // protected static Response post(Object url, Map<String, String> params) { // return new Request(url).post(params); // } // // // /** // * Shortcut method you can use instead of <pre>get(url).getHtml();</pre> // * // * @param url the url to GET // * @return an {@link Html} object // */ // protected static Html getHtml(Object url) { // return get(url).getHtml(); // } // // // /** // * Shortcut method for logging in. // * <br/> // * This method performs a POST on /login with the provided username and password parameters, like so: // * <pre> // * new Request("/login").with("username", username).with("password", password).post(); // * </pre> // * // * This method will also verify that you actually are logged in, by checking that the PLAY_SESSION cookie has been returned in the response. // * // * @param username the username // * @param password the password // * @return a {@link Response} object // */ // protected Response login(String username, String password) { // Response response = new Request("/login") // .with("username", username) // .with("password", password) // .post(); // assertThat(response.getCookieValue("PLAY_SESSION")).as("play session cookie").isNotEmpty(); // return response; // } // // /** // * Shortcut method for logging out, by calling clearCookies(); // */ // protected void logout() { // clearCookies(); // } // // // } // // Path: samples/app/models/Person.java // public class Person { // // @Required // public String firstName; // // @MinSize(4) // public String lastName; // // @Email // public String email; // // public Person(String firstName) { // this(firstName, null); // } // // public Person(String firstName, String lastName) { // this.firstName = firstName; // this.lastName = lastName; // } // // @Override // public String toString() { // return firstName + " " + lastName + "(" + email + ")"; // } // // @Override // public boolean equals(Object that) { // return reflectionEquals(this, that); // } // // @Override // public int hashCode() { // return reflectionHashCode(this); // } // } // Path: samples/test/functional/response/RenderArgsTest.java import litmus.functional.FunctionalTest; import models.Person; import org.junit.Test; import java.util.List; import static com.google.common.collect.Lists.newArrayList; /* * Copyright 2012 Ben Verbeken * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package functional.response; public class RenderArgsTest extends FunctionalTest { @Test public void simpleExample() { assertThat(get("/renderargs/arg1")).hasRenderArg("arg1"); } @Test public void worksWithTwoRequestsToo() { assertThat(get("/renderargs/arg1")).hasRenderArg("arg1"); assertThat(get("/renderargs/arg2")).hasRenderArg("arg2"); } @Test public void hasNoRenderArg() { assertThat(get("/renderargs/people")).hasNoRenderArg("unexisting"); } @Test public void collectionAsContent() {
List<Person> peopleRenderArg = get("/renderargs/people").getRenderArg("people");
bverbeken/litmus
samples/app/controllers/RenderArgsController.java
// Path: samples/app/models/Person.java // public class Person { // // @Required // public String firstName; // // @MinSize(4) // public String lastName; // // @Email // public String email; // // public Person(String firstName) { // this(firstName, null); // } // // public Person(String firstName, String lastName) { // this.firstName = firstName; // this.lastName = lastName; // } // // @Override // public String toString() { // return firstName + " " + lastName + "(" + email + ")"; // } // // @Override // public boolean equals(Object that) { // return reflectionEquals(this, that); // } // // @Override // public int hashCode() { // return reflectionHashCode(this); // } // }
import models.Person; import play.mvc.Controller; import java.util.Date; import static com.google.common.collect.Lists.newArrayList;
/* * Copyright 2012 Ben Verbeken * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package controllers; @SuppressWarnings("UnusedDeclaration") public class RenderArgsController extends Controller { public static void arg1() { addRenderArg("arg1"); } public static void arg2() { addRenderArg("arg2"); } private static void addRenderArg(String argName) { renderArgs.put(argName, "the current time is: " + new Date()); } public static void people(){ renderArgs.put("people", newArrayList(
// Path: samples/app/models/Person.java // public class Person { // // @Required // public String firstName; // // @MinSize(4) // public String lastName; // // @Email // public String email; // // public Person(String firstName) { // this(firstName, null); // } // // public Person(String firstName, String lastName) { // this.firstName = firstName; // this.lastName = lastName; // } // // @Override // public String toString() { // return firstName + " " + lastName + "(" + email + ")"; // } // // @Override // public boolean equals(Object that) { // return reflectionEquals(this, that); // } // // @Override // public int hashCode() { // return reflectionHashCode(this); // } // } // Path: samples/app/controllers/RenderArgsController.java import models.Person; import play.mvc.Controller; import java.util.Date; import static com.google.common.collect.Lists.newArrayList; /* * Copyright 2012 Ben Verbeken * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package controllers; @SuppressWarnings("UnusedDeclaration") public class RenderArgsController extends Controller { public static void arg1() { addRenderArg("arg1"); } public static void arg2() { addRenderArg("arg2"); } private static void addRenderArg(String argName) { renderArgs.put(argName, "the current time is: " + new Date()); } public static void people(){ renderArgs.put("people", newArrayList(
new Person("Alex"),
bverbeken/litmus
samples/test/unit/validation/MaxSizeValidationTest.java
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/MaxSizeModel.java // public class MaxSizeModel { // // @MaxSize(4) // public String maxString; // // @SuppressWarnings("UnusedDeclaration") // @MaxSize(3) // public List<String> maxList; // // }
import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.MaxSizeModel; import org.fest.assertions.Assertions; import org.junit.Test; import static com.google.common.collect.Lists.newArrayList;
package unit.validation; public class MaxSizeValidationTest extends ValidationTest<MaxSizeModel> { @Override
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/MaxSizeModel.java // public class MaxSizeModel { // // @MaxSize(4) // public String maxString; // // @SuppressWarnings("UnusedDeclaration") // @MaxSize(3) // public List<String> maxList; // // } // Path: samples/test/unit/validation/MaxSizeValidationTest.java import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.MaxSizeModel; import org.fest.assertions.Assertions; import org.junit.Test; import static com.google.common.collect.Lists.newArrayList; package unit.validation; public class MaxSizeValidationTest extends ValidationTest<MaxSizeModel> { @Override
protected Builder<MaxSizeModel> valid() {
bverbeken/litmus
samples/test/unit/validation/MinValidationTest.java
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/MinModel.java // public class MinModel { // // // @Min(10) // public int minInt; // // @Min(10) // public double minDouble; // // // @Min(10) // public Long minLong; // // @Min(10) // public String minString; // }
import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.MinModel; import org.junit.Test;
assertThat("minDouble").withValue(10.000000000001).isValid(); assertThat("minDouble").isInvalidWhenEqualTo(9.99999999999999); assertThat("minDouble").mustNotBeLessThan(10D); assertThat("minDouble").mustNotBeLessThan(10); } @Test public void minLong() { assertThat("minLong").withValue(11L).isValid(); assertThat("minLong").isInvalidWhenEqualTo(9L); assertThat("minLong").mustNotBeLessThan(10L); assertThat("minLong").mustNotBeLessThan(10); } @Test public void minInt() { assertThat("minInt").withValue(10).isValid(); assertThat("minInt").isInvalidWhenEqualTo(9); assertThat("minInt").mustNotBeLessThan(10); } @Test public void minString() { assertThat("minString").withValue("10").isValid(); assertThat("minString").isInvalidWhenEqualTo("9"); assertThat("minString").isInvalidWhenEqualTo("aaa"); assertThat("minString").mustNotBeLessThan(10); }
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/MinModel.java // public class MinModel { // // // @Min(10) // public int minInt; // // @Min(10) // public double minDouble; // // // @Min(10) // public Long minLong; // // @Min(10) // public String minString; // } // Path: samples/test/unit/validation/MinValidationTest.java import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.MinModel; import org.junit.Test; assertThat("minDouble").withValue(10.000000000001).isValid(); assertThat("minDouble").isInvalidWhenEqualTo(9.99999999999999); assertThat("minDouble").mustNotBeLessThan(10D); assertThat("minDouble").mustNotBeLessThan(10); } @Test public void minLong() { assertThat("minLong").withValue(11L).isValid(); assertThat("minLong").isInvalidWhenEqualTo(9L); assertThat("minLong").mustNotBeLessThan(10L); assertThat("minLong").mustNotBeLessThan(10); } @Test public void minInt() { assertThat("minInt").withValue(10).isValid(); assertThat("minInt").isInvalidWhenEqualTo(9); assertThat("minInt").mustNotBeLessThan(10); } @Test public void minString() { assertThat("minString").withValue("10").isValid(); assertThat("minString").isInvalidWhenEqualTo("9"); assertThat("minString").isInvalidWhenEqualTo("aaa"); assertThat("minString").mustNotBeLessThan(10); }
public static class MinModelBuilder extends Builder<MinModel> {
bverbeken/litmus
app/litmus/unit/validation/Validator.java
// Path: app/litmus/util/ReflectionUtil.java // @SuppressWarnings("unchecked") // public static <T> T get(String fieldName, Object object) { // try { // Field field = findFieldInClassHierarchy(object.getClass(), fieldName); // field.setAccessible(true); // return (T) field.get(object); // } catch (Exception e) { // throw new RuntimeException(e); // } // }
import play.data.validation.Error; import play.data.validation.Validation; import java.util.ArrayList; import java.util.List; import java.util.Map; import static play.data.validation.Validation.ValidationResult; import static litmus.util.ReflectionUtil.get;
/* * Copyright 2012 Ben Verbeken * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package litmus.unit.validation; class Validator { public static boolean isValid(Object actual) { return validate(actual).ok; } public static List<String> getErrorsForField(Object actual, String fieldName) { validate(actual); return getErrorMessagesForField(fieldName); } private static ValidationResult validate(Object actual) { Validation.clear(); return Validation.current().valid(actual); } public static List<String> getErrorMessagesForField(String field) { List<String> result = new ArrayList<String>();
// Path: app/litmus/util/ReflectionUtil.java // @SuppressWarnings("unchecked") // public static <T> T get(String fieldName, Object object) { // try { // Field field = findFieldInClassHierarchy(object.getClass(), fieldName); // field.setAccessible(true); // return (T) field.get(object); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // Path: app/litmus/unit/validation/Validator.java import play.data.validation.Error; import play.data.validation.Validation; import java.util.ArrayList; import java.util.List; import java.util.Map; import static play.data.validation.Validation.ValidationResult; import static litmus.util.ReflectionUtil.get; /* * Copyright 2012 Ben Verbeken * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package litmus.unit.validation; class Validator { public static boolean isValid(Object actual) { return validate(actual).ok; } public static List<String> getErrorsForField(Object actual, String fieldName) { validate(actual); return getErrorMessagesForField(fieldName); } private static ValidationResult validate(Object actual) { Validation.clear(); return Validation.current().valid(actual); } public static List<String> getErrorMessagesForField(String field) { List<String> result = new ArrayList<String>();
List<play.data.validation.Error> errors = Validation.current().errorsMap().get("." + field);
jeeeyul/eclipse.js
net.jeeeyul.eclipsejs/src/net/jeeeyul/eclipsejs/script/lib/ui/EJSLibraryInitializer.java
// Path: net.jeeeyul.eclipsejs/src/net/jeeeyul/eclipsejs/EclipseJSCore.java // public class EclipseJSCore extends AbstractUIPlugin implements // IResourceChangeListener { // /** // * Name of the runtime project. // */ // public static final String PROJECT_NAME = ".eclipse.js"; // // /** // * The Plugin ID. // */ // public static final String PLUGIN_ID = "net.jeeeyul.eclipsejs"; //$NON-NLS-1$ // // // The shared instance // private static EclipseJSCore plugin; // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static EclipseJSCore getDefault() { // return plugin; // } // // private IProject runtimeProject; // // private EnsureRuntimeProject ensureRuntimeProject;; // // /** // * The constructor // */ // public EclipseJSCore() { // } // // private EnsureRuntimeProject getEnsureRuntimeProject() { // if (ensureRuntimeProject == null) { // ensureRuntimeProject = new EnsureRuntimeProject(); // ensureRuntimeProject.addCallback(new IRuntimeProjectCallback() { // @Override // public void projectPrepared(IProject project) { // runtimeProject = project; // } // }); // } // return ensureRuntimeProject; // } // // /** // * // * @return Runtime project. What if project is not ready yet, it will return // * <code>null</code>. // */ // public IProject getPreparedRuntimeProject() { // return runtimeProject; // } // // /** // * Gets runtime project. // * // * @param callback // * callback that handle runtime project when it is ready. // */ // public void getRuntimeProject(IRuntimeProjectCallback callback) { // getEnsureRuntimeProject().addCallback(callback); // } // // /** // * // * @return whether the runtime project is ready. // */ // public boolean isRuntimeProjectPrepared() { // return runtimeProject != null && runtimeProject.exists() // && runtimeProject.isOpen(); // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext // * ) // */ // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // getRuntimeProject(new IRuntimeProjectCallback() { // @Override // public void projectPrepared(IProject project) { // } // }); // // ResourcesPlugin.getWorkspace().addResourceChangeListener(this); // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext // * ) // */ // public void stop(BundleContext context) throws Exception { // plugin = null; // ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); // super.stop(context); // } // // @Override // public void resourceChanged(IResourceChangeEvent event) { // IResourceDelta delta = event.getDelta(); // if (delta == null) { // return; // } // IResourceDelta member = delta.findMember(new Path("/" + PROJECT_NAME)); // if (member != null) { // Require.unloadModulesForAllThread(); // } // } // // /** // * Gets EJS extensions. // * // * @param point // * extension point name. // * @param id // * extension id. // * @param args // * extension construction arguments. // * @return {@link EJSExtension} for given arguments. Can be // * <code>null</code>. // */ // public EJSExtension getExtension(String point, String id, Object... args) { // return new EJSExtension(point, id, args); // } // // }
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import net.jeeeyul.eclipsejs.EclipseJSCore; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.wst.jsdt.core.IJavaScriptProject; import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer; import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer; import org.eclipse.wst.jsdt.core.compiler.libraries.LibraryLocation; import org.osgi.framework.Bundle;
package net.jeeeyul.eclipsejs.script.lib.ui; /** * eclipse.js jsdt library initializer. * * @author Jeeeyul * */ public class EJSLibraryInitializer extends JsGlobalScopeContainerInitializer implements IJsGlobalScopeContainer { /** * JSDT Library ID. */ public static final String LIB_ID = "net.jeeeyul.eclipsejs.lib"; /** * Human readable Library name. */ public static final String LIB_NAME = "Eclipse.JS Libraries"; @Override public LibraryLocation getLibraryLocation() { return EJSLibraryLocation.getInstance(); } static class EJSLibraryLocation implements LibraryLocation { public EJSLibraryLocation() {
// Path: net.jeeeyul.eclipsejs/src/net/jeeeyul/eclipsejs/EclipseJSCore.java // public class EclipseJSCore extends AbstractUIPlugin implements // IResourceChangeListener { // /** // * Name of the runtime project. // */ // public static final String PROJECT_NAME = ".eclipse.js"; // // /** // * The Plugin ID. // */ // public static final String PLUGIN_ID = "net.jeeeyul.eclipsejs"; //$NON-NLS-1$ // // // The shared instance // private static EclipseJSCore plugin; // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static EclipseJSCore getDefault() { // return plugin; // } // // private IProject runtimeProject; // // private EnsureRuntimeProject ensureRuntimeProject;; // // /** // * The constructor // */ // public EclipseJSCore() { // } // // private EnsureRuntimeProject getEnsureRuntimeProject() { // if (ensureRuntimeProject == null) { // ensureRuntimeProject = new EnsureRuntimeProject(); // ensureRuntimeProject.addCallback(new IRuntimeProjectCallback() { // @Override // public void projectPrepared(IProject project) { // runtimeProject = project; // } // }); // } // return ensureRuntimeProject; // } // // /** // * // * @return Runtime project. What if project is not ready yet, it will return // * <code>null</code>. // */ // public IProject getPreparedRuntimeProject() { // return runtimeProject; // } // // /** // * Gets runtime project. // * // * @param callback // * callback that handle runtime project when it is ready. // */ // public void getRuntimeProject(IRuntimeProjectCallback callback) { // getEnsureRuntimeProject().addCallback(callback); // } // // /** // * // * @return whether the runtime project is ready. // */ // public boolean isRuntimeProjectPrepared() { // return runtimeProject != null && runtimeProject.exists() // && runtimeProject.isOpen(); // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext // * ) // */ // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // getRuntimeProject(new IRuntimeProjectCallback() { // @Override // public void projectPrepared(IProject project) { // } // }); // // ResourcesPlugin.getWorkspace().addResourceChangeListener(this); // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext // * ) // */ // public void stop(BundleContext context) throws Exception { // plugin = null; // ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); // super.stop(context); // } // // @Override // public void resourceChanged(IResourceChangeEvent event) { // IResourceDelta delta = event.getDelta(); // if (delta == null) { // return; // } // IResourceDelta member = delta.findMember(new Path("/" + PROJECT_NAME)); // if (member != null) { // Require.unloadModulesForAllThread(); // } // } // // /** // * Gets EJS extensions. // * // * @param point // * extension point name. // * @param id // * extension id. // * @param args // * extension construction arguments. // * @return {@link EJSExtension} for given arguments. Can be // * <code>null</code>. // */ // public EJSExtension getExtension(String point, String id, Object... args) { // return new EJSExtension(point, id, args); // } // // } // Path: net.jeeeyul.eclipsejs/src/net/jeeeyul/eclipsejs/script/lib/ui/EJSLibraryInitializer.java import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import net.jeeeyul.eclipsejs.EclipseJSCore; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.wst.jsdt.core.IJavaScriptProject; import org.eclipse.wst.jsdt.core.IJsGlobalScopeContainer; import org.eclipse.wst.jsdt.core.JsGlobalScopeContainerInitializer; import org.eclipse.wst.jsdt.core.compiler.libraries.LibraryLocation; import org.osgi.framework.Bundle; package net.jeeeyul.eclipsejs.script.lib.ui; /** * eclipse.js jsdt library initializer. * * @author Jeeeyul * */ public class EJSLibraryInitializer extends JsGlobalScopeContainerInitializer implements IJsGlobalScopeContainer { /** * JSDT Library ID. */ public static final String LIB_ID = "net.jeeeyul.eclipsejs.lib"; /** * Human readable Library name. */ public static final String LIB_NAME = "Eclipse.JS Libraries"; @Override public LibraryLocation getLibraryLocation() { return EJSLibraryLocation.getInstance(); } static class EJSLibraryLocation implements LibraryLocation { public EJSLibraryLocation() {
IPath stateLocation = EclipseJSCore.getDefault().getStateLocation();
jeeeyul/eclipse.js
net.jeeeyul.eclipsejs/src/net/jeeeyul/eclipsejs/runtime/EnsureRuntimeProject.java
// Path: net.jeeeyul.eclipsejs/src/net/jeeeyul/eclipsejs/EclipseJSCore.java // public class EclipseJSCore extends AbstractUIPlugin implements // IResourceChangeListener { // /** // * Name of the runtime project. // */ // public static final String PROJECT_NAME = ".eclipse.js"; // // /** // * The Plugin ID. // */ // public static final String PLUGIN_ID = "net.jeeeyul.eclipsejs"; //$NON-NLS-1$ // // // The shared instance // private static EclipseJSCore plugin; // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static EclipseJSCore getDefault() { // return plugin; // } // // private IProject runtimeProject; // // private EnsureRuntimeProject ensureRuntimeProject;; // // /** // * The constructor // */ // public EclipseJSCore() { // } // // private EnsureRuntimeProject getEnsureRuntimeProject() { // if (ensureRuntimeProject == null) { // ensureRuntimeProject = new EnsureRuntimeProject(); // ensureRuntimeProject.addCallback(new IRuntimeProjectCallback() { // @Override // public void projectPrepared(IProject project) { // runtimeProject = project; // } // }); // } // return ensureRuntimeProject; // } // // /** // * // * @return Runtime project. What if project is not ready yet, it will return // * <code>null</code>. // */ // public IProject getPreparedRuntimeProject() { // return runtimeProject; // } // // /** // * Gets runtime project. // * // * @param callback // * callback that handle runtime project when it is ready. // */ // public void getRuntimeProject(IRuntimeProjectCallback callback) { // getEnsureRuntimeProject().addCallback(callback); // } // // /** // * // * @return whether the runtime project is ready. // */ // public boolean isRuntimeProjectPrepared() { // return runtimeProject != null && runtimeProject.exists() // && runtimeProject.isOpen(); // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext // * ) // */ // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // getRuntimeProject(new IRuntimeProjectCallback() { // @Override // public void projectPrepared(IProject project) { // } // }); // // ResourcesPlugin.getWorkspace().addResourceChangeListener(this); // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext // * ) // */ // public void stop(BundleContext context) throws Exception { // plugin = null; // ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); // super.stop(context); // } // // @Override // public void resourceChanged(IResourceChangeEvent event) { // IResourceDelta delta = event.getDelta(); // if (delta == null) { // return; // } // IResourceDelta member = delta.findMember(new Path("/" + PROJECT_NAME)); // if (member != null) { // Require.unloadModulesForAllThread(); // } // } // // /** // * Gets EJS extensions. // * // * @param point // * extension point name. // * @param id // * extension id. // * @param args // * extension construction arguments. // * @return {@link EJSExtension} for given arguments. Can be // * <code>null</code>. // */ // public EJSExtension getExtension(String point, String id, Object... args) { // return new EJSExtension(point, id, args); // } // // }
import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import net.jeeeyul.eclipsejs.EclipseJSCore; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.resources.WorkspaceJob; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status;
return container; } private void finish(IProject project) { IRuntimeProjectCallback[] array; synchronized (callbacks) { array = callbacks.toArray(new IRuntimeProjectCallback[callbacks .size()]); callbacks.clear(); } for (IRuntimeProjectCallback each : array) { each.projectPrepared(project); } } @Override public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { if (project == null || !project.exists()) { project = resolveProject(); } finish(project); return Status.OK_STATUS; } private IProject resolveProject() throws CoreException {
// Path: net.jeeeyul.eclipsejs/src/net/jeeeyul/eclipsejs/EclipseJSCore.java // public class EclipseJSCore extends AbstractUIPlugin implements // IResourceChangeListener { // /** // * Name of the runtime project. // */ // public static final String PROJECT_NAME = ".eclipse.js"; // // /** // * The Plugin ID. // */ // public static final String PLUGIN_ID = "net.jeeeyul.eclipsejs"; //$NON-NLS-1$ // // // The shared instance // private static EclipseJSCore plugin; // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static EclipseJSCore getDefault() { // return plugin; // } // // private IProject runtimeProject; // // private EnsureRuntimeProject ensureRuntimeProject;; // // /** // * The constructor // */ // public EclipseJSCore() { // } // // private EnsureRuntimeProject getEnsureRuntimeProject() { // if (ensureRuntimeProject == null) { // ensureRuntimeProject = new EnsureRuntimeProject(); // ensureRuntimeProject.addCallback(new IRuntimeProjectCallback() { // @Override // public void projectPrepared(IProject project) { // runtimeProject = project; // } // }); // } // return ensureRuntimeProject; // } // // /** // * // * @return Runtime project. What if project is not ready yet, it will return // * <code>null</code>. // */ // public IProject getPreparedRuntimeProject() { // return runtimeProject; // } // // /** // * Gets runtime project. // * // * @param callback // * callback that handle runtime project when it is ready. // */ // public void getRuntimeProject(IRuntimeProjectCallback callback) { // getEnsureRuntimeProject().addCallback(callback); // } // // /** // * // * @return whether the runtime project is ready. // */ // public boolean isRuntimeProjectPrepared() { // return runtimeProject != null && runtimeProject.exists() // && runtimeProject.isOpen(); // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext // * ) // */ // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // getRuntimeProject(new IRuntimeProjectCallback() { // @Override // public void projectPrepared(IProject project) { // } // }); // // ResourcesPlugin.getWorkspace().addResourceChangeListener(this); // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext // * ) // */ // public void stop(BundleContext context) throws Exception { // plugin = null; // ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); // super.stop(context); // } // // @Override // public void resourceChanged(IResourceChangeEvent event) { // IResourceDelta delta = event.getDelta(); // if (delta == null) { // return; // } // IResourceDelta member = delta.findMember(new Path("/" + PROJECT_NAME)); // if (member != null) { // Require.unloadModulesForAllThread(); // } // } // // /** // * Gets EJS extensions. // * // * @param point // * extension point name. // * @param id // * extension id. // * @param args // * extension construction arguments. // * @return {@link EJSExtension} for given arguments. Can be // * <code>null</code>. // */ // public EJSExtension getExtension(String point, String id, Object... args) { // return new EJSExtension(point, id, args); // } // // } // Path: net.jeeeyul.eclipsejs/src/net/jeeeyul/eclipsejs/runtime/EnsureRuntimeProject.java import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import net.jeeeyul.eclipsejs.EclipseJSCore; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.resources.WorkspaceJob; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; return container; } private void finish(IProject project) { IRuntimeProjectCallback[] array; synchronized (callbacks) { array = callbacks.toArray(new IRuntimeProjectCallback[callbacks .size()]); callbacks.clear(); } for (IRuntimeProjectCallback each : array) { each.projectPrepared(project); } } @Override public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { if (project == null || !project.exists()) { project = resolveProject(); } finish(project); return Status.OK_STATUS; } private IProject resolveProject() throws CoreException {
Enumeration<URL> entries = EclipseJSCore.getDefault().getBundle()
jeeeyul/eclipse.js
net.jeeeyul.eclipsejs/src/net/jeeeyul/eclipsejs/script/internal/ExecuteQueryViewScriptHandler.java
// Path: net.jeeeyul.eclipsejs/src/net/jeeeyul/eclipsejs/ui/queryview/QueryView.java // @SuppressWarnings("restriction") // public class QueryView extends ViewPart implements IScriptProvider { // private static final Path QUERY_SCRIPT_PATH = new Path("user/query.js"); // /** // * View ID. // */ // public static final String ID = QueryView.class.getCanonicalName(); // // private EmbededJSDTEditorSite editorSite; // private CompilationUnitEditor editor; // private PageBook pageBook; // private IProject project; // private Composite editorWrapper; // private CompilationUnitEditorActionContributor contributor; // private ExecuteScriptJob executeScriptJob; // // /** // * Creates Query View. // */ // public QueryView() { // editor = new EmbededJSDTEditor(); // contributor = new CompilationUnitEditorActionContributor(); // } // // private void createEditor() { // if (Display.getDefault().getThread() != Thread.currentThread()) { // Display.getDefault().asyncExec(new Runnable() { // @Override // public void run() { // createEditor(); // } // }); // return; // } // IFile file = project.getFile(QUERY_SCRIPT_PATH); // try { // editor.init(editorSite, new FileEditorInput(file)); // } catch (PartInitException e) { // e.printStackTrace(); // } // // editorWrapper = new Composite(pageBook, SWT.NORMAL); // editorWrapper.setData("org.eclipse.e4.ui.css.CssClassName", // "MPart Editor"); // editorWrapper.setLayout(new FillLayout()); // editor.createPartControl(editorWrapper); // // contributor.setActiveEditor(editor); // pageBook.showPage(editorWrapper); // } // // @Override // public void createPartControl(Composite parent) { // pageBook = new PageBook(parent, SWT.NORMAL); // Label label = new Label(pageBook, SWT.NORMAL); // label.setText("Preparing Workspace Query Runtime..."); // pageBook.showPage(label); // if (project != null) { // createEditor(); // } // } // // /** // * // * @return An {@link ExecuteScriptJob} for scripts in query view. // */ // public ExecuteScriptJob getExecuteScriptJob() { // if (executeScriptJob == null) { // executeScriptJob = new ExecuteScriptJob(this); // } // return executeScriptJob; // } // // @Override // public IPath getFullPath() { // return project.getFile(QUERY_SCRIPT_PATH).getFullPath(); // } // // public String getScript() { // return editor.getViewer().getDocument().get(); // } // // @Override // public void init(IViewSite site) throws PartInitException { // super.init(site); // // editorSite = new EmbededJSDTEditorSite(site); // EclipseJSCore.getDefault().getRuntimeProject( // new IRuntimeProjectCallback() { // @Override // public void projectPrepared(IProject project) { // QueryView.this.project = project; // if (pageBook != null) { // createEditor(); // } // } // }); // // IActionBars actionBars = getViewSite().getActionBars(); // contributor.init(actionBars); // // actionBars.setGlobalActionHandler(ActionFactory.SAVE.getId(), // new Action() { // @Override // public void run() { // if (editor != null) { // editor.doSave(new NullProgressMonitor()); // } // } // }); // // IContextService service = (IContextService) site // .getService(IContextService.class); // service.activateContext("net.jeeeyul.eclipsejs.script.view"); // } // // @Override // public void saveState(IMemento memento) { // if (editor != null && editorWrapper != null // && !editorWrapper.isDisposed()) { // editor.doSave(new NullProgressMonitor()); // } // super.saveState(memento); // } // // @Override // public void setFocus() { // pageBook.setFocus(); // } // // }
import net.jeeeyul.eclipsejs.ui.queryview.QueryView; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil;
package net.jeeeyul.eclipsejs.script.internal; /** * Handler for executing query view script command. * * @author Jeeeyul * */ public class ExecuteQueryViewScriptHandler extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
// Path: net.jeeeyul.eclipsejs/src/net/jeeeyul/eclipsejs/ui/queryview/QueryView.java // @SuppressWarnings("restriction") // public class QueryView extends ViewPart implements IScriptProvider { // private static final Path QUERY_SCRIPT_PATH = new Path("user/query.js"); // /** // * View ID. // */ // public static final String ID = QueryView.class.getCanonicalName(); // // private EmbededJSDTEditorSite editorSite; // private CompilationUnitEditor editor; // private PageBook pageBook; // private IProject project; // private Composite editorWrapper; // private CompilationUnitEditorActionContributor contributor; // private ExecuteScriptJob executeScriptJob; // // /** // * Creates Query View. // */ // public QueryView() { // editor = new EmbededJSDTEditor(); // contributor = new CompilationUnitEditorActionContributor(); // } // // private void createEditor() { // if (Display.getDefault().getThread() != Thread.currentThread()) { // Display.getDefault().asyncExec(new Runnable() { // @Override // public void run() { // createEditor(); // } // }); // return; // } // IFile file = project.getFile(QUERY_SCRIPT_PATH); // try { // editor.init(editorSite, new FileEditorInput(file)); // } catch (PartInitException e) { // e.printStackTrace(); // } // // editorWrapper = new Composite(pageBook, SWT.NORMAL); // editorWrapper.setData("org.eclipse.e4.ui.css.CssClassName", // "MPart Editor"); // editorWrapper.setLayout(new FillLayout()); // editor.createPartControl(editorWrapper); // // contributor.setActiveEditor(editor); // pageBook.showPage(editorWrapper); // } // // @Override // public void createPartControl(Composite parent) { // pageBook = new PageBook(parent, SWT.NORMAL); // Label label = new Label(pageBook, SWT.NORMAL); // label.setText("Preparing Workspace Query Runtime..."); // pageBook.showPage(label); // if (project != null) { // createEditor(); // } // } // // /** // * // * @return An {@link ExecuteScriptJob} for scripts in query view. // */ // public ExecuteScriptJob getExecuteScriptJob() { // if (executeScriptJob == null) { // executeScriptJob = new ExecuteScriptJob(this); // } // return executeScriptJob; // } // // @Override // public IPath getFullPath() { // return project.getFile(QUERY_SCRIPT_PATH).getFullPath(); // } // // public String getScript() { // return editor.getViewer().getDocument().get(); // } // // @Override // public void init(IViewSite site) throws PartInitException { // super.init(site); // // editorSite = new EmbededJSDTEditorSite(site); // EclipseJSCore.getDefault().getRuntimeProject( // new IRuntimeProjectCallback() { // @Override // public void projectPrepared(IProject project) { // QueryView.this.project = project; // if (pageBook != null) { // createEditor(); // } // } // }); // // IActionBars actionBars = getViewSite().getActionBars(); // contributor.init(actionBars); // // actionBars.setGlobalActionHandler(ActionFactory.SAVE.getId(), // new Action() { // @Override // public void run() { // if (editor != null) { // editor.doSave(new NullProgressMonitor()); // } // } // }); // // IContextService service = (IContextService) site // .getService(IContextService.class); // service.activateContext("net.jeeeyul.eclipsejs.script.view"); // } // // @Override // public void saveState(IMemento memento) { // if (editor != null && editorWrapper != null // && !editorWrapper.isDisposed()) { // editor.doSave(new NullProgressMonitor()); // } // super.saveState(memento); // } // // @Override // public void setFocus() { // pageBook.setFocus(); // } // // } // Path: net.jeeeyul.eclipsejs/src/net/jeeeyul/eclipsejs/script/internal/ExecuteQueryViewScriptHandler.java import net.jeeeyul.eclipsejs.ui.queryview.QueryView; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.handlers.HandlerUtil; package net.jeeeyul.eclipsejs.script.internal; /** * Handler for executing query view script command. * * @author Jeeeyul * */ public class ExecuteQueryViewScriptHandler extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
QueryView view = (QueryView) window.getActivePage().findView(
jeeeyul/eclipse.js
net.jeeeyul.eclipsejs/src/net/jeeeyul/eclipsejs/ui/console/BundleLink.java
// Path: net.jeeeyul.eclipsejs/src/net/jeeeyul/eclipsejs/EclipseJSCore.java // public class EclipseJSCore extends AbstractUIPlugin implements // IResourceChangeListener { // /** // * Name of the runtime project. // */ // public static final String PROJECT_NAME = ".eclipse.js"; // // /** // * The Plugin ID. // */ // public static final String PLUGIN_ID = "net.jeeeyul.eclipsejs"; //$NON-NLS-1$ // // // The shared instance // private static EclipseJSCore plugin; // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static EclipseJSCore getDefault() { // return plugin; // } // // private IProject runtimeProject; // // private EnsureRuntimeProject ensureRuntimeProject;; // // /** // * The constructor // */ // public EclipseJSCore() { // } // // private EnsureRuntimeProject getEnsureRuntimeProject() { // if (ensureRuntimeProject == null) { // ensureRuntimeProject = new EnsureRuntimeProject(); // ensureRuntimeProject.addCallback(new IRuntimeProjectCallback() { // @Override // public void projectPrepared(IProject project) { // runtimeProject = project; // } // }); // } // return ensureRuntimeProject; // } // // /** // * // * @return Runtime project. What if project is not ready yet, it will return // * <code>null</code>. // */ // public IProject getPreparedRuntimeProject() { // return runtimeProject; // } // // /** // * Gets runtime project. // * // * @param callback // * callback that handle runtime project when it is ready. // */ // public void getRuntimeProject(IRuntimeProjectCallback callback) { // getEnsureRuntimeProject().addCallback(callback); // } // // /** // * // * @return whether the runtime project is ready. // */ // public boolean isRuntimeProjectPrepared() { // return runtimeProject != null && runtimeProject.exists() // && runtimeProject.isOpen(); // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext // * ) // */ // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // getRuntimeProject(new IRuntimeProjectCallback() { // @Override // public void projectPrepared(IProject project) { // } // }); // // ResourcesPlugin.getWorkspace().addResourceChangeListener(this); // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext // * ) // */ // public void stop(BundleContext context) throws Exception { // plugin = null; // ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); // super.stop(context); // } // // @Override // public void resourceChanged(IResourceChangeEvent event) { // IResourceDelta delta = event.getDelta(); // if (delta == null) { // return; // } // IResourceDelta member = delta.findMember(new Path("/" + PROJECT_NAME)); // if (member != null) { // Require.unloadModulesForAllThread(); // } // } // // /** // * Gets EJS extensions. // * // * @param point // * extension point name. // * @param id // * extension id. // * @param args // * extension construction arguments. // * @return {@link EJSExtension} for given arguments. Can be // * <code>null</code>. // */ // public EJSExtension getExtension(String point, String id, Object... args) { // return new EJSExtension(point, id, args); // } // // }
import net.jeeeyul.eclipsejs.EclipseJSCore; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.console.IHyperlink; import org.eclipse.ui.ide.IDE; import org.eclipse.ui.texteditor.AbstractTextEditor; import org.eclipse.wst.jsdt.core.IClassFile; import org.eclipse.wst.jsdt.core.IJavaScriptElement; import org.eclipse.wst.jsdt.core.IJavaScriptModel; import org.eclipse.wst.jsdt.core.IJavaScriptProject; import org.eclipse.wst.jsdt.core.IPackageFragment; import org.eclipse.wst.jsdt.core.IPackageFragmentRoot; import org.eclipse.wst.jsdt.core.JavaScriptCore; import org.eclipse.wst.jsdt.core.JavaScriptModelException; import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility;
package net.jeeeyul.eclipsejs.ui.console; /** * A link that indicated built-in script. built-in script means that this script * is provided by eclipse.js jsdt library. * * @author Jeeeyul * @since 0.1 */ @SuppressWarnings("restriction") public class BundleLink implements IHyperlink { private String path; private int line; /** * Creates a link. * * @param path * path for eclipse.js script. this path is relative to * "/libraries" folder in this project. * @param line */ public BundleLink(String path, int line) { this.path = path; this.line = line; } @Override public void linkEntered() { } @Override public void linkExited() { } @Override public void linkActivated() {
// Path: net.jeeeyul.eclipsejs/src/net/jeeeyul/eclipsejs/EclipseJSCore.java // public class EclipseJSCore extends AbstractUIPlugin implements // IResourceChangeListener { // /** // * Name of the runtime project. // */ // public static final String PROJECT_NAME = ".eclipse.js"; // // /** // * The Plugin ID. // */ // public static final String PLUGIN_ID = "net.jeeeyul.eclipsejs"; //$NON-NLS-1$ // // // The shared instance // private static EclipseJSCore plugin; // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static EclipseJSCore getDefault() { // return plugin; // } // // private IProject runtimeProject; // // private EnsureRuntimeProject ensureRuntimeProject;; // // /** // * The constructor // */ // public EclipseJSCore() { // } // // private EnsureRuntimeProject getEnsureRuntimeProject() { // if (ensureRuntimeProject == null) { // ensureRuntimeProject = new EnsureRuntimeProject(); // ensureRuntimeProject.addCallback(new IRuntimeProjectCallback() { // @Override // public void projectPrepared(IProject project) { // runtimeProject = project; // } // }); // } // return ensureRuntimeProject; // } // // /** // * // * @return Runtime project. What if project is not ready yet, it will return // * <code>null</code>. // */ // public IProject getPreparedRuntimeProject() { // return runtimeProject; // } // // /** // * Gets runtime project. // * // * @param callback // * callback that handle runtime project when it is ready. // */ // public void getRuntimeProject(IRuntimeProjectCallback callback) { // getEnsureRuntimeProject().addCallback(callback); // } // // /** // * // * @return whether the runtime project is ready. // */ // public boolean isRuntimeProjectPrepared() { // return runtimeProject != null && runtimeProject.exists() // && runtimeProject.isOpen(); // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext // * ) // */ // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // getRuntimeProject(new IRuntimeProjectCallback() { // @Override // public void projectPrepared(IProject project) { // } // }); // // ResourcesPlugin.getWorkspace().addResourceChangeListener(this); // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext // * ) // */ // public void stop(BundleContext context) throws Exception { // plugin = null; // ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); // super.stop(context); // } // // @Override // public void resourceChanged(IResourceChangeEvent event) { // IResourceDelta delta = event.getDelta(); // if (delta == null) { // return; // } // IResourceDelta member = delta.findMember(new Path("/" + PROJECT_NAME)); // if (member != null) { // Require.unloadModulesForAllThread(); // } // } // // /** // * Gets EJS extensions. // * // * @param point // * extension point name. // * @param id // * extension id. // * @param args // * extension construction arguments. // * @return {@link EJSExtension} for given arguments. Can be // * <code>null</code>. // */ // public EJSExtension getExtension(String point, String id, Object... args) { // return new EJSExtension(point, id, args); // } // // } // Path: net.jeeeyul.eclipsejs/src/net/jeeeyul/eclipsejs/ui/console/BundleLink.java import net.jeeeyul.eclipsejs.EclipseJSCore; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.console.IHyperlink; import org.eclipse.ui.ide.IDE; import org.eclipse.ui.texteditor.AbstractTextEditor; import org.eclipse.wst.jsdt.core.IClassFile; import org.eclipse.wst.jsdt.core.IJavaScriptElement; import org.eclipse.wst.jsdt.core.IJavaScriptModel; import org.eclipse.wst.jsdt.core.IJavaScriptProject; import org.eclipse.wst.jsdt.core.IPackageFragment; import org.eclipse.wst.jsdt.core.IPackageFragmentRoot; import org.eclipse.wst.jsdt.core.JavaScriptCore; import org.eclipse.wst.jsdt.core.JavaScriptModelException; import org.eclipse.wst.jsdt.internal.ui.javaeditor.EditorUtility; package net.jeeeyul.eclipsejs.ui.console; /** * A link that indicated built-in script. built-in script means that this script * is provided by eclipse.js jsdt library. * * @author Jeeeyul * @since 0.1 */ @SuppressWarnings("restriction") public class BundleLink implements IHyperlink { private String path; private int line; /** * Creates a link. * * @param path * path for eclipse.js script. this path is relative to * "/libraries" folder in this project. * @param line */ public BundleLink(String path, int line) { this.path = path; this.line = line; } @Override public void linkEntered() { } @Override public void linkExited() { } @Override public void linkActivated() {
IPath path = EclipseJSCore.getDefault().getStateLocation()
jeeeyul/eclipse.js
net.jeeeyul.eclipsejs/src/net/jeeeyul/eclipsejs/script/FileScript.java
// Path: net.jeeeyul.eclipsejs/src/net/jeeeyul/eclipsejs/util/FileUtil.java // public class FileUtil { // private static final FileUtil instance = new FileUtil(); // // /** // * @return A singleton instance. // */ // public static FileUtil getInstance() { // return instance; // } // // /** // * // * @param is // * {@link InputStream} to read. // * @param charset // * encoding to read. // * @return Text Content of given input stream. // * @throws IOException // */ // public String getTextContent(InputStream is, String charset) throws IOException { // byte[] buf = new byte[512]; // int len = -1; // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // while ((len = is.read(buf)) != -1) { // baos.write(buf, 0, len); // } // is.close(); // return baos.toString(charset); // } // // /** // * Store given text content into {@link IFile}. // * // * @param file // * file to save. // * @param content // * text content to store. // * @throws UnsupportedEncodingException // * @throws CoreException // */ // public void setTextContent(IFile file, String content) throws UnsupportedEncodingException, CoreException { // byte[] data = content.getBytes(file.getCharset()); // file.setContents(new ByteArrayInputStream(data), true, true, new NullProgressMonitor()); // } // // /** // * Store give text content into {@link IFile}. // * // * @param file // * file to create. // * @param content // * text content to store. // * @throws UnsupportedEncodingException // * @throws CoreException // */ // public void createWithTextContent(IFile file, String content) throws UnsupportedEncodingException, CoreException { // byte[] data = content.getBytes(file.getCharset()); // file.create(new ByteArrayInputStream(data), true, new NullProgressMonitor()); // } // // /** // * Ensure existence of folder. // * // * @param folder // * folder to ensure existence. It will ensure all it's parents. // */ // public void mkdirp(IFolder folder) { // if (folder.exists()) { // return; // } // // IContainer parent = folder.getParent(); // if (!parent.exists()) { // if (parent instanceof IFolder) { // mkdirp((IFolder) parent); // } else { // throw new RuntimeException("Project can't be created through mkdirp"); // } // } // // try { // folder.create(true, false, new NullProgressMonitor()); // } catch (CoreException e) { // e.printStackTrace(); // } // } // }
import net.jeeeyul.eclipsejs.util.FileUtil; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IPath;
package net.jeeeyul.eclipsejs.script; /** * {@link IScriptProvider} based on {@link IFile}. * * @author Jeeeyul * */ public class FileScript implements IScriptProvider { private IFile file; /** * Creates an {@link FileScript}. * * @param file */ public FileScript(IFile file) { this.file = file; } @Override public String getScript() { try {
// Path: net.jeeeyul.eclipsejs/src/net/jeeeyul/eclipsejs/util/FileUtil.java // public class FileUtil { // private static final FileUtil instance = new FileUtil(); // // /** // * @return A singleton instance. // */ // public static FileUtil getInstance() { // return instance; // } // // /** // * // * @param is // * {@link InputStream} to read. // * @param charset // * encoding to read. // * @return Text Content of given input stream. // * @throws IOException // */ // public String getTextContent(InputStream is, String charset) throws IOException { // byte[] buf = new byte[512]; // int len = -1; // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // while ((len = is.read(buf)) != -1) { // baos.write(buf, 0, len); // } // is.close(); // return baos.toString(charset); // } // // /** // * Store given text content into {@link IFile}. // * // * @param file // * file to save. // * @param content // * text content to store. // * @throws UnsupportedEncodingException // * @throws CoreException // */ // public void setTextContent(IFile file, String content) throws UnsupportedEncodingException, CoreException { // byte[] data = content.getBytes(file.getCharset()); // file.setContents(new ByteArrayInputStream(data), true, true, new NullProgressMonitor()); // } // // /** // * Store give text content into {@link IFile}. // * // * @param file // * file to create. // * @param content // * text content to store. // * @throws UnsupportedEncodingException // * @throws CoreException // */ // public void createWithTextContent(IFile file, String content) throws UnsupportedEncodingException, CoreException { // byte[] data = content.getBytes(file.getCharset()); // file.create(new ByteArrayInputStream(data), true, new NullProgressMonitor()); // } // // /** // * Ensure existence of folder. // * // * @param folder // * folder to ensure existence. It will ensure all it's parents. // */ // public void mkdirp(IFolder folder) { // if (folder.exists()) { // return; // } // // IContainer parent = folder.getParent(); // if (!parent.exists()) { // if (parent instanceof IFolder) { // mkdirp((IFolder) parent); // } else { // throw new RuntimeException("Project can't be created through mkdirp"); // } // } // // try { // folder.create(true, false, new NullProgressMonitor()); // } catch (CoreException e) { // e.printStackTrace(); // } // } // } // Path: net.jeeeyul.eclipsejs/src/net/jeeeyul/eclipsejs/script/FileScript.java import net.jeeeyul.eclipsejs.util.FileUtil; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IPath; package net.jeeeyul.eclipsejs.script; /** * {@link IScriptProvider} based on {@link IFile}. * * @author Jeeeyul * */ public class FileScript implements IScriptProvider { private IFile file; /** * Creates an {@link FileScript}. * * @param file */ public FileScript(IFile file) { this.file = file; } @Override public String getScript() { try {
return FileUtil.getInstance().getTextContent(file.getContents(), file.getCharset());
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/channel/EagerExchangeChannel.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // }
import io.netty.bootstrap.Bootstrap; import sailfish.remoting.exceptions.SailfishException;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.channel; /** * @author spccold * @version $Id: EagerExchangeChannel.java, v 0.1 2016年11月21日 下午11:17:02 spccold Exp $ */ public final class EagerExchangeChannel extends SingleConnctionExchangeChannel { EagerExchangeChannel(Bootstrap bootstrap, ExchangeChannelGroup parent, int reconnectInterval)
// Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/channel/EagerExchangeChannel.java import io.netty.bootstrap.Bootstrap; import sailfish.remoting.exceptions.SailfishException; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.channel; /** * @author spccold * @version $Id: EagerExchangeChannel.java, v 0.1 2016年11月21日 下午11:17:02 spccold Exp $ */ public final class EagerExchangeChannel extends SingleConnctionExchangeChannel { EagerExchangeChannel(Bootstrap bootstrap, ExchangeChannelGroup parent, int reconnectInterval)
throws SailfishException {
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/protocol/Protocol.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // }
import io.netty.buffer.ByteBuf; import sailfish.remoting.exceptions.SailfishException;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.protocol; /** * * @author spccold * @version $Id: Protocol.java, v 0.1 2016年10月4日 下午3:01:29 jileng Exp $ */ public interface Protocol { /** * request or response direction */ boolean request(); /** * heartbeat request/response */ boolean heartbeat(); /** * serialize bytes data to channel */
// Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/protocol/Protocol.java import io.netty.buffer.ByteBuf; import sailfish.remoting.exceptions.SailfishException; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.protocol; /** * * @author spccold * @version $Id: Protocol.java, v 0.1 2016年10月4日 下午3:01:29 jileng Exp $ */ public interface Protocol { /** * request or response direction */ boolean request(); /** * heartbeat request/response */ boolean heartbeat(); /** * serialize bytes data to channel */
void serialize(ByteBuf output) throws SailfishException;
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/channel/ExchangeChannelChooserFactory.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // }
import sailfish.remoting.exceptions.SailfishException;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.channel; /** * Factory that creates new {@link ExchangeChannelChooser}s. * * @author spccold * @version $Id: ExchangeChannelChooserFactory.java, v 0.1 2016年11月22日 下午4:36:58 spccold Exp $ */ public interface ExchangeChannelChooserFactory { /** * Returns a new {@link ExchangeChannelChooser}. */ ExchangeChannelChooser newChooser(ExchangeChannel[] channels, ExchangeChannel[] deadChannels); /** * Chooses the next {@link ExchangeChannel} to use. */ interface ExchangeChannelChooser { /** * Returns the new {@link ExchangeChannel} to use. */
// Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/channel/ExchangeChannelChooserFactory.java import sailfish.remoting.exceptions.SailfishException; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.channel; /** * Factory that creates new {@link ExchangeChannelChooser}s. * * @author spccold * @version $Id: ExchangeChannelChooserFactory.java, v 0.1 2016年11月22日 下午4:36:58 spccold Exp $ */ public interface ExchangeChannelChooserFactory { /** * Returns a new {@link ExchangeChannelChooser}. */ ExchangeChannelChooser newChooser(ExchangeChannel[] channels, ExchangeChannel[] deadChannels); /** * Chooses the next {@link ExchangeChannel} to use. */ interface ExchangeChannelChooser { /** * Returns the new {@link ExchangeChannel} to use. */
ExchangeChannel next() throws SailfishException;
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/utils/ChannelUtil.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/ChannelAttrKeys.java // public interface ChannelAttrKeys { // AttributeKey<HighPerformanceChannelWriter> highPerformanceWriter = AttributeKey.valueOf("sailfish.highPerformanceWriter"); // // // for idle handle and heart beat // AttributeKey<Byte> maxIdleTimeout = AttributeKey.valueOf("sailfish.maxIdleTimeout"); // AttributeKey<Long> lastReadTimeMillis = AttributeKey.valueOf("sailfish.lastReadTimeMillis"); // // // side // AttributeKey<Boolean> clientSide = AttributeKey.valueOf("sailfish.side"); // // AttributeKey<ExchangeChannelGroup> channelGroup = AttributeKey.valueOf("sailfish.channelGroup"); // AttributeKey<DefaultServer> exchangeServer = AttributeKey.valueOf("sailfish.exchangeServer"); // AttributeKey<String> uuidStr = AttributeKey.valueOf("sailfish.uuidStr"); // // interface OneTime { // // for idle handle // AttributeKey<Byte> idleTimeout = AttributeKey.valueOf("sailfish.idleTimeout"); // AttributeKey<CountDownLatch> awaitNegotiate = AttributeKey.valueOf("sailfish.awaitNegotiate"); // // AttributeKey<NegotiateConfig> channelConfig = AttributeKey.valueOf("sailfish.channelConfig"); // } // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.util.Attribute; import sailfish.remoting.constants.ChannelAttrKeys;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.utils; /** * @author spccold * @version $Id: ChannelUtil.java, v 0.1 2016年11月23日 下午11:13:40 spccold Exp $ */ public class ChannelUtil { private static final Logger logger = LoggerFactory.getLogger(ChannelUtil.class); public static boolean clientSide(ChannelHandlerContext ctx) {
// Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/ChannelAttrKeys.java // public interface ChannelAttrKeys { // AttributeKey<HighPerformanceChannelWriter> highPerformanceWriter = AttributeKey.valueOf("sailfish.highPerformanceWriter"); // // // for idle handle and heart beat // AttributeKey<Byte> maxIdleTimeout = AttributeKey.valueOf("sailfish.maxIdleTimeout"); // AttributeKey<Long> lastReadTimeMillis = AttributeKey.valueOf("sailfish.lastReadTimeMillis"); // // // side // AttributeKey<Boolean> clientSide = AttributeKey.valueOf("sailfish.side"); // // AttributeKey<ExchangeChannelGroup> channelGroup = AttributeKey.valueOf("sailfish.channelGroup"); // AttributeKey<DefaultServer> exchangeServer = AttributeKey.valueOf("sailfish.exchangeServer"); // AttributeKey<String> uuidStr = AttributeKey.valueOf("sailfish.uuidStr"); // // interface OneTime { // // for idle handle // AttributeKey<Byte> idleTimeout = AttributeKey.valueOf("sailfish.idleTimeout"); // AttributeKey<CountDownLatch> awaitNegotiate = AttributeKey.valueOf("sailfish.awaitNegotiate"); // // AttributeKey<NegotiateConfig> channelConfig = AttributeKey.valueOf("sailfish.channelConfig"); // } // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/utils/ChannelUtil.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.util.Attribute; import sailfish.remoting.constants.ChannelAttrKeys; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.utils; /** * @author spccold * @version $Id: ChannelUtil.java, v 0.1 2016年11月23日 下午11:13:40 spccold Exp $ */ public class ChannelUtil { private static final Logger logger = LoggerFactory.getLogger(ChannelUtil.class); public static boolean clientSide(ChannelHandlerContext ctx) {
Attribute<Boolean> clientSideAttr = ctx.channel().attr(ChannelAttrKeys.clientSide);
spccold/sailfish
sailfish-kernel/src/test/java/sailfish/remoting/BytesTest.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/utils/Bytes.java // public class Bytes { // public static int bytes2int(byte[] bytes) { // if (null == bytes || bytes.length != 4) { // throw new IllegalArgumentException(); // } // return bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3] << 0; // } // // //high byte first // public static byte[] int2bytes(int integer) { // byte[] bytes = new byte[4]; // bytes[0] = (byte) (integer >> 24 & 0xFF); // bytes[1] = (byte) (integer >> 16 & 0xFF); // bytes[2] = (byte) (integer >> 8 & 0xFF); // bytes[3] = (byte) (integer >> 0 & 0xFF); // return bytes; // } // }
import org.junit.Assert; import org.junit.Test; import sailfish.remoting.utils.Bytes;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting; /** * * @author spccold * @version $Id: BytesTest.java, v 0.1 2016年11月8日 下午7:53:57 jileng Exp $ */ public class BytesTest { @Test public void test() { //test positive int integer = 1;
// Path: sailfish-kernel/src/main/java/sailfish/remoting/utils/Bytes.java // public class Bytes { // public static int bytes2int(byte[] bytes) { // if (null == bytes || bytes.length != 4) { // throw new IllegalArgumentException(); // } // return bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3] << 0; // } // // //high byte first // public static byte[] int2bytes(int integer) { // byte[] bytes = new byte[4]; // bytes[0] = (byte) (integer >> 24 & 0xFF); // bytes[1] = (byte) (integer >> 16 & 0xFF); // bytes[2] = (byte) (integer >> 8 & 0xFF); // bytes[3] = (byte) (integer >> 0 & 0xFF); // return bytes; // } // } // Path: sailfish-kernel/src/test/java/sailfish/remoting/BytesTest.java import org.junit.Assert; import org.junit.Test; import sailfish.remoting.utils.Bytes; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting; /** * * @author spccold * @version $Id: BytesTest.java, v 0.1 2016年11月8日 下午7:53:57 jileng Exp $ */ public class BytesTest { @Test public void test() { //test positive int integer = 1;
Assert.assertTrue(integer == Bytes.bytes2int(Bytes.int2bytes(integer)));
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/Address.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/utils/ParameterChecker.java // public class ParameterChecker { // // public static <T> T checkNotNull(T reference, String hint) { // if (reference == null) { // throw new NullPointerException(hint); // } // return reference; // } // // public static String checkNotBlank(String content, String hint){ // if(StrUtils.isBlank(content)){ // throw new IllegalArgumentException(hint); // } // return content; // } // // public static int checkNotNegative(int number, String hint){ // if(number < 0){ // throw new IllegalArgumentException(hint + ": " + number + " (expected: >= 0)"); // } // return number; // } // // public static int checkPositive(int number, String hint){ // if(number <= 0){ // throw new IllegalArgumentException(hint + ": " + number + " (expected: > 0)"); // } // return number; // } // // public static short checkPositive(short number, String hint){ // if(number <= 0){ // throw new IllegalArgumentException(hint + ": " + number + " (expected: > 0)"); // } // return number; // } // // public static long checkPositive(long number, String hint){ // if(number <= 0){ // throw new IllegalArgumentException(hint + ": " + number + " (expected: > 0)"); // } // return number; // } // // public static int checkBytePositive(int number){ // if(number <= 0 || number > 0x7F){ // throw new IllegalArgumentException("number: " + number + " (expected: 0 < number <= 0x7F)"); // } // return number; // } // }
import java.net.SocketAddress; import sailfish.remoting.utils.ParameterChecker;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting; /** * remote address or local address * @author spccold * @version $Id: RemoteAddress.java, v 0.1 2016年10月26日 下午11:48:58 jileng Exp $ */ public class Address extends SocketAddress{ private static final long serialVersionUID = 1L; private String host; private int port; public Address(String host, int port) {
// Path: sailfish-kernel/src/main/java/sailfish/remoting/utils/ParameterChecker.java // public class ParameterChecker { // // public static <T> T checkNotNull(T reference, String hint) { // if (reference == null) { // throw new NullPointerException(hint); // } // return reference; // } // // public static String checkNotBlank(String content, String hint){ // if(StrUtils.isBlank(content)){ // throw new IllegalArgumentException(hint); // } // return content; // } // // public static int checkNotNegative(int number, String hint){ // if(number < 0){ // throw new IllegalArgumentException(hint + ": " + number + " (expected: >= 0)"); // } // return number; // } // // public static int checkPositive(int number, String hint){ // if(number <= 0){ // throw new IllegalArgumentException(hint + ": " + number + " (expected: > 0)"); // } // return number; // } // // public static short checkPositive(short number, String hint){ // if(number <= 0){ // throw new IllegalArgumentException(hint + ": " + number + " (expected: > 0)"); // } // return number; // } // // public static long checkPositive(long number, String hint){ // if(number <= 0){ // throw new IllegalArgumentException(hint + ": " + number + " (expected: > 0)"); // } // return number; // } // // public static int checkBytePositive(int number){ // if(number <= 0 || number > 0x7F){ // throw new IllegalArgumentException("number: " + number + " (expected: 0 < number <= 0x7F)"); // } // return number; // } // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/Address.java import java.net.SocketAddress; import sailfish.remoting.utils.ParameterChecker; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting; /** * remote address or local address * @author spccold * @version $Id: RemoteAddress.java, v 0.1 2016年10月26日 下午11:48:58 jileng Exp $ */ public class Address extends SocketAddress{ private static final long serialVersionUID = 1L; private String host; private int port; public Address(String host, int port) {
this.host = ParameterChecker.checkNotBlank(host, "host");
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/future/ResponseFuture.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/ResponseCallback.java // public interface ResponseCallback<T> { // /** // * should take advantage of {@link FastThreadLocalThread} with {@link DefaultThreadFactory} // */ // Executor getExecutor(); // // void handleResponse(T resp); // void handleException(Exception cause); // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // }
import java.util.concurrent.TimeUnit; import sailfish.remoting.ResponseCallback; import sailfish.remoting.exceptions.SailfishException;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.future; /** * * @author spccold * @version $Id: ResponseFuture.java, v 0.1 2016年10月4日 下午3:56:21 jileng Exp $ */ public interface ResponseFuture<T>{ void putResponse(T resp, byte result, SailfishException cause); boolean isDone();
// Path: sailfish-kernel/src/main/java/sailfish/remoting/ResponseCallback.java // public interface ResponseCallback<T> { // /** // * should take advantage of {@link FastThreadLocalThread} with {@link DefaultThreadFactory} // */ // Executor getExecutor(); // // void handleResponse(T resp); // void handleException(Exception cause); // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/future/ResponseFuture.java import java.util.concurrent.TimeUnit; import sailfish.remoting.ResponseCallback; import sailfish.remoting.exceptions.SailfishException; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.future; /** * * @author spccold * @version $Id: ResponseFuture.java, v 0.1 2016年10月4日 下午3:56:21 jileng Exp $ */ public interface ResponseFuture<T>{ void putResponse(T resp, byte result, SailfishException cause); boolean isDone();
void setCallback(ResponseCallback<T> callback, int timeout);
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/processors/Request.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/CompressType.java // public interface CompressType { // //TODO compressType with multiple mode, needs to perfect in future // byte NON_COMPRESS = 0; // byte LZ4_COMPRESS = 1; // byte GZIP_COMPRESS = 2; // byte DEFLATE_COMPRESS = 3; // byte SNAPPY_COMPRESS = 4; // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/SerializeType.java // public interface SerializeType { // //pure bytes, no need any serialize and deserialize // byte NON_SERIALIZE = 0; // //java platform // byte JDK_SERIALIZE = 1; // //java platform with high performance // byte KRYO_SERIALIZE = 2; // byte FST_SERIALIZE = 3; // //cross-platform // byte JSON_SERIALIZE = 4; // //cross-platform with high performance // byte HESSIAN_SERIALIZE = 5; // byte AVRO_SERIALIZE = 6; // byte THRIFT_SERIALIZE = 7; // byte PROTOBUF_SERIALIZE = 8; // byte FLATBUFFER_SERIALIZE = 9; // }
import sailfish.remoting.constants.CompressType; import sailfish.remoting.constants.SerializeType;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.processors; /** * @author spccold * @version $Id: Request.java, v 0.1 2016年11月29日 下午5:13:03 spccold Exp $ */ public class Request { private boolean oneway;
// Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/CompressType.java // public interface CompressType { // //TODO compressType with multiple mode, needs to perfect in future // byte NON_COMPRESS = 0; // byte LZ4_COMPRESS = 1; // byte GZIP_COMPRESS = 2; // byte DEFLATE_COMPRESS = 3; // byte SNAPPY_COMPRESS = 4; // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/SerializeType.java // public interface SerializeType { // //pure bytes, no need any serialize and deserialize // byte NON_SERIALIZE = 0; // //java platform // byte JDK_SERIALIZE = 1; // //java platform with high performance // byte KRYO_SERIALIZE = 2; // byte FST_SERIALIZE = 3; // //cross-platform // byte JSON_SERIALIZE = 4; // //cross-platform with high performance // byte HESSIAN_SERIALIZE = 5; // byte AVRO_SERIALIZE = 6; // byte THRIFT_SERIALIZE = 7; // byte PROTOBUF_SERIALIZE = 8; // byte FLATBUFFER_SERIALIZE = 9; // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/processors/Request.java import sailfish.remoting.constants.CompressType; import sailfish.remoting.constants.SerializeType; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.processors; /** * @author spccold * @version $Id: Request.java, v 0.1 2016年11月29日 下午5:13:03 spccold Exp $ */ public class Request { private boolean oneway;
private byte serializeType = SerializeType.NON_SERIALIZE;
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/processors/Request.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/CompressType.java // public interface CompressType { // //TODO compressType with multiple mode, needs to perfect in future // byte NON_COMPRESS = 0; // byte LZ4_COMPRESS = 1; // byte GZIP_COMPRESS = 2; // byte DEFLATE_COMPRESS = 3; // byte SNAPPY_COMPRESS = 4; // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/SerializeType.java // public interface SerializeType { // //pure bytes, no need any serialize and deserialize // byte NON_SERIALIZE = 0; // //java platform // byte JDK_SERIALIZE = 1; // //java platform with high performance // byte KRYO_SERIALIZE = 2; // byte FST_SERIALIZE = 3; // //cross-platform // byte JSON_SERIALIZE = 4; // //cross-platform with high performance // byte HESSIAN_SERIALIZE = 5; // byte AVRO_SERIALIZE = 6; // byte THRIFT_SERIALIZE = 7; // byte PROTOBUF_SERIALIZE = 8; // byte FLATBUFFER_SERIALIZE = 9; // }
import sailfish.remoting.constants.CompressType; import sailfish.remoting.constants.SerializeType;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.processors; /** * @author spccold * @version $Id: Request.java, v 0.1 2016年11月29日 下午5:13:03 spccold Exp $ */ public class Request { private boolean oneway; private byte serializeType = SerializeType.NON_SERIALIZE;
// Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/CompressType.java // public interface CompressType { // //TODO compressType with multiple mode, needs to perfect in future // byte NON_COMPRESS = 0; // byte LZ4_COMPRESS = 1; // byte GZIP_COMPRESS = 2; // byte DEFLATE_COMPRESS = 3; // byte SNAPPY_COMPRESS = 4; // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/SerializeType.java // public interface SerializeType { // //pure bytes, no need any serialize and deserialize // byte NON_SERIALIZE = 0; // //java platform // byte JDK_SERIALIZE = 1; // //java platform with high performance // byte KRYO_SERIALIZE = 2; // byte FST_SERIALIZE = 3; // //cross-platform // byte JSON_SERIALIZE = 4; // //cross-platform with high performance // byte HESSIAN_SERIALIZE = 5; // byte AVRO_SERIALIZE = 6; // byte THRIFT_SERIALIZE = 7; // byte PROTOBUF_SERIALIZE = 8; // byte FLATBUFFER_SERIALIZE = 9; // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/processors/Request.java import sailfish.remoting.constants.CompressType; import sailfish.remoting.constants.SerializeType; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.processors; /** * @author spccold * @version $Id: Request.java, v 0.1 2016年11月29日 下午5:13:03 spccold Exp $ */ public class Request { private boolean oneway; private byte serializeType = SerializeType.NON_SERIALIZE;
private byte compressType = CompressType.NON_COMPRESS;
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/eventgroup/AbstractReusedEventGroup.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/NettyPlatformIndependent.java // public class NettyPlatformIndependent { // // public static EventLoopGroup newEventLoopGroup(int nThreads, ThreadFactory threadFactory) { // if (PlatformUtil.isLinux()) { // return new EpollEventLoopGroup(nThreads, threadFactory); // } // return new NioEventLoopGroup(nThreads, threadFactory); // } // // public static Class<? extends Channel> channelClass() { // if (PlatformUtil.isLinux()) { // return EpollSocketChannel.class; // } // return NioSocketChannel.class; // } // // public static Class<? extends ServerChannel> serverChannelClass() { // if (PlatformUtil.isLinux()) { // return EpollServerSocketChannel.class; // } // return NioServerSocketChannel.class; // } // }
import io.netty.channel.EventLoopGroup; import io.netty.util.concurrent.DefaultEventExecutorGroup; import io.netty.util.concurrent.DefaultThreadFactory; import io.netty.util.concurrent.EventExecutorGroup; import sailfish.remoting.NettyPlatformIndependent;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.eventgroup; /** * @author spccold * @version $Id: AbstractReusedEventGroup.java, v 0.1 2016年11月20日 下午7:29:59 * spccold Exp $ */ public abstract class AbstractReusedEventGroup implements ReusedEventGroup { protected final EventLoopGroup reusedEventLoopGroup; protected final EventExecutorGroup reusedEventExecutorGroup; protected AbstractReusedEventGroup(int ioThreads, String ioThreadName, int eventThreads, String eventThreadName) {
// Path: sailfish-kernel/src/main/java/sailfish/remoting/NettyPlatformIndependent.java // public class NettyPlatformIndependent { // // public static EventLoopGroup newEventLoopGroup(int nThreads, ThreadFactory threadFactory) { // if (PlatformUtil.isLinux()) { // return new EpollEventLoopGroup(nThreads, threadFactory); // } // return new NioEventLoopGroup(nThreads, threadFactory); // } // // public static Class<? extends Channel> channelClass() { // if (PlatformUtil.isLinux()) { // return EpollSocketChannel.class; // } // return NioSocketChannel.class; // } // // public static Class<? extends ServerChannel> serverChannelClass() { // if (PlatformUtil.isLinux()) { // return EpollServerSocketChannel.class; // } // return NioServerSocketChannel.class; // } // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/eventgroup/AbstractReusedEventGroup.java import io.netty.channel.EventLoopGroup; import io.netty.util.concurrent.DefaultEventExecutorGroup; import io.netty.util.concurrent.DefaultThreadFactory; import io.netty.util.concurrent.EventExecutorGroup; import sailfish.remoting.NettyPlatformIndependent; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.eventgroup; /** * @author spccold * @version $Id: AbstractReusedEventGroup.java, v 0.1 2016年11月20日 下午7:29:59 * spccold Exp $ */ public abstract class AbstractReusedEventGroup implements ReusedEventGroup { protected final EventLoopGroup reusedEventLoopGroup; protected final EventExecutorGroup reusedEventExecutorGroup; protected AbstractReusedEventGroup(int ioThreads, String ioThreadName, int eventThreads, String eventThreadName) {
this.reusedEventLoopGroup = NettyPlatformIndependent.newEventLoopGroup(ioThreads,
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/channel/ExchangeChannel.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // }
import java.net.SocketAddress; import io.netty.channel.Channel; import sailfish.remoting.exceptions.SailfishException;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.channel; /** * @author spccold * @version $Id: ExchangeChannel.java, v 0.1 2016年11月21日 下午7:26:12 spccold Exp $ */ public interface ExchangeChannel extends ExchangeChannelGroup{ /** * Returns a reference to itself. */ @Override ExchangeChannel next(); /** * Return the {@link ExchangeChannelGroup} which is the parent of this {@link ExchangeChannel}, */ ExchangeChannelGroup parent(); /** * update this {@link ExchangeChannel} underlying {@link Channel} * @param newChannel * @return old {@link Channel} */ Channel update(Channel newChannel); /** * connect to remote peer * @returnSailfishException * @throws SailfishException */
// Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/channel/ExchangeChannel.java import java.net.SocketAddress; import io.netty.channel.Channel; import sailfish.remoting.exceptions.SailfishException; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.channel; /** * @author spccold * @version $Id: ExchangeChannel.java, v 0.1 2016年11月21日 下午7:26:12 spccold Exp $ */ public interface ExchangeChannel extends ExchangeChannelGroup{ /** * Returns a reference to itself. */ @Override ExchangeChannel next(); /** * Return the {@link ExchangeChannelGroup} which is the parent of this {@link ExchangeChannel}, */ ExchangeChannelGroup parent(); /** * update this {@link ExchangeChannel} underlying {@link Channel} * @param newChannel * @return old {@link Channel} */ Channel update(Channel newChannel); /** * connect to remote peer * @returnSailfishException * @throws SailfishException */
Channel doConnect() throws SailfishException;
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/ReconnectManager.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/channel/ExchangeChannel.java // public interface ExchangeChannel extends ExchangeChannelGroup{ // /** // * Returns a reference to itself. // */ // @Override // ExchangeChannel next(); // // /** // * Return the {@link ExchangeChannelGroup} which is the parent of this {@link ExchangeChannel}, // */ // ExchangeChannelGroup parent(); // // /** // * update this {@link ExchangeChannel} underlying {@link Channel} // * @param newChannel // * @return old {@link Channel} // */ // Channel update(Channel newChannel); // // /** // * connect to remote peer // * @returnSailfishException // * @throws SailfishException // */ // Channel doConnect() throws SailfishException; // // /** // * recover this {@link ExchangeChannel} if {@link #isAvailable()} return false // */ // void recover(); // // SocketAddress localAddress(); // SocketAddress remoteAdress(); // }
import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sailfish.remoting.channel.ExchangeChannel;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting; /** * * @author spccold * @version $Id: ReconnectManager.java, v 0.1 2016年11月7日 下午4:26:22 jileng Exp $ */ public class ReconnectManager { private static final Logger logger = LoggerFactory.getLogger(ReconnectManager.class); public static final ReconnectManager INSTANCE = new ReconnectManager(); private final ScheduledThreadPoolExecutor reconnectExecutor; private ReconnectManager(){ reconnectExecutor = new ScheduledThreadPoolExecutor(1, new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(); t.setName("sailfish-ReconnectManager"); t.setDaemon(true); return t; } }); reconnectExecutor.setKeepAliveTime(1, TimeUnit.MINUTES); }
// Path: sailfish-kernel/src/main/java/sailfish/remoting/channel/ExchangeChannel.java // public interface ExchangeChannel extends ExchangeChannelGroup{ // /** // * Returns a reference to itself. // */ // @Override // ExchangeChannel next(); // // /** // * Return the {@link ExchangeChannelGroup} which is the parent of this {@link ExchangeChannel}, // */ // ExchangeChannelGroup parent(); // // /** // * update this {@link ExchangeChannel} underlying {@link Channel} // * @param newChannel // * @return old {@link Channel} // */ // Channel update(Channel newChannel); // // /** // * connect to remote peer // * @returnSailfishException // * @throws SailfishException // */ // Channel doConnect() throws SailfishException; // // /** // * recover this {@link ExchangeChannel} if {@link #isAvailable()} return false // */ // void recover(); // // SocketAddress localAddress(); // SocketAddress remoteAdress(); // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/ReconnectManager.java import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sailfish.remoting.channel.ExchangeChannel; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting; /** * * @author spccold * @version $Id: ReconnectManager.java, v 0.1 2016年11月7日 下午4:26:22 jileng Exp $ */ public class ReconnectManager { private static final Logger logger = LoggerFactory.getLogger(ReconnectManager.class); public static final ReconnectManager INSTANCE = new ReconnectManager(); private final ScheduledThreadPoolExecutor reconnectExecutor; private ReconnectManager(){ reconnectExecutor = new ScheduledThreadPoolExecutor(1, new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(); t.setName("sailfish-ReconnectManager"); t.setDaemon(true); return t; } }); reconnectExecutor.setKeepAliveTime(1, TimeUnit.MINUTES); }
public void addReconnectTask(ExchangeChannel reconnectedChannel, int reconnectInterval){
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/channel/HighPerformanceChannelWriter.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/ChannelAttrKeys.java // public interface ChannelAttrKeys { // AttributeKey<HighPerformanceChannelWriter> highPerformanceWriter = AttributeKey.valueOf("sailfish.highPerformanceWriter"); // // // for idle handle and heart beat // AttributeKey<Byte> maxIdleTimeout = AttributeKey.valueOf("sailfish.maxIdleTimeout"); // AttributeKey<Long> lastReadTimeMillis = AttributeKey.valueOf("sailfish.lastReadTimeMillis"); // // // side // AttributeKey<Boolean> clientSide = AttributeKey.valueOf("sailfish.side"); // // AttributeKey<ExchangeChannelGroup> channelGroup = AttributeKey.valueOf("sailfish.channelGroup"); // AttributeKey<DefaultServer> exchangeServer = AttributeKey.valueOf("sailfish.exchangeServer"); // AttributeKey<String> uuidStr = AttributeKey.valueOf("sailfish.uuidStr"); // // interface OneTime { // // for idle handle // AttributeKey<Byte> idleTimeout = AttributeKey.valueOf("sailfish.idleTimeout"); // AttributeKey<CountDownLatch> awaitNegotiate = AttributeKey.valueOf("sailfish.awaitNegotiate"); // // AttributeKey<NegotiateConfig> channelConfig = AttributeKey.valueOf("sailfish.channelConfig"); // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/protocol/Protocol.java // public interface Protocol { // /** // * request or response direction // */ // boolean request(); // // /** // * heartbeat request/response // */ // boolean heartbeat(); // // /** // * serialize bytes data to channel // */ // void serialize(ByteBuf output) throws SailfishException; // // /** // * deserialize bytes data from channel // */ // void deserialize(ByteBuf input, int totalLength) throws SailfishException; // }
import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; import io.netty.channel.Channel; import io.netty.util.Attribute; import io.netty.util.internal.PlatformDependent; import sailfish.remoting.constants.ChannelAttrKeys; import sailfish.remoting.protocol.Protocol;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.channel; /** * <pre> * <a href="https://github.com/netty/netty/issues/1759">Optimize writeAndFlush</a> * <a href="https://github.com/stepancheg/netty-td">netty-td</a> * </pre> * * @author spccold * @version $Id: HighPerformanceChannelWriter.java, v 0.1 2016年11月30日 下午10:10:40 spccold Exp $ */ public class HighPerformanceChannelWriter { /** * task for "merge" all pending flushes */ private final WriteAndFlushTask writeAndFlushTask = new WriteAndFlushTask(this); private final AtomicInteger state = new AtomicInteger(); // lock free(See https://github.com/spccold/JCTools)
// Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/ChannelAttrKeys.java // public interface ChannelAttrKeys { // AttributeKey<HighPerformanceChannelWriter> highPerformanceWriter = AttributeKey.valueOf("sailfish.highPerformanceWriter"); // // // for idle handle and heart beat // AttributeKey<Byte> maxIdleTimeout = AttributeKey.valueOf("sailfish.maxIdleTimeout"); // AttributeKey<Long> lastReadTimeMillis = AttributeKey.valueOf("sailfish.lastReadTimeMillis"); // // // side // AttributeKey<Boolean> clientSide = AttributeKey.valueOf("sailfish.side"); // // AttributeKey<ExchangeChannelGroup> channelGroup = AttributeKey.valueOf("sailfish.channelGroup"); // AttributeKey<DefaultServer> exchangeServer = AttributeKey.valueOf("sailfish.exchangeServer"); // AttributeKey<String> uuidStr = AttributeKey.valueOf("sailfish.uuidStr"); // // interface OneTime { // // for idle handle // AttributeKey<Byte> idleTimeout = AttributeKey.valueOf("sailfish.idleTimeout"); // AttributeKey<CountDownLatch> awaitNegotiate = AttributeKey.valueOf("sailfish.awaitNegotiate"); // // AttributeKey<NegotiateConfig> channelConfig = AttributeKey.valueOf("sailfish.channelConfig"); // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/protocol/Protocol.java // public interface Protocol { // /** // * request or response direction // */ // boolean request(); // // /** // * heartbeat request/response // */ // boolean heartbeat(); // // /** // * serialize bytes data to channel // */ // void serialize(ByteBuf output) throws SailfishException; // // /** // * deserialize bytes data from channel // */ // void deserialize(ByteBuf input, int totalLength) throws SailfishException; // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/channel/HighPerformanceChannelWriter.java import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; import io.netty.channel.Channel; import io.netty.util.Attribute; import io.netty.util.internal.PlatformDependent; import sailfish.remoting.constants.ChannelAttrKeys; import sailfish.remoting.protocol.Protocol; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.channel; /** * <pre> * <a href="https://github.com/netty/netty/issues/1759">Optimize writeAndFlush</a> * <a href="https://github.com/stepancheg/netty-td">netty-td</a> * </pre> * * @author spccold * @version $Id: HighPerformanceChannelWriter.java, v 0.1 2016年11月30日 下午10:10:40 spccold Exp $ */ public class HighPerformanceChannelWriter { /** * task for "merge" all pending flushes */ private final WriteAndFlushTask writeAndFlushTask = new WriteAndFlushTask(this); private final AtomicInteger state = new AtomicInteger(); // lock free(See https://github.com/spccold/JCTools)
private final Queue<Protocol> queue = PlatformDependent.newMpscQueue();
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/channel/HighPerformanceChannelWriter.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/ChannelAttrKeys.java // public interface ChannelAttrKeys { // AttributeKey<HighPerformanceChannelWriter> highPerformanceWriter = AttributeKey.valueOf("sailfish.highPerformanceWriter"); // // // for idle handle and heart beat // AttributeKey<Byte> maxIdleTimeout = AttributeKey.valueOf("sailfish.maxIdleTimeout"); // AttributeKey<Long> lastReadTimeMillis = AttributeKey.valueOf("sailfish.lastReadTimeMillis"); // // // side // AttributeKey<Boolean> clientSide = AttributeKey.valueOf("sailfish.side"); // // AttributeKey<ExchangeChannelGroup> channelGroup = AttributeKey.valueOf("sailfish.channelGroup"); // AttributeKey<DefaultServer> exchangeServer = AttributeKey.valueOf("sailfish.exchangeServer"); // AttributeKey<String> uuidStr = AttributeKey.valueOf("sailfish.uuidStr"); // // interface OneTime { // // for idle handle // AttributeKey<Byte> idleTimeout = AttributeKey.valueOf("sailfish.idleTimeout"); // AttributeKey<CountDownLatch> awaitNegotiate = AttributeKey.valueOf("sailfish.awaitNegotiate"); // // AttributeKey<NegotiateConfig> channelConfig = AttributeKey.valueOf("sailfish.channelConfig"); // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/protocol/Protocol.java // public interface Protocol { // /** // * request or response direction // */ // boolean request(); // // /** // * heartbeat request/response // */ // boolean heartbeat(); // // /** // * serialize bytes data to channel // */ // void serialize(ByteBuf output) throws SailfishException; // // /** // * deserialize bytes data from channel // */ // void deserialize(ByteBuf input, int totalLength) throws SailfishException; // }
import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; import io.netty.channel.Channel; import io.netty.util.Attribute; import io.netty.util.internal.PlatformDependent; import sailfish.remoting.constants.ChannelAttrKeys; import sailfish.remoting.protocol.Protocol;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.channel; /** * <pre> * <a href="https://github.com/netty/netty/issues/1759">Optimize writeAndFlush</a> * <a href="https://github.com/stepancheg/netty-td">netty-td</a> * </pre> * * @author spccold * @version $Id: HighPerformanceChannelWriter.java, v 0.1 2016年11月30日 下午10:10:40 spccold Exp $ */ public class HighPerformanceChannelWriter { /** * task for "merge" all pending flushes */ private final WriteAndFlushTask writeAndFlushTask = new WriteAndFlushTask(this); private final AtomicInteger state = new AtomicInteger(); // lock free(See https://github.com/spccold/JCTools) private final Queue<Protocol> queue = PlatformDependent.newMpscQueue(); private final Channel channel; public HighPerformanceChannelWriter(Channel channel) { this.channel = channel; } public static void write(Channel channel, Protocol protocol) { final HighPerformanceChannelWriter highPerformanceWriter = getWriter(channel); highPerformanceWriter.queue.add(protocol); if (highPerformanceWriter.addTask()) { channel.eventLoop().execute(highPerformanceWriter.writeAndFlushTask); } } private static HighPerformanceChannelWriter getWriter(Channel channel) {
// Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/ChannelAttrKeys.java // public interface ChannelAttrKeys { // AttributeKey<HighPerformanceChannelWriter> highPerformanceWriter = AttributeKey.valueOf("sailfish.highPerformanceWriter"); // // // for idle handle and heart beat // AttributeKey<Byte> maxIdleTimeout = AttributeKey.valueOf("sailfish.maxIdleTimeout"); // AttributeKey<Long> lastReadTimeMillis = AttributeKey.valueOf("sailfish.lastReadTimeMillis"); // // // side // AttributeKey<Boolean> clientSide = AttributeKey.valueOf("sailfish.side"); // // AttributeKey<ExchangeChannelGroup> channelGroup = AttributeKey.valueOf("sailfish.channelGroup"); // AttributeKey<DefaultServer> exchangeServer = AttributeKey.valueOf("sailfish.exchangeServer"); // AttributeKey<String> uuidStr = AttributeKey.valueOf("sailfish.uuidStr"); // // interface OneTime { // // for idle handle // AttributeKey<Byte> idleTimeout = AttributeKey.valueOf("sailfish.idleTimeout"); // AttributeKey<CountDownLatch> awaitNegotiate = AttributeKey.valueOf("sailfish.awaitNegotiate"); // // AttributeKey<NegotiateConfig> channelConfig = AttributeKey.valueOf("sailfish.channelConfig"); // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/protocol/Protocol.java // public interface Protocol { // /** // * request or response direction // */ // boolean request(); // // /** // * heartbeat request/response // */ // boolean heartbeat(); // // /** // * serialize bytes data to channel // */ // void serialize(ByteBuf output) throws SailfishException; // // /** // * deserialize bytes data from channel // */ // void deserialize(ByteBuf input, int totalLength) throws SailfishException; // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/channel/HighPerformanceChannelWriter.java import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; import io.netty.channel.Channel; import io.netty.util.Attribute; import io.netty.util.internal.PlatformDependent; import sailfish.remoting.constants.ChannelAttrKeys; import sailfish.remoting.protocol.Protocol; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.channel; /** * <pre> * <a href="https://github.com/netty/netty/issues/1759">Optimize writeAndFlush</a> * <a href="https://github.com/stepancheg/netty-td">netty-td</a> * </pre> * * @author spccold * @version $Id: HighPerformanceChannelWriter.java, v 0.1 2016年11月30日 下午10:10:40 spccold Exp $ */ public class HighPerformanceChannelWriter { /** * task for "merge" all pending flushes */ private final WriteAndFlushTask writeAndFlushTask = new WriteAndFlushTask(this); private final AtomicInteger state = new AtomicInteger(); // lock free(See https://github.com/spccold/JCTools) private final Queue<Protocol> queue = PlatformDependent.newMpscQueue(); private final Channel channel; public HighPerformanceChannelWriter(Channel channel) { this.channel = channel; } public static void write(Channel channel, Protocol protocol) { final HighPerformanceChannelWriter highPerformanceWriter = getWriter(channel); highPerformanceWriter.queue.add(protocol); if (highPerformanceWriter.addTask()) { channel.eventLoop().execute(highPerformanceWriter.writeAndFlushTask); } } private static HighPerformanceChannelWriter getWriter(Channel channel) {
Attribute<HighPerformanceChannelWriter> attr = channel.attr(ChannelAttrKeys.highPerformanceWriter);
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/codec/RemotingDecoder.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/RemotingConstants.java // public interface RemotingConstants { // // 压缩阀值, KB // int COMPRESS_THRESHOLD = 4 * 1024; // // sailfish binary protocol magic // short SAILFISH_MAGIC = ByteBuffer.wrap("SH".getBytes()).getShort(); // // // max frame size, 8MB // int DEFAULT_PAYLOAD_LENGTH = 8 * 1024 * 1024; // // // milliseconds // int DEFAULT_CONNECT_TIMEOUT = 2000; // int DEFAULT_RECONNECT_INTERVAL = 1000; // // seconds // byte DEFAULT_IDLE_TIMEOUT = 10; // byte DEFAULT_MAX_IDLE_TIMEOUT = 3 * DEFAULT_IDLE_TIMEOUT; // // // result // byte RESULT_SUCCESS = 0; // byte RESULT_FAIL = 1; // // // channel type for read write splitting // byte WRITE_CHANNEL = 0; // byte READ_CHANNEL = 1; // // int DEFAULT_IO_THREADS = Runtime.getRuntime().availableProcessors() + 1; // int DEFAULT_EVENT_THREADS = 1; // String CLIENT_IO_THREADNAME = "sailfish-client-io"; // String CLIENT_EVENT_THREADNAME = "sailfish-client-event"; // String SERVER_IO_THREADNAME = "sailfish-server-io"; // String SERVER_EVENT_THREADNAME = "sailfish-server-event"; // String SERVER_ACCEPT_THREADNAME = "sailfish-server-accept"; // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/ExceptionCode.java // public enum ExceptionCode { // BAD_PACKAGE, // RESPONSE_TIMEOUT, // WRITE_TIMEOUT, // EXCHANGER_NOT_AVAILABLE, // UNFINISHED_REQUEST, // CHANNEL_WRITE_FAIL, // DEFAULT, // ; // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/utils/ChannelUtil.java // public class ChannelUtil { // // private static final Logger logger = LoggerFactory.getLogger(ChannelUtil.class); // // public static boolean clientSide(ChannelHandlerContext ctx) { // Attribute<Boolean> clientSideAttr = ctx.channel().attr(ChannelAttrKeys.clientSide); // return (null != clientSideAttr && null != clientSideAttr.get() && clientSideAttr.get()); // } // // public static void closeChannel(final Channel channel) { // if (null == channel) { // return; // } // channel.close().addListener(new ChannelFutureListener() { // @Override // public void operationComplete(ChannelFuture future) throws Exception { // String log = String.format( // "closeChannel: close connection to remoteAddress [%s] , localAddress [%s], ret:[%b]", // null != channel.remoteAddress() ? channel.remoteAddress().toString() : "null", // null != channel.localAddress() ? channel.localAddress().toString() : "null", // future.isSuccess()); // logger.info(log); // } // }); // } // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import sailfish.remoting.constants.RemotingConstants; import sailfish.remoting.exceptions.ExceptionCode; import sailfish.remoting.exceptions.SailfishException; import sailfish.remoting.utils.ChannelUtil;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.codec; /** * * @author spccold * @version $Id: RemotingDecoder.java, v 0.1 2016年10月15日 上午11:20:55 jileng Exp $ */ public class RemotingDecoder extends LengthFieldBasedFrameDecoder { private static final Logger logger = LoggerFactory.getLogger(RemotingDecoder.class); public RemotingDecoder() {
// Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/RemotingConstants.java // public interface RemotingConstants { // // 压缩阀值, KB // int COMPRESS_THRESHOLD = 4 * 1024; // // sailfish binary protocol magic // short SAILFISH_MAGIC = ByteBuffer.wrap("SH".getBytes()).getShort(); // // // max frame size, 8MB // int DEFAULT_PAYLOAD_LENGTH = 8 * 1024 * 1024; // // // milliseconds // int DEFAULT_CONNECT_TIMEOUT = 2000; // int DEFAULT_RECONNECT_INTERVAL = 1000; // // seconds // byte DEFAULT_IDLE_TIMEOUT = 10; // byte DEFAULT_MAX_IDLE_TIMEOUT = 3 * DEFAULT_IDLE_TIMEOUT; // // // result // byte RESULT_SUCCESS = 0; // byte RESULT_FAIL = 1; // // // channel type for read write splitting // byte WRITE_CHANNEL = 0; // byte READ_CHANNEL = 1; // // int DEFAULT_IO_THREADS = Runtime.getRuntime().availableProcessors() + 1; // int DEFAULT_EVENT_THREADS = 1; // String CLIENT_IO_THREADNAME = "sailfish-client-io"; // String CLIENT_EVENT_THREADNAME = "sailfish-client-event"; // String SERVER_IO_THREADNAME = "sailfish-server-io"; // String SERVER_EVENT_THREADNAME = "sailfish-server-event"; // String SERVER_ACCEPT_THREADNAME = "sailfish-server-accept"; // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/ExceptionCode.java // public enum ExceptionCode { // BAD_PACKAGE, // RESPONSE_TIMEOUT, // WRITE_TIMEOUT, // EXCHANGER_NOT_AVAILABLE, // UNFINISHED_REQUEST, // CHANNEL_WRITE_FAIL, // DEFAULT, // ; // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/utils/ChannelUtil.java // public class ChannelUtil { // // private static final Logger logger = LoggerFactory.getLogger(ChannelUtil.class); // // public static boolean clientSide(ChannelHandlerContext ctx) { // Attribute<Boolean> clientSideAttr = ctx.channel().attr(ChannelAttrKeys.clientSide); // return (null != clientSideAttr && null != clientSideAttr.get() && clientSideAttr.get()); // } // // public static void closeChannel(final Channel channel) { // if (null == channel) { // return; // } // channel.close().addListener(new ChannelFutureListener() { // @Override // public void operationComplete(ChannelFuture future) throws Exception { // String log = String.format( // "closeChannel: close connection to remoteAddress [%s] , localAddress [%s], ret:[%b]", // null != channel.remoteAddress() ? channel.remoteAddress().toString() : "null", // null != channel.localAddress() ? channel.localAddress().toString() : "null", // future.isSuccess()); // logger.info(log); // } // }); // } // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/codec/RemotingDecoder.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import sailfish.remoting.constants.RemotingConstants; import sailfish.remoting.exceptions.ExceptionCode; import sailfish.remoting.exceptions.SailfishException; import sailfish.remoting.utils.ChannelUtil; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.codec; /** * * @author spccold * @version $Id: RemotingDecoder.java, v 0.1 2016年10月15日 上午11:20:55 jileng Exp $ */ public class RemotingDecoder extends LengthFieldBasedFrameDecoder { private static final Logger logger = LoggerFactory.getLogger(RemotingDecoder.class); public RemotingDecoder() {
super(RemotingConstants.DEFAULT_PAYLOAD_LENGTH, 2, 4);
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/RequestControl.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/utils/ParameterChecker.java // public class ParameterChecker { // // public static <T> T checkNotNull(T reference, String hint) { // if (reference == null) { // throw new NullPointerException(hint); // } // return reference; // } // // public static String checkNotBlank(String content, String hint){ // if(StrUtils.isBlank(content)){ // throw new IllegalArgumentException(hint); // } // return content; // } // // public static int checkNotNegative(int number, String hint){ // if(number < 0){ // throw new IllegalArgumentException(hint + ": " + number + " (expected: >= 0)"); // } // return number; // } // // public static int checkPositive(int number, String hint){ // if(number <= 0){ // throw new IllegalArgumentException(hint + ": " + number + " (expected: > 0)"); // } // return number; // } // // public static short checkPositive(short number, String hint){ // if(number <= 0){ // throw new IllegalArgumentException(hint + ": " + number + " (expected: > 0)"); // } // return number; // } // // public static long checkPositive(long number, String hint){ // if(number <= 0){ // throw new IllegalArgumentException(hint + ": " + number + " (expected: > 0)"); // } // return number; // } // // public static int checkBytePositive(int number){ // if(number <= 0 || number > 0x7F){ // throw new IllegalArgumentException("number: " + number + " (expected: 0 < number <= 0x7F)"); // } // return number; // } // }
import sailfish.remoting.utils.ParameterChecker;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting; /** * * @author spccold * @version $Id: RequestControl.java, v 0.1 2016年11月1日 下午2:24:47 jileng Exp $ */ public class RequestControl { /** * response timeout or write timeout if {@code sent} is true */ private int timeout = 2000; private short opcode; private byte serializeType; private byte compressType; //wait write success or not private boolean sent; /** * {@code sent} will be ignored when {@code preferHighPerformanceWriter} is true */ private boolean preferHighPerformanceWriter; public RequestControl(){ this(false); } public RequestControl(boolean preferHighPerformanceWriter) { this.preferHighPerformanceWriter = preferHighPerformanceWriter; } public int timeout() { return timeout; } public void timeout(int timeout) {
// Path: sailfish-kernel/src/main/java/sailfish/remoting/utils/ParameterChecker.java // public class ParameterChecker { // // public static <T> T checkNotNull(T reference, String hint) { // if (reference == null) { // throw new NullPointerException(hint); // } // return reference; // } // // public static String checkNotBlank(String content, String hint){ // if(StrUtils.isBlank(content)){ // throw new IllegalArgumentException(hint); // } // return content; // } // // public static int checkNotNegative(int number, String hint){ // if(number < 0){ // throw new IllegalArgumentException(hint + ": " + number + " (expected: >= 0)"); // } // return number; // } // // public static int checkPositive(int number, String hint){ // if(number <= 0){ // throw new IllegalArgumentException(hint + ": " + number + " (expected: > 0)"); // } // return number; // } // // public static short checkPositive(short number, String hint){ // if(number <= 0){ // throw new IllegalArgumentException(hint + ": " + number + " (expected: > 0)"); // } // return number; // } // // public static long checkPositive(long number, String hint){ // if(number <= 0){ // throw new IllegalArgumentException(hint + ": " + number + " (expected: > 0)"); // } // return number; // } // // public static int checkBytePositive(int number){ // if(number <= 0 || number > 0x7F){ // throw new IllegalArgumentException("number: " + number + " (expected: 0 < number <= 0x7F)"); // } // return number; // } // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/RequestControl.java import sailfish.remoting.utils.ParameterChecker; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting; /** * * @author spccold * @version $Id: RequestControl.java, v 0.1 2016年11月1日 下午2:24:47 jileng Exp $ */ public class RequestControl { /** * response timeout or write timeout if {@code sent} is true */ private int timeout = 2000; private short opcode; private byte serializeType; private byte compressType; //wait write success or not private boolean sent; /** * {@code sent} will be ignored when {@code preferHighPerformanceWriter} is true */ private boolean preferHighPerformanceWriter; public RequestControl(){ this(false); } public RequestControl(boolean preferHighPerformanceWriter) { this.preferHighPerformanceWriter = preferHighPerformanceWriter; } public int timeout() { return timeout; } public void timeout(int timeout) {
this.timeout = ParameterChecker.checkPositive(timeout, "timeout");
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/handler/ConcreteRequestHandler.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/channel/ExchangeChannelGroup.java // public interface ExchangeChannelGroup extends Endpoint, MessageExchangePattern{ // /** // * like {@link Channel#id()}, Returns the globally unique identifier of this {@link ExchangeChannelGroup}. // */ // UUID id(); // // /** // * Return {@code true} if this {@link ExchangeChannelGroup} is available, this means that the {@link ExchangeChannelGroup} // * can receive bytes from remote peer or write bytes to remote peer // */ // boolean isAvailable(); // // /** // * Returns one of the {@link ExchangeChannel}s managed by this {@link ExchangeChannelGroup}. // */ // ExchangeChannel next() throws SailfishException; // // /** // * Return the {@link MsgHandler} of this {@link ExchangeChannelGroup} which used for process {@link ResponseProtocol} // * sent by the {@link ExchangeChannelGroup} // */ // MsgHandler<Protocol> getMsgHander(); // // /** // * Return the {@link Tracer} of this {@link ExchangeChannelGroup} which used for trace {@link ResponseProtocol} // * sent by the {@link ExchangeChannelGroup} // * @return // */ // Tracer getTracer(); // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/ChannelAttrKeys.java // public interface ChannelAttrKeys { // AttributeKey<HighPerformanceChannelWriter> highPerformanceWriter = AttributeKey.valueOf("sailfish.highPerformanceWriter"); // // // for idle handle and heart beat // AttributeKey<Byte> maxIdleTimeout = AttributeKey.valueOf("sailfish.maxIdleTimeout"); // AttributeKey<Long> lastReadTimeMillis = AttributeKey.valueOf("sailfish.lastReadTimeMillis"); // // // side // AttributeKey<Boolean> clientSide = AttributeKey.valueOf("sailfish.side"); // // AttributeKey<ExchangeChannelGroup> channelGroup = AttributeKey.valueOf("sailfish.channelGroup"); // AttributeKey<DefaultServer> exchangeServer = AttributeKey.valueOf("sailfish.exchangeServer"); // AttributeKey<String> uuidStr = AttributeKey.valueOf("sailfish.uuidStr"); // // interface OneTime { // // for idle handle // AttributeKey<Byte> idleTimeout = AttributeKey.valueOf("sailfish.idleTimeout"); // AttributeKey<CountDownLatch> awaitNegotiate = AttributeKey.valueOf("sailfish.awaitNegotiate"); // // AttributeKey<NegotiateConfig> channelConfig = AttributeKey.valueOf("sailfish.channelConfig"); // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/protocol/Protocol.java // public interface Protocol { // /** // * request or response direction // */ // boolean request(); // // /** // * heartbeat request/response // */ // boolean heartbeat(); // // /** // * serialize bytes data to channel // */ // void serialize(ByteBuf output) throws SailfishException; // // /** // * deserialize bytes data from channel // */ // void deserialize(ByteBuf input, int totalLength) throws SailfishException; // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/utils/ChannelUtil.java // public class ChannelUtil { // // private static final Logger logger = LoggerFactory.getLogger(ChannelUtil.class); // // public static boolean clientSide(ChannelHandlerContext ctx) { // Attribute<Boolean> clientSideAttr = ctx.channel().attr(ChannelAttrKeys.clientSide); // return (null != clientSideAttr && null != clientSideAttr.get() && clientSideAttr.get()); // } // // public static void closeChannel(final Channel channel) { // if (null == channel) { // return; // } // channel.close().addListener(new ChannelFutureListener() { // @Override // public void operationComplete(ChannelFuture future) throws Exception { // String log = String.format( // "closeChannel: close connection to remoteAddress [%s] , localAddress [%s], ret:[%b]", // null != channel.remoteAddress() ? channel.remoteAddress().toString() : "null", // null != channel.localAddress() ? channel.localAddress().toString() : "null", // future.isSuccess()); // logger.info(log); // } // }); // } // }
import io.netty.channel.ChannelHandlerContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.channel.ChannelHandler; import io.netty.channel.SimpleChannelInboundHandler; import sailfish.remoting.channel.ExchangeChannelGroup; import sailfish.remoting.constants.ChannelAttrKeys; import sailfish.remoting.protocol.Protocol; import sailfish.remoting.utils.ChannelUtil;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.handler; /** * * @author spccold * @version $Id: ConcreteRequestHandler.java, v 0.1 2016年11月1日 下午2:17:59 jileng Exp $ */ @ChannelHandler.Sharable public class ConcreteRequestHandler extends SimpleChannelInboundHandler<Protocol> { private static final Logger logger = LoggerFactory.getLogger(ConcreteRequestHandler.class); public static final ConcreteRequestHandler INSTANCE = new ConcreteRequestHandler(); private ConcreteRequestHandler() {} @Override protected void channelRead0(ChannelHandlerContext ctx, Protocol msg) throws Exception {
// Path: sailfish-kernel/src/main/java/sailfish/remoting/channel/ExchangeChannelGroup.java // public interface ExchangeChannelGroup extends Endpoint, MessageExchangePattern{ // /** // * like {@link Channel#id()}, Returns the globally unique identifier of this {@link ExchangeChannelGroup}. // */ // UUID id(); // // /** // * Return {@code true} if this {@link ExchangeChannelGroup} is available, this means that the {@link ExchangeChannelGroup} // * can receive bytes from remote peer or write bytes to remote peer // */ // boolean isAvailable(); // // /** // * Returns one of the {@link ExchangeChannel}s managed by this {@link ExchangeChannelGroup}. // */ // ExchangeChannel next() throws SailfishException; // // /** // * Return the {@link MsgHandler} of this {@link ExchangeChannelGroup} which used for process {@link ResponseProtocol} // * sent by the {@link ExchangeChannelGroup} // */ // MsgHandler<Protocol> getMsgHander(); // // /** // * Return the {@link Tracer} of this {@link ExchangeChannelGroup} which used for trace {@link ResponseProtocol} // * sent by the {@link ExchangeChannelGroup} // * @return // */ // Tracer getTracer(); // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/ChannelAttrKeys.java // public interface ChannelAttrKeys { // AttributeKey<HighPerformanceChannelWriter> highPerformanceWriter = AttributeKey.valueOf("sailfish.highPerformanceWriter"); // // // for idle handle and heart beat // AttributeKey<Byte> maxIdleTimeout = AttributeKey.valueOf("sailfish.maxIdleTimeout"); // AttributeKey<Long> lastReadTimeMillis = AttributeKey.valueOf("sailfish.lastReadTimeMillis"); // // // side // AttributeKey<Boolean> clientSide = AttributeKey.valueOf("sailfish.side"); // // AttributeKey<ExchangeChannelGroup> channelGroup = AttributeKey.valueOf("sailfish.channelGroup"); // AttributeKey<DefaultServer> exchangeServer = AttributeKey.valueOf("sailfish.exchangeServer"); // AttributeKey<String> uuidStr = AttributeKey.valueOf("sailfish.uuidStr"); // // interface OneTime { // // for idle handle // AttributeKey<Byte> idleTimeout = AttributeKey.valueOf("sailfish.idleTimeout"); // AttributeKey<CountDownLatch> awaitNegotiate = AttributeKey.valueOf("sailfish.awaitNegotiate"); // // AttributeKey<NegotiateConfig> channelConfig = AttributeKey.valueOf("sailfish.channelConfig"); // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/protocol/Protocol.java // public interface Protocol { // /** // * request or response direction // */ // boolean request(); // // /** // * heartbeat request/response // */ // boolean heartbeat(); // // /** // * serialize bytes data to channel // */ // void serialize(ByteBuf output) throws SailfishException; // // /** // * deserialize bytes data from channel // */ // void deserialize(ByteBuf input, int totalLength) throws SailfishException; // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/utils/ChannelUtil.java // public class ChannelUtil { // // private static final Logger logger = LoggerFactory.getLogger(ChannelUtil.class); // // public static boolean clientSide(ChannelHandlerContext ctx) { // Attribute<Boolean> clientSideAttr = ctx.channel().attr(ChannelAttrKeys.clientSide); // return (null != clientSideAttr && null != clientSideAttr.get() && clientSideAttr.get()); // } // // public static void closeChannel(final Channel channel) { // if (null == channel) { // return; // } // channel.close().addListener(new ChannelFutureListener() { // @Override // public void operationComplete(ChannelFuture future) throws Exception { // String log = String.format( // "closeChannel: close connection to remoteAddress [%s] , localAddress [%s], ret:[%b]", // null != channel.remoteAddress() ? channel.remoteAddress().toString() : "null", // null != channel.localAddress() ? channel.localAddress().toString() : "null", // future.isSuccess()); // logger.info(log); // } // }); // } // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/handler/ConcreteRequestHandler.java import io.netty.channel.ChannelHandlerContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.channel.ChannelHandler; import io.netty.channel.SimpleChannelInboundHandler; import sailfish.remoting.channel.ExchangeChannelGroup; import sailfish.remoting.constants.ChannelAttrKeys; import sailfish.remoting.protocol.Protocol; import sailfish.remoting.utils.ChannelUtil; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.handler; /** * * @author spccold * @version $Id: ConcreteRequestHandler.java, v 0.1 2016年11月1日 下午2:17:59 jileng Exp $ */ @ChannelHandler.Sharable public class ConcreteRequestHandler extends SimpleChannelInboundHandler<Protocol> { private static final Logger logger = LoggerFactory.getLogger(ConcreteRequestHandler.class); public static final ConcreteRequestHandler INSTANCE = new ConcreteRequestHandler(); private ConcreteRequestHandler() {} @Override protected void channelRead0(ChannelHandlerContext ctx, Protocol msg) throws Exception {
ExchangeChannelGroup channelGroup = ctx.channel().attr(ChannelAttrKeys.channelGroup).get();
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/handler/ConcreteRequestHandler.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/channel/ExchangeChannelGroup.java // public interface ExchangeChannelGroup extends Endpoint, MessageExchangePattern{ // /** // * like {@link Channel#id()}, Returns the globally unique identifier of this {@link ExchangeChannelGroup}. // */ // UUID id(); // // /** // * Return {@code true} if this {@link ExchangeChannelGroup} is available, this means that the {@link ExchangeChannelGroup} // * can receive bytes from remote peer or write bytes to remote peer // */ // boolean isAvailable(); // // /** // * Returns one of the {@link ExchangeChannel}s managed by this {@link ExchangeChannelGroup}. // */ // ExchangeChannel next() throws SailfishException; // // /** // * Return the {@link MsgHandler} of this {@link ExchangeChannelGroup} which used for process {@link ResponseProtocol} // * sent by the {@link ExchangeChannelGroup} // */ // MsgHandler<Protocol> getMsgHander(); // // /** // * Return the {@link Tracer} of this {@link ExchangeChannelGroup} which used for trace {@link ResponseProtocol} // * sent by the {@link ExchangeChannelGroup} // * @return // */ // Tracer getTracer(); // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/ChannelAttrKeys.java // public interface ChannelAttrKeys { // AttributeKey<HighPerformanceChannelWriter> highPerformanceWriter = AttributeKey.valueOf("sailfish.highPerformanceWriter"); // // // for idle handle and heart beat // AttributeKey<Byte> maxIdleTimeout = AttributeKey.valueOf("sailfish.maxIdleTimeout"); // AttributeKey<Long> lastReadTimeMillis = AttributeKey.valueOf("sailfish.lastReadTimeMillis"); // // // side // AttributeKey<Boolean> clientSide = AttributeKey.valueOf("sailfish.side"); // // AttributeKey<ExchangeChannelGroup> channelGroup = AttributeKey.valueOf("sailfish.channelGroup"); // AttributeKey<DefaultServer> exchangeServer = AttributeKey.valueOf("sailfish.exchangeServer"); // AttributeKey<String> uuidStr = AttributeKey.valueOf("sailfish.uuidStr"); // // interface OneTime { // // for idle handle // AttributeKey<Byte> idleTimeout = AttributeKey.valueOf("sailfish.idleTimeout"); // AttributeKey<CountDownLatch> awaitNegotiate = AttributeKey.valueOf("sailfish.awaitNegotiate"); // // AttributeKey<NegotiateConfig> channelConfig = AttributeKey.valueOf("sailfish.channelConfig"); // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/protocol/Protocol.java // public interface Protocol { // /** // * request or response direction // */ // boolean request(); // // /** // * heartbeat request/response // */ // boolean heartbeat(); // // /** // * serialize bytes data to channel // */ // void serialize(ByteBuf output) throws SailfishException; // // /** // * deserialize bytes data from channel // */ // void deserialize(ByteBuf input, int totalLength) throws SailfishException; // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/utils/ChannelUtil.java // public class ChannelUtil { // // private static final Logger logger = LoggerFactory.getLogger(ChannelUtil.class); // // public static boolean clientSide(ChannelHandlerContext ctx) { // Attribute<Boolean> clientSideAttr = ctx.channel().attr(ChannelAttrKeys.clientSide); // return (null != clientSideAttr && null != clientSideAttr.get() && clientSideAttr.get()); // } // // public static void closeChannel(final Channel channel) { // if (null == channel) { // return; // } // channel.close().addListener(new ChannelFutureListener() { // @Override // public void operationComplete(ChannelFuture future) throws Exception { // String log = String.format( // "closeChannel: close connection to remoteAddress [%s] , localAddress [%s], ret:[%b]", // null != channel.remoteAddress() ? channel.remoteAddress().toString() : "null", // null != channel.localAddress() ? channel.localAddress().toString() : "null", // future.isSuccess()); // logger.info(log); // } // }); // } // }
import io.netty.channel.ChannelHandlerContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.channel.ChannelHandler; import io.netty.channel.SimpleChannelInboundHandler; import sailfish.remoting.channel.ExchangeChannelGroup; import sailfish.remoting.constants.ChannelAttrKeys; import sailfish.remoting.protocol.Protocol; import sailfish.remoting.utils.ChannelUtil;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.handler; /** * * @author spccold * @version $Id: ConcreteRequestHandler.java, v 0.1 2016年11月1日 下午2:17:59 jileng Exp $ */ @ChannelHandler.Sharable public class ConcreteRequestHandler extends SimpleChannelInboundHandler<Protocol> { private static final Logger logger = LoggerFactory.getLogger(ConcreteRequestHandler.class); public static final ConcreteRequestHandler INSTANCE = new ConcreteRequestHandler(); private ConcreteRequestHandler() {} @Override protected void channelRead0(ChannelHandlerContext ctx, Protocol msg) throws Exception {
// Path: sailfish-kernel/src/main/java/sailfish/remoting/channel/ExchangeChannelGroup.java // public interface ExchangeChannelGroup extends Endpoint, MessageExchangePattern{ // /** // * like {@link Channel#id()}, Returns the globally unique identifier of this {@link ExchangeChannelGroup}. // */ // UUID id(); // // /** // * Return {@code true} if this {@link ExchangeChannelGroup} is available, this means that the {@link ExchangeChannelGroup} // * can receive bytes from remote peer or write bytes to remote peer // */ // boolean isAvailable(); // // /** // * Returns one of the {@link ExchangeChannel}s managed by this {@link ExchangeChannelGroup}. // */ // ExchangeChannel next() throws SailfishException; // // /** // * Return the {@link MsgHandler} of this {@link ExchangeChannelGroup} which used for process {@link ResponseProtocol} // * sent by the {@link ExchangeChannelGroup} // */ // MsgHandler<Protocol> getMsgHander(); // // /** // * Return the {@link Tracer} of this {@link ExchangeChannelGroup} which used for trace {@link ResponseProtocol} // * sent by the {@link ExchangeChannelGroup} // * @return // */ // Tracer getTracer(); // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/ChannelAttrKeys.java // public interface ChannelAttrKeys { // AttributeKey<HighPerformanceChannelWriter> highPerformanceWriter = AttributeKey.valueOf("sailfish.highPerformanceWriter"); // // // for idle handle and heart beat // AttributeKey<Byte> maxIdleTimeout = AttributeKey.valueOf("sailfish.maxIdleTimeout"); // AttributeKey<Long> lastReadTimeMillis = AttributeKey.valueOf("sailfish.lastReadTimeMillis"); // // // side // AttributeKey<Boolean> clientSide = AttributeKey.valueOf("sailfish.side"); // // AttributeKey<ExchangeChannelGroup> channelGroup = AttributeKey.valueOf("sailfish.channelGroup"); // AttributeKey<DefaultServer> exchangeServer = AttributeKey.valueOf("sailfish.exchangeServer"); // AttributeKey<String> uuidStr = AttributeKey.valueOf("sailfish.uuidStr"); // // interface OneTime { // // for idle handle // AttributeKey<Byte> idleTimeout = AttributeKey.valueOf("sailfish.idleTimeout"); // AttributeKey<CountDownLatch> awaitNegotiate = AttributeKey.valueOf("sailfish.awaitNegotiate"); // // AttributeKey<NegotiateConfig> channelConfig = AttributeKey.valueOf("sailfish.channelConfig"); // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/protocol/Protocol.java // public interface Protocol { // /** // * request or response direction // */ // boolean request(); // // /** // * heartbeat request/response // */ // boolean heartbeat(); // // /** // * serialize bytes data to channel // */ // void serialize(ByteBuf output) throws SailfishException; // // /** // * deserialize bytes data from channel // */ // void deserialize(ByteBuf input, int totalLength) throws SailfishException; // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/utils/ChannelUtil.java // public class ChannelUtil { // // private static final Logger logger = LoggerFactory.getLogger(ChannelUtil.class); // // public static boolean clientSide(ChannelHandlerContext ctx) { // Attribute<Boolean> clientSideAttr = ctx.channel().attr(ChannelAttrKeys.clientSide); // return (null != clientSideAttr && null != clientSideAttr.get() && clientSideAttr.get()); // } // // public static void closeChannel(final Channel channel) { // if (null == channel) { // return; // } // channel.close().addListener(new ChannelFutureListener() { // @Override // public void operationComplete(ChannelFuture future) throws Exception { // String log = String.format( // "closeChannel: close connection to remoteAddress [%s] , localAddress [%s], ret:[%b]", // null != channel.remoteAddress() ? channel.remoteAddress().toString() : "null", // null != channel.localAddress() ? channel.localAddress().toString() : "null", // future.isSuccess()); // logger.info(log); // } // }); // } // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/handler/ConcreteRequestHandler.java import io.netty.channel.ChannelHandlerContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.channel.ChannelHandler; import io.netty.channel.SimpleChannelInboundHandler; import sailfish.remoting.channel.ExchangeChannelGroup; import sailfish.remoting.constants.ChannelAttrKeys; import sailfish.remoting.protocol.Protocol; import sailfish.remoting.utils.ChannelUtil; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.handler; /** * * @author spccold * @version $Id: ConcreteRequestHandler.java, v 0.1 2016年11月1日 下午2:17:59 jileng Exp $ */ @ChannelHandler.Sharable public class ConcreteRequestHandler extends SimpleChannelInboundHandler<Protocol> { private static final Logger logger = LoggerFactory.getLogger(ConcreteRequestHandler.class); public static final ConcreteRequestHandler INSTANCE = new ConcreteRequestHandler(); private ConcreteRequestHandler() {} @Override protected void channelRead0(ChannelHandlerContext ctx, Protocol msg) throws Exception {
ExchangeChannelGroup channelGroup = ctx.channel().attr(ChannelAttrKeys.channelGroup).get();
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/handler/ConcreteRequestHandler.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/channel/ExchangeChannelGroup.java // public interface ExchangeChannelGroup extends Endpoint, MessageExchangePattern{ // /** // * like {@link Channel#id()}, Returns the globally unique identifier of this {@link ExchangeChannelGroup}. // */ // UUID id(); // // /** // * Return {@code true} if this {@link ExchangeChannelGroup} is available, this means that the {@link ExchangeChannelGroup} // * can receive bytes from remote peer or write bytes to remote peer // */ // boolean isAvailable(); // // /** // * Returns one of the {@link ExchangeChannel}s managed by this {@link ExchangeChannelGroup}. // */ // ExchangeChannel next() throws SailfishException; // // /** // * Return the {@link MsgHandler} of this {@link ExchangeChannelGroup} which used for process {@link ResponseProtocol} // * sent by the {@link ExchangeChannelGroup} // */ // MsgHandler<Protocol> getMsgHander(); // // /** // * Return the {@link Tracer} of this {@link ExchangeChannelGroup} which used for trace {@link ResponseProtocol} // * sent by the {@link ExchangeChannelGroup} // * @return // */ // Tracer getTracer(); // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/ChannelAttrKeys.java // public interface ChannelAttrKeys { // AttributeKey<HighPerformanceChannelWriter> highPerformanceWriter = AttributeKey.valueOf("sailfish.highPerformanceWriter"); // // // for idle handle and heart beat // AttributeKey<Byte> maxIdleTimeout = AttributeKey.valueOf("sailfish.maxIdleTimeout"); // AttributeKey<Long> lastReadTimeMillis = AttributeKey.valueOf("sailfish.lastReadTimeMillis"); // // // side // AttributeKey<Boolean> clientSide = AttributeKey.valueOf("sailfish.side"); // // AttributeKey<ExchangeChannelGroup> channelGroup = AttributeKey.valueOf("sailfish.channelGroup"); // AttributeKey<DefaultServer> exchangeServer = AttributeKey.valueOf("sailfish.exchangeServer"); // AttributeKey<String> uuidStr = AttributeKey.valueOf("sailfish.uuidStr"); // // interface OneTime { // // for idle handle // AttributeKey<Byte> idleTimeout = AttributeKey.valueOf("sailfish.idleTimeout"); // AttributeKey<CountDownLatch> awaitNegotiate = AttributeKey.valueOf("sailfish.awaitNegotiate"); // // AttributeKey<NegotiateConfig> channelConfig = AttributeKey.valueOf("sailfish.channelConfig"); // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/protocol/Protocol.java // public interface Protocol { // /** // * request or response direction // */ // boolean request(); // // /** // * heartbeat request/response // */ // boolean heartbeat(); // // /** // * serialize bytes data to channel // */ // void serialize(ByteBuf output) throws SailfishException; // // /** // * deserialize bytes data from channel // */ // void deserialize(ByteBuf input, int totalLength) throws SailfishException; // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/utils/ChannelUtil.java // public class ChannelUtil { // // private static final Logger logger = LoggerFactory.getLogger(ChannelUtil.class); // // public static boolean clientSide(ChannelHandlerContext ctx) { // Attribute<Boolean> clientSideAttr = ctx.channel().attr(ChannelAttrKeys.clientSide); // return (null != clientSideAttr && null != clientSideAttr.get() && clientSideAttr.get()); // } // // public static void closeChannel(final Channel channel) { // if (null == channel) { // return; // } // channel.close().addListener(new ChannelFutureListener() { // @Override // public void operationComplete(ChannelFuture future) throws Exception { // String log = String.format( // "closeChannel: close connection to remoteAddress [%s] , localAddress [%s], ret:[%b]", // null != channel.remoteAddress() ? channel.remoteAddress().toString() : "null", // null != channel.localAddress() ? channel.localAddress().toString() : "null", // future.isSuccess()); // logger.info(log); // } // }); // } // }
import io.netty.channel.ChannelHandlerContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.channel.ChannelHandler; import io.netty.channel.SimpleChannelInboundHandler; import sailfish.remoting.channel.ExchangeChannelGroup; import sailfish.remoting.constants.ChannelAttrKeys; import sailfish.remoting.protocol.Protocol; import sailfish.remoting.utils.ChannelUtil;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.handler; /** * * @author spccold * @version $Id: ConcreteRequestHandler.java, v 0.1 2016年11月1日 下午2:17:59 jileng Exp $ */ @ChannelHandler.Sharable public class ConcreteRequestHandler extends SimpleChannelInboundHandler<Protocol> { private static final Logger logger = LoggerFactory.getLogger(ConcreteRequestHandler.class); public static final ConcreteRequestHandler INSTANCE = new ConcreteRequestHandler(); private ConcreteRequestHandler() {} @Override protected void channelRead0(ChannelHandlerContext ctx, Protocol msg) throws Exception { ExchangeChannelGroup channelGroup = ctx.channel().attr(ChannelAttrKeys.channelGroup).get(); if(null != channelGroup){ channelGroup.getMsgHander().handle(channelGroup, msg); }else{
// Path: sailfish-kernel/src/main/java/sailfish/remoting/channel/ExchangeChannelGroup.java // public interface ExchangeChannelGroup extends Endpoint, MessageExchangePattern{ // /** // * like {@link Channel#id()}, Returns the globally unique identifier of this {@link ExchangeChannelGroup}. // */ // UUID id(); // // /** // * Return {@code true} if this {@link ExchangeChannelGroup} is available, this means that the {@link ExchangeChannelGroup} // * can receive bytes from remote peer or write bytes to remote peer // */ // boolean isAvailable(); // // /** // * Returns one of the {@link ExchangeChannel}s managed by this {@link ExchangeChannelGroup}. // */ // ExchangeChannel next() throws SailfishException; // // /** // * Return the {@link MsgHandler} of this {@link ExchangeChannelGroup} which used for process {@link ResponseProtocol} // * sent by the {@link ExchangeChannelGroup} // */ // MsgHandler<Protocol> getMsgHander(); // // /** // * Return the {@link Tracer} of this {@link ExchangeChannelGroup} which used for trace {@link ResponseProtocol} // * sent by the {@link ExchangeChannelGroup} // * @return // */ // Tracer getTracer(); // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/ChannelAttrKeys.java // public interface ChannelAttrKeys { // AttributeKey<HighPerformanceChannelWriter> highPerformanceWriter = AttributeKey.valueOf("sailfish.highPerformanceWriter"); // // // for idle handle and heart beat // AttributeKey<Byte> maxIdleTimeout = AttributeKey.valueOf("sailfish.maxIdleTimeout"); // AttributeKey<Long> lastReadTimeMillis = AttributeKey.valueOf("sailfish.lastReadTimeMillis"); // // // side // AttributeKey<Boolean> clientSide = AttributeKey.valueOf("sailfish.side"); // // AttributeKey<ExchangeChannelGroup> channelGroup = AttributeKey.valueOf("sailfish.channelGroup"); // AttributeKey<DefaultServer> exchangeServer = AttributeKey.valueOf("sailfish.exchangeServer"); // AttributeKey<String> uuidStr = AttributeKey.valueOf("sailfish.uuidStr"); // // interface OneTime { // // for idle handle // AttributeKey<Byte> idleTimeout = AttributeKey.valueOf("sailfish.idleTimeout"); // AttributeKey<CountDownLatch> awaitNegotiate = AttributeKey.valueOf("sailfish.awaitNegotiate"); // // AttributeKey<NegotiateConfig> channelConfig = AttributeKey.valueOf("sailfish.channelConfig"); // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/protocol/Protocol.java // public interface Protocol { // /** // * request or response direction // */ // boolean request(); // // /** // * heartbeat request/response // */ // boolean heartbeat(); // // /** // * serialize bytes data to channel // */ // void serialize(ByteBuf output) throws SailfishException; // // /** // * deserialize bytes data from channel // */ // void deserialize(ByteBuf input, int totalLength) throws SailfishException; // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/utils/ChannelUtil.java // public class ChannelUtil { // // private static final Logger logger = LoggerFactory.getLogger(ChannelUtil.class); // // public static boolean clientSide(ChannelHandlerContext ctx) { // Attribute<Boolean> clientSideAttr = ctx.channel().attr(ChannelAttrKeys.clientSide); // return (null != clientSideAttr && null != clientSideAttr.get() && clientSideAttr.get()); // } // // public static void closeChannel(final Channel channel) { // if (null == channel) { // return; // } // channel.close().addListener(new ChannelFutureListener() { // @Override // public void operationComplete(ChannelFuture future) throws Exception { // String log = String.format( // "closeChannel: close connection to remoteAddress [%s] , localAddress [%s], ret:[%b]", // null != channel.remoteAddress() ? channel.remoteAddress().toString() : "null", // null != channel.localAddress() ? channel.localAddress().toString() : "null", // future.isSuccess()); // logger.info(log); // } // }); // } // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/handler/ConcreteRequestHandler.java import io.netty.channel.ChannelHandlerContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.channel.ChannelHandler; import io.netty.channel.SimpleChannelInboundHandler; import sailfish.remoting.channel.ExchangeChannelGroup; import sailfish.remoting.constants.ChannelAttrKeys; import sailfish.remoting.protocol.Protocol; import sailfish.remoting.utils.ChannelUtil; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.handler; /** * * @author spccold * @version $Id: ConcreteRequestHandler.java, v 0.1 2016年11月1日 下午2:17:59 jileng Exp $ */ @ChannelHandler.Sharable public class ConcreteRequestHandler extends SimpleChannelInboundHandler<Protocol> { private static final Logger logger = LoggerFactory.getLogger(ConcreteRequestHandler.class); public static final ConcreteRequestHandler INSTANCE = new ConcreteRequestHandler(); private ConcreteRequestHandler() {} @Override protected void channelRead0(ChannelHandlerContext ctx, Protocol msg) throws Exception { ExchangeChannelGroup channelGroup = ctx.channel().attr(ChannelAttrKeys.channelGroup).get(); if(null != channelGroup){ channelGroup.getMsgHander().handle(channelGroup, msg); }else{
logger.warn("channelGroup not exist, side[{}], protocol[{}]", ChannelUtil.clientSide(ctx) ? "client" : "server", msg);
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/eventgroup/ServerEventGroup.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/RemotingConstants.java // public interface RemotingConstants { // // 压缩阀值, KB // int COMPRESS_THRESHOLD = 4 * 1024; // // sailfish binary protocol magic // short SAILFISH_MAGIC = ByteBuffer.wrap("SH".getBytes()).getShort(); // // // max frame size, 8MB // int DEFAULT_PAYLOAD_LENGTH = 8 * 1024 * 1024; // // // milliseconds // int DEFAULT_CONNECT_TIMEOUT = 2000; // int DEFAULT_RECONNECT_INTERVAL = 1000; // // seconds // byte DEFAULT_IDLE_TIMEOUT = 10; // byte DEFAULT_MAX_IDLE_TIMEOUT = 3 * DEFAULT_IDLE_TIMEOUT; // // // result // byte RESULT_SUCCESS = 0; // byte RESULT_FAIL = 1; // // // channel type for read write splitting // byte WRITE_CHANNEL = 0; // byte READ_CHANNEL = 1; // // int DEFAULT_IO_THREADS = Runtime.getRuntime().availableProcessors() + 1; // int DEFAULT_EVENT_THREADS = 1; // String CLIENT_IO_THREADNAME = "sailfish-client-io"; // String CLIENT_EVENT_THREADNAME = "sailfish-client-event"; // String SERVER_IO_THREADNAME = "sailfish-server-io"; // String SERVER_EVENT_THREADNAME = "sailfish-server-event"; // String SERVER_ACCEPT_THREADNAME = "sailfish-server-accept"; // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.util.internal.SystemPropertyUtil; import sailfish.remoting.constants.RemotingConstants;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.eventgroup; /** * @author spccold * @version $Id: ServerEventGroup.java, v 0.1 2016年11月20日 下午7:29:27 spccold Exp * $ */ public class ServerEventGroup extends AbstractReusedEventGroup { public static final Logger logger = LoggerFactory.getLogger(ServerEventGroup.class); private static final int IO_THREADS; private static final int EVENT_THREADS; public static final ServerEventGroup INSTANCE; static { IO_THREADS = Math.max(1,
// Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/RemotingConstants.java // public interface RemotingConstants { // // 压缩阀值, KB // int COMPRESS_THRESHOLD = 4 * 1024; // // sailfish binary protocol magic // short SAILFISH_MAGIC = ByteBuffer.wrap("SH".getBytes()).getShort(); // // // max frame size, 8MB // int DEFAULT_PAYLOAD_LENGTH = 8 * 1024 * 1024; // // // milliseconds // int DEFAULT_CONNECT_TIMEOUT = 2000; // int DEFAULT_RECONNECT_INTERVAL = 1000; // // seconds // byte DEFAULT_IDLE_TIMEOUT = 10; // byte DEFAULT_MAX_IDLE_TIMEOUT = 3 * DEFAULT_IDLE_TIMEOUT; // // // result // byte RESULT_SUCCESS = 0; // byte RESULT_FAIL = 1; // // // channel type for read write splitting // byte WRITE_CHANNEL = 0; // byte READ_CHANNEL = 1; // // int DEFAULT_IO_THREADS = Runtime.getRuntime().availableProcessors() + 1; // int DEFAULT_EVENT_THREADS = 1; // String CLIENT_IO_THREADNAME = "sailfish-client-io"; // String CLIENT_EVENT_THREADNAME = "sailfish-client-event"; // String SERVER_IO_THREADNAME = "sailfish-server-io"; // String SERVER_EVENT_THREADNAME = "sailfish-server-event"; // String SERVER_ACCEPT_THREADNAME = "sailfish-server-accept"; // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/eventgroup/ServerEventGroup.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.util.internal.SystemPropertyUtil; import sailfish.remoting.constants.RemotingConstants; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.eventgroup; /** * @author spccold * @version $Id: ServerEventGroup.java, v 0.1 2016年11月20日 下午7:29:27 spccold Exp * $ */ public class ServerEventGroup extends AbstractReusedEventGroup { public static final Logger logger = LoggerFactory.getLogger(ServerEventGroup.class); private static final int IO_THREADS; private static final int EVENT_THREADS; public static final ServerEventGroup INSTANCE; static { IO_THREADS = Math.max(1,
SystemPropertyUtil.getInt("sailfish.remoting.server.ioThreads", RemotingConstants.DEFAULT_IO_THREADS));
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/channel/LazyExchangeChannel.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/RequestControl.java // public class RequestControl { // /** // * response timeout or write timeout if {@code sent} is true // */ // private int timeout = 2000; // private short opcode; // private byte serializeType; // private byte compressType; // //wait write success or not // private boolean sent; // // /** // * {@code sent} will be ignored when {@code preferHighPerformanceWriter} is true // */ // private boolean preferHighPerformanceWriter; // // public RequestControl(){ // this(false); // } // public RequestControl(boolean preferHighPerformanceWriter) { // this.preferHighPerformanceWriter = preferHighPerformanceWriter; // } // // public int timeout() { // return timeout; // } // // public void timeout(int timeout) { // this.timeout = ParameterChecker.checkPositive(timeout, "timeout"); // } // // public short opcode() { // return opcode; // } // // public void opcode(short opcode) { // this.opcode = opcode; // } // // public byte serializeType() { // return serializeType; // } // // public void serializeType(byte serializeType) { // this.serializeType = serializeType; // } // // public byte compressType() { // return compressType; // } // // public void compressType(byte compressType) { // this.compressType = compressType; // } // // public boolean sent() { // return sent; // } // // public void sent(boolean sent) { // this.sent = sent; // } // // public boolean preferHighPerformanceWriter(){ // return preferHighPerformanceWriter; // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/ResponseCallback.java // public interface ResponseCallback<T> { // /** // * should take advantage of {@link FastThreadLocalThread} with {@link DefaultThreadFactory} // */ // Executor getExecutor(); // // void handleResponse(T resp); // void handleException(Exception cause); // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/future/ResponseFuture.java // public interface ResponseFuture<T>{ // void putResponse(T resp, byte result, SailfishException cause); // boolean isDone(); // void setCallback(ResponseCallback<T> callback, int timeout); // T get() throws SailfishException, InterruptedException; // T get(long timeout, TimeUnit unit) throws SailfishException, InterruptedException; // }
import io.netty.bootstrap.Bootstrap; import sailfish.remoting.RequestControl; import sailfish.remoting.ResponseCallback; import sailfish.remoting.exceptions.SailfishException; import sailfish.remoting.future.ResponseFuture;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.channel; /** * @author spccold * @version $Id: LazyExchangeChannel.java, v 0.1 2016年11月21日 下午11:18:11 spccold Exp $ */ public final class LazyExchangeChannel extends SingleConnctionExchangeChannel { private volatile boolean lazyWithOutInit = true; LazyExchangeChannel(Bootstrap bootstrap, ExchangeChannelGroup parent, int reconnectInterval)
// Path: sailfish-kernel/src/main/java/sailfish/remoting/RequestControl.java // public class RequestControl { // /** // * response timeout or write timeout if {@code sent} is true // */ // private int timeout = 2000; // private short opcode; // private byte serializeType; // private byte compressType; // //wait write success or not // private boolean sent; // // /** // * {@code sent} will be ignored when {@code preferHighPerformanceWriter} is true // */ // private boolean preferHighPerformanceWriter; // // public RequestControl(){ // this(false); // } // public RequestControl(boolean preferHighPerformanceWriter) { // this.preferHighPerformanceWriter = preferHighPerformanceWriter; // } // // public int timeout() { // return timeout; // } // // public void timeout(int timeout) { // this.timeout = ParameterChecker.checkPositive(timeout, "timeout"); // } // // public short opcode() { // return opcode; // } // // public void opcode(short opcode) { // this.opcode = opcode; // } // // public byte serializeType() { // return serializeType; // } // // public void serializeType(byte serializeType) { // this.serializeType = serializeType; // } // // public byte compressType() { // return compressType; // } // // public void compressType(byte compressType) { // this.compressType = compressType; // } // // public boolean sent() { // return sent; // } // // public void sent(boolean sent) { // this.sent = sent; // } // // public boolean preferHighPerformanceWriter(){ // return preferHighPerformanceWriter; // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/ResponseCallback.java // public interface ResponseCallback<T> { // /** // * should take advantage of {@link FastThreadLocalThread} with {@link DefaultThreadFactory} // */ // Executor getExecutor(); // // void handleResponse(T resp); // void handleException(Exception cause); // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/future/ResponseFuture.java // public interface ResponseFuture<T>{ // void putResponse(T resp, byte result, SailfishException cause); // boolean isDone(); // void setCallback(ResponseCallback<T> callback, int timeout); // T get() throws SailfishException, InterruptedException; // T get(long timeout, TimeUnit unit) throws SailfishException, InterruptedException; // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/channel/LazyExchangeChannel.java import io.netty.bootstrap.Bootstrap; import sailfish.remoting.RequestControl; import sailfish.remoting.ResponseCallback; import sailfish.remoting.exceptions.SailfishException; import sailfish.remoting.future.ResponseFuture; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.channel; /** * @author spccold * @version $Id: LazyExchangeChannel.java, v 0.1 2016年11月21日 下午11:18:11 spccold Exp $ */ public final class LazyExchangeChannel extends SingleConnctionExchangeChannel { private volatile boolean lazyWithOutInit = true; LazyExchangeChannel(Bootstrap bootstrap, ExchangeChannelGroup parent, int reconnectInterval)
throws SailfishException {
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/channel/LazyExchangeChannel.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/RequestControl.java // public class RequestControl { // /** // * response timeout or write timeout if {@code sent} is true // */ // private int timeout = 2000; // private short opcode; // private byte serializeType; // private byte compressType; // //wait write success or not // private boolean sent; // // /** // * {@code sent} will be ignored when {@code preferHighPerformanceWriter} is true // */ // private boolean preferHighPerformanceWriter; // // public RequestControl(){ // this(false); // } // public RequestControl(boolean preferHighPerformanceWriter) { // this.preferHighPerformanceWriter = preferHighPerformanceWriter; // } // // public int timeout() { // return timeout; // } // // public void timeout(int timeout) { // this.timeout = ParameterChecker.checkPositive(timeout, "timeout"); // } // // public short opcode() { // return opcode; // } // // public void opcode(short opcode) { // this.opcode = opcode; // } // // public byte serializeType() { // return serializeType; // } // // public void serializeType(byte serializeType) { // this.serializeType = serializeType; // } // // public byte compressType() { // return compressType; // } // // public void compressType(byte compressType) { // this.compressType = compressType; // } // // public boolean sent() { // return sent; // } // // public void sent(boolean sent) { // this.sent = sent; // } // // public boolean preferHighPerformanceWriter(){ // return preferHighPerformanceWriter; // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/ResponseCallback.java // public interface ResponseCallback<T> { // /** // * should take advantage of {@link FastThreadLocalThread} with {@link DefaultThreadFactory} // */ // Executor getExecutor(); // // void handleResponse(T resp); // void handleException(Exception cause); // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/future/ResponseFuture.java // public interface ResponseFuture<T>{ // void putResponse(T resp, byte result, SailfishException cause); // boolean isDone(); // void setCallback(ResponseCallback<T> callback, int timeout); // T get() throws SailfishException, InterruptedException; // T get(long timeout, TimeUnit unit) throws SailfishException, InterruptedException; // }
import io.netty.bootstrap.Bootstrap; import sailfish.remoting.RequestControl; import sailfish.remoting.ResponseCallback; import sailfish.remoting.exceptions.SailfishException; import sailfish.remoting.future.ResponseFuture;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.channel; /** * @author spccold * @version $Id: LazyExchangeChannel.java, v 0.1 2016年11月21日 下午11:18:11 spccold Exp $ */ public final class LazyExchangeChannel extends SingleConnctionExchangeChannel { private volatile boolean lazyWithOutInit = true; LazyExchangeChannel(Bootstrap bootstrap, ExchangeChannelGroup parent, int reconnectInterval) throws SailfishException { super(bootstrap, parent, reconnectInterval, false); } @Override
// Path: sailfish-kernel/src/main/java/sailfish/remoting/RequestControl.java // public class RequestControl { // /** // * response timeout or write timeout if {@code sent} is true // */ // private int timeout = 2000; // private short opcode; // private byte serializeType; // private byte compressType; // //wait write success or not // private boolean sent; // // /** // * {@code sent} will be ignored when {@code preferHighPerformanceWriter} is true // */ // private boolean preferHighPerformanceWriter; // // public RequestControl(){ // this(false); // } // public RequestControl(boolean preferHighPerformanceWriter) { // this.preferHighPerformanceWriter = preferHighPerformanceWriter; // } // // public int timeout() { // return timeout; // } // // public void timeout(int timeout) { // this.timeout = ParameterChecker.checkPositive(timeout, "timeout"); // } // // public short opcode() { // return opcode; // } // // public void opcode(short opcode) { // this.opcode = opcode; // } // // public byte serializeType() { // return serializeType; // } // // public void serializeType(byte serializeType) { // this.serializeType = serializeType; // } // // public byte compressType() { // return compressType; // } // // public void compressType(byte compressType) { // this.compressType = compressType; // } // // public boolean sent() { // return sent; // } // // public void sent(boolean sent) { // this.sent = sent; // } // // public boolean preferHighPerformanceWriter(){ // return preferHighPerformanceWriter; // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/ResponseCallback.java // public interface ResponseCallback<T> { // /** // * should take advantage of {@link FastThreadLocalThread} with {@link DefaultThreadFactory} // */ // Executor getExecutor(); // // void handleResponse(T resp); // void handleException(Exception cause); // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/future/ResponseFuture.java // public interface ResponseFuture<T>{ // void putResponse(T resp, byte result, SailfishException cause); // boolean isDone(); // void setCallback(ResponseCallback<T> callback, int timeout); // T get() throws SailfishException, InterruptedException; // T get(long timeout, TimeUnit unit) throws SailfishException, InterruptedException; // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/channel/LazyExchangeChannel.java import io.netty.bootstrap.Bootstrap; import sailfish.remoting.RequestControl; import sailfish.remoting.ResponseCallback; import sailfish.remoting.exceptions.SailfishException; import sailfish.remoting.future.ResponseFuture; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.channel; /** * @author spccold * @version $Id: LazyExchangeChannel.java, v 0.1 2016年11月21日 下午11:18:11 spccold Exp $ */ public final class LazyExchangeChannel extends SingleConnctionExchangeChannel { private volatile boolean lazyWithOutInit = true; LazyExchangeChannel(Bootstrap bootstrap, ExchangeChannelGroup parent, int reconnectInterval) throws SailfishException { super(bootstrap, parent, reconnectInterval, false); } @Override
public void oneway(byte[] data, RequestControl requestControl) throws SailfishException {
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/channel/LazyExchangeChannel.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/RequestControl.java // public class RequestControl { // /** // * response timeout or write timeout if {@code sent} is true // */ // private int timeout = 2000; // private short opcode; // private byte serializeType; // private byte compressType; // //wait write success or not // private boolean sent; // // /** // * {@code sent} will be ignored when {@code preferHighPerformanceWriter} is true // */ // private boolean preferHighPerformanceWriter; // // public RequestControl(){ // this(false); // } // public RequestControl(boolean preferHighPerformanceWriter) { // this.preferHighPerformanceWriter = preferHighPerformanceWriter; // } // // public int timeout() { // return timeout; // } // // public void timeout(int timeout) { // this.timeout = ParameterChecker.checkPositive(timeout, "timeout"); // } // // public short opcode() { // return opcode; // } // // public void opcode(short opcode) { // this.opcode = opcode; // } // // public byte serializeType() { // return serializeType; // } // // public void serializeType(byte serializeType) { // this.serializeType = serializeType; // } // // public byte compressType() { // return compressType; // } // // public void compressType(byte compressType) { // this.compressType = compressType; // } // // public boolean sent() { // return sent; // } // // public void sent(boolean sent) { // this.sent = sent; // } // // public boolean preferHighPerformanceWriter(){ // return preferHighPerformanceWriter; // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/ResponseCallback.java // public interface ResponseCallback<T> { // /** // * should take advantage of {@link FastThreadLocalThread} with {@link DefaultThreadFactory} // */ // Executor getExecutor(); // // void handleResponse(T resp); // void handleException(Exception cause); // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/future/ResponseFuture.java // public interface ResponseFuture<T>{ // void putResponse(T resp, byte result, SailfishException cause); // boolean isDone(); // void setCallback(ResponseCallback<T> callback, int timeout); // T get() throws SailfishException, InterruptedException; // T get(long timeout, TimeUnit unit) throws SailfishException, InterruptedException; // }
import io.netty.bootstrap.Bootstrap; import sailfish.remoting.RequestControl; import sailfish.remoting.ResponseCallback; import sailfish.remoting.exceptions.SailfishException; import sailfish.remoting.future.ResponseFuture;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.channel; /** * @author spccold * @version $Id: LazyExchangeChannel.java, v 0.1 2016年11月21日 下午11:18:11 spccold Exp $ */ public final class LazyExchangeChannel extends SingleConnctionExchangeChannel { private volatile boolean lazyWithOutInit = true; LazyExchangeChannel(Bootstrap bootstrap, ExchangeChannelGroup parent, int reconnectInterval) throws SailfishException { super(bootstrap, parent, reconnectInterval, false); } @Override public void oneway(byte[] data, RequestControl requestControl) throws SailfishException { initChannel(); super.oneway(data, requestControl); } @Override
// Path: sailfish-kernel/src/main/java/sailfish/remoting/RequestControl.java // public class RequestControl { // /** // * response timeout or write timeout if {@code sent} is true // */ // private int timeout = 2000; // private short opcode; // private byte serializeType; // private byte compressType; // //wait write success or not // private boolean sent; // // /** // * {@code sent} will be ignored when {@code preferHighPerformanceWriter} is true // */ // private boolean preferHighPerformanceWriter; // // public RequestControl(){ // this(false); // } // public RequestControl(boolean preferHighPerformanceWriter) { // this.preferHighPerformanceWriter = preferHighPerformanceWriter; // } // // public int timeout() { // return timeout; // } // // public void timeout(int timeout) { // this.timeout = ParameterChecker.checkPositive(timeout, "timeout"); // } // // public short opcode() { // return opcode; // } // // public void opcode(short opcode) { // this.opcode = opcode; // } // // public byte serializeType() { // return serializeType; // } // // public void serializeType(byte serializeType) { // this.serializeType = serializeType; // } // // public byte compressType() { // return compressType; // } // // public void compressType(byte compressType) { // this.compressType = compressType; // } // // public boolean sent() { // return sent; // } // // public void sent(boolean sent) { // this.sent = sent; // } // // public boolean preferHighPerformanceWriter(){ // return preferHighPerformanceWriter; // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/ResponseCallback.java // public interface ResponseCallback<T> { // /** // * should take advantage of {@link FastThreadLocalThread} with {@link DefaultThreadFactory} // */ // Executor getExecutor(); // // void handleResponse(T resp); // void handleException(Exception cause); // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/future/ResponseFuture.java // public interface ResponseFuture<T>{ // void putResponse(T resp, byte result, SailfishException cause); // boolean isDone(); // void setCallback(ResponseCallback<T> callback, int timeout); // T get() throws SailfishException, InterruptedException; // T get(long timeout, TimeUnit unit) throws SailfishException, InterruptedException; // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/channel/LazyExchangeChannel.java import io.netty.bootstrap.Bootstrap; import sailfish.remoting.RequestControl; import sailfish.remoting.ResponseCallback; import sailfish.remoting.exceptions.SailfishException; import sailfish.remoting.future.ResponseFuture; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.channel; /** * @author spccold * @version $Id: LazyExchangeChannel.java, v 0.1 2016年11月21日 下午11:18:11 spccold Exp $ */ public final class LazyExchangeChannel extends SingleConnctionExchangeChannel { private volatile boolean lazyWithOutInit = true; LazyExchangeChannel(Bootstrap bootstrap, ExchangeChannelGroup parent, int reconnectInterval) throws SailfishException { super(bootstrap, parent, reconnectInterval, false); } @Override public void oneway(byte[] data, RequestControl requestControl) throws SailfishException { initChannel(); super.oneway(data, requestControl); } @Override
public ResponseFuture<byte[]> request(byte[] data, RequestControl requestControl) throws SailfishException {
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/channel/LazyExchangeChannel.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/RequestControl.java // public class RequestControl { // /** // * response timeout or write timeout if {@code sent} is true // */ // private int timeout = 2000; // private short opcode; // private byte serializeType; // private byte compressType; // //wait write success or not // private boolean sent; // // /** // * {@code sent} will be ignored when {@code preferHighPerformanceWriter} is true // */ // private boolean preferHighPerformanceWriter; // // public RequestControl(){ // this(false); // } // public RequestControl(boolean preferHighPerformanceWriter) { // this.preferHighPerformanceWriter = preferHighPerformanceWriter; // } // // public int timeout() { // return timeout; // } // // public void timeout(int timeout) { // this.timeout = ParameterChecker.checkPositive(timeout, "timeout"); // } // // public short opcode() { // return opcode; // } // // public void opcode(short opcode) { // this.opcode = opcode; // } // // public byte serializeType() { // return serializeType; // } // // public void serializeType(byte serializeType) { // this.serializeType = serializeType; // } // // public byte compressType() { // return compressType; // } // // public void compressType(byte compressType) { // this.compressType = compressType; // } // // public boolean sent() { // return sent; // } // // public void sent(boolean sent) { // this.sent = sent; // } // // public boolean preferHighPerformanceWriter(){ // return preferHighPerformanceWriter; // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/ResponseCallback.java // public interface ResponseCallback<T> { // /** // * should take advantage of {@link FastThreadLocalThread} with {@link DefaultThreadFactory} // */ // Executor getExecutor(); // // void handleResponse(T resp); // void handleException(Exception cause); // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/future/ResponseFuture.java // public interface ResponseFuture<T>{ // void putResponse(T resp, byte result, SailfishException cause); // boolean isDone(); // void setCallback(ResponseCallback<T> callback, int timeout); // T get() throws SailfishException, InterruptedException; // T get(long timeout, TimeUnit unit) throws SailfishException, InterruptedException; // }
import io.netty.bootstrap.Bootstrap; import sailfish.remoting.RequestControl; import sailfish.remoting.ResponseCallback; import sailfish.remoting.exceptions.SailfishException; import sailfish.remoting.future.ResponseFuture;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.channel; /** * @author spccold * @version $Id: LazyExchangeChannel.java, v 0.1 2016年11月21日 下午11:18:11 spccold Exp $ */ public final class LazyExchangeChannel extends SingleConnctionExchangeChannel { private volatile boolean lazyWithOutInit = true; LazyExchangeChannel(Bootstrap bootstrap, ExchangeChannelGroup parent, int reconnectInterval) throws SailfishException { super(bootstrap, parent, reconnectInterval, false); } @Override public void oneway(byte[] data, RequestControl requestControl) throws SailfishException { initChannel(); super.oneway(data, requestControl); } @Override public ResponseFuture<byte[]> request(byte[] data, RequestControl requestControl) throws SailfishException { initChannel(); return super.request(data, requestControl); } @Override
// Path: sailfish-kernel/src/main/java/sailfish/remoting/RequestControl.java // public class RequestControl { // /** // * response timeout or write timeout if {@code sent} is true // */ // private int timeout = 2000; // private short opcode; // private byte serializeType; // private byte compressType; // //wait write success or not // private boolean sent; // // /** // * {@code sent} will be ignored when {@code preferHighPerformanceWriter} is true // */ // private boolean preferHighPerformanceWriter; // // public RequestControl(){ // this(false); // } // public RequestControl(boolean preferHighPerformanceWriter) { // this.preferHighPerformanceWriter = preferHighPerformanceWriter; // } // // public int timeout() { // return timeout; // } // // public void timeout(int timeout) { // this.timeout = ParameterChecker.checkPositive(timeout, "timeout"); // } // // public short opcode() { // return opcode; // } // // public void opcode(short opcode) { // this.opcode = opcode; // } // // public byte serializeType() { // return serializeType; // } // // public void serializeType(byte serializeType) { // this.serializeType = serializeType; // } // // public byte compressType() { // return compressType; // } // // public void compressType(byte compressType) { // this.compressType = compressType; // } // // public boolean sent() { // return sent; // } // // public void sent(boolean sent) { // this.sent = sent; // } // // public boolean preferHighPerformanceWriter(){ // return preferHighPerformanceWriter; // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/ResponseCallback.java // public interface ResponseCallback<T> { // /** // * should take advantage of {@link FastThreadLocalThread} with {@link DefaultThreadFactory} // */ // Executor getExecutor(); // // void handleResponse(T resp); // void handleException(Exception cause); // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/future/ResponseFuture.java // public interface ResponseFuture<T>{ // void putResponse(T resp, byte result, SailfishException cause); // boolean isDone(); // void setCallback(ResponseCallback<T> callback, int timeout); // T get() throws SailfishException, InterruptedException; // T get(long timeout, TimeUnit unit) throws SailfishException, InterruptedException; // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/channel/LazyExchangeChannel.java import io.netty.bootstrap.Bootstrap; import sailfish.remoting.RequestControl; import sailfish.remoting.ResponseCallback; import sailfish.remoting.exceptions.SailfishException; import sailfish.remoting.future.ResponseFuture; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.channel; /** * @author spccold * @version $Id: LazyExchangeChannel.java, v 0.1 2016年11月21日 下午11:18:11 spccold Exp $ */ public final class LazyExchangeChannel extends SingleConnctionExchangeChannel { private volatile boolean lazyWithOutInit = true; LazyExchangeChannel(Bootstrap bootstrap, ExchangeChannelGroup parent, int reconnectInterval) throws SailfishException { super(bootstrap, parent, reconnectInterval, false); } @Override public void oneway(byte[] data, RequestControl requestControl) throws SailfishException { initChannel(); super.oneway(data, requestControl); } @Override public ResponseFuture<byte[]> request(byte[] data, RequestControl requestControl) throws SailfishException { initChannel(); return super.request(data, requestControl); } @Override
public void request(byte[] data, ResponseCallback<byte[]> callback, RequestControl requestControl)
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/processors/Response.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/CompressType.java // public interface CompressType { // //TODO compressType with multiple mode, needs to perfect in future // byte NON_COMPRESS = 0; // byte LZ4_COMPRESS = 1; // byte GZIP_COMPRESS = 2; // byte DEFLATE_COMPRESS = 3; // byte SNAPPY_COMPRESS = 4; // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/SerializeType.java // public interface SerializeType { // //pure bytes, no need any serialize and deserialize // byte NON_SERIALIZE = 0; // //java platform // byte JDK_SERIALIZE = 1; // //java platform with high performance // byte KRYO_SERIALIZE = 2; // byte FST_SERIALIZE = 3; // //cross-platform // byte JSON_SERIALIZE = 4; // //cross-platform with high performance // byte HESSIAN_SERIALIZE = 5; // byte AVRO_SERIALIZE = 6; // byte THRIFT_SERIALIZE = 7; // byte PROTOBUF_SERIALIZE = 8; // byte FLATBUFFER_SERIALIZE = 9; // }
import sailfish.remoting.constants.CompressType; import sailfish.remoting.constants.SerializeType;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.processors; /** * @author spccold * @version $Id: Response.java, v 0.1 2016年11月29日 下午5:18:01 spccold Exp $ */ public class Response { private boolean success;
// Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/CompressType.java // public interface CompressType { // //TODO compressType with multiple mode, needs to perfect in future // byte NON_COMPRESS = 0; // byte LZ4_COMPRESS = 1; // byte GZIP_COMPRESS = 2; // byte DEFLATE_COMPRESS = 3; // byte SNAPPY_COMPRESS = 4; // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/SerializeType.java // public interface SerializeType { // //pure bytes, no need any serialize and deserialize // byte NON_SERIALIZE = 0; // //java platform // byte JDK_SERIALIZE = 1; // //java platform with high performance // byte KRYO_SERIALIZE = 2; // byte FST_SERIALIZE = 3; // //cross-platform // byte JSON_SERIALIZE = 4; // //cross-platform with high performance // byte HESSIAN_SERIALIZE = 5; // byte AVRO_SERIALIZE = 6; // byte THRIFT_SERIALIZE = 7; // byte PROTOBUF_SERIALIZE = 8; // byte FLATBUFFER_SERIALIZE = 9; // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/processors/Response.java import sailfish.remoting.constants.CompressType; import sailfish.remoting.constants.SerializeType; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.processors; /** * @author spccold * @version $Id: Response.java, v 0.1 2016年11月29日 下午5:18:01 spccold Exp $ */ public class Response { private boolean success;
private byte serializeType = SerializeType.NON_SERIALIZE;
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/processors/Response.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/CompressType.java // public interface CompressType { // //TODO compressType with multiple mode, needs to perfect in future // byte NON_COMPRESS = 0; // byte LZ4_COMPRESS = 1; // byte GZIP_COMPRESS = 2; // byte DEFLATE_COMPRESS = 3; // byte SNAPPY_COMPRESS = 4; // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/SerializeType.java // public interface SerializeType { // //pure bytes, no need any serialize and deserialize // byte NON_SERIALIZE = 0; // //java platform // byte JDK_SERIALIZE = 1; // //java platform with high performance // byte KRYO_SERIALIZE = 2; // byte FST_SERIALIZE = 3; // //cross-platform // byte JSON_SERIALIZE = 4; // //cross-platform with high performance // byte HESSIAN_SERIALIZE = 5; // byte AVRO_SERIALIZE = 6; // byte THRIFT_SERIALIZE = 7; // byte PROTOBUF_SERIALIZE = 8; // byte FLATBUFFER_SERIALIZE = 9; // }
import sailfish.remoting.constants.CompressType; import sailfish.remoting.constants.SerializeType;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.processors; /** * @author spccold * @version $Id: Response.java, v 0.1 2016年11月29日 下午5:18:01 spccold Exp $ */ public class Response { private boolean success; private byte serializeType = SerializeType.NON_SERIALIZE;
// Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/CompressType.java // public interface CompressType { // //TODO compressType with multiple mode, needs to perfect in future // byte NON_COMPRESS = 0; // byte LZ4_COMPRESS = 1; // byte GZIP_COMPRESS = 2; // byte DEFLATE_COMPRESS = 3; // byte SNAPPY_COMPRESS = 4; // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/SerializeType.java // public interface SerializeType { // //pure bytes, no need any serialize and deserialize // byte NON_SERIALIZE = 0; // //java platform // byte JDK_SERIALIZE = 1; // //java platform with high performance // byte KRYO_SERIALIZE = 2; // byte FST_SERIALIZE = 3; // //cross-platform // byte JSON_SERIALIZE = 4; // //cross-platform with high performance // byte HESSIAN_SERIALIZE = 5; // byte AVRO_SERIALIZE = 6; // byte THRIFT_SERIALIZE = 7; // byte PROTOBUF_SERIALIZE = 8; // byte FLATBUFFER_SERIALIZE = 9; // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/processors/Response.java import sailfish.remoting.constants.CompressType; import sailfish.remoting.constants.SerializeType; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.processors; /** * @author spccold * @version $Id: Response.java, v 0.1 2016年11月29日 下午5:18:01 spccold Exp $ */ public class Response { private boolean success; private byte serializeType = SerializeType.NON_SERIALIZE;
private byte compressType = CompressType.NON_COMPRESS;
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/eventgroup/ClientEventGroup.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/RemotingConstants.java // public interface RemotingConstants { // // 压缩阀值, KB // int COMPRESS_THRESHOLD = 4 * 1024; // // sailfish binary protocol magic // short SAILFISH_MAGIC = ByteBuffer.wrap("SH".getBytes()).getShort(); // // // max frame size, 8MB // int DEFAULT_PAYLOAD_LENGTH = 8 * 1024 * 1024; // // // milliseconds // int DEFAULT_CONNECT_TIMEOUT = 2000; // int DEFAULT_RECONNECT_INTERVAL = 1000; // // seconds // byte DEFAULT_IDLE_TIMEOUT = 10; // byte DEFAULT_MAX_IDLE_TIMEOUT = 3 * DEFAULT_IDLE_TIMEOUT; // // // result // byte RESULT_SUCCESS = 0; // byte RESULT_FAIL = 1; // // // channel type for read write splitting // byte WRITE_CHANNEL = 0; // byte READ_CHANNEL = 1; // // int DEFAULT_IO_THREADS = Runtime.getRuntime().availableProcessors() + 1; // int DEFAULT_EVENT_THREADS = 1; // String CLIENT_IO_THREADNAME = "sailfish-client-io"; // String CLIENT_EVENT_THREADNAME = "sailfish-client-event"; // String SERVER_IO_THREADNAME = "sailfish-server-io"; // String SERVER_EVENT_THREADNAME = "sailfish-server-event"; // String SERVER_ACCEPT_THREADNAME = "sailfish-server-accept"; // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.util.internal.SystemPropertyUtil; import sailfish.remoting.constants.RemotingConstants;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.eventgroup; /** * @author spccold * @version $Id: ClientEventGroup.java, v 0.1 2016年11月20日 下午7:29:07 spccold Exp * $ */ public class ClientEventGroup extends AbstractReusedEventGroup { private static final Logger logger = LoggerFactory.getLogger(ClientEventGroup.class); private static final int IO_THREADS; private static final int EVENT_THREADS; public static final ClientEventGroup INSTANCE; static { IO_THREADS = Math.max(1,
// Path: sailfish-kernel/src/main/java/sailfish/remoting/constants/RemotingConstants.java // public interface RemotingConstants { // // 压缩阀值, KB // int COMPRESS_THRESHOLD = 4 * 1024; // // sailfish binary protocol magic // short SAILFISH_MAGIC = ByteBuffer.wrap("SH".getBytes()).getShort(); // // // max frame size, 8MB // int DEFAULT_PAYLOAD_LENGTH = 8 * 1024 * 1024; // // // milliseconds // int DEFAULT_CONNECT_TIMEOUT = 2000; // int DEFAULT_RECONNECT_INTERVAL = 1000; // // seconds // byte DEFAULT_IDLE_TIMEOUT = 10; // byte DEFAULT_MAX_IDLE_TIMEOUT = 3 * DEFAULT_IDLE_TIMEOUT; // // // result // byte RESULT_SUCCESS = 0; // byte RESULT_FAIL = 1; // // // channel type for read write splitting // byte WRITE_CHANNEL = 0; // byte READ_CHANNEL = 1; // // int DEFAULT_IO_THREADS = Runtime.getRuntime().availableProcessors() + 1; // int DEFAULT_EVENT_THREADS = 1; // String CLIENT_IO_THREADNAME = "sailfish-client-io"; // String CLIENT_EVENT_THREADNAME = "sailfish-client-event"; // String SERVER_IO_THREADNAME = "sailfish-server-io"; // String SERVER_EVENT_THREADNAME = "sailfish-server-event"; // String SERVER_ACCEPT_THREADNAME = "sailfish-server-accept"; // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/eventgroup/ClientEventGroup.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.util.internal.SystemPropertyUtil; import sailfish.remoting.constants.RemotingConstants; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.eventgroup; /** * @author spccold * @version $Id: ClientEventGroup.java, v 0.1 2016年11月20日 下午7:29:07 spccold Exp * $ */ public class ClientEventGroup extends AbstractReusedEventGroup { private static final Logger logger = LoggerFactory.getLogger(ClientEventGroup.class); private static final int IO_THREADS; private static final int EVENT_THREADS; public static final ClientEventGroup INSTANCE; static { IO_THREADS = Math.max(1,
SystemPropertyUtil.getInt("sailfish.remoting.client.ioThreads", RemotingConstants.DEFAULT_IO_THREADS));
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/channel/DefaultExchangeChannelChooserFactory.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/ExceptionCode.java // public enum ExceptionCode { // BAD_PACKAGE, // RESPONSE_TIMEOUT, // WRITE_TIMEOUT, // EXCHANGER_NOT_AVAILABLE, // UNFINISHED_REQUEST, // CHANNEL_WRITE_FAIL, // DEFAULT, // ; // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // }
import java.util.concurrent.atomic.AtomicInteger; import sailfish.remoting.exceptions.ExceptionCode; import sailfish.remoting.exceptions.SailfishException;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.channel; /** * Default implementation which uses simple round-robin to choose next * {@link ExchangeChannel} until which {@link ExchangeChannel#isAvailable()} * return true or all children has been chosen. * * @author spccold * @version $Id: DefaultExchangeChannelChooserFactory.java, v 0.1 2016年11月22日 * 下午4:40:01 spccold Exp $ */ public class DefaultExchangeChannelChooserFactory implements ExchangeChannelChooserFactory { public static final DefaultExchangeChannelChooserFactory INSTANCE = new DefaultExchangeChannelChooserFactory(); private DefaultExchangeChannelChooserFactory() { } @Override public ExchangeChannelChooser newChooser(ExchangeChannel[] channels, ExchangeChannel[] deadChannels) { if (isPowerOfTwo(channels.length)) { return new PowerOfTowExchangeChannelChooser(channels, deadChannels); } else { return new GenericExchangeChannelChooser(channels, deadChannels); } } private static boolean isPowerOfTwo(int val) { return (val & -val) == val; } private static final class PowerOfTowExchangeChannelChooser implements ExchangeChannelChooser { private final AtomicInteger idx = new AtomicInteger(); private final ExchangeChannel[] channels; private final ExchangeChannel[] deadChannels; PowerOfTowExchangeChannelChooser(ExchangeChannel[] channels, ExchangeChannel[] deadChannels) { this.channels = channels; this.deadChannels = deadChannels; } @Override
// Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/ExceptionCode.java // public enum ExceptionCode { // BAD_PACKAGE, // RESPONSE_TIMEOUT, // WRITE_TIMEOUT, // EXCHANGER_NOT_AVAILABLE, // UNFINISHED_REQUEST, // CHANNEL_WRITE_FAIL, // DEFAULT, // ; // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/channel/DefaultExchangeChannelChooserFactory.java import java.util.concurrent.atomic.AtomicInteger; import sailfish.remoting.exceptions.ExceptionCode; import sailfish.remoting.exceptions.SailfishException; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.channel; /** * Default implementation which uses simple round-robin to choose next * {@link ExchangeChannel} until which {@link ExchangeChannel#isAvailable()} * return true or all children has been chosen. * * @author spccold * @version $Id: DefaultExchangeChannelChooserFactory.java, v 0.1 2016年11月22日 * 下午4:40:01 spccold Exp $ */ public class DefaultExchangeChannelChooserFactory implements ExchangeChannelChooserFactory { public static final DefaultExchangeChannelChooserFactory INSTANCE = new DefaultExchangeChannelChooserFactory(); private DefaultExchangeChannelChooserFactory() { } @Override public ExchangeChannelChooser newChooser(ExchangeChannel[] channels, ExchangeChannel[] deadChannels) { if (isPowerOfTwo(channels.length)) { return new PowerOfTowExchangeChannelChooser(channels, deadChannels); } else { return new GenericExchangeChannelChooser(channels, deadChannels); } } private static boolean isPowerOfTwo(int val) { return (val & -val) == val; } private static final class PowerOfTowExchangeChannelChooser implements ExchangeChannelChooser { private final AtomicInteger idx = new AtomicInteger(); private final ExchangeChannel[] channels; private final ExchangeChannel[] deadChannels; PowerOfTowExchangeChannelChooser(ExchangeChannel[] channels, ExchangeChannel[] deadChannels) { this.channels = channels; this.deadChannels = deadChannels; } @Override
public ExchangeChannel next() throws SailfishException {
spccold/sailfish
sailfish-kernel/src/main/java/sailfish/remoting/channel/DefaultExchangeChannelChooserFactory.java
// Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/ExceptionCode.java // public enum ExceptionCode { // BAD_PACKAGE, // RESPONSE_TIMEOUT, // WRITE_TIMEOUT, // EXCHANGER_NOT_AVAILABLE, // UNFINISHED_REQUEST, // CHANNEL_WRITE_FAIL, // DEFAULT, // ; // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // }
import java.util.concurrent.atomic.AtomicInteger; import sailfish.remoting.exceptions.ExceptionCode; import sailfish.remoting.exceptions.SailfishException;
/** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.channel; /** * Default implementation which uses simple round-robin to choose next * {@link ExchangeChannel} until which {@link ExchangeChannel#isAvailable()} * return true or all children has been chosen. * * @author spccold * @version $Id: DefaultExchangeChannelChooserFactory.java, v 0.1 2016年11月22日 * 下午4:40:01 spccold Exp $ */ public class DefaultExchangeChannelChooserFactory implements ExchangeChannelChooserFactory { public static final DefaultExchangeChannelChooserFactory INSTANCE = new DefaultExchangeChannelChooserFactory(); private DefaultExchangeChannelChooserFactory() { } @Override public ExchangeChannelChooser newChooser(ExchangeChannel[] channels, ExchangeChannel[] deadChannels) { if (isPowerOfTwo(channels.length)) { return new PowerOfTowExchangeChannelChooser(channels, deadChannels); } else { return new GenericExchangeChannelChooser(channels, deadChannels); } } private static boolean isPowerOfTwo(int val) { return (val & -val) == val; } private static final class PowerOfTowExchangeChannelChooser implements ExchangeChannelChooser { private final AtomicInteger idx = new AtomicInteger(); private final ExchangeChannel[] channels; private final ExchangeChannel[] deadChannels; PowerOfTowExchangeChannelChooser(ExchangeChannel[] channels, ExchangeChannel[] deadChannels) { this.channels = channels; this.deadChannels = deadChannels; } @Override public ExchangeChannel next() throws SailfishException { if(channels.length == 1){//one connection check if(null == channels[0] || !channels[0].isAvailable()){
// Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/ExceptionCode.java // public enum ExceptionCode { // BAD_PACKAGE, // RESPONSE_TIMEOUT, // WRITE_TIMEOUT, // EXCHANGER_NOT_AVAILABLE, // UNFINISHED_REQUEST, // CHANNEL_WRITE_FAIL, // DEFAULT, // ; // } // // Path: sailfish-kernel/src/main/java/sailfish/remoting/exceptions/SailfishException.java // public class SailfishException extends Exception { // // /** */ // private static final long serialVersionUID = 1L; // private ExceptionCode errorCode; // // public SailfishException(String message) { // super(message); // } // // public SailfishException(Throwable cause){ // super(cause); // } // // public SailfishException(ExceptionCode errorCode, String message) { // super(message(errorCode, message)); // this.errorCode = errorCode; // } // // public SailfishException(String message, Throwable cause) { // super(message, cause); // } // // public SailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(message(errorCode, message), cause); // this.errorCode = errorCode; // } // // private static String message(ExceptionCode errorCode, String message) { // if(null == errorCode){ // errorCode = ExceptionCode.DEFAULT; // } // String prefix = "[errorCode:" + errorCode.toString() + "]"; // return StrUtils.isBlank(message) ? prefix : prefix + ", "+ message; // } // // public ExceptionCode code() { // return errorCode; // } // // public RemoteSailfishException toRemoteException() { // return new RemoteSailfishException(errorCode, getMessage(), getCause()); // } // // /** // * exception for remote peer // */ // class RemoteSailfishException extends SailfishException{ // private static final long serialVersionUID = 1L; // public RemoteSailfishException(ExceptionCode errorCode, String message, Throwable cause) { // super(errorCode, message, cause); // } // } // } // Path: sailfish-kernel/src/main/java/sailfish/remoting/channel/DefaultExchangeChannelChooserFactory.java import java.util.concurrent.atomic.AtomicInteger; import sailfish.remoting.exceptions.ExceptionCode; import sailfish.remoting.exceptions.SailfishException; /** * * Copyright 2016-2016 spccold * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package sailfish.remoting.channel; /** * Default implementation which uses simple round-robin to choose next * {@link ExchangeChannel} until which {@link ExchangeChannel#isAvailable()} * return true or all children has been chosen. * * @author spccold * @version $Id: DefaultExchangeChannelChooserFactory.java, v 0.1 2016年11月22日 * 下午4:40:01 spccold Exp $ */ public class DefaultExchangeChannelChooserFactory implements ExchangeChannelChooserFactory { public static final DefaultExchangeChannelChooserFactory INSTANCE = new DefaultExchangeChannelChooserFactory(); private DefaultExchangeChannelChooserFactory() { } @Override public ExchangeChannelChooser newChooser(ExchangeChannel[] channels, ExchangeChannel[] deadChannels) { if (isPowerOfTwo(channels.length)) { return new PowerOfTowExchangeChannelChooser(channels, deadChannels); } else { return new GenericExchangeChannelChooser(channels, deadChannels); } } private static boolean isPowerOfTwo(int val) { return (val & -val) == val; } private static final class PowerOfTowExchangeChannelChooser implements ExchangeChannelChooser { private final AtomicInteger idx = new AtomicInteger(); private final ExchangeChannel[] channels; private final ExchangeChannel[] deadChannels; PowerOfTowExchangeChannelChooser(ExchangeChannel[] channels, ExchangeChannel[] deadChannels) { this.channels = channels; this.deadChannels = deadChannels; } @Override public ExchangeChannel next() throws SailfishException { if(channels.length == 1){//one connection check if(null == channels[0] || !channels[0].isAvailable()){
throw new SailfishException(ExceptionCode.EXCHANGER_NOT_AVAILABLE, "exchanger is not available!");
diffplug/durian-swt
durian-swt/src/main/java/com/diffplug/common/swt/dnd/DragSourceRouter.java
// Path: durian-swt/src/main/java/com/diffplug/common/swt/OnePerWidget.java // public abstract class OnePerWidget<WidgetType extends Widget, T> { // /** Creates a OnePerWidget instance where objects are created using the given function. */ // public static <WidgetType extends Widget, T> OnePerWidget<WidgetType, T> from(Function<? super WidgetType, ? extends T> creator) { // return new OnePerWidget<WidgetType, T>() { // @Override // protected T create(WidgetType widget) { // return creator.apply(widget); // } // }; // } // // private Map<WidgetType, T> map = new HashMap<>(); // // /** Returns the object for the given control. */ // public T forWidget(WidgetType ctl) { // T value = map.get(ctl); // if (value == null) { // value = create(ctl); // map.put(ctl, value); // ctl.addListener(SWT.Dispose, e -> { // map.remove(ctl); // }); // } // return value; // } // // /** Creates a new object for the control. */ // protected abstract T create(WidgetType ctl); // }
import com.diffplug.common.swt.OnePerWidget; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.DragSourceListener; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.widgets.Control;
/* * Copyright 2020 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.diffplug.common.swt.dnd; /** * Provides a mechanism for a single control to route its DragSourceEvents to various listeners. * * There is only one active listener at a time. */ public final class DragSourceRouter { private final DragSource source; private DragSourceListener currentListener; /** Private constructor to force people to use the map. */ private DragSourceRouter(Control ctl) { source = new DragSource(ctl, DndOp.dragAll()); currentListener = null; } /** Sets the DragSourceListener which will get called for this DragSource. */ public void setActiveListener(DragSourceListener newListener, Transfer[] transfers) { if (currentListener != null) { source.removeDragListener(currentListener); } currentListener = newListener; source.setTransfer(transfers); if (currentListener != null) { source.addDragListener(currentListener); } } /** Returns the MultipleDragSource for the given Control. */ public static DragSourceRouter forControl(final Control ctl) { return onePerControl.forWidget(ctl); }
// Path: durian-swt/src/main/java/com/diffplug/common/swt/OnePerWidget.java // public abstract class OnePerWidget<WidgetType extends Widget, T> { // /** Creates a OnePerWidget instance where objects are created using the given function. */ // public static <WidgetType extends Widget, T> OnePerWidget<WidgetType, T> from(Function<? super WidgetType, ? extends T> creator) { // return new OnePerWidget<WidgetType, T>() { // @Override // protected T create(WidgetType widget) { // return creator.apply(widget); // } // }; // } // // private Map<WidgetType, T> map = new HashMap<>(); // // /** Returns the object for the given control. */ // public T forWidget(WidgetType ctl) { // T value = map.get(ctl); // if (value == null) { // value = create(ctl); // map.put(ctl, value); // ctl.addListener(SWT.Dispose, e -> { // map.remove(ctl); // }); // } // return value; // } // // /** Creates a new object for the control. */ // protected abstract T create(WidgetType ctl); // } // Path: durian-swt/src/main/java/com/diffplug/common/swt/dnd/DragSourceRouter.java import com.diffplug.common.swt.OnePerWidget; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.DragSourceListener; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.widgets.Control; /* * Copyright 2020 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.diffplug.common.swt.dnd; /** * Provides a mechanism for a single control to route its DragSourceEvents to various listeners. * * There is only one active listener at a time. */ public final class DragSourceRouter { private final DragSource source; private DragSourceListener currentListener; /** Private constructor to force people to use the map. */ private DragSourceRouter(Control ctl) { source = new DragSource(ctl, DndOp.dragAll()); currentListener = null; } /** Sets the DragSourceListener which will get called for this DragSource. */ public void setActiveListener(DragSourceListener newListener, Transfer[] transfers) { if (currentListener != null) { source.removeDragListener(currentListener); } currentListener = newListener; source.setTransfer(transfers); if (currentListener != null) { source.addDragListener(currentListener); } } /** Returns the MultipleDragSource for the given Control. */ public static DragSourceRouter forControl(final Control ctl) { return onePerControl.forWidget(ctl); }
private static OnePerWidget<Control, DragSourceRouter> onePerControl = OnePerWidget.from(DragSourceRouter::new);
diffplug/durian-swt
durian-swt/src/main/java/com/diffplug/common/swt/jface/ImageDescriptors.java
// Path: durian-swt/src/main/java/com/diffplug/common/swt/OnePerWidget.java // public abstract class OnePerWidget<WidgetType extends Widget, T> { // /** Creates a OnePerWidget instance where objects are created using the given function. */ // public static <WidgetType extends Widget, T> OnePerWidget<WidgetType, T> from(Function<? super WidgetType, ? extends T> creator) { // return new OnePerWidget<WidgetType, T>() { // @Override // protected T create(WidgetType widget) { // return creator.apply(widget); // } // }; // } // // private Map<WidgetType, T> map = new HashMap<>(); // // /** Returns the object for the given control. */ // public T forWidget(WidgetType ctl) { // T value = map.get(ctl); // if (value == null) { // value = create(ctl); // map.put(ctl, value); // ctl.addListener(SWT.Dispose, e -> { // map.remove(ctl); // }); // } // return value; // } // // /** Creates a new object for the control. */ // protected abstract T create(WidgetType ctl); // }
import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Widget; import com.diffplug.common.base.Box; import com.diffplug.common.base.Errors; import com.diffplug.common.base.Unhandled; import com.diffplug.common.swt.OnePerWidget; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.function.Consumer; import java.util.function.Supplier; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.widgets.Button;
public void set(ImageDescriptor newDesc) { // make sure nobody else messed with the image if (!Objects.equals(imageGetter.get(), lastImg)) { // if someone else did mess with it, we can probably survive, so best to just // log the failure and continue with setting the image Errors.log().accept(new IllegalStateException("Setter must have exclusive control over the image field.")); } // set the new image Image newImg; if (newDesc != null) { newImg = (Image) newDesc.createResource(lifecycle.getDisplay()); } else { newImg = null; } imageSetter.accept(newImg); // if an image was already set, destroy it if (lastDesc != null) { lastDesc.destroyResource(lastImg); } // save the fields for the next go-round lastDesc = newDesc; lastImg = newImg; } }; } /** Global cache of widget -> image descriptor setters. */
// Path: durian-swt/src/main/java/com/diffplug/common/swt/OnePerWidget.java // public abstract class OnePerWidget<WidgetType extends Widget, T> { // /** Creates a OnePerWidget instance where objects are created using the given function. */ // public static <WidgetType extends Widget, T> OnePerWidget<WidgetType, T> from(Function<? super WidgetType, ? extends T> creator) { // return new OnePerWidget<WidgetType, T>() { // @Override // protected T create(WidgetType widget) { // return creator.apply(widget); // } // }; // } // // private Map<WidgetType, T> map = new HashMap<>(); // // /** Returns the object for the given control. */ // public T forWidget(WidgetType ctl) { // T value = map.get(ctl); // if (value == null) { // value = create(ctl); // map.put(ctl, value); // ctl.addListener(SWT.Dispose, e -> { // map.remove(ctl); // }); // } // return value; // } // // /** Creates a new object for the control. */ // protected abstract T create(WidgetType ctl); // } // Path: durian-swt/src/main/java/com/diffplug/common/swt/jface/ImageDescriptors.java import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Widget; import com.diffplug.common.base.Box; import com.diffplug.common.base.Errors; import com.diffplug.common.base.Unhandled; import com.diffplug.common.swt.OnePerWidget; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.function.Consumer; import java.util.function.Supplier; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.widgets.Button; public void set(ImageDescriptor newDesc) { // make sure nobody else messed with the image if (!Objects.equals(imageGetter.get(), lastImg)) { // if someone else did mess with it, we can probably survive, so best to just // log the failure and continue with setting the image Errors.log().accept(new IllegalStateException("Setter must have exclusive control over the image field.")); } // set the new image Image newImg; if (newDesc != null) { newImg = (Image) newDesc.createResource(lifecycle.getDisplay()); } else { newImg = null; } imageSetter.accept(newImg); // if an image was already set, destroy it if (lastDesc != null) { lastDesc.destroyResource(lastImg); } // save the fields for the next go-round lastDesc = newDesc; lastImg = newImg; } }; } /** Global cache of widget -> image descriptor setters. */
private static final OnePerWidget<Widget, Box.Nullable<ImageDescriptor>> globalSetter = OnePerWidget.from((Widget widget) -> {
diffplug/durian-swt
durian-swt/src/main/java/com/diffplug/common/swt/dnd/DropTargetRouter.java
// Path: durian-swt/src/main/java/com/diffplug/common/swt/OnePerWidget.java // public abstract class OnePerWidget<WidgetType extends Widget, T> { // /** Creates a OnePerWidget instance where objects are created using the given function. */ // public static <WidgetType extends Widget, T> OnePerWidget<WidgetType, T> from(Function<? super WidgetType, ? extends T> creator) { // return new OnePerWidget<WidgetType, T>() { // @Override // protected T create(WidgetType widget) { // return creator.apply(widget); // } // }; // } // // private Map<WidgetType, T> map = new HashMap<>(); // // /** Returns the object for the given control. */ // public T forWidget(WidgetType ctl) { // T value = map.get(ctl); // if (value == null) { // value = create(ctl); // map.put(ctl, value); // ctl.addListener(SWT.Dispose, e -> { // map.remove(ctl); // }); // } // return value; // } // // /** Creates a new object for the control. */ // protected abstract T create(WidgetType ctl); // }
import com.diffplug.common.swt.OnePerWidget; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import org.eclipse.swt.dnd.DropTarget; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.DropTargetListener; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.widgets.Control;
/* * Copyright 2020 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.diffplug.common.swt.dnd; public class DropTargetRouter { private DropTarget target; /** All of the Transfers currently supported by this DropTargetRouter. */ private Set<Transfer> transferSet = new HashSet<>(); /** Private constructor to force people to use the map. */ private DropTargetRouter(Control ctl) { target = new DropTarget(ctl, DndOp.dropAll()); target.addDropListener(new DelegatingListener()); target.setDropTargetEffect(null); } private void addTransfers(Transfer[] transfers) { transferSet.addAll(Arrays.asList(transfers)); Transfer[] allTransfers = transferSet.toArray(new Transfer[transferSet.size()]); target.setTransfer(allTransfers); } private Disposable subscription = null; /** Sets the DropTargetListener which will get called for this DropTarget. */ public Disposable subscribe(DropTargetListener listener, DropTargetEvent e) { if (subscription != null) { subscription.unsubscribe(e); } subscription = new Disposable(listener, e); return subscription; } public class Disposable { private DropTargetListener listener; private boolean unsubscribed = false; /** Call dragEnter on subscription. */ private Disposable(DropTargetListener listener, DropTargetEvent e) { this.listener = listener; listener.dragEnter(e); } /** Call dragLeave on unsubscribe. Don't complete the unsubscription until drop or dropAccept is called. */ public void unsubscribe(DropTargetEvent e) { if (unsubscribed) { if (subscription == this) { subscription = null; } } else { unsubscribed = true; listener.dragLeave(e); } } public void dragOperationChanged(DropTargetEvent e) { if (unsubscribed) { subscription = null; } else { listener.dragOperationChanged(e); } } public void dragOver(DropTargetEvent e) { if (unsubscribed) { subscription = null; } else { listener.dragOver(e); } } public void drop(DropTargetEvent e) { listener.drop(e); } public void dropAccept(DropTargetEvent e) { listener.dropAccept(e); } } /** Adds a listener which bypasses the routing mechanism. */ public void addBypassListener(DropTargetListener listener) { target.addDropListener(listener); } /** Adds a listener which bypasses the routing mechanism. */ public void removeBypassListener(DropTargetListener listener) { target.removeDropListener(listener); } /** Listener which delegates its calls to the currentListener. */ private class DelegatingListener implements DropTargetListener { // enter / leave is handled by the Disposable object @Override public void dragEnter(DropTargetEvent e) {} @Override public void dragLeave(DropTargetEvent e) {} @Override public void dragOperationChanged(DropTargetEvent e) { if (subscription != null) { subscription.dragOperationChanged(e); } } @Override public void dragOver(DropTargetEvent e) { if (subscription != null) { subscription.dragOver(e); } } @Override public void drop(DropTargetEvent e) { if (subscription != null) { subscription.drop(e); } } @Override public void dropAccept(DropTargetEvent e) { if (subscription != null) { subscription.dropAccept(e); } } } /** Returns the MultipleDragSource for the given Control. */ public static DropTargetRouter forControl(Control ctl, Transfer[] transfers) { DropTargetRouter router = onePerControl.forWidget(ctl); router.addTransfers(transfers); return router; }
// Path: durian-swt/src/main/java/com/diffplug/common/swt/OnePerWidget.java // public abstract class OnePerWidget<WidgetType extends Widget, T> { // /** Creates a OnePerWidget instance where objects are created using the given function. */ // public static <WidgetType extends Widget, T> OnePerWidget<WidgetType, T> from(Function<? super WidgetType, ? extends T> creator) { // return new OnePerWidget<WidgetType, T>() { // @Override // protected T create(WidgetType widget) { // return creator.apply(widget); // } // }; // } // // private Map<WidgetType, T> map = new HashMap<>(); // // /** Returns the object for the given control. */ // public T forWidget(WidgetType ctl) { // T value = map.get(ctl); // if (value == null) { // value = create(ctl); // map.put(ctl, value); // ctl.addListener(SWT.Dispose, e -> { // map.remove(ctl); // }); // } // return value; // } // // /** Creates a new object for the control. */ // protected abstract T create(WidgetType ctl); // } // Path: durian-swt/src/main/java/com/diffplug/common/swt/dnd/DropTargetRouter.java import com.diffplug.common.swt.OnePerWidget; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import org.eclipse.swt.dnd.DropTarget; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.DropTargetListener; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.widgets.Control; /* * Copyright 2020 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.diffplug.common.swt.dnd; public class DropTargetRouter { private DropTarget target; /** All of the Transfers currently supported by this DropTargetRouter. */ private Set<Transfer> transferSet = new HashSet<>(); /** Private constructor to force people to use the map. */ private DropTargetRouter(Control ctl) { target = new DropTarget(ctl, DndOp.dropAll()); target.addDropListener(new DelegatingListener()); target.setDropTargetEffect(null); } private void addTransfers(Transfer[] transfers) { transferSet.addAll(Arrays.asList(transfers)); Transfer[] allTransfers = transferSet.toArray(new Transfer[transferSet.size()]); target.setTransfer(allTransfers); } private Disposable subscription = null; /** Sets the DropTargetListener which will get called for this DropTarget. */ public Disposable subscribe(DropTargetListener listener, DropTargetEvent e) { if (subscription != null) { subscription.unsubscribe(e); } subscription = new Disposable(listener, e); return subscription; } public class Disposable { private DropTargetListener listener; private boolean unsubscribed = false; /** Call dragEnter on subscription. */ private Disposable(DropTargetListener listener, DropTargetEvent e) { this.listener = listener; listener.dragEnter(e); } /** Call dragLeave on unsubscribe. Don't complete the unsubscription until drop or dropAccept is called. */ public void unsubscribe(DropTargetEvent e) { if (unsubscribed) { if (subscription == this) { subscription = null; } } else { unsubscribed = true; listener.dragLeave(e); } } public void dragOperationChanged(DropTargetEvent e) { if (unsubscribed) { subscription = null; } else { listener.dragOperationChanged(e); } } public void dragOver(DropTargetEvent e) { if (unsubscribed) { subscription = null; } else { listener.dragOver(e); } } public void drop(DropTargetEvent e) { listener.drop(e); } public void dropAccept(DropTargetEvent e) { listener.dropAccept(e); } } /** Adds a listener which bypasses the routing mechanism. */ public void addBypassListener(DropTargetListener listener) { target.addDropListener(listener); } /** Adds a listener which bypasses the routing mechanism. */ public void removeBypassListener(DropTargetListener listener) { target.removeDropListener(listener); } /** Listener which delegates its calls to the currentListener. */ private class DelegatingListener implements DropTargetListener { // enter / leave is handled by the Disposable object @Override public void dragEnter(DropTargetEvent e) {} @Override public void dragLeave(DropTargetEvent e) {} @Override public void dragOperationChanged(DropTargetEvent e) { if (subscription != null) { subscription.dragOperationChanged(e); } } @Override public void dragOver(DropTargetEvent e) { if (subscription != null) { subscription.dragOver(e); } } @Override public void drop(DropTargetEvent e) { if (subscription != null) { subscription.drop(e); } } @Override public void dropAccept(DropTargetEvent e) { if (subscription != null) { subscription.dropAccept(e); } } } /** Returns the MultipleDragSource for the given Control. */ public static DropTargetRouter forControl(Control ctl, Transfer[] transfers) { DropTargetRouter router = onePerControl.forWidget(ctl); router.addTransfers(transfers); return router; }
private static final OnePerWidget<Control, DropTargetRouter> onePerControl = OnePerWidget.from(DropTargetRouter::new);
diffplug/durian-swt
durian-swt/src/main/java/com/diffplug/common/swt/Shells.java
// Path: durian-swt.os/src/main/java/com/diffplug/common/swt/os/WS.java // public enum WS { // WIN, COCOA, GTK; // // public boolean isWin() { // return this == WIN; // } // // public boolean isCocoa() { // return this == COCOA; // } // // public boolean isGTK() { // return this == GTK; // } // // public <T> T winCocoaGtk(T win, T cocoa, T gtk) { // // @formatter:off // switch (this) { // case WIN: return win; // case COCOA: return cocoa; // case GTK: return gtk; // default: throw unsupportedException(this); // } // // @formatter:on // } // // private static final WS RUNNING_WS = OS.getRunning().winMacLinux(WIN, COCOA, GTK); // // public static WS getRunning() { // return RUNNING_WS; // } // // /** Returns an UnsupportedOperationException for the given arch. */ // public static UnsupportedOperationException unsupportedException(WS ws) { // return new UnsupportedOperationException("Window system '" + ws + "' is unsupported."); // } // }
import com.diffplug.common.base.Preconditions; import com.diffplug.common.collect.Maps; import com.diffplug.common.swt.os.WS; import com.diffplug.common.tree.TreeIterable; import com.diffplug.common.tree.TreeQuery; import com.diffplug.common.tree.TreeStream; import io.reactivex.disposables.Disposable; import io.reactivex.disposables.Disposables; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import javax.annotation.Nullable; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell;
} /** Opens the shell on the currently active shell and blocks. */ public void openOnActiveBlocking() { Preconditions.checkArgument(!dontOpen); SwtMisc.loopUntilDisposed(openOnActive()); } /** Opens the shell as a root shell. */ public Shell openOnDisplay() { Display display = SwtMisc.assertUI(); if (location == null) { location = Maps.immutableEntry(Corner.CENTER, display.getCursorLocation()); } Shell shell = new Shell(display, style); setupShell(shell); return shell; } /** Opens the shell as a root shell and blocks. */ public void openOnDisplayBlocking() { Preconditions.checkArgument(!dontOpen); SwtMisc.loopUntilDisposed(openOnDisplay()); } private void setupShell(Shell shell) { // set the text, image, and alpha if (title != null) { shell.setText(title); }
// Path: durian-swt.os/src/main/java/com/diffplug/common/swt/os/WS.java // public enum WS { // WIN, COCOA, GTK; // // public boolean isWin() { // return this == WIN; // } // // public boolean isCocoa() { // return this == COCOA; // } // // public boolean isGTK() { // return this == GTK; // } // // public <T> T winCocoaGtk(T win, T cocoa, T gtk) { // // @formatter:off // switch (this) { // case WIN: return win; // case COCOA: return cocoa; // case GTK: return gtk; // default: throw unsupportedException(this); // } // // @formatter:on // } // // private static final WS RUNNING_WS = OS.getRunning().winMacLinux(WIN, COCOA, GTK); // // public static WS getRunning() { // return RUNNING_WS; // } // // /** Returns an UnsupportedOperationException for the given arch. */ // public static UnsupportedOperationException unsupportedException(WS ws) { // return new UnsupportedOperationException("Window system '" + ws + "' is unsupported."); // } // } // Path: durian-swt/src/main/java/com/diffplug/common/swt/Shells.java import com.diffplug.common.base.Preconditions; import com.diffplug.common.collect.Maps; import com.diffplug.common.swt.os.WS; import com.diffplug.common.tree.TreeIterable; import com.diffplug.common.tree.TreeQuery; import com.diffplug.common.tree.TreeStream; import io.reactivex.disposables.Disposable; import io.reactivex.disposables.Disposables; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import javax.annotation.Nullable; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; } /** Opens the shell on the currently active shell and blocks. */ public void openOnActiveBlocking() { Preconditions.checkArgument(!dontOpen); SwtMisc.loopUntilDisposed(openOnActive()); } /** Opens the shell as a root shell. */ public Shell openOnDisplay() { Display display = SwtMisc.assertUI(); if (location == null) { location = Maps.immutableEntry(Corner.CENTER, display.getCursorLocation()); } Shell shell = new Shell(display, style); setupShell(shell); return shell; } /** Opens the shell as a root shell and blocks. */ public void openOnDisplayBlocking() { Preconditions.checkArgument(!dontOpen); SwtMisc.loopUntilDisposed(openOnDisplay()); } private void setupShell(Shell shell) { // set the text, image, and alpha if (title != null) { shell.setText(title); }
if (image != null && WS.getRunning() != WS.COCOA) {
diffplug/durian-swt
durian-swt/src/test/java/com/diffplug/common/swt/InteractiveTestTest.java
// Path: durian-swt/src/main/java/com/diffplug/common/swt/InteractiveTest.java // public static class FailsWithoutUser {}
import com.diffplug.common.collect.Range; import com.diffplug.common.swt.InteractiveTest.FailsWithoutUser; import com.diffplug.common.util.concurrent.Uninterruptibles; import java.util.concurrent.TimeUnit; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Text; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category;
/* * Copyright 2020 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.diffplug.common.swt; @Category(InteractiveTest.class) public class InteractiveTestTest {
// Path: durian-swt/src/main/java/com/diffplug/common/swt/InteractiveTest.java // public static class FailsWithoutUser {} // Path: durian-swt/src/test/java/com/diffplug/common/swt/InteractiveTestTest.java import com.diffplug.common.collect.Range; import com.diffplug.common.swt.InteractiveTest.FailsWithoutUser; import com.diffplug.common.util.concurrent.Uninterruptibles; import java.util.concurrent.TimeUnit; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Text; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; /* * Copyright 2020 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.diffplug.common.swt; @Category(InteractiveTest.class) public class InteractiveTestTest {
@Category(FailsWithoutUser.class)
diffplug/durian-swt
durian-swt/src/main/java/com/diffplug/common/swt/widgets/AbstractSmoothTable.java
// Path: durian-swt/src/main/java/com/diffplug/common/swt/SiliconFix.java // public class SiliconFix { // private static final boolean APPLY_FIX = OS.getRunning().isMac() && Arch.getRunning() == Arch.arm64; // // public static void fix(Table table) { // if (APPLY_FIX) { // table.setFont(null); // } // } // // public static void fix(Tree tree) { // if (APPLY_FIX) { // tree.setFont(null); // } // } // // public static void fix(List list) { // if (APPLY_FIX) { // list.setFont(null); // } // } // }
import com.diffplug.common.swt.SiliconFix; import java.util.function.DoubleConsumer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Layout; import org.eclipse.swt.widgets.Table;
/* * Copyright (C) 2020-2022 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.diffplug.common.swt.widgets; /** * A table which can be scrolled past its limits (positive and negative). * Support per-pixel scrolling on all platforms. */ abstract class AbstractSmoothTable extends Composite { protected final Table table; protected final int rowHeight; private final int scrollBarWidth; protected int offset; protected double topRow; protected int topPixel; private int width; protected int height; private int tableHeight; private int itemCount; static final DoubleConsumer DO_NOTHING = value -> {}; private DoubleConsumer topIndexListener = DO_NOTHING; private DoubleConsumer numVisibleListener = DO_NOTHING; protected final boolean extraRow; protected final boolean hasVScroll; /** Stuff for things. */ AbstractSmoothTable(Composite parent, int style) { // if there's a BORDER, apply it to the Composite instead super(parent, (style & SWT.V_SCROLL) | (style & SWT.BORDER)); if ((style & SWT.H_SCROLL) == SWT.H_SCROLL) { throw new IllegalArgumentException("Must not set H_SCROLL"); } // the table can't have the BORDER table = new Table(this, style & (~SWT.BORDER));
// Path: durian-swt/src/main/java/com/diffplug/common/swt/SiliconFix.java // public class SiliconFix { // private static final boolean APPLY_FIX = OS.getRunning().isMac() && Arch.getRunning() == Arch.arm64; // // public static void fix(Table table) { // if (APPLY_FIX) { // table.setFont(null); // } // } // // public static void fix(Tree tree) { // if (APPLY_FIX) { // tree.setFont(null); // } // } // // public static void fix(List list) { // if (APPLY_FIX) { // list.setFont(null); // } // } // } // Path: durian-swt/src/main/java/com/diffplug/common/swt/widgets/AbstractSmoothTable.java import com.diffplug.common.swt.SiliconFix; import java.util.function.DoubleConsumer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Layout; import org.eclipse.swt.widgets.Table; /* * Copyright (C) 2020-2022 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.diffplug.common.swt.widgets; /** * A table which can be scrolled past its limits (positive and negative). * Support per-pixel scrolling on all platforms. */ abstract class AbstractSmoothTable extends Composite { protected final Table table; protected final int rowHeight; private final int scrollBarWidth; protected int offset; protected double topRow; protected int topPixel; private int width; protected int height; private int tableHeight; private int itemCount; static final DoubleConsumer DO_NOTHING = value -> {}; private DoubleConsumer topIndexListener = DO_NOTHING; private DoubleConsumer numVisibleListener = DO_NOTHING; protected final boolean extraRow; protected final boolean hasVScroll; /** Stuff for things. */ AbstractSmoothTable(Composite parent, int style) { // if there's a BORDER, apply it to the Composite instead super(parent, (style & SWT.V_SCROLL) | (style & SWT.BORDER)); if ((style & SWT.H_SCROLL) == SWT.H_SCROLL) { throw new IllegalArgumentException("Must not set H_SCROLL"); } // the table can't have the BORDER table = new Table(this, style & (~SWT.BORDER));
SiliconFix.fix(table);
UweTrottmann/MovieTracker
SeriesGuideMovies/src/com/uwetrottmann/movies/entities/MovieDetails.java
// Path: SeriesGuideMovies/src/com/uwetrottmann/tmdb/entities/Casts.java // public class Casts implements TmdbEntity { // private static final long serialVersionUID = -7947291466017850804L; // // public static class CastMember implements TmdbEntity { // private static final long serialVersionUID = -6164786116196155740L; // // public Integer id; // public String name; // public String character; // public Integer order; // public String profile_path; // } // // public static class CrewMember implements TmdbEntity { // private static final long serialVersionUID = -6267166779666363892L; // // public Integer id; // public String name; // public String department; // public String job; // public String profile_path; // } // // public Integer id; // public List<CastMember> cast; // public List<CrewMember> crew; // // } // // Path: SeriesGuideMovies/src/com/uwetrottmann/tmdb/entities/Trailers.java // public class Trailers implements TmdbEntity { // private static final long serialVersionUID = 665059823359173539L; // // public Integer id; // public List<Trailer> quicktime; // public List<Trailer> youtube; // }
import com.uwetrottmann.tmdb.entities.Casts; import com.uwetrottmann.tmdb.entities.Movie; import com.uwetrottmann.tmdb.entities.Trailers;
package com.uwetrottmann.movies.entities; /** * Holder class for movie details. */ public class MovieDetails { public Movie movie;
// Path: SeriesGuideMovies/src/com/uwetrottmann/tmdb/entities/Casts.java // public class Casts implements TmdbEntity { // private static final long serialVersionUID = -7947291466017850804L; // // public static class CastMember implements TmdbEntity { // private static final long serialVersionUID = -6164786116196155740L; // // public Integer id; // public String name; // public String character; // public Integer order; // public String profile_path; // } // // public static class CrewMember implements TmdbEntity { // private static final long serialVersionUID = -6267166779666363892L; // // public Integer id; // public String name; // public String department; // public String job; // public String profile_path; // } // // public Integer id; // public List<CastMember> cast; // public List<CrewMember> crew; // // } // // Path: SeriesGuideMovies/src/com/uwetrottmann/tmdb/entities/Trailers.java // public class Trailers implements TmdbEntity { // private static final long serialVersionUID = 665059823359173539L; // // public Integer id; // public List<Trailer> quicktime; // public List<Trailer> youtube; // } // Path: SeriesGuideMovies/src/com/uwetrottmann/movies/entities/MovieDetails.java import com.uwetrottmann.tmdb.entities.Casts; import com.uwetrottmann.tmdb.entities.Movie; import com.uwetrottmann.tmdb.entities.Trailers; package com.uwetrottmann.movies.entities; /** * Holder class for movie details. */ public class MovieDetails { public Movie movie;
public Trailers trailers;
UweTrottmann/MovieTracker
SeriesGuideMovies/src/com/uwetrottmann/movies/entities/MovieDetails.java
// Path: SeriesGuideMovies/src/com/uwetrottmann/tmdb/entities/Casts.java // public class Casts implements TmdbEntity { // private static final long serialVersionUID = -7947291466017850804L; // // public static class CastMember implements TmdbEntity { // private static final long serialVersionUID = -6164786116196155740L; // // public Integer id; // public String name; // public String character; // public Integer order; // public String profile_path; // } // // public static class CrewMember implements TmdbEntity { // private static final long serialVersionUID = -6267166779666363892L; // // public Integer id; // public String name; // public String department; // public String job; // public String profile_path; // } // // public Integer id; // public List<CastMember> cast; // public List<CrewMember> crew; // // } // // Path: SeriesGuideMovies/src/com/uwetrottmann/tmdb/entities/Trailers.java // public class Trailers implements TmdbEntity { // private static final long serialVersionUID = 665059823359173539L; // // public Integer id; // public List<Trailer> quicktime; // public List<Trailer> youtube; // }
import com.uwetrottmann.tmdb.entities.Casts; import com.uwetrottmann.tmdb.entities.Movie; import com.uwetrottmann.tmdb.entities.Trailers;
package com.uwetrottmann.movies.entities; /** * Holder class for movie details. */ public class MovieDetails { public Movie movie; public Trailers trailers;
// Path: SeriesGuideMovies/src/com/uwetrottmann/tmdb/entities/Casts.java // public class Casts implements TmdbEntity { // private static final long serialVersionUID = -7947291466017850804L; // // public static class CastMember implements TmdbEntity { // private static final long serialVersionUID = -6164786116196155740L; // // public Integer id; // public String name; // public String character; // public Integer order; // public String profile_path; // } // // public static class CrewMember implements TmdbEntity { // private static final long serialVersionUID = -6267166779666363892L; // // public Integer id; // public String name; // public String department; // public String job; // public String profile_path; // } // // public Integer id; // public List<CastMember> cast; // public List<CrewMember> crew; // // } // // Path: SeriesGuideMovies/src/com/uwetrottmann/tmdb/entities/Trailers.java // public class Trailers implements TmdbEntity { // private static final long serialVersionUID = 665059823359173539L; // // public Integer id; // public List<Trailer> quicktime; // public List<Trailer> youtube; // } // Path: SeriesGuideMovies/src/com/uwetrottmann/movies/entities/MovieDetails.java import com.uwetrottmann.tmdb.entities.Casts; import com.uwetrottmann.tmdb.entities.Movie; import com.uwetrottmann.tmdb.entities.Trailers; package com.uwetrottmann.movies.entities; /** * Holder class for movie details. */ public class MovieDetails { public Movie movie; public Trailers trailers;
public Casts casts;
UweTrottmann/MovieTracker
SeriesGuideMovies/src/com/jakewharton/trakt/entities/TvShowEpisode.java
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktEntity.java // public interface TraktEntity extends Serializable {} // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/Rating.java // public enum Rating implements TraktEnumeration { // Love("love"), // Hate("hate"), // Unrate("unrate"); // // private final String value; // // private Rating(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, Rating> STRING_MAPPING = new HashMap<String, Rating>(); // // static { // for (Rating via : Rating.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static Rating fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // }
import com.google.myjson.annotations.SerializedName; import com.jakewharton.trakt.TraktEntity; import com.jakewharton.trakt.enumerations.Rating; import java.util.Calendar; import java.util.Date;
package com.jakewharton.trakt.entities; public class TvShowEpisode implements TraktEntity { private static final long serialVersionUID = -1550739539663499211L; public Integer season; public Integer number; public String title; public String overview; public String url; @SerializedName("first_aired") public Date firstAired; public Calendar inserted; public Integer plays; public Images images; public Ratings ratings; public Boolean watched;
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktEntity.java // public interface TraktEntity extends Serializable {} // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/Rating.java // public enum Rating implements TraktEnumeration { // Love("love"), // Hate("hate"), // Unrate("unrate"); // // private final String value; // // private Rating(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, Rating> STRING_MAPPING = new HashMap<String, Rating>(); // // static { // for (Rating via : Rating.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static Rating fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // Path: SeriesGuideMovies/src/com/jakewharton/trakt/entities/TvShowEpisode.java import com.google.myjson.annotations.SerializedName; import com.jakewharton.trakt.TraktEntity; import com.jakewharton.trakt.enumerations.Rating; import java.util.Calendar; import java.util.Date; package com.jakewharton.trakt.entities; public class TvShowEpisode implements TraktEntity { private static final long serialVersionUID = -1550739539663499211L; public Integer season; public Integer number; public String title; public String overview; public String url; @SerializedName("first_aired") public Date firstAired; public Calendar inserted; public Integer plays; public Images images; public Ratings ratings; public Boolean watched;
public Rating rating;
UweTrottmann/MovieTracker
SeriesGuideMovies/src/com/jakewharton/trakt/entities/ListItem.java
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktEntity.java // public interface TraktEntity extends Serializable {} // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/ListItemType.java // public enum ListItemType implements TraktEnumeration { // Movie("movie"), // TvShow("show"), // TvShowSeason("season"), // TvShowEpisode("episode"); // // private final String value; // // private ListItemType(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, ListItemType> STRING_MAPPING = new HashMap<String, ListItemType>(); // // static { // for (ListItemType via : ListItemType.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static ListItemType fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // }
import com.google.myjson.annotations.SerializedName; import com.jakewharton.trakt.TraktEntity; import com.jakewharton.trakt.enumerations.ListItemType;
package com.jakewharton.trakt.entities; public class ListItem implements TraktEntity { private static final long serialVersionUID = 7584772036063464460L;
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktEntity.java // public interface TraktEntity extends Serializable {} // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/ListItemType.java // public enum ListItemType implements TraktEnumeration { // Movie("movie"), // TvShow("show"), // TvShowSeason("season"), // TvShowEpisode("episode"); // // private final String value; // // private ListItemType(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, ListItemType> STRING_MAPPING = new HashMap<String, ListItemType>(); // // static { // for (ListItemType via : ListItemType.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static ListItemType fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // Path: SeriesGuideMovies/src/com/jakewharton/trakt/entities/ListItem.java import com.google.myjson.annotations.SerializedName; import com.jakewharton.trakt.TraktEntity; import com.jakewharton.trakt.enumerations.ListItemType; package com.jakewharton.trakt.entities; public class ListItem implements TraktEntity { private static final long serialVersionUID = 7584772036063464460L;
public ListItemType type;
UweTrottmann/MovieTracker
SeriesGuideMovies/src/com/jakewharton/trakt/entities/UserProfile.java
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktEntity.java // public interface TraktEntity extends Serializable {} // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/Gender.java // public enum Gender implements TraktEnumeration { // Male("male"), // Female("female"); // // private final String value; // // private Gender(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, Gender> STRING_MAPPING = new HashMap<String, Gender>(); // // static { // for (Gender via : Gender.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static Gender fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // }
import com.google.myjson.annotations.SerializedName; import com.jakewharton.trakt.TraktEntity; import com.jakewharton.trakt.enumerations.Gender; import java.util.Calendar; import java.util.List;
package com.jakewharton.trakt.entities; public class UserProfile implements TraktEntity { private static final long serialVersionUID = -4145012978937162733L; public static class Stats implements TraktEntity { private static final long serialVersionUID = -2737256634772977389L; public static class Shows implements TraktEntity { private static final long serialVersionUID = -2888630218268563052L; public Integer library; /** @deprecated Use {@link #library} */ @Deprecated public Integer getLibrary() { return this.library; } } public static class Episodes implements TraktEntity { private static final long serialVersionUID = 7210925664642958187L; public Integer watched; @SerializedName("watched_unique") public Integer watchedUnique; @SerializedName("watched_trakt") public Integer watchedTrakt; @SerializedName("watched_trakt_unique") public Integer watchedTraktUnique; @SerializedName("watched_elsewhere") public Integer watchedElsewhere; public Integer unwatched; /** @deprecated Use {@link #watched} */ @Deprecated public Integer getWatched() { return this.watched; } /** @deprecated Use {@link #watchedUnique} */ @Deprecated public Integer getWatchedUnique() { return this.watchedUnique; } /** @deprecated Use {@link #watchedTrakt} */ @Deprecated public Integer getWatchedTrakt() { return this.watchedTrakt; } /** @deprecated Use {@link #watchedTraktUnique} */ @Deprecated public Integer getWatchedTraktUnique() { return this.watchedTraktUnique; } /** @deprecated Use {@link #watchedElsewhere} */ @Deprecated public Integer getWatchedElsewhere() { return this.watchedElsewhere; } /** @deprecated Use {@link #unwatched} */ @Deprecated public Integer getUnwatched() { return this.unwatched; } } public static class Movies implements TraktEntity { private static final long serialVersionUID = 5061541628681754141L; public Integer watched; @SerializedName("watched_unique") public Integer watchedUnique; @SerializedName("watched_trakt") public Integer watchedTrakt; @SerializedName("watched_trakt_unique") public Integer watchedTraktUnique; @SerializedName("watched_elsewhere") public Integer watchedElsewhere; public Integer library; public Integer unwatched; /** @deprecated Use {@link #watched} */ @Deprecated public Integer getWatched() { return this.watched; } /** @deprecated Use {@link #watchedUnique} */ @Deprecated public Integer getWatchedUnique() { return this.watchedUnique; } /** @deprecated Use {@link #watchedTrakt} */ @Deprecated public Integer getWatchedTrakt() { return this.watchedTrakt; } /** @deprecated Use {@link #watchedTraktUnique} */ @Deprecated public Integer getWatchedTraktUnique() { return this.watchedTraktUnique; } /** @deprecated Use {@link #watchedElsewhere} */ @Deprecated public Integer getWatchedElsewhere() { return this.watchedElsewhere; } /** @deprecated Use {@link #library} */ @Deprecated public Integer getLibrary() { return this.library; } /** @deprecated Use {@link #unwatched} */ @Deprecated public Integer getUnwatched() { return this.unwatched; } } public Integer friends; public Shows shows; public Episodes episodes; public Movies movies; /** @deprecated Use {@link #friends} */ @Deprecated public Integer getFriends() { return this.friends; } /** @deprecated Use {@link #shows} */ @Deprecated public Shows getShows() { return this.shows; } /** @deprecated Use {@link #episodes} */ @Deprecated public Episodes getEpisodes() { return this.episodes; } /** @deprecated Use {@link #movies} */ @Deprecated public Movies getMovies() { return this.movies; } } public String username; @SerializedName("protected") public Boolean _protected; @SerializedName("full_name") public String fullName;
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktEntity.java // public interface TraktEntity extends Serializable {} // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/Gender.java // public enum Gender implements TraktEnumeration { // Male("male"), // Female("female"); // // private final String value; // // private Gender(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, Gender> STRING_MAPPING = new HashMap<String, Gender>(); // // static { // for (Gender via : Gender.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static Gender fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // Path: SeriesGuideMovies/src/com/jakewharton/trakt/entities/UserProfile.java import com.google.myjson.annotations.SerializedName; import com.jakewharton.trakt.TraktEntity; import com.jakewharton.trakt.enumerations.Gender; import java.util.Calendar; import java.util.List; package com.jakewharton.trakt.entities; public class UserProfile implements TraktEntity { private static final long serialVersionUID = -4145012978937162733L; public static class Stats implements TraktEntity { private static final long serialVersionUID = -2737256634772977389L; public static class Shows implements TraktEntity { private static final long serialVersionUID = -2888630218268563052L; public Integer library; /** @deprecated Use {@link #library} */ @Deprecated public Integer getLibrary() { return this.library; } } public static class Episodes implements TraktEntity { private static final long serialVersionUID = 7210925664642958187L; public Integer watched; @SerializedName("watched_unique") public Integer watchedUnique; @SerializedName("watched_trakt") public Integer watchedTrakt; @SerializedName("watched_trakt_unique") public Integer watchedTraktUnique; @SerializedName("watched_elsewhere") public Integer watchedElsewhere; public Integer unwatched; /** @deprecated Use {@link #watched} */ @Deprecated public Integer getWatched() { return this.watched; } /** @deprecated Use {@link #watchedUnique} */ @Deprecated public Integer getWatchedUnique() { return this.watchedUnique; } /** @deprecated Use {@link #watchedTrakt} */ @Deprecated public Integer getWatchedTrakt() { return this.watchedTrakt; } /** @deprecated Use {@link #watchedTraktUnique} */ @Deprecated public Integer getWatchedTraktUnique() { return this.watchedTraktUnique; } /** @deprecated Use {@link #watchedElsewhere} */ @Deprecated public Integer getWatchedElsewhere() { return this.watchedElsewhere; } /** @deprecated Use {@link #unwatched} */ @Deprecated public Integer getUnwatched() { return this.unwatched; } } public static class Movies implements TraktEntity { private static final long serialVersionUID = 5061541628681754141L; public Integer watched; @SerializedName("watched_unique") public Integer watchedUnique; @SerializedName("watched_trakt") public Integer watchedTrakt; @SerializedName("watched_trakt_unique") public Integer watchedTraktUnique; @SerializedName("watched_elsewhere") public Integer watchedElsewhere; public Integer library; public Integer unwatched; /** @deprecated Use {@link #watched} */ @Deprecated public Integer getWatched() { return this.watched; } /** @deprecated Use {@link #watchedUnique} */ @Deprecated public Integer getWatchedUnique() { return this.watchedUnique; } /** @deprecated Use {@link #watchedTrakt} */ @Deprecated public Integer getWatchedTrakt() { return this.watchedTrakt; } /** @deprecated Use {@link #watchedTraktUnique} */ @Deprecated public Integer getWatchedTraktUnique() { return this.watchedTraktUnique; } /** @deprecated Use {@link #watchedElsewhere} */ @Deprecated public Integer getWatchedElsewhere() { return this.watchedElsewhere; } /** @deprecated Use {@link #library} */ @Deprecated public Integer getLibrary() { return this.library; } /** @deprecated Use {@link #unwatched} */ @Deprecated public Integer getUnwatched() { return this.unwatched; } } public Integer friends; public Shows shows; public Episodes episodes; public Movies movies; /** @deprecated Use {@link #friends} */ @Deprecated public Integer getFriends() { return this.friends; } /** @deprecated Use {@link #shows} */ @Deprecated public Shows getShows() { return this.shows; } /** @deprecated Use {@link #episodes} */ @Deprecated public Episodes getEpisodes() { return this.episodes; } /** @deprecated Use {@link #movies} */ @Deprecated public Movies getMovies() { return this.movies; } } public String username; @SerializedName("protected") public Boolean _protected; @SerializedName("full_name") public String fullName;
public Gender gender;
UweTrottmann/MovieTracker
SeriesGuideMovies/src/com/jakewharton/trakt/entities/TvShow.java
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktEntity.java // public interface TraktEntity extends Serializable {} // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/DayOfTheWeek.java // public enum DayOfTheWeek implements TraktEnumeration { // Sunday("Sunday"), // Monday("Monday"), // Tuesday("Tuesday"), // Wednesday("Wednesday"), // Thursday("Thursday"), // Friday("Friday"), // Saturday("Saturday"); // // private final String value; // // private DayOfTheWeek(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, DayOfTheWeek> STRING_MAPPING = new HashMap<String, DayOfTheWeek>(); // // static { // for (DayOfTheWeek via : DayOfTheWeek.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static DayOfTheWeek fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // }
import com.google.myjson.annotations.SerializedName; import com.jakewharton.trakt.TraktEntity; import com.jakewharton.trakt.enumerations.DayOfTheWeek; import java.util.Date; import java.util.List;
package com.jakewharton.trakt.entities; public class TvShow extends MediaBase implements TraktEntity { private static final long serialVersionUID = 862473930551420996L; @SerializedName("first_aired") public Date firstAired; public String country; public String overview; public Integer runtime; public String network;
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktEntity.java // public interface TraktEntity extends Serializable {} // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/DayOfTheWeek.java // public enum DayOfTheWeek implements TraktEnumeration { // Sunday("Sunday"), // Monday("Monday"), // Tuesday("Tuesday"), // Wednesday("Wednesday"), // Thursday("Thursday"), // Friday("Friday"), // Saturday("Saturday"); // // private final String value; // // private DayOfTheWeek(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, DayOfTheWeek> STRING_MAPPING = new HashMap<String, DayOfTheWeek>(); // // static { // for (DayOfTheWeek via : DayOfTheWeek.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static DayOfTheWeek fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // Path: SeriesGuideMovies/src/com/jakewharton/trakt/entities/TvShow.java import com.google.myjson.annotations.SerializedName; import com.jakewharton.trakt.TraktEntity; import com.jakewharton.trakt.enumerations.DayOfTheWeek; import java.util.Date; import java.util.List; package com.jakewharton.trakt.entities; public class TvShow extends MediaBase implements TraktEntity { private static final long serialVersionUID = 862473930551420996L; @SerializedName("first_aired") public Date firstAired; public String country; public String overview; public Integer runtime; public String network;
@SerializedName("air_day") public DayOfTheWeek airDay;
UweTrottmann/MovieTracker
SeriesGuideMovies/src/com/jakewharton/trakt/entities/ActivityItemBase.java
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktEntity.java // public interface TraktEntity extends Serializable {} // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/ActivityAction.java // public enum ActivityAction implements TraktEnumeration { // All("all"), // Watching("watching"), // Scrobble("scrobble"), // Checkin("checkin"), // Seen("seen"), // Collection("collection"), // Rating("rating"), // Watchlist("watchlist"), // Shout("shout"), // Created("created"), // ItemAdded("item_added"); // // private final String value; // // private ActivityAction(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, ActivityAction> STRING_MAPPING = new HashMap<String, ActivityAction>(); // // static { // for (ActivityAction via : ActivityAction.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static ActivityAction fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/ActivityType.java // public enum ActivityType implements TraktEnumeration { // All("all"), // Episode("episode"), // Show("show"), // Movie("movie"), // List("list"); // // private final String value; // // private ActivityType(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, ActivityType> STRING_MAPPING = new HashMap<String, ActivityType>(); // // static { // for (ActivityType via : ActivityType.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static ActivityType fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/Rating.java // public enum Rating implements TraktEnumeration { // Love("love"), // Hate("hate"), // Unrate("unrate"); // // private final String value; // // private Rating(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, Rating> STRING_MAPPING = new HashMap<String, Rating>(); // // static { // for (Rating via : Rating.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static Rating fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // }
import com.google.myjson.annotations.SerializedName; import com.jakewharton.trakt.TraktEntity; import com.jakewharton.trakt.enumerations.ActivityAction; import com.jakewharton.trakt.enumerations.ActivityType; import com.jakewharton.trakt.enumerations.Rating; import java.util.Date;
package com.jakewharton.trakt.entities; /** * Represents a Trakt activity item. See * <a href="http://trakt.tv/api-docs/activity-community"> the documentation</a> * for a list of {@link #type}s and {@link #action}s and which properties they * include. */ public class ActivityItemBase implements TraktEntity { private static final long serialVersionUID = -7644201423350992899L; public static class When implements TraktEntity { private static final long serialVersionUID = 8126529523279348951L; public String day; public String time; } public static class Elapsed implements TraktEntity { private static final long serialVersionUID = -6458210319412047876L; @SerializedName("short") public String _short; public String full; } public static class Shout implements TraktEntity { private static final long serialVersionUID = 7034369697434197979L; public String text; } public Date timestamp; public Date watched; public When when; public Elapsed elapsed;
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktEntity.java // public interface TraktEntity extends Serializable {} // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/ActivityAction.java // public enum ActivityAction implements TraktEnumeration { // All("all"), // Watching("watching"), // Scrobble("scrobble"), // Checkin("checkin"), // Seen("seen"), // Collection("collection"), // Rating("rating"), // Watchlist("watchlist"), // Shout("shout"), // Created("created"), // ItemAdded("item_added"); // // private final String value; // // private ActivityAction(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, ActivityAction> STRING_MAPPING = new HashMap<String, ActivityAction>(); // // static { // for (ActivityAction via : ActivityAction.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static ActivityAction fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/ActivityType.java // public enum ActivityType implements TraktEnumeration { // All("all"), // Episode("episode"), // Show("show"), // Movie("movie"), // List("list"); // // private final String value; // // private ActivityType(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, ActivityType> STRING_MAPPING = new HashMap<String, ActivityType>(); // // static { // for (ActivityType via : ActivityType.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static ActivityType fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/Rating.java // public enum Rating implements TraktEnumeration { // Love("love"), // Hate("hate"), // Unrate("unrate"); // // private final String value; // // private Rating(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, Rating> STRING_MAPPING = new HashMap<String, Rating>(); // // static { // for (Rating via : Rating.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static Rating fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // Path: SeriesGuideMovies/src/com/jakewharton/trakt/entities/ActivityItemBase.java import com.google.myjson.annotations.SerializedName; import com.jakewharton.trakt.TraktEntity; import com.jakewharton.trakt.enumerations.ActivityAction; import com.jakewharton.trakt.enumerations.ActivityType; import com.jakewharton.trakt.enumerations.Rating; import java.util.Date; package com.jakewharton.trakt.entities; /** * Represents a Trakt activity item. See * <a href="http://trakt.tv/api-docs/activity-community"> the documentation</a> * for a list of {@link #type}s and {@link #action}s and which properties they * include. */ public class ActivityItemBase implements TraktEntity { private static final long serialVersionUID = -7644201423350992899L; public static class When implements TraktEntity { private static final long serialVersionUID = 8126529523279348951L; public String day; public String time; } public static class Elapsed implements TraktEntity { private static final long serialVersionUID = -6458210319412047876L; @SerializedName("short") public String _short; public String full; } public static class Shout implements TraktEntity { private static final long serialVersionUID = 7034369697434197979L; public String text; } public Date timestamp; public Date watched; public When when; public Elapsed elapsed;
public ActivityType type;
UweTrottmann/MovieTracker
SeriesGuideMovies/src/com/jakewharton/trakt/entities/ActivityItemBase.java
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktEntity.java // public interface TraktEntity extends Serializable {} // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/ActivityAction.java // public enum ActivityAction implements TraktEnumeration { // All("all"), // Watching("watching"), // Scrobble("scrobble"), // Checkin("checkin"), // Seen("seen"), // Collection("collection"), // Rating("rating"), // Watchlist("watchlist"), // Shout("shout"), // Created("created"), // ItemAdded("item_added"); // // private final String value; // // private ActivityAction(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, ActivityAction> STRING_MAPPING = new HashMap<String, ActivityAction>(); // // static { // for (ActivityAction via : ActivityAction.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static ActivityAction fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/ActivityType.java // public enum ActivityType implements TraktEnumeration { // All("all"), // Episode("episode"), // Show("show"), // Movie("movie"), // List("list"); // // private final String value; // // private ActivityType(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, ActivityType> STRING_MAPPING = new HashMap<String, ActivityType>(); // // static { // for (ActivityType via : ActivityType.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static ActivityType fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/Rating.java // public enum Rating implements TraktEnumeration { // Love("love"), // Hate("hate"), // Unrate("unrate"); // // private final String value; // // private Rating(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, Rating> STRING_MAPPING = new HashMap<String, Rating>(); // // static { // for (Rating via : Rating.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static Rating fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // }
import com.google.myjson.annotations.SerializedName; import com.jakewharton.trakt.TraktEntity; import com.jakewharton.trakt.enumerations.ActivityAction; import com.jakewharton.trakt.enumerations.ActivityType; import com.jakewharton.trakt.enumerations.Rating; import java.util.Date;
package com.jakewharton.trakt.entities; /** * Represents a Trakt activity item. See * <a href="http://trakt.tv/api-docs/activity-community"> the documentation</a> * for a list of {@link #type}s and {@link #action}s and which properties they * include. */ public class ActivityItemBase implements TraktEntity { private static final long serialVersionUID = -7644201423350992899L; public static class When implements TraktEntity { private static final long serialVersionUID = 8126529523279348951L; public String day; public String time; } public static class Elapsed implements TraktEntity { private static final long serialVersionUID = -6458210319412047876L; @SerializedName("short") public String _short; public String full; } public static class Shout implements TraktEntity { private static final long serialVersionUID = 7034369697434197979L; public String text; } public Date timestamp; public Date watched; public When when; public Elapsed elapsed; public ActivityType type;
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktEntity.java // public interface TraktEntity extends Serializable {} // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/ActivityAction.java // public enum ActivityAction implements TraktEnumeration { // All("all"), // Watching("watching"), // Scrobble("scrobble"), // Checkin("checkin"), // Seen("seen"), // Collection("collection"), // Rating("rating"), // Watchlist("watchlist"), // Shout("shout"), // Created("created"), // ItemAdded("item_added"); // // private final String value; // // private ActivityAction(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, ActivityAction> STRING_MAPPING = new HashMap<String, ActivityAction>(); // // static { // for (ActivityAction via : ActivityAction.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static ActivityAction fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/ActivityType.java // public enum ActivityType implements TraktEnumeration { // All("all"), // Episode("episode"), // Show("show"), // Movie("movie"), // List("list"); // // private final String value; // // private ActivityType(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, ActivityType> STRING_MAPPING = new HashMap<String, ActivityType>(); // // static { // for (ActivityType via : ActivityType.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static ActivityType fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/Rating.java // public enum Rating implements TraktEnumeration { // Love("love"), // Hate("hate"), // Unrate("unrate"); // // private final String value; // // private Rating(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, Rating> STRING_MAPPING = new HashMap<String, Rating>(); // // static { // for (Rating via : Rating.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static Rating fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // Path: SeriesGuideMovies/src/com/jakewharton/trakt/entities/ActivityItemBase.java import com.google.myjson.annotations.SerializedName; import com.jakewharton.trakt.TraktEntity; import com.jakewharton.trakt.enumerations.ActivityAction; import com.jakewharton.trakt.enumerations.ActivityType; import com.jakewharton.trakt.enumerations.Rating; import java.util.Date; package com.jakewharton.trakt.entities; /** * Represents a Trakt activity item. See * <a href="http://trakt.tv/api-docs/activity-community"> the documentation</a> * for a list of {@link #type}s and {@link #action}s and which properties they * include. */ public class ActivityItemBase implements TraktEntity { private static final long serialVersionUID = -7644201423350992899L; public static class When implements TraktEntity { private static final long serialVersionUID = 8126529523279348951L; public String day; public String time; } public static class Elapsed implements TraktEntity { private static final long serialVersionUID = -6458210319412047876L; @SerializedName("short") public String _short; public String full; } public static class Shout implements TraktEntity { private static final long serialVersionUID = 7034369697434197979L; public String text; } public Date timestamp; public Date watched; public When when; public Elapsed elapsed; public ActivityType type;
public ActivityAction action;
UweTrottmann/MovieTracker
SeriesGuideMovies/src/com/jakewharton/trakt/entities/ActivityItemBase.java
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktEntity.java // public interface TraktEntity extends Serializable {} // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/ActivityAction.java // public enum ActivityAction implements TraktEnumeration { // All("all"), // Watching("watching"), // Scrobble("scrobble"), // Checkin("checkin"), // Seen("seen"), // Collection("collection"), // Rating("rating"), // Watchlist("watchlist"), // Shout("shout"), // Created("created"), // ItemAdded("item_added"); // // private final String value; // // private ActivityAction(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, ActivityAction> STRING_MAPPING = new HashMap<String, ActivityAction>(); // // static { // for (ActivityAction via : ActivityAction.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static ActivityAction fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/ActivityType.java // public enum ActivityType implements TraktEnumeration { // All("all"), // Episode("episode"), // Show("show"), // Movie("movie"), // List("list"); // // private final String value; // // private ActivityType(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, ActivityType> STRING_MAPPING = new HashMap<String, ActivityType>(); // // static { // for (ActivityType via : ActivityType.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static ActivityType fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/Rating.java // public enum Rating implements TraktEnumeration { // Love("love"), // Hate("hate"), // Unrate("unrate"); // // private final String value; // // private Rating(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, Rating> STRING_MAPPING = new HashMap<String, Rating>(); // // static { // for (Rating via : Rating.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static Rating fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // }
import com.google.myjson.annotations.SerializedName; import com.jakewharton.trakt.TraktEntity; import com.jakewharton.trakt.enumerations.ActivityAction; import com.jakewharton.trakt.enumerations.ActivityType; import com.jakewharton.trakt.enumerations.Rating; import java.util.Date;
package com.jakewharton.trakt.entities; /** * Represents a Trakt activity item. See * <a href="http://trakt.tv/api-docs/activity-community"> the documentation</a> * for a list of {@link #type}s and {@link #action}s and which properties they * include. */ public class ActivityItemBase implements TraktEntity { private static final long serialVersionUID = -7644201423350992899L; public static class When implements TraktEntity { private static final long serialVersionUID = 8126529523279348951L; public String day; public String time; } public static class Elapsed implements TraktEntity { private static final long serialVersionUID = -6458210319412047876L; @SerializedName("short") public String _short; public String full; } public static class Shout implements TraktEntity { private static final long serialVersionUID = 7034369697434197979L; public String text; } public Date timestamp; public Date watched; public When when; public Elapsed elapsed; public ActivityType type; public ActivityAction action; public UserProfile user;
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktEntity.java // public interface TraktEntity extends Serializable {} // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/ActivityAction.java // public enum ActivityAction implements TraktEnumeration { // All("all"), // Watching("watching"), // Scrobble("scrobble"), // Checkin("checkin"), // Seen("seen"), // Collection("collection"), // Rating("rating"), // Watchlist("watchlist"), // Shout("shout"), // Created("created"), // ItemAdded("item_added"); // // private final String value; // // private ActivityAction(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, ActivityAction> STRING_MAPPING = new HashMap<String, ActivityAction>(); // // static { // for (ActivityAction via : ActivityAction.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static ActivityAction fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/ActivityType.java // public enum ActivityType implements TraktEnumeration { // All("all"), // Episode("episode"), // Show("show"), // Movie("movie"), // List("list"); // // private final String value; // // private ActivityType(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, ActivityType> STRING_MAPPING = new HashMap<String, ActivityType>(); // // static { // for (ActivityType via : ActivityType.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static ActivityType fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/Rating.java // public enum Rating implements TraktEnumeration { // Love("love"), // Hate("hate"), // Unrate("unrate"); // // private final String value; // // private Rating(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, Rating> STRING_MAPPING = new HashMap<String, Rating>(); // // static { // for (Rating via : Rating.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static Rating fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // Path: SeriesGuideMovies/src/com/jakewharton/trakt/entities/ActivityItemBase.java import com.google.myjson.annotations.SerializedName; import com.jakewharton.trakt.TraktEntity; import com.jakewharton.trakt.enumerations.ActivityAction; import com.jakewharton.trakt.enumerations.ActivityType; import com.jakewharton.trakt.enumerations.Rating; import java.util.Date; package com.jakewharton.trakt.entities; /** * Represents a Trakt activity item. See * <a href="http://trakt.tv/api-docs/activity-community"> the documentation</a> * for a list of {@link #type}s and {@link #action}s and which properties they * include. */ public class ActivityItemBase implements TraktEntity { private static final long serialVersionUID = -7644201423350992899L; public static class When implements TraktEntity { private static final long serialVersionUID = 8126529523279348951L; public String day; public String time; } public static class Elapsed implements TraktEntity { private static final long serialVersionUID = -6458210319412047876L; @SerializedName("short") public String _short; public String full; } public static class Shout implements TraktEntity { private static final long serialVersionUID = 7034369697434197979L; public String text; } public Date timestamp; public Date watched; public When when; public Elapsed elapsed; public ActivityType type; public ActivityAction action; public UserProfile user;
public Rating rating;
UweTrottmann/MovieTracker
SeriesGuideMovies/src/com/jakewharton/trakt/entities/MediaBase.java
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktEntity.java // public interface TraktEntity extends Serializable {} // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/Rating.java // public enum Rating implements TraktEnumeration { // Love("love"), // Hate("hate"), // Unrate("unrate"); // // private final String value; // // private Rating(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, Rating> STRING_MAPPING = new HashMap<String, Rating>(); // // static { // for (Rating via : Rating.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static Rating fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // }
import com.google.myjson.annotations.SerializedName; import com.jakewharton.trakt.TraktEntity; import com.jakewharton.trakt.enumerations.Rating; import java.util.Date; import java.util.List;
package com.jakewharton.trakt.entities; public abstract class MediaBase implements TraktEntity { private static final long serialVersionUID = 753880113366868498L; public static class Stats implements TraktEntity { private static final long serialVersionUID = -5436127125832664020L; public Integer watchers; public Integer plays; /** @deprecated Use {@link #watchers} */ @Deprecated public Integer getWatchers() { return this.watchers; } /** @deprecated Use {@link #plays} */ @Deprecated public Integer getPlays() { return this.plays; } } public String title; public Integer year; public String url; public Images images; @SerializedName("top_watchers") public List<UserProfile> topWatchers; public Ratings ratings; public Stats stats; @SerializedName("imdb_id") public String imdbId;
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktEntity.java // public interface TraktEntity extends Serializable {} // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/Rating.java // public enum Rating implements TraktEnumeration { // Love("love"), // Hate("hate"), // Unrate("unrate"); // // private final String value; // // private Rating(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, Rating> STRING_MAPPING = new HashMap<String, Rating>(); // // static { // for (Rating via : Rating.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static Rating fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // Path: SeriesGuideMovies/src/com/jakewharton/trakt/entities/MediaBase.java import com.google.myjson.annotations.SerializedName; import com.jakewharton.trakt.TraktEntity; import com.jakewharton.trakt.enumerations.Rating; import java.util.Date; import java.util.List; package com.jakewharton.trakt.entities; public abstract class MediaBase implements TraktEntity { private static final long serialVersionUID = 753880113366868498L; public static class Stats implements TraktEntity { private static final long serialVersionUID = -5436127125832664020L; public Integer watchers; public Integer plays; /** @deprecated Use {@link #watchers} */ @Deprecated public Integer getWatchers() { return this.watchers; } /** @deprecated Use {@link #plays} */ @Deprecated public Integer getPlays() { return this.plays; } } public String title; public Integer year; public String url; public Images images; @SerializedName("top_watchers") public List<UserProfile> topWatchers; public Ratings ratings; public Stats stats; @SerializedName("imdb_id") public String imdbId;
public Rating rating;
UweTrottmann/MovieTracker
SeriesGuideMovies/src/com/uwetrottmann/movies/util/SimpleCrypto.java
// Path: SeriesGuideMovies/src/com/uwetrottmann/movies/ui/AppPreferences.java // public class AppPreferences { // // public static final String KEY_TRAKTUSER = "com.uwetrottmann.movies.trakt.username"; // // public static final String KEY_TRAKTPWD = "com.uwetrottmann.movies.trakt.password"; // // public static final String KEY_RANDOM = "com.uwetrottmann.movies.random"; // // public static final String KEY_ENABLEANALYTICS = "com.uwetrottmann.movies.analytics"; // // public static final String KEY_SHAREWITHGETGLUE = "com.uwetrottmann.movies.share.getglue"; // // public static final String KEY_SHAREWITHTRAKT = "com.uwetrottmann.movies.share.trakt"; // // public static final String KEY_NAVSELECTION = "com.uwetrottmann.movies.navselections"; // // }
import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.uwetrottmann.movies.ui.AppPreferences; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec;
/* * Copyright 2012 Uwe Trottmann * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.uwetrottmann.movies.util; /** * Usage: * * <pre> * String crypto = SimpleCrypto.encrypt(cleartext) * ... * String cleartext = SimpleCrypto.decrypt(crypto) * </pre> * * @author ferenc.hechler, modified by Uwe Trottmann for SeriesGuide */ public class SimpleCrypto { public static String encrypt(String cleartext, Context context) throws Exception { byte[] rawKey = getRawKey(context); byte[] result = encrypt(rawKey, cleartext.getBytes()); return toHex(result); } public static String decrypt(String encrypted, Context context) throws Exception { byte[] rawKey = getRawKey(context); byte[] enc = toByte(encrypted); byte[] result = decrypt(rawKey, enc); return new String(result); } private static byte[] getRawKey(Context context) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context .getApplicationContext());
// Path: SeriesGuideMovies/src/com/uwetrottmann/movies/ui/AppPreferences.java // public class AppPreferences { // // public static final String KEY_TRAKTUSER = "com.uwetrottmann.movies.trakt.username"; // // public static final String KEY_TRAKTPWD = "com.uwetrottmann.movies.trakt.password"; // // public static final String KEY_RANDOM = "com.uwetrottmann.movies.random"; // // public static final String KEY_ENABLEANALYTICS = "com.uwetrottmann.movies.analytics"; // // public static final String KEY_SHAREWITHGETGLUE = "com.uwetrottmann.movies.share.getglue"; // // public static final String KEY_SHAREWITHTRAKT = "com.uwetrottmann.movies.share.trakt"; // // public static final String KEY_NAVSELECTION = "com.uwetrottmann.movies.navselections"; // // } // Path: SeriesGuideMovies/src/com/uwetrottmann/movies/util/SimpleCrypto.java import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.uwetrottmann.movies.ui.AppPreferences; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /* * Copyright 2012 Uwe Trottmann * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.uwetrottmann.movies.util; /** * Usage: * * <pre> * String crypto = SimpleCrypto.encrypt(cleartext) * ... * String cleartext = SimpleCrypto.decrypt(crypto) * </pre> * * @author ferenc.hechler, modified by Uwe Trottmann for SeriesGuide */ public class SimpleCrypto { public static String encrypt(String cleartext, Context context) throws Exception { byte[] rawKey = getRawKey(context); byte[] result = encrypt(rawKey, cleartext.getBytes()); return toHex(result); } public static String decrypt(String encrypted, Context context) throws Exception { byte[] rawKey = getRawKey(context); byte[] enc = toByte(encrypted); byte[] result = decrypt(rawKey, enc); return new String(result); } private static byte[] getRawKey(Context context) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context .getApplicationContext());
String seed = prefs.getString(AppPreferences.KEY_RANDOM, null);
UweTrottmann/MovieTracker
SeriesGuideMovies/src/com/jakewharton/trakt/entities/RatingResponse.java
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktEntity.java // public interface TraktEntity extends Serializable {} // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/Rating.java // public enum Rating implements TraktEnumeration { // Love("love"), // Hate("hate"), // Unrate("unrate"); // // private final String value; // // private Rating(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, Rating> STRING_MAPPING = new HashMap<String, Rating>(); // // static { // for (Rating via : Rating.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static Rating fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/RatingType.java // public enum RatingType implements TraktEnumeration { // Episode("episode"), // Movie("movie"), // Show("show"); // // private final String value; // // private RatingType(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, RatingType> STRING_MAPPING = new HashMap<String, RatingType>(); // // static { // for (RatingType via : RatingType.values()) { // STRING_MAPPING.put(via.toString(), via); // } // } // // public static RatingType fromValue(String value) { // return STRING_MAPPING.get(value); // } // }
import com.jakewharton.trakt.TraktEntity; import com.jakewharton.trakt.enumerations.Rating; import com.jakewharton.trakt.enumerations.RatingType;
package com.jakewharton.trakt.entities; public class RatingResponse extends Response implements TraktEntity { private static final long serialVersionUID = 8424378149600617021L;
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktEntity.java // public interface TraktEntity extends Serializable {} // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/Rating.java // public enum Rating implements TraktEnumeration { // Love("love"), // Hate("hate"), // Unrate("unrate"); // // private final String value; // // private Rating(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, Rating> STRING_MAPPING = new HashMap<String, Rating>(); // // static { // for (Rating via : Rating.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static Rating fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/RatingType.java // public enum RatingType implements TraktEnumeration { // Episode("episode"), // Movie("movie"), // Show("show"); // // private final String value; // // private RatingType(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, RatingType> STRING_MAPPING = new HashMap<String, RatingType>(); // // static { // for (RatingType via : RatingType.values()) { // STRING_MAPPING.put(via.toString(), via); // } // } // // public static RatingType fromValue(String value) { // return STRING_MAPPING.get(value); // } // } // Path: SeriesGuideMovies/src/com/jakewharton/trakt/entities/RatingResponse.java import com.jakewharton.trakt.TraktEntity; import com.jakewharton.trakt.enumerations.Rating; import com.jakewharton.trakt.enumerations.RatingType; package com.jakewharton.trakt.entities; public class RatingResponse extends Response implements TraktEntity { private static final long serialVersionUID = 8424378149600617021L;
public RatingType type;
UweTrottmann/MovieTracker
SeriesGuideMovies/src/com/jakewharton/trakt/entities/RatingResponse.java
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktEntity.java // public interface TraktEntity extends Serializable {} // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/Rating.java // public enum Rating implements TraktEnumeration { // Love("love"), // Hate("hate"), // Unrate("unrate"); // // private final String value; // // private Rating(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, Rating> STRING_MAPPING = new HashMap<String, Rating>(); // // static { // for (Rating via : Rating.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static Rating fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/RatingType.java // public enum RatingType implements TraktEnumeration { // Episode("episode"), // Movie("movie"), // Show("show"); // // private final String value; // // private RatingType(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, RatingType> STRING_MAPPING = new HashMap<String, RatingType>(); // // static { // for (RatingType via : RatingType.values()) { // STRING_MAPPING.put(via.toString(), via); // } // } // // public static RatingType fromValue(String value) { // return STRING_MAPPING.get(value); // } // }
import com.jakewharton.trakt.TraktEntity; import com.jakewharton.trakt.enumerations.Rating; import com.jakewharton.trakt.enumerations.RatingType;
package com.jakewharton.trakt.entities; public class RatingResponse extends Response implements TraktEntity { private static final long serialVersionUID = 8424378149600617021L; public RatingType type;
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktEntity.java // public interface TraktEntity extends Serializable {} // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/Rating.java // public enum Rating implements TraktEnumeration { // Love("love"), // Hate("hate"), // Unrate("unrate"); // // private final String value; // // private Rating(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, Rating> STRING_MAPPING = new HashMap<String, Rating>(); // // static { // for (Rating via : Rating.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static Rating fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/RatingType.java // public enum RatingType implements TraktEnumeration { // Episode("episode"), // Movie("movie"), // Show("show"); // // private final String value; // // private RatingType(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, RatingType> STRING_MAPPING = new HashMap<String, RatingType>(); // // static { // for (RatingType via : RatingType.values()) { // STRING_MAPPING.put(via.toString(), via); // } // } // // public static RatingType fromValue(String value) { // return STRING_MAPPING.get(value); // } // } // Path: SeriesGuideMovies/src/com/jakewharton/trakt/entities/RatingResponse.java import com.jakewharton.trakt.TraktEntity; import com.jakewharton.trakt.enumerations.Rating; import com.jakewharton.trakt.enumerations.RatingType; package com.jakewharton.trakt.entities; public class RatingResponse extends Response implements TraktEntity { private static final long serialVersionUID = 8424378149600617021L; public RatingType type;
public Rating rating;
UweTrottmann/MovieTracker
SeriesGuideMovies/src/com/uwetrottmann/tmdb/TmdbApiBuilder.java
// Path: SeriesGuideMovies/src/com/uwetrottmann/tmdb/entities/Response.java // public class Response implements TmdbEntity { // private static final long serialVersionUID = 6943424166245929700L; // // public String status_code; // public String status_message; // }
import com.google.myjson.GsonBuilder; import com.google.myjson.JsonElement; import com.google.myjson.JsonObject; import com.google.myjson.JsonParseException; import com.google.myjson.reflect.TypeToken; import com.jakewharton.apibuilder.ApiBuilder; import com.jakewharton.apibuilder.ApiException; import com.uwetrottmann.tmdb.entities.Response; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.List;
/** * <p> * Execute the remote API method and return the JSON object result. * <p> * <p> * This method can be overridden to select a specific subset of the JSON * object. The overriding implementation should still call 'super.execute()' * and then perform the filtering from there. * </p> * * @return JSON object instance. */ protected final JsonElement execute() { String url = this.buildUrl(); while (url.endsWith("/")) { url = url.substring(0, url.length() - 1); } try { switch (this.method) { case Get: return this.service.get(url); case Post: return this.service.post(url, this.postBody.toString()); default: throw new IllegalArgumentException("Unknown HttpMethod type " + this.method.toString()); } } catch (ApiException ae) { try {
// Path: SeriesGuideMovies/src/com/uwetrottmann/tmdb/entities/Response.java // public class Response implements TmdbEntity { // private static final long serialVersionUID = 6943424166245929700L; // // public String status_code; // public String status_message; // } // Path: SeriesGuideMovies/src/com/uwetrottmann/tmdb/TmdbApiBuilder.java import com.google.myjson.GsonBuilder; import com.google.myjson.JsonElement; import com.google.myjson.JsonObject; import com.google.myjson.JsonParseException; import com.google.myjson.reflect.TypeToken; import com.jakewharton.apibuilder.ApiBuilder; import com.jakewharton.apibuilder.ApiException; import com.uwetrottmann.tmdb.entities.Response; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.List; /** * <p> * Execute the remote API method and return the JSON object result. * <p> * <p> * This method can be overridden to select a specific subset of the JSON * object. The overriding implementation should still call 'super.execute()' * and then perform the filtering from there. * </p> * * @return JSON object instance. */ protected final JsonElement execute() { String url = this.buildUrl(); while (url.endsWith("/")) { url = url.substring(0, url.length() - 1); } try { switch (this.method) { case Get: return this.service.get(url); case Post: return this.service.post(url, this.postBody.toString()); default: throw new IllegalArgumentException("Unknown HttpMethod type " + this.method.toString()); } } catch (ApiException ae) { try {
Response response = this.service.unmarshall(new TypeToken<Response>() {
UweTrottmann/MovieTracker
SeriesGuideMovies/src/com/jakewharton/trakt/TraktApiBuilder.java
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/entities/Response.java // public class Response implements TraktEntity { // private static final long serialVersionUID = 5921890886906816035L; // // public String status; //TODO: enum // public String message; // public String error; // public int wait; // // /** @deprecated Use {@link #status} */ // @Deprecated // public String getStatus() { // return this.status; // } // /** @deprecated Use {@link #message} */ // @Deprecated // public String getMessage() { // return this.message; // } // /** @deprecated Use {@link #error} */ // @Deprecated // public String getError() { // return this.error; // } // }
import com.google.myjson.GsonBuilder; import com.google.myjson.JsonElement; import com.google.myjson.JsonObject; import com.google.myjson.JsonParseException; import com.google.myjson.reflect.TypeToken; import com.jakewharton.apibuilder.ApiBuilder; import com.jakewharton.apibuilder.ApiException; import com.jakewharton.trakt.entities.Response; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.List;
this.postParameter(POST_APP_VERSION, service.getAppVersion()); this.postParameter(POST_APP_DATE, service.getAppDate()); } /** * <p>Execute the remote API method and return the JSON object result.<p> * * <p>This method can be overridden to select a specific subset of the JSON * object. The overriding implementation should still call 'super.execute()' * and then perform the filtering from there.</p> * * @return JSON object instance. */ protected final JsonElement execute() { String url = this.buildUrl(); while (url.endsWith("/")) { url = url.substring(0, url.length() - 1); } try { switch (this.method) { case Get: return this.service.get(url); case Post: return this.service.post(url, this.postBody.toString()); default: throw new IllegalArgumentException("Unknown HttpMethod type " + this.method.toString()); } } catch (ApiException ae) { try {
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/entities/Response.java // public class Response implements TraktEntity { // private static final long serialVersionUID = 5921890886906816035L; // // public String status; //TODO: enum // public String message; // public String error; // public int wait; // // /** @deprecated Use {@link #status} */ // @Deprecated // public String getStatus() { // return this.status; // } // /** @deprecated Use {@link #message} */ // @Deprecated // public String getMessage() { // return this.message; // } // /** @deprecated Use {@link #error} */ // @Deprecated // public String getError() { // return this.error; // } // } // Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktApiBuilder.java import com.google.myjson.GsonBuilder; import com.google.myjson.JsonElement; import com.google.myjson.JsonObject; import com.google.myjson.JsonParseException; import com.google.myjson.reflect.TypeToken; import com.jakewharton.apibuilder.ApiBuilder; import com.jakewharton.apibuilder.ApiException; import com.jakewharton.trakt.entities.Response; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.List; this.postParameter(POST_APP_VERSION, service.getAppVersion()); this.postParameter(POST_APP_DATE, service.getAppDate()); } /** * <p>Execute the remote API method and return the JSON object result.<p> * * <p>This method can be overridden to select a specific subset of the JSON * object. The overriding implementation should still call 'super.execute()' * and then perform the filtering from there.</p> * * @return JSON object instance. */ protected final JsonElement execute() { String url = this.buildUrl(); while (url.endsWith("/")) { url = url.substring(0, url.length() - 1); } try { switch (this.method) { case Get: return this.service.get(url); case Post: return this.service.post(url, this.postBody.toString()); default: throw new IllegalArgumentException("Unknown HttpMethod type " + this.method.toString()); } } catch (ApiException ae) { try {
Response response = this.service.unmarshall(new TypeToken<Response>() {}, ae.getMessage());
UweTrottmann/MovieTracker
SeriesGuideMovies/src/com/jakewharton/trakt/entities/ListResponse.java
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/ListPrivacy.java // public enum ListPrivacy implements TraktEnumeration { // Public("public"), // Friends("friends"), // Private("private"); // // private final String value; // // private ListPrivacy(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, ListPrivacy> STRING_MAPPING = new HashMap<String, ListPrivacy>(); // // static { // for (ListPrivacy via : ListPrivacy.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static ListPrivacy fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // }
import com.jakewharton.trakt.enumerations.ListPrivacy;
package com.jakewharton.trakt.entities; public class ListResponse extends Response { private static final long serialVersionUID = 5368378936105337182L; public String name; public String slug;
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/ListPrivacy.java // public enum ListPrivacy implements TraktEnumeration { // Public("public"), // Friends("friends"), // Private("private"); // // private final String value; // // private ListPrivacy(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, ListPrivacy> STRING_MAPPING = new HashMap<String, ListPrivacy>(); // // static { // for (ListPrivacy via : ListPrivacy.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static ListPrivacy fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // Path: SeriesGuideMovies/src/com/jakewharton/trakt/entities/ListResponse.java import com.jakewharton.trakt.enumerations.ListPrivacy; package com.jakewharton.trakt.entities; public class ListResponse extends Response { private static final long serialVersionUID = 5368378936105337182L; public String name; public String slug;
public ListPrivacy privacy;
UweTrottmann/MovieTracker
SeriesGuideMovies/src/com/jakewharton/trakt/TraktException.java
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/entities/Response.java // public class Response implements TraktEntity { // private static final long serialVersionUID = 5921890886906816035L; // // public String status; //TODO: enum // public String message; // public String error; // public int wait; // // /** @deprecated Use {@link #status} */ // @Deprecated // public String getStatus() { // return this.status; // } // /** @deprecated Use {@link #message} */ // @Deprecated // public String getMessage() { // return this.message; // } // /** @deprecated Use {@link #error} */ // @Deprecated // public String getError() { // return this.error; // } // }
import com.google.myjson.JsonObject; import com.jakewharton.apibuilder.ApiException; import com.jakewharton.trakt.entities.Response;
package com.jakewharton.trakt; public final class TraktException extends RuntimeException { private static final long serialVersionUID = 6158978902757706299L; private final String url; private final JsonObject postBody;
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/entities/Response.java // public class Response implements TraktEntity { // private static final long serialVersionUID = 5921890886906816035L; // // public String status; //TODO: enum // public String message; // public String error; // public int wait; // // /** @deprecated Use {@link #status} */ // @Deprecated // public String getStatus() { // return this.status; // } // /** @deprecated Use {@link #message} */ // @Deprecated // public String getMessage() { // return this.message; // } // /** @deprecated Use {@link #error} */ // @Deprecated // public String getError() { // return this.error; // } // } // Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktException.java import com.google.myjson.JsonObject; import com.jakewharton.apibuilder.ApiException; import com.jakewharton.trakt.entities.Response; package com.jakewharton.trakt; public final class TraktException extends RuntimeException { private static final long serialVersionUID = 6158978902757706299L; private final String url; private final JsonObject postBody;
private final Response response;
UweTrottmann/MovieTracker
SeriesGuideMovies/src/com/jakewharton/trakt/entities/List.java
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktEntity.java // public interface TraktEntity extends Serializable {} // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/ListPrivacy.java // public enum ListPrivacy implements TraktEnumeration { // Public("public"), // Friends("friends"), // Private("private"); // // private final String value; // // private ListPrivacy(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, ListPrivacy> STRING_MAPPING = new HashMap<String, ListPrivacy>(); // // static { // for (ListPrivacy via : ListPrivacy.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static ListPrivacy fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // }
import com.jakewharton.trakt.TraktEntity; import com.jakewharton.trakt.enumerations.ListPrivacy;
package com.jakewharton.trakt.entities; public class List implements TraktEntity { private static final long serialVersionUID = -5768791212077534364L; public String name; public String slug; public String url; public String description;
// Path: SeriesGuideMovies/src/com/jakewharton/trakt/TraktEntity.java // public interface TraktEntity extends Serializable {} // // Path: SeriesGuideMovies/src/com/jakewharton/trakt/enumerations/ListPrivacy.java // public enum ListPrivacy implements TraktEnumeration { // Public("public"), // Friends("friends"), // Private("private"); // // private final String value; // // private ListPrivacy(String value) { // this.value = value; // } // // @Override // public String toString() { // return this.value; // } // // private static final Map<String, ListPrivacy> STRING_MAPPING = new HashMap<String, ListPrivacy>(); // // static { // for (ListPrivacy via : ListPrivacy.values()) { // STRING_MAPPING.put(via.toString().toUpperCase(), via); // } // } // // public static ListPrivacy fromValue(String value) { // return STRING_MAPPING.get(value.toUpperCase()); // } // } // Path: SeriesGuideMovies/src/com/jakewharton/trakt/entities/List.java import com.jakewharton.trakt.TraktEntity; import com.jakewharton.trakt.enumerations.ListPrivacy; package com.jakewharton.trakt.entities; public class List implements TraktEntity { private static final long serialVersionUID = -5768791212077534364L; public String name; public String slug; public String url; public String description;
public ListPrivacy privacy;
UweTrottmann/MovieTracker
SeriesGuideMovies/src/com/uwetrottmann/tmdb/TmdbException.java
// Path: SeriesGuideMovies/src/com/uwetrottmann/tmdb/entities/Response.java // public class Response implements TmdbEntity { // private static final long serialVersionUID = 6943424166245929700L; // // public String status_code; // public String status_message; // }
import com.google.myjson.JsonObject; import com.jakewharton.apibuilder.ApiException; import com.uwetrottmann.tmdb.entities.Response;
/* * Copyright 2012 Uwe Trottmann * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.uwetrottmann.tmdb; public final class TmdbException extends RuntimeException { private static final long serialVersionUID = -5280024879091580667L; private final String url; private final JsonObject postBody;
// Path: SeriesGuideMovies/src/com/uwetrottmann/tmdb/entities/Response.java // public class Response implements TmdbEntity { // private static final long serialVersionUID = 6943424166245929700L; // // public String status_code; // public String status_message; // } // Path: SeriesGuideMovies/src/com/uwetrottmann/tmdb/TmdbException.java import com.google.myjson.JsonObject; import com.jakewharton.apibuilder.ApiException; import com.uwetrottmann.tmdb.entities.Response; /* * Copyright 2012 Uwe Trottmann * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.uwetrottmann.tmdb; public final class TmdbException extends RuntimeException { private static final long serialVersionUID = -5280024879091580667L; private final String url; private final JsonObject postBody;
private final Response response;
jmarranz/relproxy_examples
relproxy_ex_jsf/src/com/journaldev/jsfBeans/ViewEmployeesManagedBean.java
// Path: relproxy_ex_jsf/src/com/journaldev/data/Employee.java // public class Employee { // private String employeeId; // private String employeeName; // public String getEmployeeId() { // return employeeId; // } // public void setEmployeeId(String employeeId) { // this.employeeId = employeeId; // } // public String getEmployeeName() { // return employeeName; // } // public void setEmployeeName(String employeeName) { // this.employeeName = employeeName; // } // }
import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import com.innowhere.relproxy.jproxy.JProxy; import com.journaldev.data.Employee;
package com.journaldev.jsfBeans; @ManagedBean @SessionScoped public class ViewEmployeesManagedBean {
// Path: relproxy_ex_jsf/src/com/journaldev/data/Employee.java // public class Employee { // private String employeeId; // private String employeeName; // public String getEmployeeId() { // return employeeId; // } // public void setEmployeeId(String employeeId) { // this.employeeId = employeeId; // } // public String getEmployeeName() { // return employeeName; // } // public void setEmployeeName(String employeeName) { // this.employeeName = employeeName; // } // } // Path: relproxy_ex_jsf/src/com/journaldev/jsfBeans/ViewEmployeesManagedBean.java import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import com.innowhere.relproxy.jproxy.JProxy; import com.journaldev.data.Employee; package com.journaldev.jsfBeans; @ManagedBean @SessionScoped public class ViewEmployeesManagedBean {
private List<Employee> employees = new ArrayList<Employee>();
jmarranz/relproxy_examples
relproxy_ex_jsf/src/com/journaldev/jsfBeans/ViewEmployeesManagedBeanDelegateImpl.java
// Path: relproxy_ex_jsf/src/com/journaldev/data/Employee.java // public class Employee { // private String employeeId; // private String employeeName; // public String getEmployeeId() { // return employeeId; // } // public void setEmployeeId(String employeeId) { // this.employeeId = employeeId; // } // public String getEmployeeName() { // return employeeName; // } // public void setEmployeeName(String employeeName) { // this.employeeName = employeeName; // } // }
import java.util.List; import com.journaldev.data.Employee;
package com.journaldev.jsfBeans; public class ViewEmployeesManagedBeanDelegateImpl implements ViewEmployeesManagedBeanDelegate {
// Path: relproxy_ex_jsf/src/com/journaldev/data/Employee.java // public class Employee { // private String employeeId; // private String employeeName; // public String getEmployeeId() { // return employeeId; // } // public void setEmployeeId(String employeeId) { // this.employeeId = employeeId; // } // public String getEmployeeName() { // return employeeName; // } // public void setEmployeeName(String employeeName) { // this.employeeName = employeeName; // } // } // Path: relproxy_ex_jsf/src/com/journaldev/jsfBeans/ViewEmployeesManagedBeanDelegateImpl.java import java.util.List; import com.journaldev.data.Employee; package com.journaldev.jsfBeans; public class ViewEmployeesManagedBeanDelegateImpl implements ViewEmployeesManagedBeanDelegate {
public void populateEmployeeList(List<Employee> employees){
jmarranz/relproxy_examples
relproxy_ex_liferay-portlet/docroot/WEB-INF/src/com/meera/conf/JProxyServletContextListener.java
// Path: relproxy_ex_liferay-portlet/docroot/WEB-INF/src/com/meera/liferaymvc/EmployeeLiferayMVC.java // public class EmployeeLiferayMVC extends MVCPortlet { // // protected EmployeeLiferayMVCDelegate delegate; // // public EmployeeLiferayMVC() // { // this.delegate = JProxy.create(new EmployeeLiferayMVCDelegateImpl(this), EmployeeLiferayMVCDelegate.class); // } // // public void addEmployee(ActionRequest actionRequest, // ActionResponse actionResponse) throws IOException, PortletException { // // delegate.addEmployee(actionRequest, actionResponse); // } // } // // Path: relproxy_ex_liferay-portlet/docroot/WEB-INF/src/com/meera/liferaymvc/EmployeeLiferayMVCDelegate.java // public interface EmployeeLiferayMVCDelegate { // // public void addEmployee(ActionRequest actionRequest, // ActionResponse actionResponse) throws IOException, PortletException; // }
import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Properties; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaFileObject; import com.innowhere.relproxy.RelProxyOnReloadListener; import com.innowhere.relproxy.jproxy.JProxy; import com.innowhere.relproxy.jproxy.JProxyCompilerListener; import com.innowhere.relproxy.jproxy.JProxyConfig; import com.innowhere.relproxy.jproxy.JProxyDiagnosticsListener; import com.innowhere.relproxy.jproxy.JProxyInputSourceFileExcludedListener; import com.meera.liferaymvc.EmployeeLiferayMVC; import com.meera.liferaymvc.EmployeeLiferayMVCDelegate;
prop.load(input); inputSourcePath = prop.getProperty("inputSourcePath"); tomcatLibPath = prop.getProperty("tomcatLibPath"); } catch (Exception ex) { throw new RuntimeException(ex); } finally { if (input != null) try { input.close(); } catch (IOException ex) { throw new RuntimeException(ex); } } if (inputSourcePath == null) throw new RuntimeException("Missing inputSourcePath in conf_relproxy.properties"); if (tomcatLibPath == null) throw new RuntimeException("Missing tomcatLibPath in conf_relproxy.properties"); tomcatLibPath += File.separatorChar + "ext" + File.separatorChar + "portlet.jar"; JProxyInputSourceFileExcludedListener excludedListener = new JProxyInputSourceFileExcludedListener() { @Override public boolean isExcluded(File file, File rootFolderOfSources) { String absPath = file.getAbsolutePath(); if (file.isDirectory()) { return absPath.endsWith(File.separatorChar + "conf"); } else {
// Path: relproxy_ex_liferay-portlet/docroot/WEB-INF/src/com/meera/liferaymvc/EmployeeLiferayMVC.java // public class EmployeeLiferayMVC extends MVCPortlet { // // protected EmployeeLiferayMVCDelegate delegate; // // public EmployeeLiferayMVC() // { // this.delegate = JProxy.create(new EmployeeLiferayMVCDelegateImpl(this), EmployeeLiferayMVCDelegate.class); // } // // public void addEmployee(ActionRequest actionRequest, // ActionResponse actionResponse) throws IOException, PortletException { // // delegate.addEmployee(actionRequest, actionResponse); // } // } // // Path: relproxy_ex_liferay-portlet/docroot/WEB-INF/src/com/meera/liferaymvc/EmployeeLiferayMVCDelegate.java // public interface EmployeeLiferayMVCDelegate { // // public void addEmployee(ActionRequest actionRequest, // ActionResponse actionResponse) throws IOException, PortletException; // } // Path: relproxy_ex_liferay-portlet/docroot/WEB-INF/src/com/meera/conf/JProxyServletContextListener.java import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Properties; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaFileObject; import com.innowhere.relproxy.RelProxyOnReloadListener; import com.innowhere.relproxy.jproxy.JProxy; import com.innowhere.relproxy.jproxy.JProxyCompilerListener; import com.innowhere.relproxy.jproxy.JProxyConfig; import com.innowhere.relproxy.jproxy.JProxyDiagnosticsListener; import com.innowhere.relproxy.jproxy.JProxyInputSourceFileExcludedListener; import com.meera.liferaymvc.EmployeeLiferayMVC; import com.meera.liferaymvc.EmployeeLiferayMVCDelegate; prop.load(input); inputSourcePath = prop.getProperty("inputSourcePath"); tomcatLibPath = prop.getProperty("tomcatLibPath"); } catch (Exception ex) { throw new RuntimeException(ex); } finally { if (input != null) try { input.close(); } catch (IOException ex) { throw new RuntimeException(ex); } } if (inputSourcePath == null) throw new RuntimeException("Missing inputSourcePath in conf_relproxy.properties"); if (tomcatLibPath == null) throw new RuntimeException("Missing tomcatLibPath in conf_relproxy.properties"); tomcatLibPath += File.separatorChar + "ext" + File.separatorChar + "portlet.jar"; JProxyInputSourceFileExcludedListener excludedListener = new JProxyInputSourceFileExcludedListener() { @Override public boolean isExcluded(File file, File rootFolderOfSources) { String absPath = file.getAbsolutePath(); if (file.isDirectory()) { return absPath.endsWith(File.separatorChar + "conf"); } else {
return absPath.endsWith(EmployeeLiferayMVC.class.getSimpleName() + ".java") ||
jmarranz/relproxy_examples
relproxy_ex_liferay-portlet/docroot/WEB-INF/src/com/meera/conf/JProxyServletContextListener.java
// Path: relproxy_ex_liferay-portlet/docroot/WEB-INF/src/com/meera/liferaymvc/EmployeeLiferayMVC.java // public class EmployeeLiferayMVC extends MVCPortlet { // // protected EmployeeLiferayMVCDelegate delegate; // // public EmployeeLiferayMVC() // { // this.delegate = JProxy.create(new EmployeeLiferayMVCDelegateImpl(this), EmployeeLiferayMVCDelegate.class); // } // // public void addEmployee(ActionRequest actionRequest, // ActionResponse actionResponse) throws IOException, PortletException { // // delegate.addEmployee(actionRequest, actionResponse); // } // } // // Path: relproxy_ex_liferay-portlet/docroot/WEB-INF/src/com/meera/liferaymvc/EmployeeLiferayMVCDelegate.java // public interface EmployeeLiferayMVCDelegate { // // public void addEmployee(ActionRequest actionRequest, // ActionResponse actionResponse) throws IOException, PortletException; // }
import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Properties; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaFileObject; import com.innowhere.relproxy.RelProxyOnReloadListener; import com.innowhere.relproxy.jproxy.JProxy; import com.innowhere.relproxy.jproxy.JProxyCompilerListener; import com.innowhere.relproxy.jproxy.JProxyConfig; import com.innowhere.relproxy.jproxy.JProxyDiagnosticsListener; import com.innowhere.relproxy.jproxy.JProxyInputSourceFileExcludedListener; import com.meera.liferaymvc.EmployeeLiferayMVC; import com.meera.liferaymvc.EmployeeLiferayMVCDelegate;
inputSourcePath = prop.getProperty("inputSourcePath"); tomcatLibPath = prop.getProperty("tomcatLibPath"); } catch (Exception ex) { throw new RuntimeException(ex); } finally { if (input != null) try { input.close(); } catch (IOException ex) { throw new RuntimeException(ex); } } if (inputSourcePath == null) throw new RuntimeException("Missing inputSourcePath in conf_relproxy.properties"); if (tomcatLibPath == null) throw new RuntimeException("Missing tomcatLibPath in conf_relproxy.properties"); tomcatLibPath += File.separatorChar + "ext" + File.separatorChar + "portlet.jar"; JProxyInputSourceFileExcludedListener excludedListener = new JProxyInputSourceFileExcludedListener() { @Override public boolean isExcluded(File file, File rootFolderOfSources) { String absPath = file.getAbsolutePath(); if (file.isDirectory()) { return absPath.endsWith(File.separatorChar + "conf"); } else { return absPath.endsWith(EmployeeLiferayMVC.class.getSimpleName() + ".java") ||
// Path: relproxy_ex_liferay-portlet/docroot/WEB-INF/src/com/meera/liferaymvc/EmployeeLiferayMVC.java // public class EmployeeLiferayMVC extends MVCPortlet { // // protected EmployeeLiferayMVCDelegate delegate; // // public EmployeeLiferayMVC() // { // this.delegate = JProxy.create(new EmployeeLiferayMVCDelegateImpl(this), EmployeeLiferayMVCDelegate.class); // } // // public void addEmployee(ActionRequest actionRequest, // ActionResponse actionResponse) throws IOException, PortletException { // // delegate.addEmployee(actionRequest, actionResponse); // } // } // // Path: relproxy_ex_liferay-portlet/docroot/WEB-INF/src/com/meera/liferaymvc/EmployeeLiferayMVCDelegate.java // public interface EmployeeLiferayMVCDelegate { // // public void addEmployee(ActionRequest actionRequest, // ActionResponse actionResponse) throws IOException, PortletException; // } // Path: relproxy_ex_liferay-portlet/docroot/WEB-INF/src/com/meera/conf/JProxyServletContextListener.java import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Properties; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaFileObject; import com.innowhere.relproxy.RelProxyOnReloadListener; import com.innowhere.relproxy.jproxy.JProxy; import com.innowhere.relproxy.jproxy.JProxyCompilerListener; import com.innowhere.relproxy.jproxy.JProxyConfig; import com.innowhere.relproxy.jproxy.JProxyDiagnosticsListener; import com.innowhere.relproxy.jproxy.JProxyInputSourceFileExcludedListener; import com.meera.liferaymvc.EmployeeLiferayMVC; import com.meera.liferaymvc.EmployeeLiferayMVCDelegate; inputSourcePath = prop.getProperty("inputSourcePath"); tomcatLibPath = prop.getProperty("tomcatLibPath"); } catch (Exception ex) { throw new RuntimeException(ex); } finally { if (input != null) try { input.close(); } catch (IOException ex) { throw new RuntimeException(ex); } } if (inputSourcePath == null) throw new RuntimeException("Missing inputSourcePath in conf_relproxy.properties"); if (tomcatLibPath == null) throw new RuntimeException("Missing tomcatLibPath in conf_relproxy.properties"); tomcatLibPath += File.separatorChar + "ext" + File.separatorChar + "portlet.jar"; JProxyInputSourceFileExcludedListener excludedListener = new JProxyInputSourceFileExcludedListener() { @Override public boolean isExcluded(File file, File rootFolderOfSources) { String absPath = file.getAbsolutePath(); if (file.isDirectory()) { return absPath.endsWith(File.separatorChar + "conf"); } else { return absPath.endsWith(EmployeeLiferayMVC.class.getSimpleName() + ".java") ||
absPath.endsWith(EmployeeLiferayMVCDelegate.class.getSimpleName() + ".java");
jmarranz/relproxy_examples
relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/RelProxyBuiltinRoot.java
// Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/impl/RelProxyBuiltinImpl.java // public class RelProxyBuiltinImpl implements RelProxyBuiltin // { // protected JProxyScriptEngine jProxyEngine = null; // protected LinkedHashSet<OutputListener> outListeners = new LinkedHashSet<OutputListener>(); // protected LinkedHashSet<CommandListener> commandListeners = new LinkedHashSet<CommandListener>(); // // @Override // public JProxyScriptEngine getJProxyScriptEngine() // { // if (jProxyEngine == null) jProxyEngine = (JProxyScriptEngine)JProxyScriptEngineFactory.create().getScriptEngine(); // return jProxyEngine; // } // // public JProxyScriptEngine getJProxyScriptEngineIfConfigured() // { // if (jProxyEngine == null || !jProxyEngine.isEnabled()) // return null; // return jProxyEngine; // } // // @Override // public void addOutputListener(OutputListener listener) // { // JProxyScriptEngine jProxy = getJProxyScriptEngineIfConfigured(); // if (jProxy != null) // { // listener = jProxy.create(listener,OutputListener.class); // } // outListeners.add(listener); // } // // @Override // public void removeOutputListener(OutputListener listener) // { // JProxyScriptEngine jProxy = getJProxyScriptEngineIfConfigured(); // if (jProxy != null) // { // listener = jProxy.create(listener,OutputListener.class); // } // outListeners.remove(listener); // } // // @Override // public int getOutputListenerCount() // { // return outListeners.size(); // } // // @Override // public void addCommandListener(CommandListener listener) // { // JProxyScriptEngine jProxy = getJProxyScriptEngineIfConfigured(); // if (jProxy != null) // { // listener = jProxy.create(listener,CommandListener.class); // } // commandListeners.add(listener); // } // // @Override // public void removeCommandListener(CommandListener listener) // { // JProxyScriptEngine jProxy = getJProxyScriptEngineIfConfigured(); // if (jProxy != null) // { // listener = jProxy.create(listener,CommandListener.class); // } // commandListeners.remove(listener); // } // // @Override // public int getCommandListenerCount() // { // return commandListeners.size(); // } // // @Override // public void runLoop(InputStream in,PrintStream out) // { // Scanner scanner = new Scanner(in); // // while(true) // { // out.print("Enter phrase:"); // // String input = scanner.nextLine(); // // out.println("Command list:"); // // for(OutputListener listener : outListeners) // listener.write(out); // // out.print("Enter command (or quit):"); // String command = scanner.nextLine(); // if ("quit".equals(command)) // break; // // for(CommandListener listener : commandListeners) // listener.execute(command,input,out); // } // } // }
import com.innowhere.relproxy_builtin_ex.impl.RelProxyBuiltinImpl;
package com.innowhere.relproxy_builtin_ex; /** * * @author jmarranz */ public class RelProxyBuiltinRoot {
// Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/impl/RelProxyBuiltinImpl.java // public class RelProxyBuiltinImpl implements RelProxyBuiltin // { // protected JProxyScriptEngine jProxyEngine = null; // protected LinkedHashSet<OutputListener> outListeners = new LinkedHashSet<OutputListener>(); // protected LinkedHashSet<CommandListener> commandListeners = new LinkedHashSet<CommandListener>(); // // @Override // public JProxyScriptEngine getJProxyScriptEngine() // { // if (jProxyEngine == null) jProxyEngine = (JProxyScriptEngine)JProxyScriptEngineFactory.create().getScriptEngine(); // return jProxyEngine; // } // // public JProxyScriptEngine getJProxyScriptEngineIfConfigured() // { // if (jProxyEngine == null || !jProxyEngine.isEnabled()) // return null; // return jProxyEngine; // } // // @Override // public void addOutputListener(OutputListener listener) // { // JProxyScriptEngine jProxy = getJProxyScriptEngineIfConfigured(); // if (jProxy != null) // { // listener = jProxy.create(listener,OutputListener.class); // } // outListeners.add(listener); // } // // @Override // public void removeOutputListener(OutputListener listener) // { // JProxyScriptEngine jProxy = getJProxyScriptEngineIfConfigured(); // if (jProxy != null) // { // listener = jProxy.create(listener,OutputListener.class); // } // outListeners.remove(listener); // } // // @Override // public int getOutputListenerCount() // { // return outListeners.size(); // } // // @Override // public void addCommandListener(CommandListener listener) // { // JProxyScriptEngine jProxy = getJProxyScriptEngineIfConfigured(); // if (jProxy != null) // { // listener = jProxy.create(listener,CommandListener.class); // } // commandListeners.add(listener); // } // // @Override // public void removeCommandListener(CommandListener listener) // { // JProxyScriptEngine jProxy = getJProxyScriptEngineIfConfigured(); // if (jProxy != null) // { // listener = jProxy.create(listener,CommandListener.class); // } // commandListeners.remove(listener); // } // // @Override // public int getCommandListenerCount() // { // return commandListeners.size(); // } // // @Override // public void runLoop(InputStream in,PrintStream out) // { // Scanner scanner = new Scanner(in); // // while(true) // { // out.print("Enter phrase:"); // // String input = scanner.nextLine(); // // out.println("Command list:"); // // for(OutputListener listener : outListeners) // listener.write(out); // // out.print("Enter command (or quit):"); // String command = scanner.nextLine(); // if ("quit".equals(command)) // break; // // for(CommandListener listener : commandListeners) // listener.execute(command,input,out); // } // } // } // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/RelProxyBuiltinRoot.java import com.innowhere.relproxy_builtin_ex.impl.RelProxyBuiltinImpl; package com.innowhere.relproxy_builtin_ex; /** * * @author jmarranz */ public class RelProxyBuiltinRoot {
private final static RelProxyBuiltinImpl SINGLETON = new RelProxyBuiltinImpl();
jmarranz/relproxy_examples
relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/impl/RelProxyBuiltinImpl.java
// Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/CommandListener.java // public interface CommandListener // { // public void execute(String command,String input,PrintStream out); // } // // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/OutputListener.java // public interface OutputListener // { // public void write(PrintStream out); // } // // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/RelProxyBuiltin.java // public interface RelProxyBuiltin // { // public JProxyScriptEngine getJProxyScriptEngine(); // // public void addOutputListener(OutputListener listener); // public void removeOutputListener(OutputListener listener); // public int getOutputListenerCount(); // // public void addCommandListener(CommandListener listener); // public void removeCommandListener(CommandListener listener); // public int getCommandListenerCount(); // // public void runLoop(InputStream in,PrintStream out); // }
import com.innowhere.relproxy.jproxy.JProxyScriptEngine; import com.innowhere.relproxy.jproxy.JProxyScriptEngineFactory; import com.innowhere.relproxy_builtin_ex.CommandListener; import com.innowhere.relproxy_builtin_ex.OutputListener; import com.innowhere.relproxy_builtin_ex.RelProxyBuiltin; import java.io.InputStream; import java.io.PrintStream; import java.util.LinkedHashSet; import java.util.Scanner;
package com.innowhere.relproxy_builtin_ex.impl; /** * * @author jmarranz */ public class RelProxyBuiltinImpl implements RelProxyBuiltin { protected JProxyScriptEngine jProxyEngine = null;
// Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/CommandListener.java // public interface CommandListener // { // public void execute(String command,String input,PrintStream out); // } // // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/OutputListener.java // public interface OutputListener // { // public void write(PrintStream out); // } // // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/RelProxyBuiltin.java // public interface RelProxyBuiltin // { // public JProxyScriptEngine getJProxyScriptEngine(); // // public void addOutputListener(OutputListener listener); // public void removeOutputListener(OutputListener listener); // public int getOutputListenerCount(); // // public void addCommandListener(CommandListener listener); // public void removeCommandListener(CommandListener listener); // public int getCommandListenerCount(); // // public void runLoop(InputStream in,PrintStream out); // } // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/impl/RelProxyBuiltinImpl.java import com.innowhere.relproxy.jproxy.JProxyScriptEngine; import com.innowhere.relproxy.jproxy.JProxyScriptEngineFactory; import com.innowhere.relproxy_builtin_ex.CommandListener; import com.innowhere.relproxy_builtin_ex.OutputListener; import com.innowhere.relproxy_builtin_ex.RelProxyBuiltin; import java.io.InputStream; import java.io.PrintStream; import java.util.LinkedHashSet; import java.util.Scanner; package com.innowhere.relproxy_builtin_ex.impl; /** * * @author jmarranz */ public class RelProxyBuiltinImpl implements RelProxyBuiltin { protected JProxyScriptEngine jProxyEngine = null;
protected LinkedHashSet<OutputListener> outListeners = new LinkedHashSet<OutputListener>();
jmarranz/relproxy_examples
relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/impl/RelProxyBuiltinImpl.java
// Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/CommandListener.java // public interface CommandListener // { // public void execute(String command,String input,PrintStream out); // } // // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/OutputListener.java // public interface OutputListener // { // public void write(PrintStream out); // } // // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/RelProxyBuiltin.java // public interface RelProxyBuiltin // { // public JProxyScriptEngine getJProxyScriptEngine(); // // public void addOutputListener(OutputListener listener); // public void removeOutputListener(OutputListener listener); // public int getOutputListenerCount(); // // public void addCommandListener(CommandListener listener); // public void removeCommandListener(CommandListener listener); // public int getCommandListenerCount(); // // public void runLoop(InputStream in,PrintStream out); // }
import com.innowhere.relproxy.jproxy.JProxyScriptEngine; import com.innowhere.relproxy.jproxy.JProxyScriptEngineFactory; import com.innowhere.relproxy_builtin_ex.CommandListener; import com.innowhere.relproxy_builtin_ex.OutputListener; import com.innowhere.relproxy_builtin_ex.RelProxyBuiltin; import java.io.InputStream; import java.io.PrintStream; import java.util.LinkedHashSet; import java.util.Scanner;
package com.innowhere.relproxy_builtin_ex.impl; /** * * @author jmarranz */ public class RelProxyBuiltinImpl implements RelProxyBuiltin { protected JProxyScriptEngine jProxyEngine = null; protected LinkedHashSet<OutputListener> outListeners = new LinkedHashSet<OutputListener>();
// Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/CommandListener.java // public interface CommandListener // { // public void execute(String command,String input,PrintStream out); // } // // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/OutputListener.java // public interface OutputListener // { // public void write(PrintStream out); // } // // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/RelProxyBuiltin.java // public interface RelProxyBuiltin // { // public JProxyScriptEngine getJProxyScriptEngine(); // // public void addOutputListener(OutputListener listener); // public void removeOutputListener(OutputListener listener); // public int getOutputListenerCount(); // // public void addCommandListener(CommandListener listener); // public void removeCommandListener(CommandListener listener); // public int getCommandListenerCount(); // // public void runLoop(InputStream in,PrintStream out); // } // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/impl/RelProxyBuiltinImpl.java import com.innowhere.relproxy.jproxy.JProxyScriptEngine; import com.innowhere.relproxy.jproxy.JProxyScriptEngineFactory; import com.innowhere.relproxy_builtin_ex.CommandListener; import com.innowhere.relproxy_builtin_ex.OutputListener; import com.innowhere.relproxy_builtin_ex.RelProxyBuiltin; import java.io.InputStream; import java.io.PrintStream; import java.util.LinkedHashSet; import java.util.Scanner; package com.innowhere.relproxy_builtin_ex.impl; /** * * @author jmarranz */ public class RelProxyBuiltinImpl implements RelProxyBuiltin { protected JProxyScriptEngine jProxyEngine = null; protected LinkedHashSet<OutputListener> outListeners = new LinkedHashSet<OutputListener>();
protected LinkedHashSet<CommandListener> commandListeners = new LinkedHashSet<CommandListener>();
jmarranz/relproxy_examples
relproxy_ex_gwt/src/com/innowhere/relproxyexgwt/server/GreetingServiceDelegateImpl.java
// Path: relproxy_ex_gwt/src/com/innowhere/relproxyexgwt/shared/FieldVerifier.java // public class FieldVerifier { // // /** // * Verifies that the specified name is valid for our service. // * // * In this example, we only require that the name is at least four // * characters. In your application, you can use more complex checks to ensure // * that usernames, passwords, email addresses, URLs, and other fields have the // * proper syntax. // * // * @param name the name to validate // * @return true if valid, false if invalid // */ // public static boolean isValidName(String name) { // if (name == null) { // return false; // } // return name.length() > 3; // } // }
import com.innowhere.relproxyexgwt.shared.FieldVerifier;
package com.innowhere.relproxyexgwt.server; public class GreetingServiceDelegateImpl implements GreetingServiceDelegate { protected GreetingServiceImpl parent; public GreetingServiceDelegateImpl() { } public GreetingServiceDelegateImpl(GreetingServiceImpl parent) { this.parent = parent; } public String greetServer(String input) throws IllegalArgumentException { // Verify that the input is valid.
// Path: relproxy_ex_gwt/src/com/innowhere/relproxyexgwt/shared/FieldVerifier.java // public class FieldVerifier { // // /** // * Verifies that the specified name is valid for our service. // * // * In this example, we only require that the name is at least four // * characters. In your application, you can use more complex checks to ensure // * that usernames, passwords, email addresses, URLs, and other fields have the // * proper syntax. // * // * @param name the name to validate // * @return true if valid, false if invalid // */ // public static boolean isValidName(String name) { // if (name == null) { // return false; // } // return name.length() > 3; // } // } // Path: relproxy_ex_gwt/src/com/innowhere/relproxyexgwt/server/GreetingServiceDelegateImpl.java import com.innowhere.relproxyexgwt.shared.FieldVerifier; package com.innowhere.relproxyexgwt.server; public class GreetingServiceDelegateImpl implements GreetingServiceDelegate { protected GreetingServiceImpl parent; public GreetingServiceDelegateImpl() { } public GreetingServiceDelegateImpl(GreetingServiceImpl parent) { this.parent = parent; } public String greetServer(String input) throws IllegalArgumentException { // Verify that the input is valid.
if (!FieldVerifier.isValidName(input)) {
jmarranz/relproxy_examples
relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex_main/TestListener.java
// Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/CommandListener.java // public interface CommandListener // { // public void execute(String command,String input,PrintStream out); // } // // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/OutputListener.java // public interface OutputListener // { // public void write(PrintStream out); // }
import com.innowhere.relproxy_builtin_ex.CommandListener; import com.innowhere.relproxy_builtin_ex.OutputListener; import java.io.PrintStream;
package com.innowhere.relproxy_builtin_ex_main; /** * * @author jmarranz */ public class TestListener implements OutputListener { @Override public void write(PrintStream out) { out.println("uppercase"); out.println("lowercase"); }
// Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/CommandListener.java // public interface CommandListener // { // public void execute(String command,String input,PrintStream out); // } // // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/OutputListener.java // public interface OutputListener // { // public void write(PrintStream out); // } // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex_main/TestListener.java import com.innowhere.relproxy_builtin_ex.CommandListener; import com.innowhere.relproxy_builtin_ex.OutputListener; import java.io.PrintStream; package com.innowhere.relproxy_builtin_ex_main; /** * * @author jmarranz */ public class TestListener implements OutputListener { @Override public void write(PrintStream out) { out.println("uppercase"); out.println("lowercase"); }
public CommandListener getCommandListener()
jmarranz/relproxy_examples
relproxy_ex_itsnat_maven/src/main/webapp/WEB-INF/javaex/code/example/javaex/JProxyExampleDocument.java
// Path: relproxy_ex_itsnat_netbeans/src/java/example/javaex/FalseDB.java // public class FalseDB // { // protected LinkedList<City> cities; // // public FalseDB() // { // cities = new LinkedList<City>(); // cities.add(new City("Madrid")); // cities.add(new City("Barcelona")); // cities.add(new City("Bilbao")); // } // // public LinkedList<City> getCityList() { return cities; /*cities;*/ } // }
import org.itsnat.comp.ItsNatComponentManager; import org.itsnat.comp.text.ItsNatHTMLInputText; import org.itsnat.core.ItsNatServletRequest; import org.itsnat.core.html.ItsNatHTMLDocument; import org.w3c.dom.Element; import org.w3c.dom.events.Event; import org.w3c.dom.events.EventListener; import org.w3c.dom.events.EventTarget; import org.w3c.dom.html.HTMLDocument; import example.javaex.FalseDB;
package example.javaex; public class JProxyExampleDocument { protected ItsNatHTMLDocument itsNatDoc; // ItsNatHTMLDocument protected ItsNatHTMLInputText textInput; // ItsNatHTMLInputText protected Element resultsElem; // Element
// Path: relproxy_ex_itsnat_netbeans/src/java/example/javaex/FalseDB.java // public class FalseDB // { // protected LinkedList<City> cities; // // public FalseDB() // { // cities = new LinkedList<City>(); // cities.add(new City("Madrid")); // cities.add(new City("Barcelona")); // cities.add(new City("Bilbao")); // } // // public LinkedList<City> getCityList() { return cities; /*cities;*/ } // } // Path: relproxy_ex_itsnat_maven/src/main/webapp/WEB-INF/javaex/code/example/javaex/JProxyExampleDocument.java import org.itsnat.comp.ItsNatComponentManager; import org.itsnat.comp.text.ItsNatHTMLInputText; import org.itsnat.core.ItsNatServletRequest; import org.itsnat.core.html.ItsNatHTMLDocument; import org.w3c.dom.Element; import org.w3c.dom.events.Event; import org.w3c.dom.events.EventListener; import org.w3c.dom.events.EventTarget; import org.w3c.dom.html.HTMLDocument; import example.javaex.FalseDB; package example.javaex; public class JProxyExampleDocument { protected ItsNatHTMLDocument itsNatDoc; // ItsNatHTMLDocument protected ItsNatHTMLInputText textInput; // ItsNatHTMLInputText protected Element resultsElem; // Element
public JProxyExampleDocument(ItsNatServletRequest request,ItsNatHTMLDocument itsNatDoc,FalseDB db)
jmarranz/relproxy_examples
relproxy_ex_gwt/src/com/innowhere/relproxyexgwt/server/GreetingServiceImpl.java
// Path: relproxy_ex_gwt/src/com/innowhere/relproxyexgwt/client/GreetingService.java // @RemoteServiceRelativePath("greet") // public interface GreetingService extends RemoteService { // String greetServer(String name) throws IllegalArgumentException; // }
import java.io.File; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaFileObject; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import com.innowhere.relproxy.RelProxyOnReloadListener; import com.innowhere.relproxy.jproxy.JProxy; import com.innowhere.relproxy.jproxy.JProxyCompilerListener; import com.innowhere.relproxy.jproxy.JProxyConfig; import com.innowhere.relproxy.jproxy.JProxyDiagnosticsListener; import com.innowhere.relproxy.jproxy.JProxyInputSourceFileExcludedListener; import com.innowhere.relproxyexgwt.client.GreetingService;
package com.innowhere.relproxyexgwt.server; /** * The server-side implementation of the RPC service. */ @SuppressWarnings("serial") public class GreetingServiceImpl extends RemoteServiceServlet implements
// Path: relproxy_ex_gwt/src/com/innowhere/relproxyexgwt/client/GreetingService.java // @RemoteServiceRelativePath("greet") // public interface GreetingService extends RemoteService { // String greetServer(String name) throws IllegalArgumentException; // } // Path: relproxy_ex_gwt/src/com/innowhere/relproxyexgwt/server/GreetingServiceImpl.java import java.io.File; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaFileObject; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import com.innowhere.relproxy.RelProxyOnReloadListener; import com.innowhere.relproxy.jproxy.JProxy; import com.innowhere.relproxy.jproxy.JProxyCompilerListener; import com.innowhere.relproxy.jproxy.JProxyConfig; import com.innowhere.relproxy.jproxy.JProxyDiagnosticsListener; import com.innowhere.relproxy.jproxy.JProxyInputSourceFileExcludedListener; import com.innowhere.relproxyexgwt.client.GreetingService; package com.innowhere.relproxyexgwt.server; /** * The server-side implementation of the RPC service. */ @SuppressWarnings("serial") public class GreetingServiceImpl extends RemoteServiceServlet implements
GreetingService {
jmarranz/relproxy_examples
relproxy_ex_gwt/src/com/innowhere/relproxyexgwt/client/Relproxy_ex_gwt.java
// Path: relproxy_ex_gwt/src/com/innowhere/relproxyexgwt/shared/FieldVerifier.java // public class FieldVerifier { // // /** // * Verifies that the specified name is valid for our service. // * // * In this example, we only require that the name is at least four // * characters. In your application, you can use more complex checks to ensure // * that usernames, passwords, email addresses, URLs, and other fields have the // * proper syntax. // * // * @param name the name to validate // * @return true if valid, false if invalid // */ // public static boolean isValidName(String name) { // if (name == null) { // return false; // } // return name.length() > 3; // } // }
import com.innowhere.relproxyexgwt.shared.FieldVerifier; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel;
sendButton.setEnabled(true); sendButton.setFocus(true); } }); // Create a handler for the sendButton and nameField class MyHandler implements ClickHandler, KeyUpHandler { /** * Fired when the user clicks on the sendButton. */ public void onClick(ClickEvent event) { sendNameToServer(); } /** * Fired when the user types in the nameField. */ public void onKeyUp(KeyUpEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { sendNameToServer(); } } /** * Send the name from the nameField to the server and wait for a response. */ private void sendNameToServer() { // First, we validate the input. errorLabel.setText(""); String textToServer = nameField.getText();
// Path: relproxy_ex_gwt/src/com/innowhere/relproxyexgwt/shared/FieldVerifier.java // public class FieldVerifier { // // /** // * Verifies that the specified name is valid for our service. // * // * In this example, we only require that the name is at least four // * characters. In your application, you can use more complex checks to ensure // * that usernames, passwords, email addresses, URLs, and other fields have the // * proper syntax. // * // * @param name the name to validate // * @return true if valid, false if invalid // */ // public static boolean isValidName(String name) { // if (name == null) { // return false; // } // return name.length() > 3; // } // } // Path: relproxy_ex_gwt/src/com/innowhere/relproxyexgwt/client/Relproxy_ex_gwt.java import com.innowhere.relproxyexgwt.shared.FieldVerifier; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; sendButton.setEnabled(true); sendButton.setFocus(true); } }); // Create a handler for the sendButton and nameField class MyHandler implements ClickHandler, KeyUpHandler { /** * Fired when the user clicks on the sendButton. */ public void onClick(ClickEvent event) { sendNameToServer(); } /** * Fired when the user types in the nameField. */ public void onKeyUp(KeyUpEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { sendNameToServer(); } } /** * Send the name from the nameField to the server and wait for a response. */ private void sendNameToServer() { // First, we validate the input. errorLabel.setText(""); String textToServer = nameField.getText();
if (!FieldVerifier.isValidName(textToServer)) {
jmarranz/relproxy_examples
relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex_main/Main.java
// Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/CommandListener.java // public interface CommandListener // { // public void execute(String command,String input,PrintStream out); // } // // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/RelProxyBuiltin.java // public interface RelProxyBuiltin // { // public JProxyScriptEngine getJProxyScriptEngine(); // // public void addOutputListener(OutputListener listener); // public void removeOutputListener(OutputListener listener); // public int getOutputListenerCount(); // // public void addCommandListener(CommandListener listener); // public void removeCommandListener(CommandListener listener); // public int getCommandListenerCount(); // // public void runLoop(InputStream in,PrintStream out); // } // // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/RelProxyBuiltinRoot.java // public class RelProxyBuiltinRoot // { // private final static RelProxyBuiltinImpl SINGLETON = new RelProxyBuiltinImpl(); // // public static RelProxyBuiltin get() // { // return SINGLETON; // } // }
import com.innowhere.relproxy.RelProxyOnReloadListener; import com.innowhere.relproxy.jproxy.JProxy; import com.innowhere.relproxy.jproxy.JProxyCompilerListener; import com.innowhere.relproxy.jproxy.JProxyConfig; import com.innowhere.relproxy.jproxy.JProxyDiagnosticsListener; import com.innowhere.relproxy.jproxy.JProxyInputSourceFileExcludedListener; import com.innowhere.relproxy.jproxy.JProxyScriptEngine; import com.innowhere.relproxy_builtin_ex.CommandListener; import com.innowhere.relproxy_builtin_ex.RelProxyBuiltin; import com.innowhere.relproxy_builtin_ex.RelProxyBuiltinRoot; import java.io.File; import java.lang.reflect.Method; import java.net.URL; import java.util.Arrays; import java.util.List; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaFileObject;
public void afterCompile(File file) { System.out.println("After compile: " + file); } }; JProxyDiagnosticsListener diagnosticsListener = new JProxyDiagnosticsListener() { @Override public void onDiagnostics(DiagnosticCollector<JavaFileObject> diagnostics) { List<Diagnostic<? extends JavaFileObject>> diagList = diagnostics.getDiagnostics(); int i = 1; for (Diagnostic diagnostic : diagList) { System.err.println("Diagnostic " + i); System.err.println(" code: " + diagnostic.getCode()); System.err.println(" kind: " + diagnostic.getKind()); System.err.println(" line number: " + diagnostic.getLineNumber()); System.err.println(" column number: " + diagnostic.getColumnNumber()); System.err.println(" start position: " + diagnostic.getStartPosition()); System.err.println(" position: " + diagnostic.getPosition()); System.err.println(" end position: " + diagnostic.getEndPosition()); System.err.println(" source: " + diagnostic.getSource()); System.err.println(" message: " + diagnostic.getMessage(null)); i++; } } };
// Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/CommandListener.java // public interface CommandListener // { // public void execute(String command,String input,PrintStream out); // } // // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/RelProxyBuiltin.java // public interface RelProxyBuiltin // { // public JProxyScriptEngine getJProxyScriptEngine(); // // public void addOutputListener(OutputListener listener); // public void removeOutputListener(OutputListener listener); // public int getOutputListenerCount(); // // public void addCommandListener(CommandListener listener); // public void removeCommandListener(CommandListener listener); // public int getCommandListenerCount(); // // public void runLoop(InputStream in,PrintStream out); // } // // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/RelProxyBuiltinRoot.java // public class RelProxyBuiltinRoot // { // private final static RelProxyBuiltinImpl SINGLETON = new RelProxyBuiltinImpl(); // // public static RelProxyBuiltin get() // { // return SINGLETON; // } // } // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex_main/Main.java import com.innowhere.relproxy.RelProxyOnReloadListener; import com.innowhere.relproxy.jproxy.JProxy; import com.innowhere.relproxy.jproxy.JProxyCompilerListener; import com.innowhere.relproxy.jproxy.JProxyConfig; import com.innowhere.relproxy.jproxy.JProxyDiagnosticsListener; import com.innowhere.relproxy.jproxy.JProxyInputSourceFileExcludedListener; import com.innowhere.relproxy.jproxy.JProxyScriptEngine; import com.innowhere.relproxy_builtin_ex.CommandListener; import com.innowhere.relproxy_builtin_ex.RelProxyBuiltin; import com.innowhere.relproxy_builtin_ex.RelProxyBuiltinRoot; import java.io.File; import java.lang.reflect.Method; import java.net.URL; import java.util.Arrays; import java.util.List; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaFileObject; public void afterCompile(File file) { System.out.println("After compile: " + file); } }; JProxyDiagnosticsListener diagnosticsListener = new JProxyDiagnosticsListener() { @Override public void onDiagnostics(DiagnosticCollector<JavaFileObject> diagnostics) { List<Diagnostic<? extends JavaFileObject>> diagList = diagnostics.getDiagnostics(); int i = 1; for (Diagnostic diagnostic : diagList) { System.err.println("Diagnostic " + i); System.err.println(" code: " + diagnostic.getCode()); System.err.println(" kind: " + diagnostic.getKind()); System.err.println(" line number: " + diagnostic.getLineNumber()); System.err.println(" column number: " + diagnostic.getColumnNumber()); System.err.println(" start position: " + diagnostic.getStartPosition()); System.err.println(" position: " + diagnostic.getPosition()); System.err.println(" end position: " + diagnostic.getEndPosition()); System.err.println(" source: " + diagnostic.getSource()); System.err.println(" message: " + diagnostic.getMessage(null)); i++; } } };
RelProxyBuiltin rpbRoot = RelProxyBuiltinRoot.get();
jmarranz/relproxy_examples
relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex_main/Main.java
// Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/CommandListener.java // public interface CommandListener // { // public void execute(String command,String input,PrintStream out); // } // // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/RelProxyBuiltin.java // public interface RelProxyBuiltin // { // public JProxyScriptEngine getJProxyScriptEngine(); // // public void addOutputListener(OutputListener listener); // public void removeOutputListener(OutputListener listener); // public int getOutputListenerCount(); // // public void addCommandListener(CommandListener listener); // public void removeCommandListener(CommandListener listener); // public int getCommandListenerCount(); // // public void runLoop(InputStream in,PrintStream out); // } // // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/RelProxyBuiltinRoot.java // public class RelProxyBuiltinRoot // { // private final static RelProxyBuiltinImpl SINGLETON = new RelProxyBuiltinImpl(); // // public static RelProxyBuiltin get() // { // return SINGLETON; // } // }
import com.innowhere.relproxy.RelProxyOnReloadListener; import com.innowhere.relproxy.jproxy.JProxy; import com.innowhere.relproxy.jproxy.JProxyCompilerListener; import com.innowhere.relproxy.jproxy.JProxyConfig; import com.innowhere.relproxy.jproxy.JProxyDiagnosticsListener; import com.innowhere.relproxy.jproxy.JProxyInputSourceFileExcludedListener; import com.innowhere.relproxy.jproxy.JProxyScriptEngine; import com.innowhere.relproxy_builtin_ex.CommandListener; import com.innowhere.relproxy_builtin_ex.RelProxyBuiltin; import com.innowhere.relproxy_builtin_ex.RelProxyBuiltinRoot; import java.io.File; import java.lang.reflect.Method; import java.net.URL; import java.util.Arrays; import java.util.List; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaFileObject;
public void afterCompile(File file) { System.out.println("After compile: " + file); } }; JProxyDiagnosticsListener diagnosticsListener = new JProxyDiagnosticsListener() { @Override public void onDiagnostics(DiagnosticCollector<JavaFileObject> diagnostics) { List<Diagnostic<? extends JavaFileObject>> diagList = diagnostics.getDiagnostics(); int i = 1; for (Diagnostic diagnostic : diagList) { System.err.println("Diagnostic " + i); System.err.println(" code: " + diagnostic.getCode()); System.err.println(" kind: " + diagnostic.getKind()); System.err.println(" line number: " + diagnostic.getLineNumber()); System.err.println(" column number: " + diagnostic.getColumnNumber()); System.err.println(" start position: " + diagnostic.getStartPosition()); System.err.println(" position: " + diagnostic.getPosition()); System.err.println(" end position: " + diagnostic.getEndPosition()); System.err.println(" source: " + diagnostic.getSource()); System.err.println(" message: " + diagnostic.getMessage(null)); i++; } } };
// Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/CommandListener.java // public interface CommandListener // { // public void execute(String command,String input,PrintStream out); // } // // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/RelProxyBuiltin.java // public interface RelProxyBuiltin // { // public JProxyScriptEngine getJProxyScriptEngine(); // // public void addOutputListener(OutputListener listener); // public void removeOutputListener(OutputListener listener); // public int getOutputListenerCount(); // // public void addCommandListener(CommandListener listener); // public void removeCommandListener(CommandListener listener); // public int getCommandListenerCount(); // // public void runLoop(InputStream in,PrintStream out); // } // // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/RelProxyBuiltinRoot.java // public class RelProxyBuiltinRoot // { // private final static RelProxyBuiltinImpl SINGLETON = new RelProxyBuiltinImpl(); // // public static RelProxyBuiltin get() // { // return SINGLETON; // } // } // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex_main/Main.java import com.innowhere.relproxy.RelProxyOnReloadListener; import com.innowhere.relproxy.jproxy.JProxy; import com.innowhere.relproxy.jproxy.JProxyCompilerListener; import com.innowhere.relproxy.jproxy.JProxyConfig; import com.innowhere.relproxy.jproxy.JProxyDiagnosticsListener; import com.innowhere.relproxy.jproxy.JProxyInputSourceFileExcludedListener; import com.innowhere.relproxy.jproxy.JProxyScriptEngine; import com.innowhere.relproxy_builtin_ex.CommandListener; import com.innowhere.relproxy_builtin_ex.RelProxyBuiltin; import com.innowhere.relproxy_builtin_ex.RelProxyBuiltinRoot; import java.io.File; import java.lang.reflect.Method; import java.net.URL; import java.util.Arrays; import java.util.List; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaFileObject; public void afterCompile(File file) { System.out.println("After compile: " + file); } }; JProxyDiagnosticsListener diagnosticsListener = new JProxyDiagnosticsListener() { @Override public void onDiagnostics(DiagnosticCollector<JavaFileObject> diagnostics) { List<Diagnostic<? extends JavaFileObject>> diagList = diagnostics.getDiagnostics(); int i = 1; for (Diagnostic diagnostic : diagList) { System.err.println("Diagnostic " + i); System.err.println(" code: " + diagnostic.getCode()); System.err.println(" kind: " + diagnostic.getKind()); System.err.println(" line number: " + diagnostic.getLineNumber()); System.err.println(" column number: " + diagnostic.getColumnNumber()); System.err.println(" start position: " + diagnostic.getStartPosition()); System.err.println(" position: " + diagnostic.getPosition()); System.err.println(" end position: " + diagnostic.getEndPosition()); System.err.println(" source: " + diagnostic.getSource()); System.err.println(" message: " + diagnostic.getMessage(null)); i++; } } };
RelProxyBuiltin rpbRoot = RelProxyBuiltinRoot.get();
jmarranz/relproxy_examples
relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex_main/Main.java
// Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/CommandListener.java // public interface CommandListener // { // public void execute(String command,String input,PrintStream out); // } // // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/RelProxyBuiltin.java // public interface RelProxyBuiltin // { // public JProxyScriptEngine getJProxyScriptEngine(); // // public void addOutputListener(OutputListener listener); // public void removeOutputListener(OutputListener listener); // public int getOutputListenerCount(); // // public void addCommandListener(CommandListener listener); // public void removeCommandListener(CommandListener listener); // public int getCommandListenerCount(); // // public void runLoop(InputStream in,PrintStream out); // } // // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/RelProxyBuiltinRoot.java // public class RelProxyBuiltinRoot // { // private final static RelProxyBuiltinImpl SINGLETON = new RelProxyBuiltinImpl(); // // public static RelProxyBuiltin get() // { // return SINGLETON; // } // }
import com.innowhere.relproxy.RelProxyOnReloadListener; import com.innowhere.relproxy.jproxy.JProxy; import com.innowhere.relproxy.jproxy.JProxyCompilerListener; import com.innowhere.relproxy.jproxy.JProxyConfig; import com.innowhere.relproxy.jproxy.JProxyDiagnosticsListener; import com.innowhere.relproxy.jproxy.JProxyInputSourceFileExcludedListener; import com.innowhere.relproxy.jproxy.JProxyScriptEngine; import com.innowhere.relproxy_builtin_ex.CommandListener; import com.innowhere.relproxy_builtin_ex.RelProxyBuiltin; import com.innowhere.relproxy_builtin_ex.RelProxyBuiltinRoot; import java.io.File; import java.lang.reflect.Method; import java.net.URL; import java.util.Arrays; import java.util.List; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaFileObject;
.setJProxyDiagnosticsListener(diagnosticsListener); engine.init(jpConfig); System.out.println("RelProxy running"); } public void tearDown() { RelProxyBuiltin rpbRoot = RelProxyBuiltinRoot.get(); JProxyScriptEngine engine = rpbRoot.getJProxyScriptEngine(); engine.stop(); System.out.println("RelProxy stopped"); } public void mainTest() { RelProxyBuiltin rpbRoot = RelProxyBuiltinRoot.get(); TestListener listener = new TestListener(); rpbRoot.addOutputListener(listener); assertTrue(rpbRoot.getOutputListenerCount() == 1); rpbRoot.removeOutputListener(listener); assertTrue(rpbRoot.getOutputListenerCount() == 0); rpbRoot.addOutputListener(listener);
// Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/CommandListener.java // public interface CommandListener // { // public void execute(String command,String input,PrintStream out); // } // // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/RelProxyBuiltin.java // public interface RelProxyBuiltin // { // public JProxyScriptEngine getJProxyScriptEngine(); // // public void addOutputListener(OutputListener listener); // public void removeOutputListener(OutputListener listener); // public int getOutputListenerCount(); // // public void addCommandListener(CommandListener listener); // public void removeCommandListener(CommandListener listener); // public int getCommandListenerCount(); // // public void runLoop(InputStream in,PrintStream out); // } // // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex/RelProxyBuiltinRoot.java // public class RelProxyBuiltinRoot // { // private final static RelProxyBuiltinImpl SINGLETON = new RelProxyBuiltinImpl(); // // public static RelProxyBuiltin get() // { // return SINGLETON; // } // } // Path: relproxy_builtin_ex/src/main/java/com/innowhere/relproxy_builtin_ex_main/Main.java import com.innowhere.relproxy.RelProxyOnReloadListener; import com.innowhere.relproxy.jproxy.JProxy; import com.innowhere.relproxy.jproxy.JProxyCompilerListener; import com.innowhere.relproxy.jproxy.JProxyConfig; import com.innowhere.relproxy.jproxy.JProxyDiagnosticsListener; import com.innowhere.relproxy.jproxy.JProxyInputSourceFileExcludedListener; import com.innowhere.relproxy.jproxy.JProxyScriptEngine; import com.innowhere.relproxy_builtin_ex.CommandListener; import com.innowhere.relproxy_builtin_ex.RelProxyBuiltin; import com.innowhere.relproxy_builtin_ex.RelProxyBuiltinRoot; import java.io.File; import java.lang.reflect.Method; import java.net.URL; import java.util.Arrays; import java.util.List; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaFileObject; .setJProxyDiagnosticsListener(diagnosticsListener); engine.init(jpConfig); System.out.println("RelProxy running"); } public void tearDown() { RelProxyBuiltin rpbRoot = RelProxyBuiltinRoot.get(); JProxyScriptEngine engine = rpbRoot.getJProxyScriptEngine(); engine.stop(); System.out.println("RelProxy stopped"); } public void mainTest() { RelProxyBuiltin rpbRoot = RelProxyBuiltinRoot.get(); TestListener listener = new TestListener(); rpbRoot.addOutputListener(listener); assertTrue(rpbRoot.getOutputListenerCount() == 1); rpbRoot.removeOutputListener(listener); assertTrue(rpbRoot.getOutputListenerCount() == 0); rpbRoot.addOutputListener(listener);
CommandListener commandListener = listener.getCommandListener();
jmarranz/relproxy_examples
relproxy_ex_itsnat_maven/src/main/webapp/WEB-INF/javaex/code/example/javaex/JProxyExampleLoadListener.java
// Path: relproxy_ex_itsnat_netbeans/src/java/example/javaex/FalseDB.java // public class FalseDB // { // protected LinkedList<City> cities; // // public FalseDB() // { // cities = new LinkedList<City>(); // cities.add(new City("Madrid")); // cities.add(new City("Barcelona")); // cities.add(new City("Bilbao")); // } // // public LinkedList<City> getCityList() { return cities; /*cities;*/ } // }
import org.itsnat.core.event.ItsNatServletRequestListener; import org.itsnat.core.ItsNatServletRequest; import org.itsnat.core.ItsNatServletResponse; import org.itsnat.core.html.ItsNatHTMLDocument; import example.javaex.FalseDB;
package example.javaex; /** * * @author jmarranz */ public class JProxyExampleLoadListener implements ItsNatServletRequestListener {
// Path: relproxy_ex_itsnat_netbeans/src/java/example/javaex/FalseDB.java // public class FalseDB // { // protected LinkedList<City> cities; // // public FalseDB() // { // cities = new LinkedList<City>(); // cities.add(new City("Madrid")); // cities.add(new City("Barcelona")); // cities.add(new City("Bilbao")); // } // // public LinkedList<City> getCityList() { return cities; /*cities;*/ } // } // Path: relproxy_ex_itsnat_maven/src/main/webapp/WEB-INF/javaex/code/example/javaex/JProxyExampleLoadListener.java import org.itsnat.core.event.ItsNatServletRequestListener; import org.itsnat.core.ItsNatServletRequest; import org.itsnat.core.ItsNatServletResponse; import org.itsnat.core.html.ItsNatHTMLDocument; import example.javaex.FalseDB; package example.javaex; /** * * @author jmarranz */ public class JProxyExampleLoadListener implements ItsNatServletRequestListener {
protected FalseDB db;
jmarranz/relproxy_examples
relproxy_ex_jsf/src/com/journaldev/jsfBeans/ViewEmployeesManagedBeanDelegate.java
// Path: relproxy_ex_jsf/src/com/journaldev/data/Employee.java // public class Employee { // private String employeeId; // private String employeeName; // public String getEmployeeId() { // return employeeId; // } // public void setEmployeeId(String employeeId) { // this.employeeId = employeeId; // } // public String getEmployeeName() { // return employeeName; // } // public void setEmployeeName(String employeeName) { // this.employeeName = employeeName; // } // }
import java.util.List; import com.journaldev.data.Employee;
package com.journaldev.jsfBeans; public interface ViewEmployeesManagedBeanDelegate {
// Path: relproxy_ex_jsf/src/com/journaldev/data/Employee.java // public class Employee { // private String employeeId; // private String employeeName; // public String getEmployeeId() { // return employeeId; // } // public void setEmployeeId(String employeeId) { // this.employeeId = employeeId; // } // public String getEmployeeName() { // return employeeName; // } // public void setEmployeeName(String employeeName) { // this.employeeName = employeeName; // } // } // Path: relproxy_ex_jsf/src/com/journaldev/jsfBeans/ViewEmployeesManagedBeanDelegate.java import java.util.List; import com.journaldev.data.Employee; package com.journaldev.jsfBeans; public interface ViewEmployeesManagedBeanDelegate {
public void populateEmployeeList(List<Employee> employees);
jmarranz/relproxy_examples
relproxy_ex_jsf/src/com/journaldev/conf/JProxyServletContextListener.java
// Path: relproxy_ex_jsf/src/com/journaldev/jsfBeans/ViewEmployeesManagedBean.java // @ManagedBean // @SessionScoped // public class ViewEmployeesManagedBean // { // private List<Employee> employees = new ArrayList<Employee>(); // private ViewEmployeesManagedBeanDelegate delegate; // // public ViewEmployeesManagedBean(){ // // } // // @PostConstruct // public void populateEmployeeList() // { // this.delegate = JProxy.create(new ViewEmployeesManagedBeanDelegateImpl(), ViewEmployeesManagedBeanDelegate.class); // delegate.populateEmployeeList(employees); // } // // public List<Employee> getEmployees() // { // return delegate.getEmployees(employees); // } // // public void setEmployees(List<Employee> employees) // { // this.employees = employees; // } // } // // Path: relproxy_ex_jsf/src/com/journaldev/jsfBeans/ViewEmployeesManagedBeanDelegate.java // public interface ViewEmployeesManagedBeanDelegate // { // public void populateEmployeeList(List<Employee> employees); // public List<Employee> getEmployees(List<Employee> employees); // }
import com.innowhere.relproxy.RelProxyOnReloadListener; import com.innowhere.relproxy.jproxy.JProxy; import com.innowhere.relproxy.jproxy.JProxyCompilerListener; import com.innowhere.relproxy.jproxy.JProxyConfig; import com.innowhere.relproxy.jproxy.JProxyDiagnosticsListener; import com.innowhere.relproxy.jproxy.JProxyInputSourceFileExcludedListener; import com.journaldev.jsfBeans.ViewEmployeesManagedBean; import com.journaldev.jsfBeans.ViewEmployeesManagedBeanDelegate; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Properties; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaFileObject;
{ if (input != null) try { input.close(); } catch (IOException ex) { throw new RuntimeException(ex); } } if (inputSourcePath == null) throw new RuntimeException("Missing webapp_folder property"); inputSourcePath += "/src"; if (!new File(inputSourcePath).exists()) { System.out.println("RelProxy is disabled, detected production mode "); return; } JProxyInputSourceFileExcludedListener excludedListener = new JProxyInputSourceFileExcludedListener() { @Override public boolean isExcluded(File file, File rootFolderOfSources) { String absPath = file.getAbsolutePath(); if (file.isDirectory()) { return absPath.endsWith(File.separatorChar + "conf") || absPath.endsWith(File.separatorChar + "data"); } else {
// Path: relproxy_ex_jsf/src/com/journaldev/jsfBeans/ViewEmployeesManagedBean.java // @ManagedBean // @SessionScoped // public class ViewEmployeesManagedBean // { // private List<Employee> employees = new ArrayList<Employee>(); // private ViewEmployeesManagedBeanDelegate delegate; // // public ViewEmployeesManagedBean(){ // // } // // @PostConstruct // public void populateEmployeeList() // { // this.delegate = JProxy.create(new ViewEmployeesManagedBeanDelegateImpl(), ViewEmployeesManagedBeanDelegate.class); // delegate.populateEmployeeList(employees); // } // // public List<Employee> getEmployees() // { // return delegate.getEmployees(employees); // } // // public void setEmployees(List<Employee> employees) // { // this.employees = employees; // } // } // // Path: relproxy_ex_jsf/src/com/journaldev/jsfBeans/ViewEmployeesManagedBeanDelegate.java // public interface ViewEmployeesManagedBeanDelegate // { // public void populateEmployeeList(List<Employee> employees); // public List<Employee> getEmployees(List<Employee> employees); // } // Path: relproxy_ex_jsf/src/com/journaldev/conf/JProxyServletContextListener.java import com.innowhere.relproxy.RelProxyOnReloadListener; import com.innowhere.relproxy.jproxy.JProxy; import com.innowhere.relproxy.jproxy.JProxyCompilerListener; import com.innowhere.relproxy.jproxy.JProxyConfig; import com.innowhere.relproxy.jproxy.JProxyDiagnosticsListener; import com.innowhere.relproxy.jproxy.JProxyInputSourceFileExcludedListener; import com.journaldev.jsfBeans.ViewEmployeesManagedBean; import com.journaldev.jsfBeans.ViewEmployeesManagedBeanDelegate; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Properties; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaFileObject; { if (input != null) try { input.close(); } catch (IOException ex) { throw new RuntimeException(ex); } } if (inputSourcePath == null) throw new RuntimeException("Missing webapp_folder property"); inputSourcePath += "/src"; if (!new File(inputSourcePath).exists()) { System.out.println("RelProxy is disabled, detected production mode "); return; } JProxyInputSourceFileExcludedListener excludedListener = new JProxyInputSourceFileExcludedListener() { @Override public boolean isExcluded(File file, File rootFolderOfSources) { String absPath = file.getAbsolutePath(); if (file.isDirectory()) { return absPath.endsWith(File.separatorChar + "conf") || absPath.endsWith(File.separatorChar + "data"); } else {
return absPath.endsWith(ViewEmployeesManagedBean.class.getSimpleName() + ".java") ||
jmarranz/relproxy_examples
relproxy_ex_jsf/src/com/journaldev/conf/JProxyServletContextListener.java
// Path: relproxy_ex_jsf/src/com/journaldev/jsfBeans/ViewEmployeesManagedBean.java // @ManagedBean // @SessionScoped // public class ViewEmployeesManagedBean // { // private List<Employee> employees = new ArrayList<Employee>(); // private ViewEmployeesManagedBeanDelegate delegate; // // public ViewEmployeesManagedBean(){ // // } // // @PostConstruct // public void populateEmployeeList() // { // this.delegate = JProxy.create(new ViewEmployeesManagedBeanDelegateImpl(), ViewEmployeesManagedBeanDelegate.class); // delegate.populateEmployeeList(employees); // } // // public List<Employee> getEmployees() // { // return delegate.getEmployees(employees); // } // // public void setEmployees(List<Employee> employees) // { // this.employees = employees; // } // } // // Path: relproxy_ex_jsf/src/com/journaldev/jsfBeans/ViewEmployeesManagedBeanDelegate.java // public interface ViewEmployeesManagedBeanDelegate // { // public void populateEmployeeList(List<Employee> employees); // public List<Employee> getEmployees(List<Employee> employees); // }
import com.innowhere.relproxy.RelProxyOnReloadListener; import com.innowhere.relproxy.jproxy.JProxy; import com.innowhere.relproxy.jproxy.JProxyCompilerListener; import com.innowhere.relproxy.jproxy.JProxyConfig; import com.innowhere.relproxy.jproxy.JProxyDiagnosticsListener; import com.innowhere.relproxy.jproxy.JProxyInputSourceFileExcludedListener; import com.journaldev.jsfBeans.ViewEmployeesManagedBean; import com.journaldev.jsfBeans.ViewEmployeesManagedBeanDelegate; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Properties; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaFileObject;
if (input != null) try { input.close(); } catch (IOException ex) { throw new RuntimeException(ex); } } if (inputSourcePath == null) throw new RuntimeException("Missing webapp_folder property"); inputSourcePath += "/src"; if (!new File(inputSourcePath).exists()) { System.out.println("RelProxy is disabled, detected production mode "); return; } JProxyInputSourceFileExcludedListener excludedListener = new JProxyInputSourceFileExcludedListener() { @Override public boolean isExcluded(File file, File rootFolderOfSources) { String absPath = file.getAbsolutePath(); if (file.isDirectory()) { return absPath.endsWith(File.separatorChar + "conf") || absPath.endsWith(File.separatorChar + "data"); } else { return absPath.endsWith(ViewEmployeesManagedBean.class.getSimpleName() + ".java") ||
// Path: relproxy_ex_jsf/src/com/journaldev/jsfBeans/ViewEmployeesManagedBean.java // @ManagedBean // @SessionScoped // public class ViewEmployeesManagedBean // { // private List<Employee> employees = new ArrayList<Employee>(); // private ViewEmployeesManagedBeanDelegate delegate; // // public ViewEmployeesManagedBean(){ // // } // // @PostConstruct // public void populateEmployeeList() // { // this.delegate = JProxy.create(new ViewEmployeesManagedBeanDelegateImpl(), ViewEmployeesManagedBeanDelegate.class); // delegate.populateEmployeeList(employees); // } // // public List<Employee> getEmployees() // { // return delegate.getEmployees(employees); // } // // public void setEmployees(List<Employee> employees) // { // this.employees = employees; // } // } // // Path: relproxy_ex_jsf/src/com/journaldev/jsfBeans/ViewEmployeesManagedBeanDelegate.java // public interface ViewEmployeesManagedBeanDelegate // { // public void populateEmployeeList(List<Employee> employees); // public List<Employee> getEmployees(List<Employee> employees); // } // Path: relproxy_ex_jsf/src/com/journaldev/conf/JProxyServletContextListener.java import com.innowhere.relproxy.RelProxyOnReloadListener; import com.innowhere.relproxy.jproxy.JProxy; import com.innowhere.relproxy.jproxy.JProxyCompilerListener; import com.innowhere.relproxy.jproxy.JProxyConfig; import com.innowhere.relproxy.jproxy.JProxyDiagnosticsListener; import com.innowhere.relproxy.jproxy.JProxyInputSourceFileExcludedListener; import com.journaldev.jsfBeans.ViewEmployeesManagedBean; import com.journaldev.jsfBeans.ViewEmployeesManagedBeanDelegate; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Properties; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaFileObject; if (input != null) try { input.close(); } catch (IOException ex) { throw new RuntimeException(ex); } } if (inputSourcePath == null) throw new RuntimeException("Missing webapp_folder property"); inputSourcePath += "/src"; if (!new File(inputSourcePath).exists()) { System.out.println("RelProxy is disabled, detected production mode "); return; } JProxyInputSourceFileExcludedListener excludedListener = new JProxyInputSourceFileExcludedListener() { @Override public boolean isExcluded(File file, File rootFolderOfSources) { String absPath = file.getAbsolutePath(); if (file.isDirectory()) { return absPath.endsWith(File.separatorChar + "conf") || absPath.endsWith(File.separatorChar + "data"); } else { return absPath.endsWith(ViewEmployeesManagedBean.class.getSimpleName() + ".java") ||
absPath.endsWith(ViewEmployeesManagedBeanDelegate.class.getSimpleName() + ".java");