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
alb-i986/selenium-tinafw
src/main/java/me/alb_i986/selenium/tinafw/ui/WebDriverFactoryLocal.java
// Path: src/main/java/me/alb_i986/selenium/tinafw/domain/SupportedBrowser.java // public enum SupportedBrowser { // // CHROME(ChromeDriver.class, DesiredCapabilities.chrome()), // FIREFOX(FirefoxDriver.class, DesiredCapabilities.firefox()), // SAFARI(SafariDriver.class, DesiredCapabilities.safari()), // IE(InternetExplorerDriver.class, DesiredCapabilities.internetExplorer()), // HTML_UNIT(HtmlUnitDriver.class, DesiredCapabilities.htmlUnit()), // ; // // private DesiredCapabilities capabilities; // private Class<? extends WebDriver> concreteWebDriverClass; // // private SupportedBrowser(Class<? extends WebDriver> clazz, DesiredCapabilities capabilities) { // this.concreteWebDriverClass = clazz; // this.capabilities = capabilities; // } // // /** // * @return the concrete WebDriver class corresponding to this SupportedBrowser // */ // public Class<? extends WebDriver> toClass() { // return this.concreteWebDriverClass; // } // // public DesiredCapabilities toCapabilities() { // return this.capabilities; // } // // /** // * @return the lower cased name of this enum constant // */ // @Override // public String toString() { // return super.toString().toLowerCase(); // } // }
import me.alb_i986.selenium.tinafw.domain.SupportedBrowser; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.firefox.FirefoxProfile;
package me.alb_i986.selenium.tinafw.ui; /** * Factory that creates {@link WebDriver}s which drive browsers on the local machine. * <p> * To keep the implementation as simple and generic as possible, it is not able to * handle browser profiles/options (e.g. {@link FirefoxProfile} or {@link ChromeOptions}). */ public class WebDriverFactoryLocal implements WebDriverFactory { /** * @throws WebDriverFactoryException if the instantiation of the WebDriver fails */ @Override
// Path: src/main/java/me/alb_i986/selenium/tinafw/domain/SupportedBrowser.java // public enum SupportedBrowser { // // CHROME(ChromeDriver.class, DesiredCapabilities.chrome()), // FIREFOX(FirefoxDriver.class, DesiredCapabilities.firefox()), // SAFARI(SafariDriver.class, DesiredCapabilities.safari()), // IE(InternetExplorerDriver.class, DesiredCapabilities.internetExplorer()), // HTML_UNIT(HtmlUnitDriver.class, DesiredCapabilities.htmlUnit()), // ; // // private DesiredCapabilities capabilities; // private Class<? extends WebDriver> concreteWebDriverClass; // // private SupportedBrowser(Class<? extends WebDriver> clazz, DesiredCapabilities capabilities) { // this.concreteWebDriverClass = clazz; // this.capabilities = capabilities; // } // // /** // * @return the concrete WebDriver class corresponding to this SupportedBrowser // */ // public Class<? extends WebDriver> toClass() { // return this.concreteWebDriverClass; // } // // public DesiredCapabilities toCapabilities() { // return this.capabilities; // } // // /** // * @return the lower cased name of this enum constant // */ // @Override // public String toString() { // return super.toString().toLowerCase(); // } // } // Path: src/main/java/me/alb_i986/selenium/tinafw/ui/WebDriverFactoryLocal.java import me.alb_i986.selenium.tinafw.domain.SupportedBrowser; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.firefox.FirefoxProfile; package me.alb_i986.selenium.tinafw.ui; /** * Factory that creates {@link WebDriver}s which drive browsers on the local machine. * <p> * To keep the implementation as simple and generic as possible, it is not able to * handle browser profiles/options (e.g. {@link FirefoxProfile} or {@link ChromeOptions}). */ public class WebDriverFactoryLocal implements WebDriverFactory { /** * @throws WebDriverFactoryException if the instantiation of the WebDriver fails */ @Override
public WebDriver getWebDriver(SupportedBrowser browserType) {
alb-i986/selenium-tinafw
src/main/java/me/alb_i986/selenium/tinafw/tasks/OrWebTask.java
// Path: src/main/java/me/alb_i986/selenium/tinafw/ui/WebPage.java // public interface WebPage { // // /** // * @see Config#getBaseUrl() // */ // public final static String BASE_URL = Config.getBaseUrl(); // // // /** // * @see WebDriver#getTitle() // */ // public String getTitle(); // // /** // * @see WebDriver#getCurrentUrl() // */ // public String getCurrentUrl(); // // }
import java.util.List; import me.alb_i986.selenium.tinafw.ui.WebPage;
package me.alb_i986.selenium.tinafw.tasks; /** * A {@link CompositeWebTask} which chains subtasks in a logical OR. * It allows to handle situations where it is not known exactly what * the state of the SUT before a task starts will be, but * it is known that there are only X possible initial states. * With {@link OrWebTask}, you can write one task for each of * the possible scenarios to handle, and have them executed in turn, * until one finishes without throwing any exception. * In case none of the alternatives finishes cleanly, then the last * thrown exception will be thrown. * All of the subtasks must be homogeneous, i.e. they all must finish on * the same page when they don't fail. * <p> * In its most basic form, {@link OrWebTask} runs subtasks in order, * until one succeeds. * This works as long as each of the failing subtasks leaves the state of * the page and the DOM intact, in a way that the next alternative is able * to run cleanly as if the previous ones had never run. * For this condition to hold, for example, each alternative * should be always on the very same page, at any time, * never navigate to another page, and should not change the state * of dialogs (i.e. should not open dialogs which were not initially open, * or close dialogs which were initially open). * <p> * This constraint can be removed by implementing a mechanism that * restores the initial situation. Two possible ways: * <ul> * <li>either by encapsulating the restoring logic in each of the alternative * subtasks itself (e.g. with a catch block which closes the dialog and * re-throws the underlying exception) * </li> * <li>or by having a more complex {@link OrWebTask} which runs * a separate "restorer" task every time an alternative subtask fails * </li> * </ul> * <p> * In the basic form, in other words by default, the "restorer" * is a {@link WebTasks#nullTask()}. * It can be changed with {@link #withRestorer(WebTask)}. */ public class OrWebTask extends CompositeWebTask { private WebTask restorer = WebTasks.nullTask(); public OrWebTask(List<WebTask> subtasks) { super(subtasks); } public OrWebTask(WebTask... subtasks) { super(subtasks); } @Override
// Path: src/main/java/me/alb_i986/selenium/tinafw/ui/WebPage.java // public interface WebPage { // // /** // * @see Config#getBaseUrl() // */ // public final static String BASE_URL = Config.getBaseUrl(); // // // /** // * @see WebDriver#getTitle() // */ // public String getTitle(); // // /** // * @see WebDriver#getCurrentUrl() // */ // public String getCurrentUrl(); // // } // Path: src/main/java/me/alb_i986/selenium/tinafw/tasks/OrWebTask.java import java.util.List; import me.alb_i986.selenium.tinafw.ui.WebPage; package me.alb_i986.selenium.tinafw.tasks; /** * A {@link CompositeWebTask} which chains subtasks in a logical OR. * It allows to handle situations where it is not known exactly what * the state of the SUT before a task starts will be, but * it is known that there are only X possible initial states. * With {@link OrWebTask}, you can write one task for each of * the possible scenarios to handle, and have them executed in turn, * until one finishes without throwing any exception. * In case none of the alternatives finishes cleanly, then the last * thrown exception will be thrown. * All of the subtasks must be homogeneous, i.e. they all must finish on * the same page when they don't fail. * <p> * In its most basic form, {@link OrWebTask} runs subtasks in order, * until one succeeds. * This works as long as each of the failing subtasks leaves the state of * the page and the DOM intact, in a way that the next alternative is able * to run cleanly as if the previous ones had never run. * For this condition to hold, for example, each alternative * should be always on the very same page, at any time, * never navigate to another page, and should not change the state * of dialogs (i.e. should not open dialogs which were not initially open, * or close dialogs which were initially open). * <p> * This constraint can be removed by implementing a mechanism that * restores the initial situation. Two possible ways: * <ul> * <li>either by encapsulating the restoring logic in each of the alternative * subtasks itself (e.g. with a catch block which closes the dialog and * re-throws the underlying exception) * </li> * <li>or by having a more complex {@link OrWebTask} which runs * a separate "restorer" task every time an alternative subtask fails * </li> * </ul> * <p> * In the basic form, in other words by default, the "restorer" * is a {@link WebTasks#nullTask()}. * It can be changed with {@link #withRestorer(WebTask)}. */ public class OrWebTask extends CompositeWebTask { private WebTask restorer = WebTasks.nullTask(); public OrWebTask(List<WebTask> subtasks) { super(subtasks); } public OrWebTask(WebTask... subtasks) { super(subtasks); } @Override
public WebPage run(WebPage initialPage) {
alb-i986/selenium-tinafw
src/main/java/me/alb_i986/selenium/tinafw/config/TinafwGuiceModule.java
// Path: src/main/java/me/alb_i986/selenium/tinafw/ui/WebDriverFactoryLocal.java // public class WebDriverFactoryLocal implements WebDriverFactory { // // /** // * @throws WebDriverFactoryException if the instantiation of the WebDriver fails // */ // @Override // public WebDriver getWebDriver(SupportedBrowser browserType) { // try { // return browserType.toClass().newInstance(); // } catch (InstantiationException | IllegalAccessException e) { // throw new WebDriverFactoryException( // "cannot create a WebDriver instance for " + browserType, e); // } // } // // } // // Path: src/main/java/me/alb_i986/selenium/tinafw/ui/WebDriverFactoryRemote.java // public class WebDriverFactoryRemote implements WebDriverFactory { // // private URL gridHubURL; // private DesiredCapabilities extraCapabilities; // // /** // * A factory creating {@link WebDriver}s matching the given set of extra, // * desired capabilities // * (see also {@link RemoteWebDriver#RemoteWebDriver(URL, Capabilities)}). // * // * @param hubURL // * @param extraCapabilities // * // * @throws IllegalArgumentException if the desired capabilities specify // * a {@link CapabilityType#BROWSER_NAME} // */ // public WebDriverFactoryRemote(URL hubURL, DesiredCapabilities extraCapabilities) { // this(hubURL); // if(extraCapabilities.is(CapabilityType.BROWSER_NAME)) // throw new IllegalArgumentException("Desired capabilities cannot specify a browser name"); // this.extraCapabilities = extraCapabilities; // } // // /** // * A factory creating {@link WebDriver}s against the given hub. // * // * @param hubURL // */ // public WebDriverFactoryRemote(URL hubURL) { // this.gridHubURL = hubURL; // } // // @Override // public WebDriver getWebDriver(SupportedBrowser browserType) { // DesiredCapabilities capabilities = browserType.toCapabilities(); // capabilities.merge(extraCapabilities); // RemoteWebDriver remoteDriver = new RemoteWebDriver(gridHubURL, capabilities); // remoteDriver.setFileDetector(new LocalFileDetector()); // return remoteDriver; // } // // }
import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Singleton; import me.alb_i986.selenium.tinafw.ui.WebDriverFactory; import me.alb_i986.selenium.tinafw.ui.WebDriverFactoryDecoratorImplicitWait; import me.alb_i986.selenium.tinafw.ui.WebDriverFactoryLocal; import me.alb_i986.selenium.tinafw.ui.WebDriverFactoryRemote; import org.openqa.selenium.remote.DesiredCapabilities; import java.net.URL;
package me.alb_i986.selenium.tinafw.config; public class TinafwGuiceModule extends AbstractModule { @Override protected void configure() { } /** * A {@link WebDriverFactory} according to the settings: * <ul> * <li>a {@link WebDriverFactoryLocal} if {@link Config#PROP_GRID_HUB_URL} is * not defined; * <li>else, a {@link WebDriverFactoryRemote} * <li>finally, decorate it with {@link WebDriverFactoryDecoratorImplicitWait}, if * {@link Config#PROP_TIMEOUT_IMPLICIT_WAIT} is defined * </ul> */ @Provides @Singleton WebDriverFactory webDriverFactoryProvider() { WebDriverFactory tmpFactoryFromConfig; URL hubURL = Config.getGridHubUrl(); if(hubURL == null) {
// Path: src/main/java/me/alb_i986/selenium/tinafw/ui/WebDriverFactoryLocal.java // public class WebDriverFactoryLocal implements WebDriverFactory { // // /** // * @throws WebDriverFactoryException if the instantiation of the WebDriver fails // */ // @Override // public WebDriver getWebDriver(SupportedBrowser browserType) { // try { // return browserType.toClass().newInstance(); // } catch (InstantiationException | IllegalAccessException e) { // throw new WebDriverFactoryException( // "cannot create a WebDriver instance for " + browserType, e); // } // } // // } // // Path: src/main/java/me/alb_i986/selenium/tinafw/ui/WebDriverFactoryRemote.java // public class WebDriverFactoryRemote implements WebDriverFactory { // // private URL gridHubURL; // private DesiredCapabilities extraCapabilities; // // /** // * A factory creating {@link WebDriver}s matching the given set of extra, // * desired capabilities // * (see also {@link RemoteWebDriver#RemoteWebDriver(URL, Capabilities)}). // * // * @param hubURL // * @param extraCapabilities // * // * @throws IllegalArgumentException if the desired capabilities specify // * a {@link CapabilityType#BROWSER_NAME} // */ // public WebDriverFactoryRemote(URL hubURL, DesiredCapabilities extraCapabilities) { // this(hubURL); // if(extraCapabilities.is(CapabilityType.BROWSER_NAME)) // throw new IllegalArgumentException("Desired capabilities cannot specify a browser name"); // this.extraCapabilities = extraCapabilities; // } // // /** // * A factory creating {@link WebDriver}s against the given hub. // * // * @param hubURL // */ // public WebDriverFactoryRemote(URL hubURL) { // this.gridHubURL = hubURL; // } // // @Override // public WebDriver getWebDriver(SupportedBrowser browserType) { // DesiredCapabilities capabilities = browserType.toCapabilities(); // capabilities.merge(extraCapabilities); // RemoteWebDriver remoteDriver = new RemoteWebDriver(gridHubURL, capabilities); // remoteDriver.setFileDetector(new LocalFileDetector()); // return remoteDriver; // } // // } // Path: src/main/java/me/alb_i986/selenium/tinafw/config/TinafwGuiceModule.java import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Singleton; import me.alb_i986.selenium.tinafw.ui.WebDriverFactory; import me.alb_i986.selenium.tinafw.ui.WebDriverFactoryDecoratorImplicitWait; import me.alb_i986.selenium.tinafw.ui.WebDriverFactoryLocal; import me.alb_i986.selenium.tinafw.ui.WebDriverFactoryRemote; import org.openqa.selenium.remote.DesiredCapabilities; import java.net.URL; package me.alb_i986.selenium.tinafw.config; public class TinafwGuiceModule extends AbstractModule { @Override protected void configure() { } /** * A {@link WebDriverFactory} according to the settings: * <ul> * <li>a {@link WebDriverFactoryLocal} if {@link Config#PROP_GRID_HUB_URL} is * not defined; * <li>else, a {@link WebDriverFactoryRemote} * <li>finally, decorate it with {@link WebDriverFactoryDecoratorImplicitWait}, if * {@link Config#PROP_TIMEOUT_IMPLICIT_WAIT} is defined * </ul> */ @Provides @Singleton WebDriverFactory webDriverFactoryProvider() { WebDriverFactory tmpFactoryFromConfig; URL hubURL = Config.getGridHubUrl(); if(hubURL == null) {
tmpFactoryFromConfig = new WebDriverFactoryLocal();
alb-i986/selenium-tinafw
src/main/java/me/alb_i986/selenium/tinafw/config/TinafwGuiceModule.java
// Path: src/main/java/me/alb_i986/selenium/tinafw/ui/WebDriverFactoryLocal.java // public class WebDriverFactoryLocal implements WebDriverFactory { // // /** // * @throws WebDriverFactoryException if the instantiation of the WebDriver fails // */ // @Override // public WebDriver getWebDriver(SupportedBrowser browserType) { // try { // return browserType.toClass().newInstance(); // } catch (InstantiationException | IllegalAccessException e) { // throw new WebDriverFactoryException( // "cannot create a WebDriver instance for " + browserType, e); // } // } // // } // // Path: src/main/java/me/alb_i986/selenium/tinafw/ui/WebDriverFactoryRemote.java // public class WebDriverFactoryRemote implements WebDriverFactory { // // private URL gridHubURL; // private DesiredCapabilities extraCapabilities; // // /** // * A factory creating {@link WebDriver}s matching the given set of extra, // * desired capabilities // * (see also {@link RemoteWebDriver#RemoteWebDriver(URL, Capabilities)}). // * // * @param hubURL // * @param extraCapabilities // * // * @throws IllegalArgumentException if the desired capabilities specify // * a {@link CapabilityType#BROWSER_NAME} // */ // public WebDriverFactoryRemote(URL hubURL, DesiredCapabilities extraCapabilities) { // this(hubURL); // if(extraCapabilities.is(CapabilityType.BROWSER_NAME)) // throw new IllegalArgumentException("Desired capabilities cannot specify a browser name"); // this.extraCapabilities = extraCapabilities; // } // // /** // * A factory creating {@link WebDriver}s against the given hub. // * // * @param hubURL // */ // public WebDriverFactoryRemote(URL hubURL) { // this.gridHubURL = hubURL; // } // // @Override // public WebDriver getWebDriver(SupportedBrowser browserType) { // DesiredCapabilities capabilities = browserType.toCapabilities(); // capabilities.merge(extraCapabilities); // RemoteWebDriver remoteDriver = new RemoteWebDriver(gridHubURL, capabilities); // remoteDriver.setFileDetector(new LocalFileDetector()); // return remoteDriver; // } // // }
import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Singleton; import me.alb_i986.selenium.tinafw.ui.WebDriverFactory; import me.alb_i986.selenium.tinafw.ui.WebDriverFactoryDecoratorImplicitWait; import me.alb_i986.selenium.tinafw.ui.WebDriverFactoryLocal; import me.alb_i986.selenium.tinafw.ui.WebDriverFactoryRemote; import org.openqa.selenium.remote.DesiredCapabilities; import java.net.URL;
package me.alb_i986.selenium.tinafw.config; public class TinafwGuiceModule extends AbstractModule { @Override protected void configure() { } /** * A {@link WebDriverFactory} according to the settings: * <ul> * <li>a {@link WebDriverFactoryLocal} if {@link Config#PROP_GRID_HUB_URL} is * not defined; * <li>else, a {@link WebDriverFactoryRemote} * <li>finally, decorate it with {@link WebDriverFactoryDecoratorImplicitWait}, if * {@link Config#PROP_TIMEOUT_IMPLICIT_WAIT} is defined * </ul> */ @Provides @Singleton WebDriverFactory webDriverFactoryProvider() { WebDriverFactory tmpFactoryFromConfig; URL hubURL = Config.getGridHubUrl(); if(hubURL == null) { tmpFactoryFromConfig = new WebDriverFactoryLocal(); } else { DesiredCapabilities extraDesiredCapabilities = new DesiredCapabilities(); extraDesiredCapabilities.setVersion(Config.getGridBrowserVersion()); extraDesiredCapabilities.setPlatform(Config.getGridPlatform());
// Path: src/main/java/me/alb_i986/selenium/tinafw/ui/WebDriverFactoryLocal.java // public class WebDriverFactoryLocal implements WebDriverFactory { // // /** // * @throws WebDriverFactoryException if the instantiation of the WebDriver fails // */ // @Override // public WebDriver getWebDriver(SupportedBrowser browserType) { // try { // return browserType.toClass().newInstance(); // } catch (InstantiationException | IllegalAccessException e) { // throw new WebDriverFactoryException( // "cannot create a WebDriver instance for " + browserType, e); // } // } // // } // // Path: src/main/java/me/alb_i986/selenium/tinafw/ui/WebDriverFactoryRemote.java // public class WebDriverFactoryRemote implements WebDriverFactory { // // private URL gridHubURL; // private DesiredCapabilities extraCapabilities; // // /** // * A factory creating {@link WebDriver}s matching the given set of extra, // * desired capabilities // * (see also {@link RemoteWebDriver#RemoteWebDriver(URL, Capabilities)}). // * // * @param hubURL // * @param extraCapabilities // * // * @throws IllegalArgumentException if the desired capabilities specify // * a {@link CapabilityType#BROWSER_NAME} // */ // public WebDriverFactoryRemote(URL hubURL, DesiredCapabilities extraCapabilities) { // this(hubURL); // if(extraCapabilities.is(CapabilityType.BROWSER_NAME)) // throw new IllegalArgumentException("Desired capabilities cannot specify a browser name"); // this.extraCapabilities = extraCapabilities; // } // // /** // * A factory creating {@link WebDriver}s against the given hub. // * // * @param hubURL // */ // public WebDriverFactoryRemote(URL hubURL) { // this.gridHubURL = hubURL; // } // // @Override // public WebDriver getWebDriver(SupportedBrowser browserType) { // DesiredCapabilities capabilities = browserType.toCapabilities(); // capabilities.merge(extraCapabilities); // RemoteWebDriver remoteDriver = new RemoteWebDriver(gridHubURL, capabilities); // remoteDriver.setFileDetector(new LocalFileDetector()); // return remoteDriver; // } // // } // Path: src/main/java/me/alb_i986/selenium/tinafw/config/TinafwGuiceModule.java import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Singleton; import me.alb_i986.selenium.tinafw.ui.WebDriverFactory; import me.alb_i986.selenium.tinafw.ui.WebDriverFactoryDecoratorImplicitWait; import me.alb_i986.selenium.tinafw.ui.WebDriverFactoryLocal; import me.alb_i986.selenium.tinafw.ui.WebDriverFactoryRemote; import org.openqa.selenium.remote.DesiredCapabilities; import java.net.URL; package me.alb_i986.selenium.tinafw.config; public class TinafwGuiceModule extends AbstractModule { @Override protected void configure() { } /** * A {@link WebDriverFactory} according to the settings: * <ul> * <li>a {@link WebDriverFactoryLocal} if {@link Config#PROP_GRID_HUB_URL} is * not defined; * <li>else, a {@link WebDriverFactoryRemote} * <li>finally, decorate it with {@link WebDriverFactoryDecoratorImplicitWait}, if * {@link Config#PROP_TIMEOUT_IMPLICIT_WAIT} is defined * </ul> */ @Provides @Singleton WebDriverFactory webDriverFactoryProvider() { WebDriverFactory tmpFactoryFromConfig; URL hubURL = Config.getGridHubUrl(); if(hubURL == null) { tmpFactoryFromConfig = new WebDriverFactoryLocal(); } else { DesiredCapabilities extraDesiredCapabilities = new DesiredCapabilities(); extraDesiredCapabilities.setVersion(Config.getGridBrowserVersion()); extraDesiredCapabilities.setPlatform(Config.getGridPlatform());
tmpFactoryFromConfig = new WebDriverFactoryRemote(hubURL, extraDesiredCapabilities);
alb-i986/selenium-tinafw
src/main/java/me/alb_i986/selenium/tinafw/tasks/WebTasks.java
// Path: src/main/java/me/alb_i986/selenium/tinafw/ui/WebPage.java // public interface WebPage { // // /** // * @see Config#getBaseUrl() // */ // public final static String BASE_URL = Config.getBaseUrl(); // // // /** // * @see WebDriver#getTitle() // */ // public String getTitle(); // // /** // * @see WebDriver#getCurrentUrl() // */ // public String getCurrentUrl(); // // }
import org.openqa.selenium.support.ui.ExpectedConditions; import me.alb_i986.selenium.tinafw.ui.WebPage;
package me.alb_i986.selenium.tinafw.tasks; /** * Static class providing factory methods for creating instances * of common {@link WebTask}'s. * Inspired by WebDriver's {@link ExpectedConditions}. * <p> * It includes factory methods for creating BDD-style tasks, following the * <a href="http://martinfowler.com/bliki/GivenWhenThen.html"> * Given When Then pattern</a>: * {@link #given(WebTask...)}, {@link #when(WebTask...)}, {@link #then(WebTask...)}. * They are simply {@link CompositeWebTask}'s, but feature a meaningful * name which helps improving the readability of tests. * */ public class WebTasks { /** * Constant that makes {@link #nullTask()} a singleton. * <p> * Though such a task has a state (mainly a user), its state is never used, * therefore it should be safe to make it a singleton. * Tests using it concurrently should be working fine. */ private static final WebTask NULL_TASK = new BaseWebTask() { @Override
// Path: src/main/java/me/alb_i986/selenium/tinafw/ui/WebPage.java // public interface WebPage { // // /** // * @see Config#getBaseUrl() // */ // public final static String BASE_URL = Config.getBaseUrl(); // // // /** // * @see WebDriver#getTitle() // */ // public String getTitle(); // // /** // * @see WebDriver#getCurrentUrl() // */ // public String getCurrentUrl(); // // } // Path: src/main/java/me/alb_i986/selenium/tinafw/tasks/WebTasks.java import org.openqa.selenium.support.ui.ExpectedConditions; import me.alb_i986.selenium.tinafw.ui.WebPage; package me.alb_i986.selenium.tinafw.tasks; /** * Static class providing factory methods for creating instances * of common {@link WebTask}'s. * Inspired by WebDriver's {@link ExpectedConditions}. * <p> * It includes factory methods for creating BDD-style tasks, following the * <a href="http://martinfowler.com/bliki/GivenWhenThen.html"> * Given When Then pattern</a>: * {@link #given(WebTask...)}, {@link #when(WebTask...)}, {@link #then(WebTask...)}. * They are simply {@link CompositeWebTask}'s, but feature a meaningful * name which helps improving the readability of tests. * */ public class WebTasks { /** * Constant that makes {@link #nullTask()} a singleton. * <p> * Though such a task has a state (mainly a user), its state is never used, * therefore it should be safe to make it a singleton. * Tests using it concurrently should be working fine. */ private static final WebTask NULL_TASK = new BaseWebTask() { @Override
public WebPage run(WebPage initialPage) {
alb-i986/selenium-tinafw
src/main/java/me/alb_i986/selenium/tinafw/tasks/ImLoggedInBase.java
// Path: src/main/java/me/alb_i986/selenium/tinafw/ui/WebPage.java // public interface WebPage { // // /** // * @see Config#getBaseUrl() // */ // public final static String BASE_URL = Config.getBaseUrl(); // // // /** // * @see WebDriver#getTitle() // */ // public String getTitle(); // // /** // * @see WebDriver#getCurrentUrl() // */ // public String getCurrentUrl(); // // }
import me.alb_i986.selenium.tinafw.ui.LoadablePage; import me.alb_i986.selenium.tinafw.ui.LoginPage; import me.alb_i986.selenium.tinafw.ui.WebPage;
package me.alb_i986.selenium.tinafw.tasks; /** * Task implementing a step for navigating to the {@link LoginPage} * and logging in by entering username and password. * <p> * Concrete subclasses need to define the method {@link #loginPageClass()}, * which is supposed to return a concrete {@link LoginPage} class. * */ public abstract class ImLoggedInBase extends NavigationWebTask { /** * Browse to the login page and do the login. * * @param noPage this param won't be considered: may be null */ @Override
// Path: src/main/java/me/alb_i986/selenium/tinafw/ui/WebPage.java // public interface WebPage { // // /** // * @see Config#getBaseUrl() // */ // public final static String BASE_URL = Config.getBaseUrl(); // // // /** // * @see WebDriver#getTitle() // */ // public String getTitle(); // // /** // * @see WebDriver#getCurrentUrl() // */ // public String getCurrentUrl(); // // } // Path: src/main/java/me/alb_i986/selenium/tinafw/tasks/ImLoggedInBase.java import me.alb_i986.selenium.tinafw.ui.LoadablePage; import me.alb_i986.selenium.tinafw.ui.LoginPage; import me.alb_i986.selenium.tinafw.ui.WebPage; package me.alb_i986.selenium.tinafw.tasks; /** * Task implementing a step for navigating to the {@link LoginPage} * and logging in by entering username and password. * <p> * Concrete subclasses need to define the method {@link #loginPageClass()}, * which is supposed to return a concrete {@link LoginPage} class. * */ public abstract class ImLoggedInBase extends NavigationWebTask { /** * Browse to the login page and do the login. * * @param noPage this param won't be considered: may be null */ @Override
public WebPage run(WebPage noPage) {
alb-i986/selenium-tinafw
src/main/java/me/alb_i986/selenium/tinafw/tasks/NavigationWebTask.java
// Path: src/main/java/me/alb_i986/selenium/tinafw/ui/WebPage.java // public interface WebPage { // // /** // * @see Config#getBaseUrl() // */ // public final static String BASE_URL = Config.getBaseUrl(); // // // /** // * @see WebDriver#getTitle() // */ // public String getTitle(); // // /** // * @see WebDriver#getCurrentUrl() // */ // public String getCurrentUrl(); // // }
import me.alb_i986.selenium.tinafw.ui.LoadablePage; import me.alb_i986.selenium.tinafw.ui.WebPage;
package me.alb_i986.selenium.tinafw.tasks; /** * A WebTask implementing a step for navigating to a {@link LoadablePage}. */ public abstract class NavigationWebTask extends BaseWebTask { /** * Navigate to {@link #pageToLoadClass()} and return its instance. * * @return an instance of {@link #pageToLoadClass()} */ @Override
// Path: src/main/java/me/alb_i986/selenium/tinafw/ui/WebPage.java // public interface WebPage { // // /** // * @see Config#getBaseUrl() // */ // public final static String BASE_URL = Config.getBaseUrl(); // // // /** // * @see WebDriver#getTitle() // */ // public String getTitle(); // // /** // * @see WebDriver#getCurrentUrl() // */ // public String getCurrentUrl(); // // } // Path: src/main/java/me/alb_i986/selenium/tinafw/tasks/NavigationWebTask.java import me.alb_i986.selenium.tinafw.ui.LoadablePage; import me.alb_i986.selenium.tinafw.ui.WebPage; package me.alb_i986.selenium.tinafw.tasks; /** * A WebTask implementing a step for navigating to a {@link LoadablePage}. */ public abstract class NavigationWebTask extends BaseWebTask { /** * Navigate to {@link #pageToLoadClass()} and return its instance. * * @return an instance of {@link #pageToLoadClass()} */ @Override
public WebPage run(WebPage previousPage) {
alb-i986/selenium-tinafw
src/test/java/me/alb_i986/selenium/tinafw/config/PropertyLoaderFromResourceTest.java
// Path: src/main/java/me/alb_i986/selenium/tinafw/config/ConfigException.java // public class ConfigException extends RuntimeException { // // private static final long serialVersionUID = -6017026647523692805L; // // public ConfigException() { // super(); // } // // public ConfigException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public ConfigException(String message, Throwable cause) { // super(message, cause); // } // // public ConfigException(String message) { // super(message); // } // // public ConfigException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/me/alb_i986/selenium/tinafw/config/PropertyLoader.java // public abstract class PropertyLoader { // // /** // * @param key the name of the property // * // * @return the value of the given property; // * null if the property is not defined // */ // public abstract String getProperty(String key); // // /** // * @return true if the given property is defined in the source. // */ // public boolean isPropertyDefined(String key) { // return getProperty(key) != null; // } // // /** // * @return true if the given property is not defined or it is an empty string // */ // public boolean isPropertyEmpty(String key) { // if(!isPropertyDefined(key)) // return true; // return getProperty(key).isEmpty(); // } // // } // // Path: src/main/java/me/alb_i986/selenium/tinafw/config/PropertyLoaderFromResource.java // public class PropertyLoaderFromResource extends PropertyLoader { // // private static final Logger logger = LogManager.getLogger(PropertyLoaderFromResource.class); // // private Properties propsFromResource; // // public PropertyLoaderFromResource(String resourceName, boolean isResourceRequired) { // this.propsFromResource = loadPropsFromResource(resourceName, isResourceRequired); // } // // @Override // public String getProperty(String key) { // return propsFromResource.getProperty(key); // } // // /** // * Load properties from a resource. // * // * @param resourceName // * @param failOnResourceNotFoundOrNotLoaded when true, a ConfigException // * is raised if the resource cannot be found or loaded // * @return a {@link Properties} instance with the properties loaded from the resource; // * might be empty if the resource is not found or if it cannot be loaded // * @throws ConfigException if the resource cannot be found or loaded, // * and failOnResourceNotFound is true // * // * @see Properties#load(InputStream) // */ // private static Properties loadPropsFromResource(String resourceName, boolean failOnResourceNotFoundOrNotLoaded) { // Properties props = new Properties(); // InputStream resource = PropertyLoaderFromResource.class.getResourceAsStream(resourceName); // boolean resourceNotFound = (resource == null); // if(resourceNotFound) { // if(failOnResourceNotFoundOrNotLoaded) { // throw new ConfigException("resource " + resourceName + " not found"); // } else { // // if the resource is not found, return an empty Properties // logger.warn("Skipping resource " + resourceName + ": file not found."); // return props; // } // } // try { // props.load(resource); // } catch (IOException e) { // if(failOnResourceNotFoundOrNotLoaded) // throw new ConfigException("Cannot load properties from " + resourceName, e); // else // logger.warn("Cannot load properties from " + resourceName + ": " + e.getMessage()); // } // return props; // } // // }
import static org.junit.Assert.*; import static org.hamcrest.Matchers.*; import me.alb_i986.selenium.tinafw.config.ConfigException; import me.alb_i986.selenium.tinafw.config.PropertyLoader; import me.alb_i986.selenium.tinafw.config.PropertyLoaderFromResource; import org.junit.Test;
package me.alb_i986.selenium.tinafw.config; public class PropertyLoaderFromResourceTest { /** * Testing the constructor * {@link PropertyLoaderFromResource#PropertyLoaderFromResource(String, boolean)}. * * <ul> * <li>Given a resource which does not exist * <li>When I instantiate a {@link PropertyLoaderFromResource} with * that resource, and the resource is <i>not</i> required * <li>Then an exception should <i>not</i> be thrown * </ul> */ @Test public void givenNonExistentResourceWhenNewAndResourceIsNotRequired() { String resourceName = givenNonExistingResource(); boolean isResourceRequired = false;
// Path: src/main/java/me/alb_i986/selenium/tinafw/config/ConfigException.java // public class ConfigException extends RuntimeException { // // private static final long serialVersionUID = -6017026647523692805L; // // public ConfigException() { // super(); // } // // public ConfigException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public ConfigException(String message, Throwable cause) { // super(message, cause); // } // // public ConfigException(String message) { // super(message); // } // // public ConfigException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/me/alb_i986/selenium/tinafw/config/PropertyLoader.java // public abstract class PropertyLoader { // // /** // * @param key the name of the property // * // * @return the value of the given property; // * null if the property is not defined // */ // public abstract String getProperty(String key); // // /** // * @return true if the given property is defined in the source. // */ // public boolean isPropertyDefined(String key) { // return getProperty(key) != null; // } // // /** // * @return true if the given property is not defined or it is an empty string // */ // public boolean isPropertyEmpty(String key) { // if(!isPropertyDefined(key)) // return true; // return getProperty(key).isEmpty(); // } // // } // // Path: src/main/java/me/alb_i986/selenium/tinafw/config/PropertyLoaderFromResource.java // public class PropertyLoaderFromResource extends PropertyLoader { // // private static final Logger logger = LogManager.getLogger(PropertyLoaderFromResource.class); // // private Properties propsFromResource; // // public PropertyLoaderFromResource(String resourceName, boolean isResourceRequired) { // this.propsFromResource = loadPropsFromResource(resourceName, isResourceRequired); // } // // @Override // public String getProperty(String key) { // return propsFromResource.getProperty(key); // } // // /** // * Load properties from a resource. // * // * @param resourceName // * @param failOnResourceNotFoundOrNotLoaded when true, a ConfigException // * is raised if the resource cannot be found or loaded // * @return a {@link Properties} instance with the properties loaded from the resource; // * might be empty if the resource is not found or if it cannot be loaded // * @throws ConfigException if the resource cannot be found or loaded, // * and failOnResourceNotFound is true // * // * @see Properties#load(InputStream) // */ // private static Properties loadPropsFromResource(String resourceName, boolean failOnResourceNotFoundOrNotLoaded) { // Properties props = new Properties(); // InputStream resource = PropertyLoaderFromResource.class.getResourceAsStream(resourceName); // boolean resourceNotFound = (resource == null); // if(resourceNotFound) { // if(failOnResourceNotFoundOrNotLoaded) { // throw new ConfigException("resource " + resourceName + " not found"); // } else { // // if the resource is not found, return an empty Properties // logger.warn("Skipping resource " + resourceName + ": file not found."); // return props; // } // } // try { // props.load(resource); // } catch (IOException e) { // if(failOnResourceNotFoundOrNotLoaded) // throw new ConfigException("Cannot load properties from " + resourceName, e); // else // logger.warn("Cannot load properties from " + resourceName + ": " + e.getMessage()); // } // return props; // } // // } // Path: src/test/java/me/alb_i986/selenium/tinafw/config/PropertyLoaderFromResourceTest.java import static org.junit.Assert.*; import static org.hamcrest.Matchers.*; import me.alb_i986.selenium.tinafw.config.ConfigException; import me.alb_i986.selenium.tinafw.config.PropertyLoader; import me.alb_i986.selenium.tinafw.config.PropertyLoaderFromResource; import org.junit.Test; package me.alb_i986.selenium.tinafw.config; public class PropertyLoaderFromResourceTest { /** * Testing the constructor * {@link PropertyLoaderFromResource#PropertyLoaderFromResource(String, boolean)}. * * <ul> * <li>Given a resource which does not exist * <li>When I instantiate a {@link PropertyLoaderFromResource} with * that resource, and the resource is <i>not</i> required * <li>Then an exception should <i>not</i> be thrown * </ul> */ @Test public void givenNonExistentResourceWhenNewAndResourceIsNotRequired() { String resourceName = givenNonExistingResource(); boolean isResourceRequired = false;
new PropertyLoaderFromResource(resourceName, isResourceRequired);
alb-i986/selenium-tinafw
src/test/java/me/alb_i986/selenium/tinafw/config/PropertyLoaderFromResourceTest.java
// Path: src/main/java/me/alb_i986/selenium/tinafw/config/ConfigException.java // public class ConfigException extends RuntimeException { // // private static final long serialVersionUID = -6017026647523692805L; // // public ConfigException() { // super(); // } // // public ConfigException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public ConfigException(String message, Throwable cause) { // super(message, cause); // } // // public ConfigException(String message) { // super(message); // } // // public ConfigException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/me/alb_i986/selenium/tinafw/config/PropertyLoader.java // public abstract class PropertyLoader { // // /** // * @param key the name of the property // * // * @return the value of the given property; // * null if the property is not defined // */ // public abstract String getProperty(String key); // // /** // * @return true if the given property is defined in the source. // */ // public boolean isPropertyDefined(String key) { // return getProperty(key) != null; // } // // /** // * @return true if the given property is not defined or it is an empty string // */ // public boolean isPropertyEmpty(String key) { // if(!isPropertyDefined(key)) // return true; // return getProperty(key).isEmpty(); // } // // } // // Path: src/main/java/me/alb_i986/selenium/tinafw/config/PropertyLoaderFromResource.java // public class PropertyLoaderFromResource extends PropertyLoader { // // private static final Logger logger = LogManager.getLogger(PropertyLoaderFromResource.class); // // private Properties propsFromResource; // // public PropertyLoaderFromResource(String resourceName, boolean isResourceRequired) { // this.propsFromResource = loadPropsFromResource(resourceName, isResourceRequired); // } // // @Override // public String getProperty(String key) { // return propsFromResource.getProperty(key); // } // // /** // * Load properties from a resource. // * // * @param resourceName // * @param failOnResourceNotFoundOrNotLoaded when true, a ConfigException // * is raised if the resource cannot be found or loaded // * @return a {@link Properties} instance with the properties loaded from the resource; // * might be empty if the resource is not found or if it cannot be loaded // * @throws ConfigException if the resource cannot be found or loaded, // * and failOnResourceNotFound is true // * // * @see Properties#load(InputStream) // */ // private static Properties loadPropsFromResource(String resourceName, boolean failOnResourceNotFoundOrNotLoaded) { // Properties props = new Properties(); // InputStream resource = PropertyLoaderFromResource.class.getResourceAsStream(resourceName); // boolean resourceNotFound = (resource == null); // if(resourceNotFound) { // if(failOnResourceNotFoundOrNotLoaded) { // throw new ConfigException("resource " + resourceName + " not found"); // } else { // // if the resource is not found, return an empty Properties // logger.warn("Skipping resource " + resourceName + ": file not found."); // return props; // } // } // try { // props.load(resource); // } catch (IOException e) { // if(failOnResourceNotFoundOrNotLoaded) // throw new ConfigException("Cannot load properties from " + resourceName, e); // else // logger.warn("Cannot load properties from " + resourceName + ": " + e.getMessage()); // } // return props; // } // // }
import static org.junit.Assert.*; import static org.hamcrest.Matchers.*; import me.alb_i986.selenium.tinafw.config.ConfigException; import me.alb_i986.selenium.tinafw.config.PropertyLoader; import me.alb_i986.selenium.tinafw.config.PropertyLoaderFromResource; import org.junit.Test;
package me.alb_i986.selenium.tinafw.config; public class PropertyLoaderFromResourceTest { /** * Testing the constructor * {@link PropertyLoaderFromResource#PropertyLoaderFromResource(String, boolean)}. * * <ul> * <li>Given a resource which does not exist * <li>When I instantiate a {@link PropertyLoaderFromResource} with * that resource, and the resource is <i>not</i> required * <li>Then an exception should <i>not</i> be thrown * </ul> */ @Test public void givenNonExistentResourceWhenNewAndResourceIsNotRequired() { String resourceName = givenNonExistingResource(); boolean isResourceRequired = false; new PropertyLoaderFromResource(resourceName, isResourceRequired); // here it should NOT throw an exception } /** * Testing the constructor * {@link PropertyLoaderFromResource#PropertyLoaderFromResource(String, boolean)}. * * <ul> * <li>Given a resource which does not exist * <li>When I instantiate a {@link PropertyLoaderFromResource} with * that resource, and the resource is required * <li>Then an exception should be thrown * </ul> */
// Path: src/main/java/me/alb_i986/selenium/tinafw/config/ConfigException.java // public class ConfigException extends RuntimeException { // // private static final long serialVersionUID = -6017026647523692805L; // // public ConfigException() { // super(); // } // // public ConfigException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public ConfigException(String message, Throwable cause) { // super(message, cause); // } // // public ConfigException(String message) { // super(message); // } // // public ConfigException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/me/alb_i986/selenium/tinafw/config/PropertyLoader.java // public abstract class PropertyLoader { // // /** // * @param key the name of the property // * // * @return the value of the given property; // * null if the property is not defined // */ // public abstract String getProperty(String key); // // /** // * @return true if the given property is defined in the source. // */ // public boolean isPropertyDefined(String key) { // return getProperty(key) != null; // } // // /** // * @return true if the given property is not defined or it is an empty string // */ // public boolean isPropertyEmpty(String key) { // if(!isPropertyDefined(key)) // return true; // return getProperty(key).isEmpty(); // } // // } // // Path: src/main/java/me/alb_i986/selenium/tinafw/config/PropertyLoaderFromResource.java // public class PropertyLoaderFromResource extends PropertyLoader { // // private static final Logger logger = LogManager.getLogger(PropertyLoaderFromResource.class); // // private Properties propsFromResource; // // public PropertyLoaderFromResource(String resourceName, boolean isResourceRequired) { // this.propsFromResource = loadPropsFromResource(resourceName, isResourceRequired); // } // // @Override // public String getProperty(String key) { // return propsFromResource.getProperty(key); // } // // /** // * Load properties from a resource. // * // * @param resourceName // * @param failOnResourceNotFoundOrNotLoaded when true, a ConfigException // * is raised if the resource cannot be found or loaded // * @return a {@link Properties} instance with the properties loaded from the resource; // * might be empty if the resource is not found or if it cannot be loaded // * @throws ConfigException if the resource cannot be found or loaded, // * and failOnResourceNotFound is true // * // * @see Properties#load(InputStream) // */ // private static Properties loadPropsFromResource(String resourceName, boolean failOnResourceNotFoundOrNotLoaded) { // Properties props = new Properties(); // InputStream resource = PropertyLoaderFromResource.class.getResourceAsStream(resourceName); // boolean resourceNotFound = (resource == null); // if(resourceNotFound) { // if(failOnResourceNotFoundOrNotLoaded) { // throw new ConfigException("resource " + resourceName + " not found"); // } else { // // if the resource is not found, return an empty Properties // logger.warn("Skipping resource " + resourceName + ": file not found."); // return props; // } // } // try { // props.load(resource); // } catch (IOException e) { // if(failOnResourceNotFoundOrNotLoaded) // throw new ConfigException("Cannot load properties from " + resourceName, e); // else // logger.warn("Cannot load properties from " + resourceName + ": " + e.getMessage()); // } // return props; // } // // } // Path: src/test/java/me/alb_i986/selenium/tinafw/config/PropertyLoaderFromResourceTest.java import static org.junit.Assert.*; import static org.hamcrest.Matchers.*; import me.alb_i986.selenium.tinafw.config.ConfigException; import me.alb_i986.selenium.tinafw.config.PropertyLoader; import me.alb_i986.selenium.tinafw.config.PropertyLoaderFromResource; import org.junit.Test; package me.alb_i986.selenium.tinafw.config; public class PropertyLoaderFromResourceTest { /** * Testing the constructor * {@link PropertyLoaderFromResource#PropertyLoaderFromResource(String, boolean)}. * * <ul> * <li>Given a resource which does not exist * <li>When I instantiate a {@link PropertyLoaderFromResource} with * that resource, and the resource is <i>not</i> required * <li>Then an exception should <i>not</i> be thrown * </ul> */ @Test public void givenNonExistentResourceWhenNewAndResourceIsNotRequired() { String resourceName = givenNonExistingResource(); boolean isResourceRequired = false; new PropertyLoaderFromResource(resourceName, isResourceRequired); // here it should NOT throw an exception } /** * Testing the constructor * {@link PropertyLoaderFromResource#PropertyLoaderFromResource(String, boolean)}. * * <ul> * <li>Given a resource which does not exist * <li>When I instantiate a {@link PropertyLoaderFromResource} with * that resource, and the resource is required * <li>Then an exception should be thrown * </ul> */
@Test(expected = ConfigException.class)
alb-i986/selenium-tinafw
src/test/java/me/alb_i986/selenium/tinafw/config/PropertyLoaderFromResourceTest.java
// Path: src/main/java/me/alb_i986/selenium/tinafw/config/ConfigException.java // public class ConfigException extends RuntimeException { // // private static final long serialVersionUID = -6017026647523692805L; // // public ConfigException() { // super(); // } // // public ConfigException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public ConfigException(String message, Throwable cause) { // super(message, cause); // } // // public ConfigException(String message) { // super(message); // } // // public ConfigException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/me/alb_i986/selenium/tinafw/config/PropertyLoader.java // public abstract class PropertyLoader { // // /** // * @param key the name of the property // * // * @return the value of the given property; // * null if the property is not defined // */ // public abstract String getProperty(String key); // // /** // * @return true if the given property is defined in the source. // */ // public boolean isPropertyDefined(String key) { // return getProperty(key) != null; // } // // /** // * @return true if the given property is not defined or it is an empty string // */ // public boolean isPropertyEmpty(String key) { // if(!isPropertyDefined(key)) // return true; // return getProperty(key).isEmpty(); // } // // } // // Path: src/main/java/me/alb_i986/selenium/tinafw/config/PropertyLoaderFromResource.java // public class PropertyLoaderFromResource extends PropertyLoader { // // private static final Logger logger = LogManager.getLogger(PropertyLoaderFromResource.class); // // private Properties propsFromResource; // // public PropertyLoaderFromResource(String resourceName, boolean isResourceRequired) { // this.propsFromResource = loadPropsFromResource(resourceName, isResourceRequired); // } // // @Override // public String getProperty(String key) { // return propsFromResource.getProperty(key); // } // // /** // * Load properties from a resource. // * // * @param resourceName // * @param failOnResourceNotFoundOrNotLoaded when true, a ConfigException // * is raised if the resource cannot be found or loaded // * @return a {@link Properties} instance with the properties loaded from the resource; // * might be empty if the resource is not found or if it cannot be loaded // * @throws ConfigException if the resource cannot be found or loaded, // * and failOnResourceNotFound is true // * // * @see Properties#load(InputStream) // */ // private static Properties loadPropsFromResource(String resourceName, boolean failOnResourceNotFoundOrNotLoaded) { // Properties props = new Properties(); // InputStream resource = PropertyLoaderFromResource.class.getResourceAsStream(resourceName); // boolean resourceNotFound = (resource == null); // if(resourceNotFound) { // if(failOnResourceNotFoundOrNotLoaded) { // throw new ConfigException("resource " + resourceName + " not found"); // } else { // // if the resource is not found, return an empty Properties // logger.warn("Skipping resource " + resourceName + ": file not found."); // return props; // } // } // try { // props.load(resource); // } catch (IOException e) { // if(failOnResourceNotFoundOrNotLoaded) // throw new ConfigException("Cannot load properties from " + resourceName, e); // else // logger.warn("Cannot load properties from " + resourceName + ": " + e.getMessage()); // } // return props; // } // // }
import static org.junit.Assert.*; import static org.hamcrest.Matchers.*; import me.alb_i986.selenium.tinafw.config.ConfigException; import me.alb_i986.selenium.tinafw.config.PropertyLoader; import me.alb_i986.selenium.tinafw.config.PropertyLoaderFromResource; import org.junit.Test;
* * <ul> * <li>Given an existing resource * <li>When I get a property whose value ends with spaces * <li>Then the value returned should contain all of the original ending spaces * </ul> */ @Test public void givenExistingResourceWhenGetExistingPropertyWhoseValueHasEndingSpaces() { String value = whenGetProperty("empty.property.whose.value.has.ending.spaces"); assertNotNull(value); assertThat(value, is("asd ")); } private String givenExistingResource() { String resourceName = getClass().getSimpleName() + ".properties"; assertNotNull("The resource " + resourceName + " should exist", getClass().getResourceAsStream(resourceName)); return resourceName; } private String givenNonExistingResource() { String resourceName = "/non-existent-resource.properties"; assertNull("The resource " + resourceName + " should not exist", getClass().getResourceAsStream(resourceName)); return resourceName; } private String whenGetProperty(String propertyName) { String resourceName = givenExistingResource();
// Path: src/main/java/me/alb_i986/selenium/tinafw/config/ConfigException.java // public class ConfigException extends RuntimeException { // // private static final long serialVersionUID = -6017026647523692805L; // // public ConfigException() { // super(); // } // // public ConfigException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public ConfigException(String message, Throwable cause) { // super(message, cause); // } // // public ConfigException(String message) { // super(message); // } // // public ConfigException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/me/alb_i986/selenium/tinafw/config/PropertyLoader.java // public abstract class PropertyLoader { // // /** // * @param key the name of the property // * // * @return the value of the given property; // * null if the property is not defined // */ // public abstract String getProperty(String key); // // /** // * @return true if the given property is defined in the source. // */ // public boolean isPropertyDefined(String key) { // return getProperty(key) != null; // } // // /** // * @return true if the given property is not defined or it is an empty string // */ // public boolean isPropertyEmpty(String key) { // if(!isPropertyDefined(key)) // return true; // return getProperty(key).isEmpty(); // } // // } // // Path: src/main/java/me/alb_i986/selenium/tinafw/config/PropertyLoaderFromResource.java // public class PropertyLoaderFromResource extends PropertyLoader { // // private static final Logger logger = LogManager.getLogger(PropertyLoaderFromResource.class); // // private Properties propsFromResource; // // public PropertyLoaderFromResource(String resourceName, boolean isResourceRequired) { // this.propsFromResource = loadPropsFromResource(resourceName, isResourceRequired); // } // // @Override // public String getProperty(String key) { // return propsFromResource.getProperty(key); // } // // /** // * Load properties from a resource. // * // * @param resourceName // * @param failOnResourceNotFoundOrNotLoaded when true, a ConfigException // * is raised if the resource cannot be found or loaded // * @return a {@link Properties} instance with the properties loaded from the resource; // * might be empty if the resource is not found or if it cannot be loaded // * @throws ConfigException if the resource cannot be found or loaded, // * and failOnResourceNotFound is true // * // * @see Properties#load(InputStream) // */ // private static Properties loadPropsFromResource(String resourceName, boolean failOnResourceNotFoundOrNotLoaded) { // Properties props = new Properties(); // InputStream resource = PropertyLoaderFromResource.class.getResourceAsStream(resourceName); // boolean resourceNotFound = (resource == null); // if(resourceNotFound) { // if(failOnResourceNotFoundOrNotLoaded) { // throw new ConfigException("resource " + resourceName + " not found"); // } else { // // if the resource is not found, return an empty Properties // logger.warn("Skipping resource " + resourceName + ": file not found."); // return props; // } // } // try { // props.load(resource); // } catch (IOException e) { // if(failOnResourceNotFoundOrNotLoaded) // throw new ConfigException("Cannot load properties from " + resourceName, e); // else // logger.warn("Cannot load properties from " + resourceName + ": " + e.getMessage()); // } // return props; // } // // } // Path: src/test/java/me/alb_i986/selenium/tinafw/config/PropertyLoaderFromResourceTest.java import static org.junit.Assert.*; import static org.hamcrest.Matchers.*; import me.alb_i986.selenium.tinafw.config.ConfigException; import me.alb_i986.selenium.tinafw.config.PropertyLoader; import me.alb_i986.selenium.tinafw.config.PropertyLoaderFromResource; import org.junit.Test; * * <ul> * <li>Given an existing resource * <li>When I get a property whose value ends with spaces * <li>Then the value returned should contain all of the original ending spaces * </ul> */ @Test public void givenExistingResourceWhenGetExistingPropertyWhoseValueHasEndingSpaces() { String value = whenGetProperty("empty.property.whose.value.has.ending.spaces"); assertNotNull(value); assertThat(value, is("asd ")); } private String givenExistingResource() { String resourceName = getClass().getSimpleName() + ".properties"; assertNotNull("The resource " + resourceName + " should exist", getClass().getResourceAsStream(resourceName)); return resourceName; } private String givenNonExistingResource() { String resourceName = "/non-existent-resource.properties"; assertNull("The resource " + resourceName + " should not exist", getClass().getResourceAsStream(resourceName)); return resourceName; } private String whenGetProperty(String propertyName) { String resourceName = givenExistingResource();
PropertyLoader propLoader = new PropertyLoaderFromResource(resourceName, true);
alb-i986/selenium-tinafw
src/main/java/me/alb_i986/selenium/tinafw/config/Config.java
// Path: src/main/java/me/alb_i986/selenium/tinafw/domain/SupportedBrowser.java // public enum SupportedBrowser { // // CHROME(ChromeDriver.class, DesiredCapabilities.chrome()), // FIREFOX(FirefoxDriver.class, DesiredCapabilities.firefox()), // SAFARI(SafariDriver.class, DesiredCapabilities.safari()), // IE(InternetExplorerDriver.class, DesiredCapabilities.internetExplorer()), // HTML_UNIT(HtmlUnitDriver.class, DesiredCapabilities.htmlUnit()), // ; // // private DesiredCapabilities capabilities; // private Class<? extends WebDriver> concreteWebDriverClass; // // private SupportedBrowser(Class<? extends WebDriver> clazz, DesiredCapabilities capabilities) { // this.concreteWebDriverClass = clazz; // this.capabilities = capabilities; // } // // /** // * @return the concrete WebDriver class corresponding to this SupportedBrowser // */ // public Class<? extends WebDriver> toClass() { // return this.concreteWebDriverClass; // } // // public DesiredCapabilities toCapabilities() { // return this.capabilities; // } // // /** // * @return the lower cased name of this enum constant // */ // @Override // public String toString() { // return super.toString().toLowerCase(); // } // } // // Path: src/main/java/me/alb_i986/selenium/tinafw/tests/rules/BrowserManager.java // public class BrowserManager extends ExternalResource { // // protected static final Logger logger = LogManager.getLogger(BrowserManager.class); // // protected Set<Browser> registeredBrowsers = new HashSet<>(); // private Mode mode; // // /** // * Default constructor: create a BrowserManager that <i>does</i> // * close the registered browsers. // */ // public BrowserManager() { // this(Mode.DEFAULT); // } // // /** // * Allows customizing the behavior. // * // * @param mode if true, the browsers will <i>not</i> be closed // */ // public BrowserManager(Mode mode) { // if(mode == null) { // throw new IllegalArgumentException("null mode"); // } // this.mode = mode; // } // // @Override // protected void after() { // if(mode == Mode.DO_NOT_CLOSE_BROWSERS) { // return; // } // logger.debug("Closing all registered browsers (" + registeredBrowsers.size() + ")"); // for (Browser browser : registeredBrowsers) { // browser.close(); // } // } // // public void registerBrowsers(Browser... browsers) { // this.registeredBrowsers.addAll(Arrays.asList(browsers)); // } // // public void registerBrowser(Browser browser) { // this.registeredBrowsers.add(browser); // } // // public enum Mode { // DEFAULT, // DO_NOT_CLOSE_BROWSERS, // } // }
import me.alb_i986.selenium.tinafw.domain.SupportedBrowser; import java.net.URL; import java.util.*; import me.alb_i986.selenium.tinafw.tests.rules.BrowserManager; import org.openqa.selenium.Platform;
return (value == null) ? null : Long.parseLong(value); } /** * @return the property {@value #PROP_TIMEOUT_EXPLICIT_WAIT} * @throws SettingNotFoundException if the property is not defined * * @see Integer#parseInt(String) */ public static int getExplicitWait() { return Integer.parseInt(getRequiredProperty(PROP_TIMEOUT_EXPLICIT_WAIT)); } /** * @return the property {@value #PROP_KEEP_BROWSERS_OPEN} * Please note, in case the property is defined and <i>empty</i>, * it will be considered as {@code false}. * @throws SettingNotFoundException if the property is not defined * * @see Boolean#parseBoolean(String) */ public static boolean getKeepBrowsersOpen() { return Boolean.parseBoolean(getRequiredProperty(PROP_KEEP_BROWSERS_OPEN)); } /** * @return the mode of the BrowserManager, based on the property {@value #PROP_KEEP_BROWSERS_OPEN} * * @see #getKeepBrowsersOpen() */
// Path: src/main/java/me/alb_i986/selenium/tinafw/domain/SupportedBrowser.java // public enum SupportedBrowser { // // CHROME(ChromeDriver.class, DesiredCapabilities.chrome()), // FIREFOX(FirefoxDriver.class, DesiredCapabilities.firefox()), // SAFARI(SafariDriver.class, DesiredCapabilities.safari()), // IE(InternetExplorerDriver.class, DesiredCapabilities.internetExplorer()), // HTML_UNIT(HtmlUnitDriver.class, DesiredCapabilities.htmlUnit()), // ; // // private DesiredCapabilities capabilities; // private Class<? extends WebDriver> concreteWebDriverClass; // // private SupportedBrowser(Class<? extends WebDriver> clazz, DesiredCapabilities capabilities) { // this.concreteWebDriverClass = clazz; // this.capabilities = capabilities; // } // // /** // * @return the concrete WebDriver class corresponding to this SupportedBrowser // */ // public Class<? extends WebDriver> toClass() { // return this.concreteWebDriverClass; // } // // public DesiredCapabilities toCapabilities() { // return this.capabilities; // } // // /** // * @return the lower cased name of this enum constant // */ // @Override // public String toString() { // return super.toString().toLowerCase(); // } // } // // Path: src/main/java/me/alb_i986/selenium/tinafw/tests/rules/BrowserManager.java // public class BrowserManager extends ExternalResource { // // protected static final Logger logger = LogManager.getLogger(BrowserManager.class); // // protected Set<Browser> registeredBrowsers = new HashSet<>(); // private Mode mode; // // /** // * Default constructor: create a BrowserManager that <i>does</i> // * close the registered browsers. // */ // public BrowserManager() { // this(Mode.DEFAULT); // } // // /** // * Allows customizing the behavior. // * // * @param mode if true, the browsers will <i>not</i> be closed // */ // public BrowserManager(Mode mode) { // if(mode == null) { // throw new IllegalArgumentException("null mode"); // } // this.mode = mode; // } // // @Override // protected void after() { // if(mode == Mode.DO_NOT_CLOSE_BROWSERS) { // return; // } // logger.debug("Closing all registered browsers (" + registeredBrowsers.size() + ")"); // for (Browser browser : registeredBrowsers) { // browser.close(); // } // } // // public void registerBrowsers(Browser... browsers) { // this.registeredBrowsers.addAll(Arrays.asList(browsers)); // } // // public void registerBrowser(Browser browser) { // this.registeredBrowsers.add(browser); // } // // public enum Mode { // DEFAULT, // DO_NOT_CLOSE_BROWSERS, // } // } // Path: src/main/java/me/alb_i986/selenium/tinafw/config/Config.java import me.alb_i986.selenium.tinafw.domain.SupportedBrowser; import java.net.URL; import java.util.*; import me.alb_i986.selenium.tinafw.tests.rules.BrowserManager; import org.openqa.selenium.Platform; return (value == null) ? null : Long.parseLong(value); } /** * @return the property {@value #PROP_TIMEOUT_EXPLICIT_WAIT} * @throws SettingNotFoundException if the property is not defined * * @see Integer#parseInt(String) */ public static int getExplicitWait() { return Integer.parseInt(getRequiredProperty(PROP_TIMEOUT_EXPLICIT_WAIT)); } /** * @return the property {@value #PROP_KEEP_BROWSERS_OPEN} * Please note, in case the property is defined and <i>empty</i>, * it will be considered as {@code false}. * @throws SettingNotFoundException if the property is not defined * * @see Boolean#parseBoolean(String) */ public static boolean getKeepBrowsersOpen() { return Boolean.parseBoolean(getRequiredProperty(PROP_KEEP_BROWSERS_OPEN)); } /** * @return the mode of the BrowserManager, based on the property {@value #PROP_KEEP_BROWSERS_OPEN} * * @see #getKeepBrowsersOpen() */
public static BrowserManager.Mode getBrowserManagerMode() {
alb-i986/selenium-tinafw
src/main/java/me/alb_i986/selenium/tinafw/config/Config.java
// Path: src/main/java/me/alb_i986/selenium/tinafw/domain/SupportedBrowser.java // public enum SupportedBrowser { // // CHROME(ChromeDriver.class, DesiredCapabilities.chrome()), // FIREFOX(FirefoxDriver.class, DesiredCapabilities.firefox()), // SAFARI(SafariDriver.class, DesiredCapabilities.safari()), // IE(InternetExplorerDriver.class, DesiredCapabilities.internetExplorer()), // HTML_UNIT(HtmlUnitDriver.class, DesiredCapabilities.htmlUnit()), // ; // // private DesiredCapabilities capabilities; // private Class<? extends WebDriver> concreteWebDriverClass; // // private SupportedBrowser(Class<? extends WebDriver> clazz, DesiredCapabilities capabilities) { // this.concreteWebDriverClass = clazz; // this.capabilities = capabilities; // } // // /** // * @return the concrete WebDriver class corresponding to this SupportedBrowser // */ // public Class<? extends WebDriver> toClass() { // return this.concreteWebDriverClass; // } // // public DesiredCapabilities toCapabilities() { // return this.capabilities; // } // // /** // * @return the lower cased name of this enum constant // */ // @Override // public String toString() { // return super.toString().toLowerCase(); // } // } // // Path: src/main/java/me/alb_i986/selenium/tinafw/tests/rules/BrowserManager.java // public class BrowserManager extends ExternalResource { // // protected static final Logger logger = LogManager.getLogger(BrowserManager.class); // // protected Set<Browser> registeredBrowsers = new HashSet<>(); // private Mode mode; // // /** // * Default constructor: create a BrowserManager that <i>does</i> // * close the registered browsers. // */ // public BrowserManager() { // this(Mode.DEFAULT); // } // // /** // * Allows customizing the behavior. // * // * @param mode if true, the browsers will <i>not</i> be closed // */ // public BrowserManager(Mode mode) { // if(mode == null) { // throw new IllegalArgumentException("null mode"); // } // this.mode = mode; // } // // @Override // protected void after() { // if(mode == Mode.DO_NOT_CLOSE_BROWSERS) { // return; // } // logger.debug("Closing all registered browsers (" + registeredBrowsers.size() + ")"); // for (Browser browser : registeredBrowsers) { // browser.close(); // } // } // // public void registerBrowsers(Browser... browsers) { // this.registeredBrowsers.addAll(Arrays.asList(browsers)); // } // // public void registerBrowser(Browser browser) { // this.registeredBrowsers.add(browser); // } // // public enum Mode { // DEFAULT, // DO_NOT_CLOSE_BROWSERS, // } // }
import me.alb_i986.selenium.tinafw.domain.SupportedBrowser; import java.net.URL; import java.util.*; import me.alb_i986.selenium.tinafw.tests.rules.BrowserManager; import org.openqa.selenium.Platform;
/** * @return the property {@value #PROP_MAX_EXECUTIONS} * @throws SettingNotFoundException if the property is not defined * * @see Integer#parseInt(String) */ public static int getMaxExecutions() { return Integer.parseInt(getRequiredProperty(PROP_MAX_EXECUTIONS)); } /** * @return the property {@value #PROP_REPORTS_DIR} * @throws SettingNotFoundException if the property is not defined */ public static String getReportsDir() { return getRequiredProperty(PROP_REPORTS_DIR); } /** * @return a List of the {@link SupportedBrowser}'s specified in the property * {@value #PROP_BROWSERS} * * @throws SettingNotFoundException if the property can't be found, * @throws ConfigException if the property is empty * @throws IllegalArgumentException if one of the values cannot be converted to * {@link SupportedBrowser} * * @see PropertiesUtils#split(String) * @see PropertiesUtils#toSupportedBrowsers(String[]) */
// Path: src/main/java/me/alb_i986/selenium/tinafw/domain/SupportedBrowser.java // public enum SupportedBrowser { // // CHROME(ChromeDriver.class, DesiredCapabilities.chrome()), // FIREFOX(FirefoxDriver.class, DesiredCapabilities.firefox()), // SAFARI(SafariDriver.class, DesiredCapabilities.safari()), // IE(InternetExplorerDriver.class, DesiredCapabilities.internetExplorer()), // HTML_UNIT(HtmlUnitDriver.class, DesiredCapabilities.htmlUnit()), // ; // // private DesiredCapabilities capabilities; // private Class<? extends WebDriver> concreteWebDriverClass; // // private SupportedBrowser(Class<? extends WebDriver> clazz, DesiredCapabilities capabilities) { // this.concreteWebDriverClass = clazz; // this.capabilities = capabilities; // } // // /** // * @return the concrete WebDriver class corresponding to this SupportedBrowser // */ // public Class<? extends WebDriver> toClass() { // return this.concreteWebDriverClass; // } // // public DesiredCapabilities toCapabilities() { // return this.capabilities; // } // // /** // * @return the lower cased name of this enum constant // */ // @Override // public String toString() { // return super.toString().toLowerCase(); // } // } // // Path: src/main/java/me/alb_i986/selenium/tinafw/tests/rules/BrowserManager.java // public class BrowserManager extends ExternalResource { // // protected static final Logger logger = LogManager.getLogger(BrowserManager.class); // // protected Set<Browser> registeredBrowsers = new HashSet<>(); // private Mode mode; // // /** // * Default constructor: create a BrowserManager that <i>does</i> // * close the registered browsers. // */ // public BrowserManager() { // this(Mode.DEFAULT); // } // // /** // * Allows customizing the behavior. // * // * @param mode if true, the browsers will <i>not</i> be closed // */ // public BrowserManager(Mode mode) { // if(mode == null) { // throw new IllegalArgumentException("null mode"); // } // this.mode = mode; // } // // @Override // protected void after() { // if(mode == Mode.DO_NOT_CLOSE_BROWSERS) { // return; // } // logger.debug("Closing all registered browsers (" + registeredBrowsers.size() + ")"); // for (Browser browser : registeredBrowsers) { // browser.close(); // } // } // // public void registerBrowsers(Browser... browsers) { // this.registeredBrowsers.addAll(Arrays.asList(browsers)); // } // // public void registerBrowser(Browser browser) { // this.registeredBrowsers.add(browser); // } // // public enum Mode { // DEFAULT, // DO_NOT_CLOSE_BROWSERS, // } // } // Path: src/main/java/me/alb_i986/selenium/tinafw/config/Config.java import me.alb_i986.selenium.tinafw.domain.SupportedBrowser; import java.net.URL; import java.util.*; import me.alb_i986.selenium.tinafw.tests.rules.BrowserManager; import org.openqa.selenium.Platform; /** * @return the property {@value #PROP_MAX_EXECUTIONS} * @throws SettingNotFoundException if the property is not defined * * @see Integer#parseInt(String) */ public static int getMaxExecutions() { return Integer.parseInt(getRequiredProperty(PROP_MAX_EXECUTIONS)); } /** * @return the property {@value #PROP_REPORTS_DIR} * @throws SettingNotFoundException if the property is not defined */ public static String getReportsDir() { return getRequiredProperty(PROP_REPORTS_DIR); } /** * @return a List of the {@link SupportedBrowser}'s specified in the property * {@value #PROP_BROWSERS} * * @throws SettingNotFoundException if the property can't be found, * @throws ConfigException if the property is empty * @throws IllegalArgumentException if one of the values cannot be converted to * {@link SupportedBrowser} * * @see PropertiesUtils#split(String) * @see PropertiesUtils#toSupportedBrowsers(String[]) */
public static List<SupportedBrowser> getBrowsers() {
alb-i986/selenium-tinafw
src/main/java/me/alb_i986/selenium/tinafw/sample/tasks/OnMyAboutMePage.java
// Path: src/main/java/me/alb_i986/selenium/tinafw/sample/ui/MyAboutMePage.java // public class MyAboutMePage extends BaseWebPage implements LoadablePage { // // private static final String DOTALL_EMBEDDED_FLAG = "(?s)"; // // @FindBy(css = "h1.name") // private WebElement nameTitle; // // @FindBy(css = "div.bio") // private WebElement biography; // // @FindBy(css = "#app-icons li.app-icon") // private List<WebElement> socialIcons; // // @FindBy(id = "terms") // private WebElement searchTextField; // // // public MyAboutMePage(WebDriver driver, WebPage previous) { // super(driver, previous); // } // // public static String getRelativeUrl() { // return "/"; // } // // public SearchResultsPage doSearch(String searchQuery) { // searchTextField.sendKeys(searchQuery); // PageHelper.hitKeys(driver, Keys.ENTER); // return new SearchResultsPage(driver, this); // } // // public MyAboutMePage assertBioMatches(String expectedBioRegex) { // String bio = biography.getText(); // assertTrue( // "bio does not match. expected regex: '" + expectedBioRegex + // "'; actual text: '" + bio + "'", // // http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#DOTALL // bio.matches(DOTALL_EMBEDDED_FLAG + expectedBioRegex) // ); // logger.info("assertBioMatches " + expectedBioRegex + " passed"); // return this; // } // // public MyAboutMePage assertSocialButtonIsDisplayed(String social) { // WebElement socialIcon = getSocialIcon(social); // assertTrue( // "social icon for " + social + " not displayed", // socialIcon.isDisplayed() // ); // logger.info("assertSocialButtonIsDisplayed " + social + " passed"); // return this; // } // // public MyAboutMePage assertSocialButtonIsLink(String social) { // WebElement socialIcon = getSocialIcon(social); // WebElement socialLink = socialIcon.findElement(By.cssSelector("a")); // String socialUrl = socialLink.getAttribute("href"); // String expectedUrl = "http.*" + social + "\\..*"; // assertTrue( // "the social icon has a wrong link" + social + ". " + // "Expected: " + expectedUrl + "; " + // "actual: " + socialUrl, // socialUrl.matches(expectedUrl) // ); // logger.info("assertSocialButtonIsLink " + social + " passed"); // return this; // } // // /* // public SamplePage assertSocialButtons(SocialButtonsAssert socialButtonsAssert) { // */ // // protected WebElement getSocialIcon(String social) { // logger.debug("getSocialIcon " + social); // By linkLocator = By.cssSelector("a." + social); // // WebElement foundSocialIcon = null; // for (WebElement socialIcon : socialIcons) { // try { // socialIcon.findElement(linkLocator); // foundSocialIcon = socialIcon; // } catch(NoSuchElementException e) { // continue; // } // } // assertNotNull("social button for " + social + " not found.", foundSocialIcon); // return foundSocialIcon; // } // // @Override // protected void waitUntilIsLoaded() { // PageHelper.waitUntil( // ExpectedConditions.visibilityOf(nameTitle), // driver // ); // } // // } // // Path: src/main/java/me/alb_i986/selenium/tinafw/tasks/NavigationWebTask.java // public abstract class NavigationWebTask extends BaseWebTask { // // /** // * Navigate to {@link #pageToLoadClass()} and return its instance. // * // * @return an instance of {@link #pageToLoadClass()} // */ // @Override // public WebPage run(WebPage previousPage) { // return browser().browseTo(pageToLoadClass()); // } // // /** // * @return the class of the {@link LoadablePage} to load // */ // protected abstract <T extends LoadablePage> Class<T> pageToLoadClass(); // // }
import me.alb_i986.selenium.tinafw.sample.ui.MyAboutMePage; import me.alb_i986.selenium.tinafw.tasks.NavigationWebTask; import me.alb_i986.selenium.tinafw.ui.LoadablePage;
package me.alb_i986.selenium.tinafw.sample.tasks; /** * Navigate to my about.me page. */ public class OnMyAboutMePage extends NavigationWebTask { @SuppressWarnings("unchecked") @Override public <T extends LoadablePage> Class<T> pageToLoadClass() {
// Path: src/main/java/me/alb_i986/selenium/tinafw/sample/ui/MyAboutMePage.java // public class MyAboutMePage extends BaseWebPage implements LoadablePage { // // private static final String DOTALL_EMBEDDED_FLAG = "(?s)"; // // @FindBy(css = "h1.name") // private WebElement nameTitle; // // @FindBy(css = "div.bio") // private WebElement biography; // // @FindBy(css = "#app-icons li.app-icon") // private List<WebElement> socialIcons; // // @FindBy(id = "terms") // private WebElement searchTextField; // // // public MyAboutMePage(WebDriver driver, WebPage previous) { // super(driver, previous); // } // // public static String getRelativeUrl() { // return "/"; // } // // public SearchResultsPage doSearch(String searchQuery) { // searchTextField.sendKeys(searchQuery); // PageHelper.hitKeys(driver, Keys.ENTER); // return new SearchResultsPage(driver, this); // } // // public MyAboutMePage assertBioMatches(String expectedBioRegex) { // String bio = biography.getText(); // assertTrue( // "bio does not match. expected regex: '" + expectedBioRegex + // "'; actual text: '" + bio + "'", // // http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#DOTALL // bio.matches(DOTALL_EMBEDDED_FLAG + expectedBioRegex) // ); // logger.info("assertBioMatches " + expectedBioRegex + " passed"); // return this; // } // // public MyAboutMePage assertSocialButtonIsDisplayed(String social) { // WebElement socialIcon = getSocialIcon(social); // assertTrue( // "social icon for " + social + " not displayed", // socialIcon.isDisplayed() // ); // logger.info("assertSocialButtonIsDisplayed " + social + " passed"); // return this; // } // // public MyAboutMePage assertSocialButtonIsLink(String social) { // WebElement socialIcon = getSocialIcon(social); // WebElement socialLink = socialIcon.findElement(By.cssSelector("a")); // String socialUrl = socialLink.getAttribute("href"); // String expectedUrl = "http.*" + social + "\\..*"; // assertTrue( // "the social icon has a wrong link" + social + ". " + // "Expected: " + expectedUrl + "; " + // "actual: " + socialUrl, // socialUrl.matches(expectedUrl) // ); // logger.info("assertSocialButtonIsLink " + social + " passed"); // return this; // } // // /* // public SamplePage assertSocialButtons(SocialButtonsAssert socialButtonsAssert) { // */ // // protected WebElement getSocialIcon(String social) { // logger.debug("getSocialIcon " + social); // By linkLocator = By.cssSelector("a." + social); // // WebElement foundSocialIcon = null; // for (WebElement socialIcon : socialIcons) { // try { // socialIcon.findElement(linkLocator); // foundSocialIcon = socialIcon; // } catch(NoSuchElementException e) { // continue; // } // } // assertNotNull("social button for " + social + " not found.", foundSocialIcon); // return foundSocialIcon; // } // // @Override // protected void waitUntilIsLoaded() { // PageHelper.waitUntil( // ExpectedConditions.visibilityOf(nameTitle), // driver // ); // } // // } // // Path: src/main/java/me/alb_i986/selenium/tinafw/tasks/NavigationWebTask.java // public abstract class NavigationWebTask extends BaseWebTask { // // /** // * Navigate to {@link #pageToLoadClass()} and return its instance. // * // * @return an instance of {@link #pageToLoadClass()} // */ // @Override // public WebPage run(WebPage previousPage) { // return browser().browseTo(pageToLoadClass()); // } // // /** // * @return the class of the {@link LoadablePage} to load // */ // protected abstract <T extends LoadablePage> Class<T> pageToLoadClass(); // // } // Path: src/main/java/me/alb_i986/selenium/tinafw/sample/tasks/OnMyAboutMePage.java import me.alb_i986.selenium.tinafw.sample.ui.MyAboutMePage; import me.alb_i986.selenium.tinafw.tasks.NavigationWebTask; import me.alb_i986.selenium.tinafw.ui.LoadablePage; package me.alb_i986.selenium.tinafw.sample.tasks; /** * Navigate to my about.me page. */ public class OnMyAboutMePage extends NavigationWebTask { @SuppressWarnings("unchecked") @Override public <T extends LoadablePage> Class<T> pageToLoadClass() {
return (Class<T>) MyAboutMePage.class;
alb-i986/selenium-tinafw
src/main/java/me/alb_i986/selenium/tinafw/ui/WebDriverFactoryRemote.java
// Path: src/main/java/me/alb_i986/selenium/tinafw/domain/SupportedBrowser.java // public enum SupportedBrowser { // // CHROME(ChromeDriver.class, DesiredCapabilities.chrome()), // FIREFOX(FirefoxDriver.class, DesiredCapabilities.firefox()), // SAFARI(SafariDriver.class, DesiredCapabilities.safari()), // IE(InternetExplorerDriver.class, DesiredCapabilities.internetExplorer()), // HTML_UNIT(HtmlUnitDriver.class, DesiredCapabilities.htmlUnit()), // ; // // private DesiredCapabilities capabilities; // private Class<? extends WebDriver> concreteWebDriverClass; // // private SupportedBrowser(Class<? extends WebDriver> clazz, DesiredCapabilities capabilities) { // this.concreteWebDriverClass = clazz; // this.capabilities = capabilities; // } // // /** // * @return the concrete WebDriver class corresponding to this SupportedBrowser // */ // public Class<? extends WebDriver> toClass() { // return this.concreteWebDriverClass; // } // // public DesiredCapabilities toCapabilities() { // return this.capabilities; // } // // /** // * @return the lower cased name of this enum constant // */ // @Override // public String toString() { // return super.toString().toLowerCase(); // } // }
import java.net.URL; import me.alb_i986.selenium.tinafw.domain.SupportedBrowser; import org.openqa.selenium.Capabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.LocalFileDetector; import org.openqa.selenium.remote.RemoteWebDriver;
package me.alb_i986.selenium.tinafw.ui; /** * Create instances of {@link WebDriver} (specifically, {@link RemoteWebDriver}) * which can drive a browser on a remote machine, part of a * <a href="https://code.google.com/p/selenium/wiki/Grid2">Selenium Grid</a>. * <p> * Such a factory needs to know the URL of the hub. * Clients may also specify a set of * <a href="https://code.google.com/p/selenium/wiki/DesiredCapabilities">desired capabilities</a>. * <p> * The instances of {@link WebDriver}s will also feature a {@link LocalFileDetector}, * which handles the upload of files from the local machine running the tests * to the selenium node running the browser. */ public class WebDriverFactoryRemote implements WebDriverFactory { private URL gridHubURL; private DesiredCapabilities extraCapabilities; /** * A factory creating {@link WebDriver}s matching the given set of extra, * desired capabilities * (see also {@link RemoteWebDriver#RemoteWebDriver(URL, Capabilities)}). * * @param hubURL * @param extraCapabilities * * @throws IllegalArgumentException if the desired capabilities specify * a {@link CapabilityType#BROWSER_NAME} */ public WebDriverFactoryRemote(URL hubURL, DesiredCapabilities extraCapabilities) { this(hubURL); if(extraCapabilities.is(CapabilityType.BROWSER_NAME)) throw new IllegalArgumentException("Desired capabilities cannot specify a browser name"); this.extraCapabilities = extraCapabilities; } /** * A factory creating {@link WebDriver}s against the given hub. * * @param hubURL */ public WebDriverFactoryRemote(URL hubURL) { this.gridHubURL = hubURL; } @Override
// Path: src/main/java/me/alb_i986/selenium/tinafw/domain/SupportedBrowser.java // public enum SupportedBrowser { // // CHROME(ChromeDriver.class, DesiredCapabilities.chrome()), // FIREFOX(FirefoxDriver.class, DesiredCapabilities.firefox()), // SAFARI(SafariDriver.class, DesiredCapabilities.safari()), // IE(InternetExplorerDriver.class, DesiredCapabilities.internetExplorer()), // HTML_UNIT(HtmlUnitDriver.class, DesiredCapabilities.htmlUnit()), // ; // // private DesiredCapabilities capabilities; // private Class<? extends WebDriver> concreteWebDriverClass; // // private SupportedBrowser(Class<? extends WebDriver> clazz, DesiredCapabilities capabilities) { // this.concreteWebDriverClass = clazz; // this.capabilities = capabilities; // } // // /** // * @return the concrete WebDriver class corresponding to this SupportedBrowser // */ // public Class<? extends WebDriver> toClass() { // return this.concreteWebDriverClass; // } // // public DesiredCapabilities toCapabilities() { // return this.capabilities; // } // // /** // * @return the lower cased name of this enum constant // */ // @Override // public String toString() { // return super.toString().toLowerCase(); // } // } // Path: src/main/java/me/alb_i986/selenium/tinafw/ui/WebDriverFactoryRemote.java import java.net.URL; import me.alb_i986.selenium.tinafw.domain.SupportedBrowser; import org.openqa.selenium.Capabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.LocalFileDetector; import org.openqa.selenium.remote.RemoteWebDriver; package me.alb_i986.selenium.tinafw.ui; /** * Create instances of {@link WebDriver} (specifically, {@link RemoteWebDriver}) * which can drive a browser on a remote machine, part of a * <a href="https://code.google.com/p/selenium/wiki/Grid2">Selenium Grid</a>. * <p> * Such a factory needs to know the URL of the hub. * Clients may also specify a set of * <a href="https://code.google.com/p/selenium/wiki/DesiredCapabilities">desired capabilities</a>. * <p> * The instances of {@link WebDriver}s will also feature a {@link LocalFileDetector}, * which handles the upload of files from the local machine running the tests * to the selenium node running the browser. */ public class WebDriverFactoryRemote implements WebDriverFactory { private URL gridHubURL; private DesiredCapabilities extraCapabilities; /** * A factory creating {@link WebDriver}s matching the given set of extra, * desired capabilities * (see also {@link RemoteWebDriver#RemoteWebDriver(URL, Capabilities)}). * * @param hubURL * @param extraCapabilities * * @throws IllegalArgumentException if the desired capabilities specify * a {@link CapabilityType#BROWSER_NAME} */ public WebDriverFactoryRemote(URL hubURL, DesiredCapabilities extraCapabilities) { this(hubURL); if(extraCapabilities.is(CapabilityType.BROWSER_NAME)) throw new IllegalArgumentException("Desired capabilities cannot specify a browser name"); this.extraCapabilities = extraCapabilities; } /** * A factory creating {@link WebDriver}s against the given hub. * * @param hubURL */ public WebDriverFactoryRemote(URL hubURL) { this.gridHubURL = hubURL; } @Override
public WebDriver getWebDriver(SupportedBrowser browserType) {
poolik/classfinder
src/test/java/com/poolik/classfinder/TestWithTestClasses.java
// Path: src/main/java/com/poolik/classfinder/io/DirUtils.java // public class DirUtils { // // private DirUtils() {} // // public static void deleteIfExists(Path path) throws IOException { // if (Files.exists(path)) { // validate(path); // Files.walkFileTree(path, new DeleteDirVisitor()); // } // } // // public static void copy(Path from, Path to, Predicate<Path> copyPredicate) throws IOException { // validate(from); // Files.walkFileTree(from, EnumSet.of(FileVisitOption.FOLLOW_LINKS),Integer.MAX_VALUE,new CopyDirVisitor(from, to, copyPredicate)); // } // // public static Collection<File> findWithSuffix(Path from, String suffix) throws IOException { // validate(from); // SuffixFileVisitor visitor = new SuffixFileVisitor(suffix); // Files.walkFileTree(from, visitor); // return visitor.getFiles(); // } // // private static void validate(Path... paths) { // for (Path path : paths) { // Objects.requireNonNull(path); // if (!Files.isDirectory(path)) { // throw new IllegalArgumentException(String.format("%s is not a directory", path.toString())); // } // } // } // } // // Path: src/main/java/com/poolik/classfinder/io/Predicate.java // public interface Predicate<T> { // boolean apply(T t); // } // // Path: src/main/java/com/poolik/classfinder/io/Predicates.java // public class Predicates { // private Predicates() {} // // public static <T> Predicate<T> alwaysTrue() { // return new Predicate<T>() { // @Override // public boolean apply(Object o) { // return true; // } // }; // } // }
import com.poolik.classfinder.io.DirUtils; import com.poolik.classfinder.io.Predicate; import com.poolik.classfinder.io.Predicates; import org.junit.Before; import org.junit.Rule; import org.junit.rules.TemporaryFolder; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Path; import java.nio.file.Paths;
package com.poolik.classfinder; public abstract class TestWithTestClasses { protected Path classesFolder; protected Path otherClassesFolder; @Rule public TemporaryFolder testFolder = new TemporaryFolder(); @Before public void createClasses() throws IOException, URISyntaxException { testFolder.create(); classesFolder = Paths.get(getTestFolder(), "classes"); otherClassesFolder = Paths.get(getTestFolder(), "otherClasses"); copyClasses("/com/poolik/classfinder/testClasses", classesFolder); copyClasses("/com/poolik/classfinder/otherTestClasses", otherClassesFolder); } protected void copyClasses(String from, Path to) throws IOException, URISyntaxException {
// Path: src/main/java/com/poolik/classfinder/io/DirUtils.java // public class DirUtils { // // private DirUtils() {} // // public static void deleteIfExists(Path path) throws IOException { // if (Files.exists(path)) { // validate(path); // Files.walkFileTree(path, new DeleteDirVisitor()); // } // } // // public static void copy(Path from, Path to, Predicate<Path> copyPredicate) throws IOException { // validate(from); // Files.walkFileTree(from, EnumSet.of(FileVisitOption.FOLLOW_LINKS),Integer.MAX_VALUE,new CopyDirVisitor(from, to, copyPredicate)); // } // // public static Collection<File> findWithSuffix(Path from, String suffix) throws IOException { // validate(from); // SuffixFileVisitor visitor = new SuffixFileVisitor(suffix); // Files.walkFileTree(from, visitor); // return visitor.getFiles(); // } // // private static void validate(Path... paths) { // for (Path path : paths) { // Objects.requireNonNull(path); // if (!Files.isDirectory(path)) { // throw new IllegalArgumentException(String.format("%s is not a directory", path.toString())); // } // } // } // } // // Path: src/main/java/com/poolik/classfinder/io/Predicate.java // public interface Predicate<T> { // boolean apply(T t); // } // // Path: src/main/java/com/poolik/classfinder/io/Predicates.java // public class Predicates { // private Predicates() {} // // public static <T> Predicate<T> alwaysTrue() { // return new Predicate<T>() { // @Override // public boolean apply(Object o) { // return true; // } // }; // } // } // Path: src/test/java/com/poolik/classfinder/TestWithTestClasses.java import com.poolik.classfinder.io.DirUtils; import com.poolik.classfinder.io.Predicate; import com.poolik.classfinder.io.Predicates; import org.junit.Before; import org.junit.Rule; import org.junit.rules.TemporaryFolder; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Path; import java.nio.file.Paths; package com.poolik.classfinder; public abstract class TestWithTestClasses { protected Path classesFolder; protected Path otherClassesFolder; @Rule public TemporaryFolder testFolder = new TemporaryFolder(); @Before public void createClasses() throws IOException, URISyntaxException { testFolder.create(); classesFolder = Paths.get(getTestFolder(), "classes"); otherClassesFolder = Paths.get(getTestFolder(), "otherClasses"); copyClasses("/com/poolik/classfinder/testClasses", classesFolder); copyClasses("/com/poolik/classfinder/otherTestClasses", otherClassesFolder); } protected void copyClasses(String from, Path to) throws IOException, URISyntaxException {
copyClasses(from, to, Predicates.<Path>alwaysTrue());
poolik/classfinder
src/test/java/com/poolik/classfinder/TestWithTestClasses.java
// Path: src/main/java/com/poolik/classfinder/io/DirUtils.java // public class DirUtils { // // private DirUtils() {} // // public static void deleteIfExists(Path path) throws IOException { // if (Files.exists(path)) { // validate(path); // Files.walkFileTree(path, new DeleteDirVisitor()); // } // } // // public static void copy(Path from, Path to, Predicate<Path> copyPredicate) throws IOException { // validate(from); // Files.walkFileTree(from, EnumSet.of(FileVisitOption.FOLLOW_LINKS),Integer.MAX_VALUE,new CopyDirVisitor(from, to, copyPredicate)); // } // // public static Collection<File> findWithSuffix(Path from, String suffix) throws IOException { // validate(from); // SuffixFileVisitor visitor = new SuffixFileVisitor(suffix); // Files.walkFileTree(from, visitor); // return visitor.getFiles(); // } // // private static void validate(Path... paths) { // for (Path path : paths) { // Objects.requireNonNull(path); // if (!Files.isDirectory(path)) { // throw new IllegalArgumentException(String.format("%s is not a directory", path.toString())); // } // } // } // } // // Path: src/main/java/com/poolik/classfinder/io/Predicate.java // public interface Predicate<T> { // boolean apply(T t); // } // // Path: src/main/java/com/poolik/classfinder/io/Predicates.java // public class Predicates { // private Predicates() {} // // public static <T> Predicate<T> alwaysTrue() { // return new Predicate<T>() { // @Override // public boolean apply(Object o) { // return true; // } // }; // } // }
import com.poolik.classfinder.io.DirUtils; import com.poolik.classfinder.io.Predicate; import com.poolik.classfinder.io.Predicates; import org.junit.Before; import org.junit.Rule; import org.junit.rules.TemporaryFolder; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Path; import java.nio.file.Paths;
package com.poolik.classfinder; public abstract class TestWithTestClasses { protected Path classesFolder; protected Path otherClassesFolder; @Rule public TemporaryFolder testFolder = new TemporaryFolder(); @Before public void createClasses() throws IOException, URISyntaxException { testFolder.create(); classesFolder = Paths.get(getTestFolder(), "classes"); otherClassesFolder = Paths.get(getTestFolder(), "otherClasses"); copyClasses("/com/poolik/classfinder/testClasses", classesFolder); copyClasses("/com/poolik/classfinder/otherTestClasses", otherClassesFolder); } protected void copyClasses(String from, Path to) throws IOException, URISyntaxException { copyClasses(from, to, Predicates.<Path>alwaysTrue()); }
// Path: src/main/java/com/poolik/classfinder/io/DirUtils.java // public class DirUtils { // // private DirUtils() {} // // public static void deleteIfExists(Path path) throws IOException { // if (Files.exists(path)) { // validate(path); // Files.walkFileTree(path, new DeleteDirVisitor()); // } // } // // public static void copy(Path from, Path to, Predicate<Path> copyPredicate) throws IOException { // validate(from); // Files.walkFileTree(from, EnumSet.of(FileVisitOption.FOLLOW_LINKS),Integer.MAX_VALUE,new CopyDirVisitor(from, to, copyPredicate)); // } // // public static Collection<File> findWithSuffix(Path from, String suffix) throws IOException { // validate(from); // SuffixFileVisitor visitor = new SuffixFileVisitor(suffix); // Files.walkFileTree(from, visitor); // return visitor.getFiles(); // } // // private static void validate(Path... paths) { // for (Path path : paths) { // Objects.requireNonNull(path); // if (!Files.isDirectory(path)) { // throw new IllegalArgumentException(String.format("%s is not a directory", path.toString())); // } // } // } // } // // Path: src/main/java/com/poolik/classfinder/io/Predicate.java // public interface Predicate<T> { // boolean apply(T t); // } // // Path: src/main/java/com/poolik/classfinder/io/Predicates.java // public class Predicates { // private Predicates() {} // // public static <T> Predicate<T> alwaysTrue() { // return new Predicate<T>() { // @Override // public boolean apply(Object o) { // return true; // } // }; // } // } // Path: src/test/java/com/poolik/classfinder/TestWithTestClasses.java import com.poolik.classfinder.io.DirUtils; import com.poolik.classfinder.io.Predicate; import com.poolik.classfinder.io.Predicates; import org.junit.Before; import org.junit.Rule; import org.junit.rules.TemporaryFolder; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Path; import java.nio.file.Paths; package com.poolik.classfinder; public abstract class TestWithTestClasses { protected Path classesFolder; protected Path otherClassesFolder; @Rule public TemporaryFolder testFolder = new TemporaryFolder(); @Before public void createClasses() throws IOException, URISyntaxException { testFolder.create(); classesFolder = Paths.get(getTestFolder(), "classes"); otherClassesFolder = Paths.get(getTestFolder(), "otherClasses"); copyClasses("/com/poolik/classfinder/testClasses", classesFolder); copyClasses("/com/poolik/classfinder/otherTestClasses", otherClassesFolder); } protected void copyClasses(String from, Path to) throws IOException, URISyntaxException { copyClasses(from, to, Predicates.<Path>alwaysTrue()); }
protected void copyClasses(String from, Path to, Predicate<Path> predicate) throws IOException, URISyntaxException {
poolik/classfinder
src/test/java/com/poolik/classfinder/TestWithTestClasses.java
// Path: src/main/java/com/poolik/classfinder/io/DirUtils.java // public class DirUtils { // // private DirUtils() {} // // public static void deleteIfExists(Path path) throws IOException { // if (Files.exists(path)) { // validate(path); // Files.walkFileTree(path, new DeleteDirVisitor()); // } // } // // public static void copy(Path from, Path to, Predicate<Path> copyPredicate) throws IOException { // validate(from); // Files.walkFileTree(from, EnumSet.of(FileVisitOption.FOLLOW_LINKS),Integer.MAX_VALUE,new CopyDirVisitor(from, to, copyPredicate)); // } // // public static Collection<File> findWithSuffix(Path from, String suffix) throws IOException { // validate(from); // SuffixFileVisitor visitor = new SuffixFileVisitor(suffix); // Files.walkFileTree(from, visitor); // return visitor.getFiles(); // } // // private static void validate(Path... paths) { // for (Path path : paths) { // Objects.requireNonNull(path); // if (!Files.isDirectory(path)) { // throw new IllegalArgumentException(String.format("%s is not a directory", path.toString())); // } // } // } // } // // Path: src/main/java/com/poolik/classfinder/io/Predicate.java // public interface Predicate<T> { // boolean apply(T t); // } // // Path: src/main/java/com/poolik/classfinder/io/Predicates.java // public class Predicates { // private Predicates() {} // // public static <T> Predicate<T> alwaysTrue() { // return new Predicate<T>() { // @Override // public boolean apply(Object o) { // return true; // } // }; // } // }
import com.poolik.classfinder.io.DirUtils; import com.poolik.classfinder.io.Predicate; import com.poolik.classfinder.io.Predicates; import org.junit.Before; import org.junit.Rule; import org.junit.rules.TemporaryFolder; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Path; import java.nio.file.Paths;
package com.poolik.classfinder; public abstract class TestWithTestClasses { protected Path classesFolder; protected Path otherClassesFolder; @Rule public TemporaryFolder testFolder = new TemporaryFolder(); @Before public void createClasses() throws IOException, URISyntaxException { testFolder.create(); classesFolder = Paths.get(getTestFolder(), "classes"); otherClassesFolder = Paths.get(getTestFolder(), "otherClasses"); copyClasses("/com/poolik/classfinder/testClasses", classesFolder); copyClasses("/com/poolik/classfinder/otherTestClasses", otherClassesFolder); } protected void copyClasses(String from, Path to) throws IOException, URISyntaxException { copyClasses(from, to, Predicates.<Path>alwaysTrue()); } protected void copyClasses(String from, Path to, Predicate<Path> predicate) throws IOException, URISyntaxException {
// Path: src/main/java/com/poolik/classfinder/io/DirUtils.java // public class DirUtils { // // private DirUtils() {} // // public static void deleteIfExists(Path path) throws IOException { // if (Files.exists(path)) { // validate(path); // Files.walkFileTree(path, new DeleteDirVisitor()); // } // } // // public static void copy(Path from, Path to, Predicate<Path> copyPredicate) throws IOException { // validate(from); // Files.walkFileTree(from, EnumSet.of(FileVisitOption.FOLLOW_LINKS),Integer.MAX_VALUE,new CopyDirVisitor(from, to, copyPredicate)); // } // // public static Collection<File> findWithSuffix(Path from, String suffix) throws IOException { // validate(from); // SuffixFileVisitor visitor = new SuffixFileVisitor(suffix); // Files.walkFileTree(from, visitor); // return visitor.getFiles(); // } // // private static void validate(Path... paths) { // for (Path path : paths) { // Objects.requireNonNull(path); // if (!Files.isDirectory(path)) { // throw new IllegalArgumentException(String.format("%s is not a directory", path.toString())); // } // } // } // } // // Path: src/main/java/com/poolik/classfinder/io/Predicate.java // public interface Predicate<T> { // boolean apply(T t); // } // // Path: src/main/java/com/poolik/classfinder/io/Predicates.java // public class Predicates { // private Predicates() {} // // public static <T> Predicate<T> alwaysTrue() { // return new Predicate<T>() { // @Override // public boolean apply(Object o) { // return true; // } // }; // } // } // Path: src/test/java/com/poolik/classfinder/TestWithTestClasses.java import com.poolik.classfinder.io.DirUtils; import com.poolik.classfinder.io.Predicate; import com.poolik.classfinder.io.Predicates; import org.junit.Before; import org.junit.Rule; import org.junit.rules.TemporaryFolder; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Path; import java.nio.file.Paths; package com.poolik.classfinder; public abstract class TestWithTestClasses { protected Path classesFolder; protected Path otherClassesFolder; @Rule public TemporaryFolder testFolder = new TemporaryFolder(); @Before public void createClasses() throws IOException, URISyntaxException { testFolder.create(); classesFolder = Paths.get(getTestFolder(), "classes"); otherClassesFolder = Paths.get(getTestFolder(), "otherClasses"); copyClasses("/com/poolik/classfinder/testClasses", classesFolder); copyClasses("/com/poolik/classfinder/otherTestClasses", otherClassesFolder); } protected void copyClasses(String from, Path to) throws IOException, URISyntaxException { copyClasses(from, to, Predicates.<Path>alwaysTrue()); } protected void copyClasses(String from, Path to, Predicate<Path> predicate) throws IOException, URISyntaxException {
DirUtils.deleteIfExists(to);
poolik/classfinder
src/main/java/com/poolik/classfinder/io/DirUtils.java
// Path: src/main/java/com/poolik/classfinder/io/visitor/SuffixFileVisitor.java // public class SuffixFileVisitor extends SimpleFileVisitor<Path> { // private final String suffix; // private final Collection<File> files = new ArrayList<>(); // // public SuffixFileVisitor(String suffix) { // this.suffix = suffix; // } // // public Collection<File> getFiles() { // return files; // } // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // if (file.getFileName().toString().endsWith(suffix)) files.add(file.toFile()); // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/com/poolik/classfinder/io/visitor/CopyDirVisitor.java // public class CopyDirVisitor extends SimpleFileVisitor<Path> { // // private final Path fromPath; // private final Path toPath; // private final StandardCopyOption copyOption; // private final Predicate<Path> copyPredicate; // // public CopyDirVisitor(Path fromPath, Path toPath, Predicate<Path> predicate) { // this(fromPath, toPath, StandardCopyOption.REPLACE_EXISTING, predicate); // } // // public CopyDirVisitor(Path fromPath, Path toPath, StandardCopyOption copyOption, Predicate<Path> predicate) { // this.fromPath = fromPath; // this.toPath = toPath; // this.copyOption = copyOption; // this.copyPredicate = predicate; // } // // @Override // public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { // // Path targetPath = toPath.resolve(fromPath.relativize(dir)); // if (!Files.exists(targetPath)) { // Files.createDirectories(targetPath); // } // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // if (copyPredicate.apply(file)) // Files.copy(file, toPath.resolve(fromPath.relativize(file)), copyOption); // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/com/poolik/classfinder/io/visitor/DeleteDirVisitor.java // public class DeleteDirVisitor extends SimpleFileVisitor<Path> { // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // Files.delete(file); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { // if (exc == null) { // Files.delete(dir); // return FileVisitResult.CONTINUE; // } // throw exc; // } // }
import com.poolik.classfinder.io.visitor.SuffixFileVisitor; import com.poolik.classfinder.io.visitor.CopyDirVisitor; import com.poolik.classfinder.io.visitor.DeleteDirVisitor; import java.io.File; import java.io.IOException; import java.nio.file.*; import java.util.Collection; import java.util.EnumSet; import java.util.Objects;
package com.poolik.classfinder.io; public class DirUtils { private DirUtils() {} public static void deleteIfExists(Path path) throws IOException { if (Files.exists(path)) { validate(path);
// Path: src/main/java/com/poolik/classfinder/io/visitor/SuffixFileVisitor.java // public class SuffixFileVisitor extends SimpleFileVisitor<Path> { // private final String suffix; // private final Collection<File> files = new ArrayList<>(); // // public SuffixFileVisitor(String suffix) { // this.suffix = suffix; // } // // public Collection<File> getFiles() { // return files; // } // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // if (file.getFileName().toString().endsWith(suffix)) files.add(file.toFile()); // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/com/poolik/classfinder/io/visitor/CopyDirVisitor.java // public class CopyDirVisitor extends SimpleFileVisitor<Path> { // // private final Path fromPath; // private final Path toPath; // private final StandardCopyOption copyOption; // private final Predicate<Path> copyPredicate; // // public CopyDirVisitor(Path fromPath, Path toPath, Predicate<Path> predicate) { // this(fromPath, toPath, StandardCopyOption.REPLACE_EXISTING, predicate); // } // // public CopyDirVisitor(Path fromPath, Path toPath, StandardCopyOption copyOption, Predicate<Path> predicate) { // this.fromPath = fromPath; // this.toPath = toPath; // this.copyOption = copyOption; // this.copyPredicate = predicate; // } // // @Override // public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { // // Path targetPath = toPath.resolve(fromPath.relativize(dir)); // if (!Files.exists(targetPath)) { // Files.createDirectories(targetPath); // } // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // if (copyPredicate.apply(file)) // Files.copy(file, toPath.resolve(fromPath.relativize(file)), copyOption); // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/com/poolik/classfinder/io/visitor/DeleteDirVisitor.java // public class DeleteDirVisitor extends SimpleFileVisitor<Path> { // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // Files.delete(file); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { // if (exc == null) { // Files.delete(dir); // return FileVisitResult.CONTINUE; // } // throw exc; // } // } // Path: src/main/java/com/poolik/classfinder/io/DirUtils.java import com.poolik.classfinder.io.visitor.SuffixFileVisitor; import com.poolik.classfinder.io.visitor.CopyDirVisitor; import com.poolik.classfinder.io.visitor.DeleteDirVisitor; import java.io.File; import java.io.IOException; import java.nio.file.*; import java.util.Collection; import java.util.EnumSet; import java.util.Objects; package com.poolik.classfinder.io; public class DirUtils { private DirUtils() {} public static void deleteIfExists(Path path) throws IOException { if (Files.exists(path)) { validate(path);
Files.walkFileTree(path, new DeleteDirVisitor());
poolik/classfinder
src/main/java/com/poolik/classfinder/io/DirUtils.java
// Path: src/main/java/com/poolik/classfinder/io/visitor/SuffixFileVisitor.java // public class SuffixFileVisitor extends SimpleFileVisitor<Path> { // private final String suffix; // private final Collection<File> files = new ArrayList<>(); // // public SuffixFileVisitor(String suffix) { // this.suffix = suffix; // } // // public Collection<File> getFiles() { // return files; // } // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // if (file.getFileName().toString().endsWith(suffix)) files.add(file.toFile()); // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/com/poolik/classfinder/io/visitor/CopyDirVisitor.java // public class CopyDirVisitor extends SimpleFileVisitor<Path> { // // private final Path fromPath; // private final Path toPath; // private final StandardCopyOption copyOption; // private final Predicate<Path> copyPredicate; // // public CopyDirVisitor(Path fromPath, Path toPath, Predicate<Path> predicate) { // this(fromPath, toPath, StandardCopyOption.REPLACE_EXISTING, predicate); // } // // public CopyDirVisitor(Path fromPath, Path toPath, StandardCopyOption copyOption, Predicate<Path> predicate) { // this.fromPath = fromPath; // this.toPath = toPath; // this.copyOption = copyOption; // this.copyPredicate = predicate; // } // // @Override // public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { // // Path targetPath = toPath.resolve(fromPath.relativize(dir)); // if (!Files.exists(targetPath)) { // Files.createDirectories(targetPath); // } // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // if (copyPredicate.apply(file)) // Files.copy(file, toPath.resolve(fromPath.relativize(file)), copyOption); // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/com/poolik/classfinder/io/visitor/DeleteDirVisitor.java // public class DeleteDirVisitor extends SimpleFileVisitor<Path> { // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // Files.delete(file); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { // if (exc == null) { // Files.delete(dir); // return FileVisitResult.CONTINUE; // } // throw exc; // } // }
import com.poolik.classfinder.io.visitor.SuffixFileVisitor; import com.poolik.classfinder.io.visitor.CopyDirVisitor; import com.poolik.classfinder.io.visitor.DeleteDirVisitor; import java.io.File; import java.io.IOException; import java.nio.file.*; import java.util.Collection; import java.util.EnumSet; import java.util.Objects;
package com.poolik.classfinder.io; public class DirUtils { private DirUtils() {} public static void deleteIfExists(Path path) throws IOException { if (Files.exists(path)) { validate(path); Files.walkFileTree(path, new DeleteDirVisitor()); } } public static void copy(Path from, Path to, Predicate<Path> copyPredicate) throws IOException { validate(from);
// Path: src/main/java/com/poolik/classfinder/io/visitor/SuffixFileVisitor.java // public class SuffixFileVisitor extends SimpleFileVisitor<Path> { // private final String suffix; // private final Collection<File> files = new ArrayList<>(); // // public SuffixFileVisitor(String suffix) { // this.suffix = suffix; // } // // public Collection<File> getFiles() { // return files; // } // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // if (file.getFileName().toString().endsWith(suffix)) files.add(file.toFile()); // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/com/poolik/classfinder/io/visitor/CopyDirVisitor.java // public class CopyDirVisitor extends SimpleFileVisitor<Path> { // // private final Path fromPath; // private final Path toPath; // private final StandardCopyOption copyOption; // private final Predicate<Path> copyPredicate; // // public CopyDirVisitor(Path fromPath, Path toPath, Predicate<Path> predicate) { // this(fromPath, toPath, StandardCopyOption.REPLACE_EXISTING, predicate); // } // // public CopyDirVisitor(Path fromPath, Path toPath, StandardCopyOption copyOption, Predicate<Path> predicate) { // this.fromPath = fromPath; // this.toPath = toPath; // this.copyOption = copyOption; // this.copyPredicate = predicate; // } // // @Override // public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { // // Path targetPath = toPath.resolve(fromPath.relativize(dir)); // if (!Files.exists(targetPath)) { // Files.createDirectories(targetPath); // } // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // if (copyPredicate.apply(file)) // Files.copy(file, toPath.resolve(fromPath.relativize(file)), copyOption); // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/com/poolik/classfinder/io/visitor/DeleteDirVisitor.java // public class DeleteDirVisitor extends SimpleFileVisitor<Path> { // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // Files.delete(file); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { // if (exc == null) { // Files.delete(dir); // return FileVisitResult.CONTINUE; // } // throw exc; // } // } // Path: src/main/java/com/poolik/classfinder/io/DirUtils.java import com.poolik.classfinder.io.visitor.SuffixFileVisitor; import com.poolik.classfinder.io.visitor.CopyDirVisitor; import com.poolik.classfinder.io.visitor.DeleteDirVisitor; import java.io.File; import java.io.IOException; import java.nio.file.*; import java.util.Collection; import java.util.EnumSet; import java.util.Objects; package com.poolik.classfinder.io; public class DirUtils { private DirUtils() {} public static void deleteIfExists(Path path) throws IOException { if (Files.exists(path)) { validate(path); Files.walkFileTree(path, new DeleteDirVisitor()); } } public static void copy(Path from, Path to, Predicate<Path> copyPredicate) throws IOException { validate(from);
Files.walkFileTree(from, EnumSet.of(FileVisitOption.FOLLOW_LINKS),Integer.MAX_VALUE,new CopyDirVisitor(from, to, copyPredicate));
poolik/classfinder
src/main/java/com/poolik/classfinder/io/DirUtils.java
// Path: src/main/java/com/poolik/classfinder/io/visitor/SuffixFileVisitor.java // public class SuffixFileVisitor extends SimpleFileVisitor<Path> { // private final String suffix; // private final Collection<File> files = new ArrayList<>(); // // public SuffixFileVisitor(String suffix) { // this.suffix = suffix; // } // // public Collection<File> getFiles() { // return files; // } // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // if (file.getFileName().toString().endsWith(suffix)) files.add(file.toFile()); // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/com/poolik/classfinder/io/visitor/CopyDirVisitor.java // public class CopyDirVisitor extends SimpleFileVisitor<Path> { // // private final Path fromPath; // private final Path toPath; // private final StandardCopyOption copyOption; // private final Predicate<Path> copyPredicate; // // public CopyDirVisitor(Path fromPath, Path toPath, Predicate<Path> predicate) { // this(fromPath, toPath, StandardCopyOption.REPLACE_EXISTING, predicate); // } // // public CopyDirVisitor(Path fromPath, Path toPath, StandardCopyOption copyOption, Predicate<Path> predicate) { // this.fromPath = fromPath; // this.toPath = toPath; // this.copyOption = copyOption; // this.copyPredicate = predicate; // } // // @Override // public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { // // Path targetPath = toPath.resolve(fromPath.relativize(dir)); // if (!Files.exists(targetPath)) { // Files.createDirectories(targetPath); // } // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // if (copyPredicate.apply(file)) // Files.copy(file, toPath.resolve(fromPath.relativize(file)), copyOption); // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/com/poolik/classfinder/io/visitor/DeleteDirVisitor.java // public class DeleteDirVisitor extends SimpleFileVisitor<Path> { // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // Files.delete(file); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { // if (exc == null) { // Files.delete(dir); // return FileVisitResult.CONTINUE; // } // throw exc; // } // }
import com.poolik.classfinder.io.visitor.SuffixFileVisitor; import com.poolik.classfinder.io.visitor.CopyDirVisitor; import com.poolik.classfinder.io.visitor.DeleteDirVisitor; import java.io.File; import java.io.IOException; import java.nio.file.*; import java.util.Collection; import java.util.EnumSet; import java.util.Objects;
package com.poolik.classfinder.io; public class DirUtils { private DirUtils() {} public static void deleteIfExists(Path path) throws IOException { if (Files.exists(path)) { validate(path); Files.walkFileTree(path, new DeleteDirVisitor()); } } public static void copy(Path from, Path to, Predicate<Path> copyPredicate) throws IOException { validate(from); Files.walkFileTree(from, EnumSet.of(FileVisitOption.FOLLOW_LINKS),Integer.MAX_VALUE,new CopyDirVisitor(from, to, copyPredicate)); } public static Collection<File> findWithSuffix(Path from, String suffix) throws IOException { validate(from);
// Path: src/main/java/com/poolik/classfinder/io/visitor/SuffixFileVisitor.java // public class SuffixFileVisitor extends SimpleFileVisitor<Path> { // private final String suffix; // private final Collection<File> files = new ArrayList<>(); // // public SuffixFileVisitor(String suffix) { // this.suffix = suffix; // } // // public Collection<File> getFiles() { // return files; // } // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // if (file.getFileName().toString().endsWith(suffix)) files.add(file.toFile()); // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/com/poolik/classfinder/io/visitor/CopyDirVisitor.java // public class CopyDirVisitor extends SimpleFileVisitor<Path> { // // private final Path fromPath; // private final Path toPath; // private final StandardCopyOption copyOption; // private final Predicate<Path> copyPredicate; // // public CopyDirVisitor(Path fromPath, Path toPath, Predicate<Path> predicate) { // this(fromPath, toPath, StandardCopyOption.REPLACE_EXISTING, predicate); // } // // public CopyDirVisitor(Path fromPath, Path toPath, StandardCopyOption copyOption, Predicate<Path> predicate) { // this.fromPath = fromPath; // this.toPath = toPath; // this.copyOption = copyOption; // this.copyPredicate = predicate; // } // // @Override // public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { // // Path targetPath = toPath.resolve(fromPath.relativize(dir)); // if (!Files.exists(targetPath)) { // Files.createDirectories(targetPath); // } // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // if (copyPredicate.apply(file)) // Files.copy(file, toPath.resolve(fromPath.relativize(file)), copyOption); // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/com/poolik/classfinder/io/visitor/DeleteDirVisitor.java // public class DeleteDirVisitor extends SimpleFileVisitor<Path> { // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // Files.delete(file); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { // if (exc == null) { // Files.delete(dir); // return FileVisitResult.CONTINUE; // } // throw exc; // } // } // Path: src/main/java/com/poolik/classfinder/io/DirUtils.java import com.poolik.classfinder.io.visitor.SuffixFileVisitor; import com.poolik.classfinder.io.visitor.CopyDirVisitor; import com.poolik.classfinder.io.visitor.DeleteDirVisitor; import java.io.File; import java.io.IOException; import java.nio.file.*; import java.util.Collection; import java.util.EnumSet; import java.util.Objects; package com.poolik.classfinder.io; public class DirUtils { private DirUtils() {} public static void deleteIfExists(Path path) throws IOException { if (Files.exists(path)) { validate(path); Files.walkFileTree(path, new DeleteDirVisitor()); } } public static void copy(Path from, Path to, Predicate<Path> copyPredicate) throws IOException { validate(from); Files.walkFileTree(from, EnumSet.of(FileVisitOption.FOLLOW_LINKS),Integer.MAX_VALUE,new CopyDirVisitor(from, to, copyPredicate)); } public static Collection<File> findWithSuffix(Path from, String suffix) throws IOException { validate(from);
SuffixFileVisitor visitor = new SuffixFileVisitor(suffix);
poolik/classfinder
src/main/java/com/poolik/classfinder/resourceLoader/JarClasspathEntriesLoader.java
// Path: src/main/java/com/poolik/classfinder/ClassFinder.java // public class ClassFinder { // // private Map<String, File> placesToSearch = new LinkedHashMap<>(); // private static Collection<AdditionalResourceLoader> resourceLoaders = Arrays.<AdditionalResourceLoader>asList(new JarClasspathEntriesLoader()); // private static final Logger log = LoggerFactory.getLogger(ClassFinder.class); // private boolean errorIfResultEmpty; // // /** // * Add the contents of the system classpath for classes. // */ // public ClassFinder addClasspath() { // try { // String path = System.getProperty("java.class.path"); // StringTokenizer tok = new StringTokenizer(path, File.pathSeparator); // while (tok.hasMoreTokens()) // add(new File(tok.nextToken())); // } catch (Exception ex) { // log.error("Unable to get class path", ex); // } // return this; // } // // /** // * Add a jar file, zip file or directory to the list of places to search // * for classes. // * // * @param file the jar file, zip file or directory // * @return this // */ // public ClassFinder add(File file) { // log.info("Adding file to look into: " + file.getAbsolutePath()); // // if (fileCanContainClasses(file)) { // String absPath = file.getAbsolutePath(); // if (placesToSearch.get(absPath) == null) { // placesToSearch.put(absPath, file); // for (AdditionalResourceLoader resourceLoader : resourceLoaders) { // if (resourceLoader.canLoadAdditional(file)) resourceLoader.loadAdditional(file, this); // } // } // } else { // log.info("The given path '" + file.getAbsolutePath() + "' cannot contain classes!"); // } // // return this; // } // // /** // * Add an array jar files, zip files and/or directories to the list of // * places to search for classes. // * // * @param files the array of jar files, zip files and/or directories. // * The array can contain a mixture of all of the above. // * @return this // */ // public ClassFinder add(File[] files) { // return add(Arrays.asList(files)); // } // // /** // * Add a <tt>Collection</tt> of jar files, zip files and/or directories // * to the list of places to search for classes. // * // * @param files the collection of jar files, zip files and/or directories. // * @return this // */ // public ClassFinder add(Collection<File> files) { // for (File file : files) // add(file); // // return this; // } // // /** // * Clear the finder's notion of where to search. // */ // public void clear() { // placesToSearch.clear(); // } // // public ClassFinder setErrorIfResultEmpty(boolean errorIfResultEmpty) { // this.errorIfResultEmpty = errorIfResultEmpty; // return this; // } // // /** // * Find all classes in the search areas, implicitly accepting all of // * them. // * // * @return Collection of found classes // */ // public Collection<ClassInfo> findClasses() { // return findClasses(null); // } // // /** // * Search all classes in the search areas, keeping only those that // * pass the specified filter. // * // * @param filter the filter, or null for no filter // * @return Collection of found classes // */ // public Collection<ClassInfo> findClasses(ClassFilter filter) { // Map<String,ClassInfo> foundClasses = new ParallelClassLoader().loadClassesFrom(placesToSearch.values()); // log.info("Loaded " + foundClasses.size() + " classes."); // // Collection<ClassInfo> filteredClasses = filterClasses(filter, foundClasses); // // if (filteredClasses.size() == 0 && errorIfResultEmpty) { // log.warn("Found no classes, throwing exception"); // throw new ClassFinderException("Didn't find any classes"); // } else { // log.info("Returning " + filteredClasses.size() + " total classes"); // } // foundClasses.clear(); // return filteredClasses; // } // // private Collection<ClassInfo> filterClasses(ClassFilter filter, Map<String, ClassInfo> foundClasses) { // Collection<ClassInfo> classes = new ArrayList<>(); // for (ClassInfo classInfo : foundClasses.values()) { // String className = classInfo.getClassName(); // String locationName = classInfo.getClassLocation().getPath(); // log.trace("Looking at " + locationName + " (" + className + ")"); // if ((filter == null) || (filter.accept(classInfo, new ClassHierarchyResolver(foundClasses)))) { // log.trace("Filter accepted " + className); // classes.add(classInfo); // } else { // log.trace("Filter rejected " + className); // } // } // return classes; // } // } // // Path: src/main/java/com/poolik/classfinder/io/FileUtil.java // public class FileUtil { // private FileUtil() {} // // public static boolean fileCanContainClasses(File file) { // boolean can = false; // String fileName = file.getPath(); // // if (file.exists()) { // can = ((fileName.toLowerCase().endsWith(".jar")) || // (fileName.toLowerCase().endsWith(".zip")) || // (file.isDirectory())); // } // // return can; // } // // public static boolean isJar(String fileName) { // return fileName.toLowerCase().endsWith(".jar"); // } // // public static boolean isZip(String fileName) { // return fileName.toLowerCase().endsWith(".zip"); // } // }
import com.poolik.classfinder.ClassFinder; import com.poolik.classfinder.io.FileUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.StringTokenizer; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest;
package com.poolik.classfinder.resourceLoader; public class JarClasspathEntriesLoader implements AdditionalResourceLoader { private static final Logger log = LoggerFactory.getLogger(JarClasspathEntriesLoader.class); @Override public boolean canLoadAdditional(File file) {
// Path: src/main/java/com/poolik/classfinder/ClassFinder.java // public class ClassFinder { // // private Map<String, File> placesToSearch = new LinkedHashMap<>(); // private static Collection<AdditionalResourceLoader> resourceLoaders = Arrays.<AdditionalResourceLoader>asList(new JarClasspathEntriesLoader()); // private static final Logger log = LoggerFactory.getLogger(ClassFinder.class); // private boolean errorIfResultEmpty; // // /** // * Add the contents of the system classpath for classes. // */ // public ClassFinder addClasspath() { // try { // String path = System.getProperty("java.class.path"); // StringTokenizer tok = new StringTokenizer(path, File.pathSeparator); // while (tok.hasMoreTokens()) // add(new File(tok.nextToken())); // } catch (Exception ex) { // log.error("Unable to get class path", ex); // } // return this; // } // // /** // * Add a jar file, zip file or directory to the list of places to search // * for classes. // * // * @param file the jar file, zip file or directory // * @return this // */ // public ClassFinder add(File file) { // log.info("Adding file to look into: " + file.getAbsolutePath()); // // if (fileCanContainClasses(file)) { // String absPath = file.getAbsolutePath(); // if (placesToSearch.get(absPath) == null) { // placesToSearch.put(absPath, file); // for (AdditionalResourceLoader resourceLoader : resourceLoaders) { // if (resourceLoader.canLoadAdditional(file)) resourceLoader.loadAdditional(file, this); // } // } // } else { // log.info("The given path '" + file.getAbsolutePath() + "' cannot contain classes!"); // } // // return this; // } // // /** // * Add an array jar files, zip files and/or directories to the list of // * places to search for classes. // * // * @param files the array of jar files, zip files and/or directories. // * The array can contain a mixture of all of the above. // * @return this // */ // public ClassFinder add(File[] files) { // return add(Arrays.asList(files)); // } // // /** // * Add a <tt>Collection</tt> of jar files, zip files and/or directories // * to the list of places to search for classes. // * // * @param files the collection of jar files, zip files and/or directories. // * @return this // */ // public ClassFinder add(Collection<File> files) { // for (File file : files) // add(file); // // return this; // } // // /** // * Clear the finder's notion of where to search. // */ // public void clear() { // placesToSearch.clear(); // } // // public ClassFinder setErrorIfResultEmpty(boolean errorIfResultEmpty) { // this.errorIfResultEmpty = errorIfResultEmpty; // return this; // } // // /** // * Find all classes in the search areas, implicitly accepting all of // * them. // * // * @return Collection of found classes // */ // public Collection<ClassInfo> findClasses() { // return findClasses(null); // } // // /** // * Search all classes in the search areas, keeping only those that // * pass the specified filter. // * // * @param filter the filter, or null for no filter // * @return Collection of found classes // */ // public Collection<ClassInfo> findClasses(ClassFilter filter) { // Map<String,ClassInfo> foundClasses = new ParallelClassLoader().loadClassesFrom(placesToSearch.values()); // log.info("Loaded " + foundClasses.size() + " classes."); // // Collection<ClassInfo> filteredClasses = filterClasses(filter, foundClasses); // // if (filteredClasses.size() == 0 && errorIfResultEmpty) { // log.warn("Found no classes, throwing exception"); // throw new ClassFinderException("Didn't find any classes"); // } else { // log.info("Returning " + filteredClasses.size() + " total classes"); // } // foundClasses.clear(); // return filteredClasses; // } // // private Collection<ClassInfo> filterClasses(ClassFilter filter, Map<String, ClassInfo> foundClasses) { // Collection<ClassInfo> classes = new ArrayList<>(); // for (ClassInfo classInfo : foundClasses.values()) { // String className = classInfo.getClassName(); // String locationName = classInfo.getClassLocation().getPath(); // log.trace("Looking at " + locationName + " (" + className + ")"); // if ((filter == null) || (filter.accept(classInfo, new ClassHierarchyResolver(foundClasses)))) { // log.trace("Filter accepted " + className); // classes.add(classInfo); // } else { // log.trace("Filter rejected " + className); // } // } // return classes; // } // } // // Path: src/main/java/com/poolik/classfinder/io/FileUtil.java // public class FileUtil { // private FileUtil() {} // // public static boolean fileCanContainClasses(File file) { // boolean can = false; // String fileName = file.getPath(); // // if (file.exists()) { // can = ((fileName.toLowerCase().endsWith(".jar")) || // (fileName.toLowerCase().endsWith(".zip")) || // (file.isDirectory())); // } // // return can; // } // // public static boolean isJar(String fileName) { // return fileName.toLowerCase().endsWith(".jar"); // } // // public static boolean isZip(String fileName) { // return fileName.toLowerCase().endsWith(".zip"); // } // } // Path: src/main/java/com/poolik/classfinder/resourceLoader/JarClasspathEntriesLoader.java import com.poolik.classfinder.ClassFinder; import com.poolik.classfinder.io.FileUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.StringTokenizer; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; package com.poolik.classfinder.resourceLoader; public class JarClasspathEntriesLoader implements AdditionalResourceLoader { private static final Logger log = LoggerFactory.getLogger(JarClasspathEntriesLoader.class); @Override public boolean canLoadAdditional(File file) {
return FileUtil.isJar(file.getAbsolutePath());
poolik/classfinder
src/main/java/com/poolik/classfinder/resourceLoader/JarClasspathEntriesLoader.java
// Path: src/main/java/com/poolik/classfinder/ClassFinder.java // public class ClassFinder { // // private Map<String, File> placesToSearch = new LinkedHashMap<>(); // private static Collection<AdditionalResourceLoader> resourceLoaders = Arrays.<AdditionalResourceLoader>asList(new JarClasspathEntriesLoader()); // private static final Logger log = LoggerFactory.getLogger(ClassFinder.class); // private boolean errorIfResultEmpty; // // /** // * Add the contents of the system classpath for classes. // */ // public ClassFinder addClasspath() { // try { // String path = System.getProperty("java.class.path"); // StringTokenizer tok = new StringTokenizer(path, File.pathSeparator); // while (tok.hasMoreTokens()) // add(new File(tok.nextToken())); // } catch (Exception ex) { // log.error("Unable to get class path", ex); // } // return this; // } // // /** // * Add a jar file, zip file or directory to the list of places to search // * for classes. // * // * @param file the jar file, zip file or directory // * @return this // */ // public ClassFinder add(File file) { // log.info("Adding file to look into: " + file.getAbsolutePath()); // // if (fileCanContainClasses(file)) { // String absPath = file.getAbsolutePath(); // if (placesToSearch.get(absPath) == null) { // placesToSearch.put(absPath, file); // for (AdditionalResourceLoader resourceLoader : resourceLoaders) { // if (resourceLoader.canLoadAdditional(file)) resourceLoader.loadAdditional(file, this); // } // } // } else { // log.info("The given path '" + file.getAbsolutePath() + "' cannot contain classes!"); // } // // return this; // } // // /** // * Add an array jar files, zip files and/or directories to the list of // * places to search for classes. // * // * @param files the array of jar files, zip files and/or directories. // * The array can contain a mixture of all of the above. // * @return this // */ // public ClassFinder add(File[] files) { // return add(Arrays.asList(files)); // } // // /** // * Add a <tt>Collection</tt> of jar files, zip files and/or directories // * to the list of places to search for classes. // * // * @param files the collection of jar files, zip files and/or directories. // * @return this // */ // public ClassFinder add(Collection<File> files) { // for (File file : files) // add(file); // // return this; // } // // /** // * Clear the finder's notion of where to search. // */ // public void clear() { // placesToSearch.clear(); // } // // public ClassFinder setErrorIfResultEmpty(boolean errorIfResultEmpty) { // this.errorIfResultEmpty = errorIfResultEmpty; // return this; // } // // /** // * Find all classes in the search areas, implicitly accepting all of // * them. // * // * @return Collection of found classes // */ // public Collection<ClassInfo> findClasses() { // return findClasses(null); // } // // /** // * Search all classes in the search areas, keeping only those that // * pass the specified filter. // * // * @param filter the filter, or null for no filter // * @return Collection of found classes // */ // public Collection<ClassInfo> findClasses(ClassFilter filter) { // Map<String,ClassInfo> foundClasses = new ParallelClassLoader().loadClassesFrom(placesToSearch.values()); // log.info("Loaded " + foundClasses.size() + " classes."); // // Collection<ClassInfo> filteredClasses = filterClasses(filter, foundClasses); // // if (filteredClasses.size() == 0 && errorIfResultEmpty) { // log.warn("Found no classes, throwing exception"); // throw new ClassFinderException("Didn't find any classes"); // } else { // log.info("Returning " + filteredClasses.size() + " total classes"); // } // foundClasses.clear(); // return filteredClasses; // } // // private Collection<ClassInfo> filterClasses(ClassFilter filter, Map<String, ClassInfo> foundClasses) { // Collection<ClassInfo> classes = new ArrayList<>(); // for (ClassInfo classInfo : foundClasses.values()) { // String className = classInfo.getClassName(); // String locationName = classInfo.getClassLocation().getPath(); // log.trace("Looking at " + locationName + " (" + className + ")"); // if ((filter == null) || (filter.accept(classInfo, new ClassHierarchyResolver(foundClasses)))) { // log.trace("Filter accepted " + className); // classes.add(classInfo); // } else { // log.trace("Filter rejected " + className); // } // } // return classes; // } // } // // Path: src/main/java/com/poolik/classfinder/io/FileUtil.java // public class FileUtil { // private FileUtil() {} // // public static boolean fileCanContainClasses(File file) { // boolean can = false; // String fileName = file.getPath(); // // if (file.exists()) { // can = ((fileName.toLowerCase().endsWith(".jar")) || // (fileName.toLowerCase().endsWith(".zip")) || // (file.isDirectory())); // } // // return can; // } // // public static boolean isJar(String fileName) { // return fileName.toLowerCase().endsWith(".jar"); // } // // public static boolean isZip(String fileName) { // return fileName.toLowerCase().endsWith(".zip"); // } // }
import com.poolik.classfinder.ClassFinder; import com.poolik.classfinder.io.FileUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.StringTokenizer; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest;
package com.poolik.classfinder.resourceLoader; public class JarClasspathEntriesLoader implements AdditionalResourceLoader { private static final Logger log = LoggerFactory.getLogger(JarClasspathEntriesLoader.class); @Override public boolean canLoadAdditional(File file) { return FileUtil.isJar(file.getAbsolutePath()); } @Override
// Path: src/main/java/com/poolik/classfinder/ClassFinder.java // public class ClassFinder { // // private Map<String, File> placesToSearch = new LinkedHashMap<>(); // private static Collection<AdditionalResourceLoader> resourceLoaders = Arrays.<AdditionalResourceLoader>asList(new JarClasspathEntriesLoader()); // private static final Logger log = LoggerFactory.getLogger(ClassFinder.class); // private boolean errorIfResultEmpty; // // /** // * Add the contents of the system classpath for classes. // */ // public ClassFinder addClasspath() { // try { // String path = System.getProperty("java.class.path"); // StringTokenizer tok = new StringTokenizer(path, File.pathSeparator); // while (tok.hasMoreTokens()) // add(new File(tok.nextToken())); // } catch (Exception ex) { // log.error("Unable to get class path", ex); // } // return this; // } // // /** // * Add a jar file, zip file or directory to the list of places to search // * for classes. // * // * @param file the jar file, zip file or directory // * @return this // */ // public ClassFinder add(File file) { // log.info("Adding file to look into: " + file.getAbsolutePath()); // // if (fileCanContainClasses(file)) { // String absPath = file.getAbsolutePath(); // if (placesToSearch.get(absPath) == null) { // placesToSearch.put(absPath, file); // for (AdditionalResourceLoader resourceLoader : resourceLoaders) { // if (resourceLoader.canLoadAdditional(file)) resourceLoader.loadAdditional(file, this); // } // } // } else { // log.info("The given path '" + file.getAbsolutePath() + "' cannot contain classes!"); // } // // return this; // } // // /** // * Add an array jar files, zip files and/or directories to the list of // * places to search for classes. // * // * @param files the array of jar files, zip files and/or directories. // * The array can contain a mixture of all of the above. // * @return this // */ // public ClassFinder add(File[] files) { // return add(Arrays.asList(files)); // } // // /** // * Add a <tt>Collection</tt> of jar files, zip files and/or directories // * to the list of places to search for classes. // * // * @param files the collection of jar files, zip files and/or directories. // * @return this // */ // public ClassFinder add(Collection<File> files) { // for (File file : files) // add(file); // // return this; // } // // /** // * Clear the finder's notion of where to search. // */ // public void clear() { // placesToSearch.clear(); // } // // public ClassFinder setErrorIfResultEmpty(boolean errorIfResultEmpty) { // this.errorIfResultEmpty = errorIfResultEmpty; // return this; // } // // /** // * Find all classes in the search areas, implicitly accepting all of // * them. // * // * @return Collection of found classes // */ // public Collection<ClassInfo> findClasses() { // return findClasses(null); // } // // /** // * Search all classes in the search areas, keeping only those that // * pass the specified filter. // * // * @param filter the filter, or null for no filter // * @return Collection of found classes // */ // public Collection<ClassInfo> findClasses(ClassFilter filter) { // Map<String,ClassInfo> foundClasses = new ParallelClassLoader().loadClassesFrom(placesToSearch.values()); // log.info("Loaded " + foundClasses.size() + " classes."); // // Collection<ClassInfo> filteredClasses = filterClasses(filter, foundClasses); // // if (filteredClasses.size() == 0 && errorIfResultEmpty) { // log.warn("Found no classes, throwing exception"); // throw new ClassFinderException("Didn't find any classes"); // } else { // log.info("Returning " + filteredClasses.size() + " total classes"); // } // foundClasses.clear(); // return filteredClasses; // } // // private Collection<ClassInfo> filterClasses(ClassFilter filter, Map<String, ClassInfo> foundClasses) { // Collection<ClassInfo> classes = new ArrayList<>(); // for (ClassInfo classInfo : foundClasses.values()) { // String className = classInfo.getClassName(); // String locationName = classInfo.getClassLocation().getPath(); // log.trace("Looking at " + locationName + " (" + className + ")"); // if ((filter == null) || (filter.accept(classInfo, new ClassHierarchyResolver(foundClasses)))) { // log.trace("Filter accepted " + className); // classes.add(classInfo); // } else { // log.trace("Filter rejected " + className); // } // } // return classes; // } // } // // Path: src/main/java/com/poolik/classfinder/io/FileUtil.java // public class FileUtil { // private FileUtil() {} // // public static boolean fileCanContainClasses(File file) { // boolean can = false; // String fileName = file.getPath(); // // if (file.exists()) { // can = ((fileName.toLowerCase().endsWith(".jar")) || // (fileName.toLowerCase().endsWith(".zip")) || // (file.isDirectory())); // } // // return can; // } // // public static boolean isJar(String fileName) { // return fileName.toLowerCase().endsWith(".jar"); // } // // public static boolean isZip(String fileName) { // return fileName.toLowerCase().endsWith(".zip"); // } // } // Path: src/main/java/com/poolik/classfinder/resourceLoader/JarClasspathEntriesLoader.java import com.poolik.classfinder.ClassFinder; import com.poolik.classfinder.io.FileUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.StringTokenizer; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; package com.poolik.classfinder.resourceLoader; public class JarClasspathEntriesLoader implements AdditionalResourceLoader { private static final Logger log = LoggerFactory.getLogger(JarClasspathEntriesLoader.class); @Override public boolean canLoadAdditional(File file) { return FileUtil.isJar(file.getAbsolutePath()); } @Override
public void loadAdditional(File jarFile, ClassFinder classFinder) {
poolik/classfinder
src/test/java/com/poolik/classfinder/otherTestClasses/ConcreteClass.java
// Path: src/main/java/com/poolik/classfinder/ClassFinderException.java // public class ClassFinderException extends RuntimeException { // // public ClassFinderException(String message) { // super(message); // } // // public ClassFinderException(String message, Throwable exception) { // super(message, exception); // } // }
import com.poolik.classfinder.ClassFinderException; import com.poolik.classfinder.TestAnnotation;
package com.poolik.classfinder.otherTestClasses; @Deprecated @TestAnnotation public class ConcreteClass extends AbstractClass { @Deprecated private String test = "test"; public int anotherValue = 0;
// Path: src/main/java/com/poolik/classfinder/ClassFinderException.java // public class ClassFinderException extends RuntimeException { // // public ClassFinderException(String message) { // super(message); // } // // public ClassFinderException(String message, Throwable exception) { // super(message, exception); // } // } // Path: src/test/java/com/poolik/classfinder/otherTestClasses/ConcreteClass.java import com.poolik.classfinder.ClassFinderException; import com.poolik.classfinder.TestAnnotation; package com.poolik.classfinder.otherTestClasses; @Deprecated @TestAnnotation public class ConcreteClass extends AbstractClass { @Deprecated private String test = "test"; public int anotherValue = 0;
private void test() throws ClassFinderException {}
poolik/classfinder
src/main/java/com/poolik/classfinder/resourceLoader/AdditionalResourceLoader.java
// Path: src/main/java/com/poolik/classfinder/ClassFinder.java // public class ClassFinder { // // private Map<String, File> placesToSearch = new LinkedHashMap<>(); // private static Collection<AdditionalResourceLoader> resourceLoaders = Arrays.<AdditionalResourceLoader>asList(new JarClasspathEntriesLoader()); // private static final Logger log = LoggerFactory.getLogger(ClassFinder.class); // private boolean errorIfResultEmpty; // // /** // * Add the contents of the system classpath for classes. // */ // public ClassFinder addClasspath() { // try { // String path = System.getProperty("java.class.path"); // StringTokenizer tok = new StringTokenizer(path, File.pathSeparator); // while (tok.hasMoreTokens()) // add(new File(tok.nextToken())); // } catch (Exception ex) { // log.error("Unable to get class path", ex); // } // return this; // } // // /** // * Add a jar file, zip file or directory to the list of places to search // * for classes. // * // * @param file the jar file, zip file or directory // * @return this // */ // public ClassFinder add(File file) { // log.info("Adding file to look into: " + file.getAbsolutePath()); // // if (fileCanContainClasses(file)) { // String absPath = file.getAbsolutePath(); // if (placesToSearch.get(absPath) == null) { // placesToSearch.put(absPath, file); // for (AdditionalResourceLoader resourceLoader : resourceLoaders) { // if (resourceLoader.canLoadAdditional(file)) resourceLoader.loadAdditional(file, this); // } // } // } else { // log.info("The given path '" + file.getAbsolutePath() + "' cannot contain classes!"); // } // // return this; // } // // /** // * Add an array jar files, zip files and/or directories to the list of // * places to search for classes. // * // * @param files the array of jar files, zip files and/or directories. // * The array can contain a mixture of all of the above. // * @return this // */ // public ClassFinder add(File[] files) { // return add(Arrays.asList(files)); // } // // /** // * Add a <tt>Collection</tt> of jar files, zip files and/or directories // * to the list of places to search for classes. // * // * @param files the collection of jar files, zip files and/or directories. // * @return this // */ // public ClassFinder add(Collection<File> files) { // for (File file : files) // add(file); // // return this; // } // // /** // * Clear the finder's notion of where to search. // */ // public void clear() { // placesToSearch.clear(); // } // // public ClassFinder setErrorIfResultEmpty(boolean errorIfResultEmpty) { // this.errorIfResultEmpty = errorIfResultEmpty; // return this; // } // // /** // * Find all classes in the search areas, implicitly accepting all of // * them. // * // * @return Collection of found classes // */ // public Collection<ClassInfo> findClasses() { // return findClasses(null); // } // // /** // * Search all classes in the search areas, keeping only those that // * pass the specified filter. // * // * @param filter the filter, or null for no filter // * @return Collection of found classes // */ // public Collection<ClassInfo> findClasses(ClassFilter filter) { // Map<String,ClassInfo> foundClasses = new ParallelClassLoader().loadClassesFrom(placesToSearch.values()); // log.info("Loaded " + foundClasses.size() + " classes."); // // Collection<ClassInfo> filteredClasses = filterClasses(filter, foundClasses); // // if (filteredClasses.size() == 0 && errorIfResultEmpty) { // log.warn("Found no classes, throwing exception"); // throw new ClassFinderException("Didn't find any classes"); // } else { // log.info("Returning " + filteredClasses.size() + " total classes"); // } // foundClasses.clear(); // return filteredClasses; // } // // private Collection<ClassInfo> filterClasses(ClassFilter filter, Map<String, ClassInfo> foundClasses) { // Collection<ClassInfo> classes = new ArrayList<>(); // for (ClassInfo classInfo : foundClasses.values()) { // String className = classInfo.getClassName(); // String locationName = classInfo.getClassLocation().getPath(); // log.trace("Looking at " + locationName + " (" + className + ")"); // if ((filter == null) || (filter.accept(classInfo, new ClassHierarchyResolver(foundClasses)))) { // log.trace("Filter accepted " + className); // classes.add(classInfo); // } else { // log.trace("Filter rejected " + className); // } // } // return classes; // } // }
import com.poolik.classfinder.ClassFinder; import java.io.File;
package com.poolik.classfinder.resourceLoader; public interface AdditionalResourceLoader { public boolean canLoadAdditional(File file);
// Path: src/main/java/com/poolik/classfinder/ClassFinder.java // public class ClassFinder { // // private Map<String, File> placesToSearch = new LinkedHashMap<>(); // private static Collection<AdditionalResourceLoader> resourceLoaders = Arrays.<AdditionalResourceLoader>asList(new JarClasspathEntriesLoader()); // private static final Logger log = LoggerFactory.getLogger(ClassFinder.class); // private boolean errorIfResultEmpty; // // /** // * Add the contents of the system classpath for classes. // */ // public ClassFinder addClasspath() { // try { // String path = System.getProperty("java.class.path"); // StringTokenizer tok = new StringTokenizer(path, File.pathSeparator); // while (tok.hasMoreTokens()) // add(new File(tok.nextToken())); // } catch (Exception ex) { // log.error("Unable to get class path", ex); // } // return this; // } // // /** // * Add a jar file, zip file or directory to the list of places to search // * for classes. // * // * @param file the jar file, zip file or directory // * @return this // */ // public ClassFinder add(File file) { // log.info("Adding file to look into: " + file.getAbsolutePath()); // // if (fileCanContainClasses(file)) { // String absPath = file.getAbsolutePath(); // if (placesToSearch.get(absPath) == null) { // placesToSearch.put(absPath, file); // for (AdditionalResourceLoader resourceLoader : resourceLoaders) { // if (resourceLoader.canLoadAdditional(file)) resourceLoader.loadAdditional(file, this); // } // } // } else { // log.info("The given path '" + file.getAbsolutePath() + "' cannot contain classes!"); // } // // return this; // } // // /** // * Add an array jar files, zip files and/or directories to the list of // * places to search for classes. // * // * @param files the array of jar files, zip files and/or directories. // * The array can contain a mixture of all of the above. // * @return this // */ // public ClassFinder add(File[] files) { // return add(Arrays.asList(files)); // } // // /** // * Add a <tt>Collection</tt> of jar files, zip files and/or directories // * to the list of places to search for classes. // * // * @param files the collection of jar files, zip files and/or directories. // * @return this // */ // public ClassFinder add(Collection<File> files) { // for (File file : files) // add(file); // // return this; // } // // /** // * Clear the finder's notion of where to search. // */ // public void clear() { // placesToSearch.clear(); // } // // public ClassFinder setErrorIfResultEmpty(boolean errorIfResultEmpty) { // this.errorIfResultEmpty = errorIfResultEmpty; // return this; // } // // /** // * Find all classes in the search areas, implicitly accepting all of // * them. // * // * @return Collection of found classes // */ // public Collection<ClassInfo> findClasses() { // return findClasses(null); // } // // /** // * Search all classes in the search areas, keeping only those that // * pass the specified filter. // * // * @param filter the filter, or null for no filter // * @return Collection of found classes // */ // public Collection<ClassInfo> findClasses(ClassFilter filter) { // Map<String,ClassInfo> foundClasses = new ParallelClassLoader().loadClassesFrom(placesToSearch.values()); // log.info("Loaded " + foundClasses.size() + " classes."); // // Collection<ClassInfo> filteredClasses = filterClasses(filter, foundClasses); // // if (filteredClasses.size() == 0 && errorIfResultEmpty) { // log.warn("Found no classes, throwing exception"); // throw new ClassFinderException("Didn't find any classes"); // } else { // log.info("Returning " + filteredClasses.size() + " total classes"); // } // foundClasses.clear(); // return filteredClasses; // } // // private Collection<ClassInfo> filterClasses(ClassFilter filter, Map<String, ClassInfo> foundClasses) { // Collection<ClassInfo> classes = new ArrayList<>(); // for (ClassInfo classInfo : foundClasses.values()) { // String className = classInfo.getClassName(); // String locationName = classInfo.getClassLocation().getPath(); // log.trace("Looking at " + locationName + " (" + className + ")"); // if ((filter == null) || (filter.accept(classInfo, new ClassHierarchyResolver(foundClasses)))) { // log.trace("Filter accepted " + className); // classes.add(classInfo); // } else { // log.trace("Filter rejected " + className); // } // } // return classes; // } // } // Path: src/main/java/com/poolik/classfinder/resourceLoader/AdditionalResourceLoader.java import com.poolik.classfinder.ClassFinder; import java.io.File; package com.poolik.classfinder.resourceLoader; public interface AdditionalResourceLoader { public boolean canLoadAdditional(File file);
public void loadAdditional(File file, ClassFinder classFinder);
poolik/classfinder
src/main/java/com/poolik/classfinder/io/visitor/CopyDirVisitor.java
// Path: src/main/java/com/poolik/classfinder/io/Predicate.java // public interface Predicate<T> { // boolean apply(T t); // }
import com.poolik.classfinder.io.Predicate; import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes;
package com.poolik.classfinder.io.visitor; public class CopyDirVisitor extends SimpleFileVisitor<Path> { private final Path fromPath; private final Path toPath; private final StandardCopyOption copyOption;
// Path: src/main/java/com/poolik/classfinder/io/Predicate.java // public interface Predicate<T> { // boolean apply(T t); // } // Path: src/main/java/com/poolik/classfinder/io/visitor/CopyDirVisitor.java import com.poolik.classfinder.io.Predicate; import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; package com.poolik.classfinder.io.visitor; public class CopyDirVisitor extends SimpleFileVisitor<Path> { private final Path fromPath; private final Path toPath; private final StandardCopyOption copyOption;
private final Predicate<Path> copyPredicate;
tsy12321/LeanoteAndroid
app/src/main/java/com/tsy/leanote/feature/note/view/adapter/NoteAdapter.java
// Path: app/src/main/java/com/tsy/leanote/feature/note/bean/Note.java // @Entity // public class Note { // @Id // private Long id; // @Unique // private String noteid; // private String notebookid; // private String uid; // private String title; // private String content; // private boolean is_markdown; // private boolean is_blog; // private boolean is_trash; // private String created_time; // private String updated_time; // private String public_time; // private int usn; //更新同步号 // // @Generated(hash = 1921932240) // public Note(Long id, String noteid, String notebookid, String uid, String title, // String content, boolean is_markdown, boolean is_blog, boolean is_trash, // String created_time, String updated_time, String public_time, int usn) { // this.id = id; // this.noteid = noteid; // this.notebookid = notebookid; // this.uid = uid; // this.title = title; // this.content = content; // this.is_markdown = is_markdown; // this.is_blog = is_blog; // this.is_trash = is_trash; // this.created_time = created_time; // this.updated_time = updated_time; // this.public_time = public_time; // this.usn = usn; // } // // @Override // public String toString() { // return "Note\n{" + // "\nid=" + id + // ", \nnoteid='" + noteid + '\'' + // ", \nnotebookid='" + notebookid + '\'' + // ", \nuid='" + uid + '\'' + // ", \ntitle='" + title + '\'' + // ", \ncontent='" + content + '\'' + // ", \nis_markdown=" + is_markdown + // ", \nis_blog=" + is_blog + // ", \nis_trash=" + is_trash + // ", \ncreated_time='" + created_time + '\'' + // ", \nupdated_time='" + updated_time + '\'' + // ", \npublic_time='" + public_time + '\'' + // ", \nusn=" + usn + // "\n}"; // } // // @Generated(hash = 1272611929) // public Note() { // } // public Long getId() { // return this.id; // } // public void setId(Long id) { // this.id = id; // } // public String getNoteid() { // return this.noteid; // } // public void setNoteid(String noteid) { // this.noteid = noteid; // } // public String getNotebookid() { // return this.notebookid; // } // public void setNotebookid(String notebookid) { // this.notebookid = notebookid; // } // public String getUid() { // return this.uid; // } // public void setUid(String uid) { // this.uid = uid; // } // public String getTitle() { // return this.title; // } // public void setTitle(String title) { // this.title = title; // } // public String getContent() { // return this.content; // } // public void setContent(String content) { // this.content = content; // } // public boolean getIs_markdown() { // return this.is_markdown; // } // public void setIs_markdown(boolean is_markdown) { // this.is_markdown = is_markdown; // } // public boolean getIs_trash() { // return this.is_trash; // } // public void setIs_trash(boolean is_trash) { // this.is_trash = is_trash; // } // public String getCreated_time() { // return this.created_time; // } // public void setCreated_time(String created_time) { // this.created_time = created_time; // } // public String getUpdated_time() { // return this.updated_time; // } // public void setUpdated_time(String updated_time) { // this.updated_time = updated_time; // } // public String getPublic_time() { // return this.public_time; // } // public void setPublic_time(String public_time) { // this.public_time = public_time; // } // public int getUsn() { // return this.usn; // } // public void setUsn(int usn) { // this.usn = usn; // } // public boolean getIs_blog() { // return this.is_blog; // } // public void setIs_blog(boolean is_blog) { // this.is_blog = is_blog; // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.tsy.leanote.R; import com.tsy.leanote.feature.note.bean.Note; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife;
package com.tsy.leanote.feature.note.view.adapter; /** * Created by tsy on 2017/1/18. */ public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.MyViewHolder> implements View.OnClickListener { private final LayoutInflater mLayoutInflater; private final Context mContext;
// Path: app/src/main/java/com/tsy/leanote/feature/note/bean/Note.java // @Entity // public class Note { // @Id // private Long id; // @Unique // private String noteid; // private String notebookid; // private String uid; // private String title; // private String content; // private boolean is_markdown; // private boolean is_blog; // private boolean is_trash; // private String created_time; // private String updated_time; // private String public_time; // private int usn; //更新同步号 // // @Generated(hash = 1921932240) // public Note(Long id, String noteid, String notebookid, String uid, String title, // String content, boolean is_markdown, boolean is_blog, boolean is_trash, // String created_time, String updated_time, String public_time, int usn) { // this.id = id; // this.noteid = noteid; // this.notebookid = notebookid; // this.uid = uid; // this.title = title; // this.content = content; // this.is_markdown = is_markdown; // this.is_blog = is_blog; // this.is_trash = is_trash; // this.created_time = created_time; // this.updated_time = updated_time; // this.public_time = public_time; // this.usn = usn; // } // // @Override // public String toString() { // return "Note\n{" + // "\nid=" + id + // ", \nnoteid='" + noteid + '\'' + // ", \nnotebookid='" + notebookid + '\'' + // ", \nuid='" + uid + '\'' + // ", \ntitle='" + title + '\'' + // ", \ncontent='" + content + '\'' + // ", \nis_markdown=" + is_markdown + // ", \nis_blog=" + is_blog + // ", \nis_trash=" + is_trash + // ", \ncreated_time='" + created_time + '\'' + // ", \nupdated_time='" + updated_time + '\'' + // ", \npublic_time='" + public_time + '\'' + // ", \nusn=" + usn + // "\n}"; // } // // @Generated(hash = 1272611929) // public Note() { // } // public Long getId() { // return this.id; // } // public void setId(Long id) { // this.id = id; // } // public String getNoteid() { // return this.noteid; // } // public void setNoteid(String noteid) { // this.noteid = noteid; // } // public String getNotebookid() { // return this.notebookid; // } // public void setNotebookid(String notebookid) { // this.notebookid = notebookid; // } // public String getUid() { // return this.uid; // } // public void setUid(String uid) { // this.uid = uid; // } // public String getTitle() { // return this.title; // } // public void setTitle(String title) { // this.title = title; // } // public String getContent() { // return this.content; // } // public void setContent(String content) { // this.content = content; // } // public boolean getIs_markdown() { // return this.is_markdown; // } // public void setIs_markdown(boolean is_markdown) { // this.is_markdown = is_markdown; // } // public boolean getIs_trash() { // return this.is_trash; // } // public void setIs_trash(boolean is_trash) { // this.is_trash = is_trash; // } // public String getCreated_time() { // return this.created_time; // } // public void setCreated_time(String created_time) { // this.created_time = created_time; // } // public String getUpdated_time() { // return this.updated_time; // } // public void setUpdated_time(String updated_time) { // this.updated_time = updated_time; // } // public String getPublic_time() { // return this.public_time; // } // public void setPublic_time(String public_time) { // this.public_time = public_time; // } // public int getUsn() { // return this.usn; // } // public void setUsn(int usn) { // this.usn = usn; // } // public boolean getIs_blog() { // return this.is_blog; // } // public void setIs_blog(boolean is_blog) { // this.is_blog = is_blog; // } // } // Path: app/src/main/java/com/tsy/leanote/feature/note/view/adapter/NoteAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.tsy.leanote.R; import com.tsy.leanote.feature.note.bean.Note; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; package com.tsy.leanote.feature.note.view.adapter; /** * Created by tsy on 2017/1/18. */ public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.MyViewHolder> implements View.OnClickListener { private final LayoutInflater mLayoutInflater; private final Context mContext;
private ArrayList<Note> mMyNotes;
tsy12321/LeanoteAndroid
app/src/main/java/com/tsy/leanote/feature/note/contract/NoteFileContract.java
// Path: app/src/main/java/com/tsy/leanote/feature/note/bean/NoteFile.java // @Entity // public class NoteFile { // @Id // private Long id; // // private String noteid; // private String fileId; // private String localFileId; // private String type; // private String title; // private boolean hasBody; // private boolean isAttach; // @Generated(hash = 2026444157) // public NoteFile(Long id, String noteid, String fileId, String localFileId, // String type, String title, boolean hasBody, boolean isAttach) { // this.id = id; // this.noteid = noteid; // this.fileId = fileId; // this.localFileId = localFileId; // this.type = type; // this.title = title; // this.hasBody = hasBody; // this.isAttach = isAttach; // } // @Generated(hash = 1417941967) // public NoteFile() { // } // public Long getId() { // return this.id; // } // public void setId(Long id) { // this.id = id; // } // public String getNoteid() { // return this.noteid; // } // public void setNoteid(String noteid) { // this.noteid = noteid; // } // public String getFileId() { // return this.fileId; // } // public void setFileId(String fileId) { // this.fileId = fileId; // } // public String getLocalFileId() { // return this.localFileId; // } // public void setLocalFileId(String localFileId) { // this.localFileId = localFileId; // } // public String getType() { // return this.type; // } // public void setType(String type) { // this.type = type; // } // public String getTitle() { // return this.title; // } // public void setTitle(String title) { // this.title = title; // } // public boolean getHasBody() { // return this.hasBody; // } // public void setHasBody(boolean hasBody) { // this.hasBody = hasBody; // } // public boolean getIsAttach() { // return this.isAttach; // } // public void setIsAttach(boolean isAttach) { // this.isAttach = isAttach; // } // } // // Path: app/src/main/java/com/tsy/leanote/feature/user/bean/UserInfo.java // @Entity // public class UserInfo { // @Id // private Long id; // @Unique // private String uid; // private String username; // private String email; // private String logo; // private String token; // private boolean verified; //邮箱是否认证 // private int last_usn; //上次同步usn // // @Generated(hash = 1860533007) // public UserInfo(Long id, String uid, String username, String email, String logo, // String token, boolean verified, int last_usn) { // this.id = id; // this.uid = uid; // this.username = username; // this.email = email; // this.logo = logo; // this.token = token; // this.verified = verified; // this.last_usn = last_usn; // } // // @Generated(hash = 1279772520) // public UserInfo() { // } // // @Override // public String toString() { // return "UserInfo{" + // "id=" + id + // ", uid='" + uid + '\'' + // ", username='" + username + '\'' + // ", email='" + email + '\'' + // ", logo='" + logo + '\'' + // ", token='" + token + '\'' + // ", verified=" + verified + // ", last_usn=" + last_usn + // '}'; // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUid() { // return this.uid; // } // // public void setUid(String uid) { // this.uid = uid; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return this.email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getLogo() { // return this.logo; // } // // public void setLogo(String logo) { // this.logo = logo; // } // // public String getToken() { // return this.token; // } // // public void setToken(String token) { // this.token = token; // } // // public boolean getVerified() { // return this.verified; // } // // public void setVerified(boolean verified) { // this.verified = verified; // } // // public int getLast_usn() { // return this.last_usn; // } // // public void setLast_usn(int last_usn) { // this.last_usn = last_usn; // } // }
import com.tsy.leanote.feature.note.bean.NoteFile; import com.tsy.leanote.feature.user.bean.UserInfo; import org.json.JSONArray; import java.util.ArrayList;
package com.tsy.leanote.feature.note.contract; /** * Created by tsy on 2017/2/15. */ public interface NoteFileContract { interface Interactor { /** * 添加某篇note里所有file * @param noteid * @param noteFiles */ void addNoteFiles(String noteid, JSONArray noteFiles); /** * 更新localFile * @param noteFiles */ void updateLocalFile(JSONArray noteFiles); /** * 加载某个笔记下的所有pics(下载下来) * @param noteid */
// Path: app/src/main/java/com/tsy/leanote/feature/note/bean/NoteFile.java // @Entity // public class NoteFile { // @Id // private Long id; // // private String noteid; // private String fileId; // private String localFileId; // private String type; // private String title; // private boolean hasBody; // private boolean isAttach; // @Generated(hash = 2026444157) // public NoteFile(Long id, String noteid, String fileId, String localFileId, // String type, String title, boolean hasBody, boolean isAttach) { // this.id = id; // this.noteid = noteid; // this.fileId = fileId; // this.localFileId = localFileId; // this.type = type; // this.title = title; // this.hasBody = hasBody; // this.isAttach = isAttach; // } // @Generated(hash = 1417941967) // public NoteFile() { // } // public Long getId() { // return this.id; // } // public void setId(Long id) { // this.id = id; // } // public String getNoteid() { // return this.noteid; // } // public void setNoteid(String noteid) { // this.noteid = noteid; // } // public String getFileId() { // return this.fileId; // } // public void setFileId(String fileId) { // this.fileId = fileId; // } // public String getLocalFileId() { // return this.localFileId; // } // public void setLocalFileId(String localFileId) { // this.localFileId = localFileId; // } // public String getType() { // return this.type; // } // public void setType(String type) { // this.type = type; // } // public String getTitle() { // return this.title; // } // public void setTitle(String title) { // this.title = title; // } // public boolean getHasBody() { // return this.hasBody; // } // public void setHasBody(boolean hasBody) { // this.hasBody = hasBody; // } // public boolean getIsAttach() { // return this.isAttach; // } // public void setIsAttach(boolean isAttach) { // this.isAttach = isAttach; // } // } // // Path: app/src/main/java/com/tsy/leanote/feature/user/bean/UserInfo.java // @Entity // public class UserInfo { // @Id // private Long id; // @Unique // private String uid; // private String username; // private String email; // private String logo; // private String token; // private boolean verified; //邮箱是否认证 // private int last_usn; //上次同步usn // // @Generated(hash = 1860533007) // public UserInfo(Long id, String uid, String username, String email, String logo, // String token, boolean verified, int last_usn) { // this.id = id; // this.uid = uid; // this.username = username; // this.email = email; // this.logo = logo; // this.token = token; // this.verified = verified; // this.last_usn = last_usn; // } // // @Generated(hash = 1279772520) // public UserInfo() { // } // // @Override // public String toString() { // return "UserInfo{" + // "id=" + id + // ", uid='" + uid + '\'' + // ", username='" + username + '\'' + // ", email='" + email + '\'' + // ", logo='" + logo + '\'' + // ", token='" + token + '\'' + // ", verified=" + verified + // ", last_usn=" + last_usn + // '}'; // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUid() { // return this.uid; // } // // public void setUid(String uid) { // this.uid = uid; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return this.email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getLogo() { // return this.logo; // } // // public void setLogo(String logo) { // this.logo = logo; // } // // public String getToken() { // return this.token; // } // // public void setToken(String token) { // this.token = token; // } // // public boolean getVerified() { // return this.verified; // } // // public void setVerified(boolean verified) { // this.verified = verified; // } // // public int getLast_usn() { // return this.last_usn; // } // // public void setLast_usn(int last_usn) { // this.last_usn = last_usn; // } // } // Path: app/src/main/java/com/tsy/leanote/feature/note/contract/NoteFileContract.java import com.tsy.leanote.feature.note.bean.NoteFile; import com.tsy.leanote.feature.user.bean.UserInfo; import org.json.JSONArray; import java.util.ArrayList; package com.tsy.leanote.feature.note.contract; /** * Created by tsy on 2017/2/15. */ public interface NoteFileContract { interface Interactor { /** * 添加某篇note里所有file * @param noteid * @param noteFiles */ void addNoteFiles(String noteid, JSONArray noteFiles); /** * 更新localFile * @param noteFiles */ void updateLocalFile(JSONArray noteFiles); /** * 加载某个笔记下的所有pics(下载下来) * @param noteid */
void loadAllPics(UserInfo userInfo, String noteid, LoadAllPicsCallback callback);
tsy12321/LeanoteAndroid
app/src/main/java/com/tsy/leanote/base/BaseFragment.java
// Path: app/src/main/java/com/tsy/leanote/MyApplication.java // public class MyApplication extends Application { // // private static MyApplication mMyApplication; // private Context mContext; // protected MyOkHttp mMyOkHttp; // private DaoSession mDaoSession; // private UserInfo mUserInfo; //当前用户 // // @Override // public void onCreate() { // super.onCreate(); // // //内存泄露分析初始化 // if(BuildConfig.DEBUG) { // if (LeakCanary.isInAnalyzerProcess(this)) { // // This process is dedicated to LeakCanary for heap analysis. // // You should not init your app in this process. // return; // } // LeakCanary.install(this); // } // // //umeng统计初始化 // if(!TextUtils.isEmpty(BuildConfig.UMENG_APPKEY)) { // MobclickAgent.setScenarioType(getApplicationContext(), MobclickAgent.EScenarioType.E_UM_NORMAL); // UMConfigure.init(this, BuildConfig.UMENG_APPKEY, "github", UMConfigure.DEVICE_TYPE_PHONE, null); // } // // mMyApplication = this; // mContext = getApplicationContext(); // // //数据库初始化 // DBHelper devOpenHelper = new DBHelper(getApplicationContext(), "leanote.db"); // DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb()); // mDaoSession = daoMaster.newSession(); // // //loading初始化 // LoadSir.beginBuilder() // .addCallback(new ErrorCallback()) // .addCallback(new EmptyCallback()) // .addCallback(new LoadingCallback()) // .commit(); // } // // private void initMyOkHttp() { // if(BuildConfig.DEBUG) { // //自定义OkHttp // HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); // logging.setLevel(HttpLoggingInterceptor.Level.BODY); // // OkHttpClient okHttpClient = new OkHttpClient.Builder() // .addInterceptor(logging) //设置开启log // .build(); // mMyOkHttp = new MyOkHttp(okHttpClient); // } else { // mMyOkHttp = new MyOkHttp(); // } // } // // /** // * myokhttp // * @return // */ // public MyOkHttp getMyOkHttp() { // if(mMyOkHttp == null) { // initMyOkHttp(); // } // // return mMyOkHttp; // } // // /** // * 获取全局Application // * @return // */ // public static synchronized MyApplication getInstance() { // return mMyApplication; // } // // /** // * 获取ApplicationContext // * @return // */ // public Context getContext() { // return mContext; // } // // /** // * 获取dao session // * @return // */ // public DaoSession getDaoSession() { // return mDaoSession; // } // // public UserInfo getUserInfo() { // return mUserInfo; // } // // public void setUserInfo(UserInfo userInfo) { // mUserInfo = userInfo; // } // }
import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import com.tsy.leanote.MyApplication; import com.tsy.leanote.R; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import pub.devrel.easypermissions.AppSettingsDialog; import pub.devrel.easypermissions.EasyPermissions;
* @param rationale alert setting rationale */ protected void alertAppSetPermission(String rationale) { new AppSettingsDialog.Builder(this, rationale) .setTitle(getString(R.string.permission_deny_again_title)) .setPositiveButton(getString(R.string.permission_deny_again_positive)) .setNegativeButton(getString(R.string.permission_deny_again_nagative), null) .build() .show(); } /** * alert AppSet Permission * @param rationale alert setting rationale * @param requestCode onActivityResult requestCode */ protected void alertAppSetPermission(String rationale, int requestCode) { new AppSettingsDialog.Builder(this, rationale) .setTitle(getString(R.string.permission_deny_again_title)) .setPositiveButton(getString(R.string.permission_deny_again_positive)) .setNegativeButton(getString(R.string.permission_deny_again_nagative), null) .setRequestCode(requestCode) .build() .show(); } @Override public void onDestroyView() { super.onDestroyView();
// Path: app/src/main/java/com/tsy/leanote/MyApplication.java // public class MyApplication extends Application { // // private static MyApplication mMyApplication; // private Context mContext; // protected MyOkHttp mMyOkHttp; // private DaoSession mDaoSession; // private UserInfo mUserInfo; //当前用户 // // @Override // public void onCreate() { // super.onCreate(); // // //内存泄露分析初始化 // if(BuildConfig.DEBUG) { // if (LeakCanary.isInAnalyzerProcess(this)) { // // This process is dedicated to LeakCanary for heap analysis. // // You should not init your app in this process. // return; // } // LeakCanary.install(this); // } // // //umeng统计初始化 // if(!TextUtils.isEmpty(BuildConfig.UMENG_APPKEY)) { // MobclickAgent.setScenarioType(getApplicationContext(), MobclickAgent.EScenarioType.E_UM_NORMAL); // UMConfigure.init(this, BuildConfig.UMENG_APPKEY, "github", UMConfigure.DEVICE_TYPE_PHONE, null); // } // // mMyApplication = this; // mContext = getApplicationContext(); // // //数据库初始化 // DBHelper devOpenHelper = new DBHelper(getApplicationContext(), "leanote.db"); // DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb()); // mDaoSession = daoMaster.newSession(); // // //loading初始化 // LoadSir.beginBuilder() // .addCallback(new ErrorCallback()) // .addCallback(new EmptyCallback()) // .addCallback(new LoadingCallback()) // .commit(); // } // // private void initMyOkHttp() { // if(BuildConfig.DEBUG) { // //自定义OkHttp // HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); // logging.setLevel(HttpLoggingInterceptor.Level.BODY); // // OkHttpClient okHttpClient = new OkHttpClient.Builder() // .addInterceptor(logging) //设置开启log // .build(); // mMyOkHttp = new MyOkHttp(okHttpClient); // } else { // mMyOkHttp = new MyOkHttp(); // } // } // // /** // * myokhttp // * @return // */ // public MyOkHttp getMyOkHttp() { // if(mMyOkHttp == null) { // initMyOkHttp(); // } // // return mMyOkHttp; // } // // /** // * 获取全局Application // * @return // */ // public static synchronized MyApplication getInstance() { // return mMyApplication; // } // // /** // * 获取ApplicationContext // * @return // */ // public Context getContext() { // return mContext; // } // // /** // * 获取dao session // * @return // */ // public DaoSession getDaoSession() { // return mDaoSession; // } // // public UserInfo getUserInfo() { // return mUserInfo; // } // // public void setUserInfo(UserInfo userInfo) { // mUserInfo = userInfo; // } // } // Path: app/src/main/java/com/tsy/leanote/base/BaseFragment.java import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import com.tsy.leanote.MyApplication; import com.tsy.leanote.R; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import pub.devrel.easypermissions.AppSettingsDialog; import pub.devrel.easypermissions.EasyPermissions; * @param rationale alert setting rationale */ protected void alertAppSetPermission(String rationale) { new AppSettingsDialog.Builder(this, rationale) .setTitle(getString(R.string.permission_deny_again_title)) .setPositiveButton(getString(R.string.permission_deny_again_positive)) .setNegativeButton(getString(R.string.permission_deny_again_nagative), null) .build() .show(); } /** * alert AppSet Permission * @param rationale alert setting rationale * @param requestCode onActivityResult requestCode */ protected void alertAppSetPermission(String rationale, int requestCode) { new AppSettingsDialog.Builder(this, rationale) .setTitle(getString(R.string.permission_deny_again_title)) .setPositiveButton(getString(R.string.permission_deny_again_positive)) .setNegativeButton(getString(R.string.permission_deny_again_nagative), null) .setRequestCode(requestCode) .build() .show(); } @Override public void onDestroyView() { super.onDestroyView();
MyApplication.getInstance().getMyOkHttp().cancel(this);
tsy12321/LeanoteAndroid
app/src/main/java/com/tsy/leanote/widget/webview/MyWebView.java
// Path: app/src/main/java/com/tsy/leanote/MyApplication.java // public class MyApplication extends Application { // // private static MyApplication mMyApplication; // private Context mContext; // protected MyOkHttp mMyOkHttp; // private DaoSession mDaoSession; // private UserInfo mUserInfo; //当前用户 // // @Override // public void onCreate() { // super.onCreate(); // // //内存泄露分析初始化 // if(BuildConfig.DEBUG) { // if (LeakCanary.isInAnalyzerProcess(this)) { // // This process is dedicated to LeakCanary for heap analysis. // // You should not init your app in this process. // return; // } // LeakCanary.install(this); // } // // //umeng统计初始化 // if(!TextUtils.isEmpty(BuildConfig.UMENG_APPKEY)) { // MobclickAgent.setScenarioType(getApplicationContext(), MobclickAgent.EScenarioType.E_UM_NORMAL); // UMConfigure.init(this, BuildConfig.UMENG_APPKEY, "github", UMConfigure.DEVICE_TYPE_PHONE, null); // } // // mMyApplication = this; // mContext = getApplicationContext(); // // //数据库初始化 // DBHelper devOpenHelper = new DBHelper(getApplicationContext(), "leanote.db"); // DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb()); // mDaoSession = daoMaster.newSession(); // // //loading初始化 // LoadSir.beginBuilder() // .addCallback(new ErrorCallback()) // .addCallback(new EmptyCallback()) // .addCallback(new LoadingCallback()) // .commit(); // } // // private void initMyOkHttp() { // if(BuildConfig.DEBUG) { // //自定义OkHttp // HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); // logging.setLevel(HttpLoggingInterceptor.Level.BODY); // // OkHttpClient okHttpClient = new OkHttpClient.Builder() // .addInterceptor(logging) //设置开启log // .build(); // mMyOkHttp = new MyOkHttp(okHttpClient); // } else { // mMyOkHttp = new MyOkHttp(); // } // } // // /** // * myokhttp // * @return // */ // public MyOkHttp getMyOkHttp() { // if(mMyOkHttp == null) { // initMyOkHttp(); // } // // return mMyOkHttp; // } // // /** // * 获取全局Application // * @return // */ // public static synchronized MyApplication getInstance() { // return mMyApplication; // } // // /** // * 获取ApplicationContext // * @return // */ // public Context getContext() { // return mContext; // } // // /** // * 获取dao session // * @return // */ // public DaoSession getDaoSession() { // return mDaoSession; // } // // public UserInfo getUserInfo() { // return mUserInfo; // } // // public void setUserInfo(UserInfo userInfo) { // mUserInfo = userInfo; // } // }
import android.content.Context; import android.util.AttributeSet; import android.webkit.WebSettings; import android.webkit.WebView; import com.tsy.leanote.MyApplication; import com.tsy.sdk.myutil.ManifestUtils; import com.tsy.sdk.myutil.NetworkUtils; import java.util.Locale;
package com.tsy.leanote.widget.webview; /** * Created by tangsiyuan on 2018/1/25. */ public class MyWebView extends WebView { public MyWebView(Context context) { super(context); } public MyWebView(Context context, AttributeSet attrs) { super(context, attrs); } public MyWebView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } //设置setting public void initSetting() { WebSettings websettings = getSettings(); websettings.setUserAgentString(websettings.getUserAgentString()); websettings.setRenderPriority(WebSettings.RenderPriority.HIGH); websettings.setDomStorageEnabled(true); websettings.setJavaScriptEnabled(true); websettings.setDefaultTextEncodingName("UTF-8"); websettings.setUseWideViewPort(true); websettings.setLoadWithOverviewMode(true); //设置agent规则 webview UA+空格+MamidianMerchant/版本号+空格+网络+空格+地区 String angent = getSettings().getUserAgentString() +
// Path: app/src/main/java/com/tsy/leanote/MyApplication.java // public class MyApplication extends Application { // // private static MyApplication mMyApplication; // private Context mContext; // protected MyOkHttp mMyOkHttp; // private DaoSession mDaoSession; // private UserInfo mUserInfo; //当前用户 // // @Override // public void onCreate() { // super.onCreate(); // // //内存泄露分析初始化 // if(BuildConfig.DEBUG) { // if (LeakCanary.isInAnalyzerProcess(this)) { // // This process is dedicated to LeakCanary for heap analysis. // // You should not init your app in this process. // return; // } // LeakCanary.install(this); // } // // //umeng统计初始化 // if(!TextUtils.isEmpty(BuildConfig.UMENG_APPKEY)) { // MobclickAgent.setScenarioType(getApplicationContext(), MobclickAgent.EScenarioType.E_UM_NORMAL); // UMConfigure.init(this, BuildConfig.UMENG_APPKEY, "github", UMConfigure.DEVICE_TYPE_PHONE, null); // } // // mMyApplication = this; // mContext = getApplicationContext(); // // //数据库初始化 // DBHelper devOpenHelper = new DBHelper(getApplicationContext(), "leanote.db"); // DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb()); // mDaoSession = daoMaster.newSession(); // // //loading初始化 // LoadSir.beginBuilder() // .addCallback(new ErrorCallback()) // .addCallback(new EmptyCallback()) // .addCallback(new LoadingCallback()) // .commit(); // } // // private void initMyOkHttp() { // if(BuildConfig.DEBUG) { // //自定义OkHttp // HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); // logging.setLevel(HttpLoggingInterceptor.Level.BODY); // // OkHttpClient okHttpClient = new OkHttpClient.Builder() // .addInterceptor(logging) //设置开启log // .build(); // mMyOkHttp = new MyOkHttp(okHttpClient); // } else { // mMyOkHttp = new MyOkHttp(); // } // } // // /** // * myokhttp // * @return // */ // public MyOkHttp getMyOkHttp() { // if(mMyOkHttp == null) { // initMyOkHttp(); // } // // return mMyOkHttp; // } // // /** // * 获取全局Application // * @return // */ // public static synchronized MyApplication getInstance() { // return mMyApplication; // } // // /** // * 获取ApplicationContext // * @return // */ // public Context getContext() { // return mContext; // } // // /** // * 获取dao session // * @return // */ // public DaoSession getDaoSession() { // return mDaoSession; // } // // public UserInfo getUserInfo() { // return mUserInfo; // } // // public void setUserInfo(UserInfo userInfo) { // mUserInfo = userInfo; // } // } // Path: app/src/main/java/com/tsy/leanote/widget/webview/MyWebView.java import android.content.Context; import android.util.AttributeSet; import android.webkit.WebSettings; import android.webkit.WebView; import com.tsy.leanote.MyApplication; import com.tsy.sdk.myutil.ManifestUtils; import com.tsy.sdk.myutil.NetworkUtils; import java.util.Locale; package com.tsy.leanote.widget.webview; /** * Created by tangsiyuan on 2018/1/25. */ public class MyWebView extends WebView { public MyWebView(Context context) { super(context); } public MyWebView(Context context, AttributeSet attrs) { super(context, attrs); } public MyWebView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } //设置setting public void initSetting() { WebSettings websettings = getSettings(); websettings.setUserAgentString(websettings.getUserAgentString()); websettings.setRenderPriority(WebSettings.RenderPriority.HIGH); websettings.setDomStorageEnabled(true); websettings.setJavaScriptEnabled(true); websettings.setDefaultTextEncodingName("UTF-8"); websettings.setUseWideViewPort(true); websettings.setLoadWithOverviewMode(true); //设置agent规则 webview UA+空格+MamidianMerchant/版本号+空格+网络+空格+地区 String angent = getSettings().getUserAgentString() +
" Leanote/" + ManifestUtils.getVersionName(MyApplication.getInstance().getContext()) +
tsy12321/LeanoteAndroid
app/src/main/java/com/tsy/leanote/base/BaseActivity.java
// Path: app/src/main/java/com/tsy/leanote/MyApplication.java // public class MyApplication extends Application { // // private static MyApplication mMyApplication; // private Context mContext; // protected MyOkHttp mMyOkHttp; // private DaoSession mDaoSession; // private UserInfo mUserInfo; //当前用户 // // @Override // public void onCreate() { // super.onCreate(); // // //内存泄露分析初始化 // if(BuildConfig.DEBUG) { // if (LeakCanary.isInAnalyzerProcess(this)) { // // This process is dedicated to LeakCanary for heap analysis. // // You should not init your app in this process. // return; // } // LeakCanary.install(this); // } // // //umeng统计初始化 // if(!TextUtils.isEmpty(BuildConfig.UMENG_APPKEY)) { // MobclickAgent.setScenarioType(getApplicationContext(), MobclickAgent.EScenarioType.E_UM_NORMAL); // UMConfigure.init(this, BuildConfig.UMENG_APPKEY, "github", UMConfigure.DEVICE_TYPE_PHONE, null); // } // // mMyApplication = this; // mContext = getApplicationContext(); // // //数据库初始化 // DBHelper devOpenHelper = new DBHelper(getApplicationContext(), "leanote.db"); // DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb()); // mDaoSession = daoMaster.newSession(); // // //loading初始化 // LoadSir.beginBuilder() // .addCallback(new ErrorCallback()) // .addCallback(new EmptyCallback()) // .addCallback(new LoadingCallback()) // .commit(); // } // // private void initMyOkHttp() { // if(BuildConfig.DEBUG) { // //自定义OkHttp // HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); // logging.setLevel(HttpLoggingInterceptor.Level.BODY); // // OkHttpClient okHttpClient = new OkHttpClient.Builder() // .addInterceptor(logging) //设置开启log // .build(); // mMyOkHttp = new MyOkHttp(okHttpClient); // } else { // mMyOkHttp = new MyOkHttp(); // } // } // // /** // * myokhttp // * @return // */ // public MyOkHttp getMyOkHttp() { // if(mMyOkHttp == null) { // initMyOkHttp(); // } // // return mMyOkHttp; // } // // /** // * 获取全局Application // * @return // */ // public static synchronized MyApplication getInstance() { // return mMyApplication; // } // // /** // * 获取ApplicationContext // * @return // */ // public Context getContext() { // return mContext; // } // // /** // * 获取dao session // * @return // */ // public DaoSession getDaoSession() { // return mDaoSession; // } // // public UserInfo getUserInfo() { // return mUserInfo; // } // // public void setUserInfo(UserInfo userInfo) { // mUserInfo = userInfo; // } // }
import android.annotation.SuppressLint; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import com.tsy.leanote.MyApplication; import com.tsy.leanote.R; import com.umeng.analytics.MobclickAgent; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import pub.devrel.easypermissions.AppSettingsDialog; import pub.devrel.easypermissions.EasyPermissions;
* alert AppSet Permission * @param rationale alert setting rationale * @param requestCode onActivityResult requestCode */ protected void alertAppSetPermission(String rationale, int requestCode) { new AppSettingsDialog.Builder(this, rationale) .setTitle(getString(R.string.permission_deny_again_title)) .setPositiveButton(getString(R.string.permission_deny_again_positive)) .setNegativeButton(getString(R.string.permission_deny_again_nagative), null) .setRequestCode(requestCode) .build() .show(); } @Override protected void onResume() { super.onResume(); MobclickAgent.onResume(this); } @Override protected void onPause() { super.onPause(); MobclickAgent.onPause(this); } @Override protected void onDestroy() { super.onDestroy();
// Path: app/src/main/java/com/tsy/leanote/MyApplication.java // public class MyApplication extends Application { // // private static MyApplication mMyApplication; // private Context mContext; // protected MyOkHttp mMyOkHttp; // private DaoSession mDaoSession; // private UserInfo mUserInfo; //当前用户 // // @Override // public void onCreate() { // super.onCreate(); // // //内存泄露分析初始化 // if(BuildConfig.DEBUG) { // if (LeakCanary.isInAnalyzerProcess(this)) { // // This process is dedicated to LeakCanary for heap analysis. // // You should not init your app in this process. // return; // } // LeakCanary.install(this); // } // // //umeng统计初始化 // if(!TextUtils.isEmpty(BuildConfig.UMENG_APPKEY)) { // MobclickAgent.setScenarioType(getApplicationContext(), MobclickAgent.EScenarioType.E_UM_NORMAL); // UMConfigure.init(this, BuildConfig.UMENG_APPKEY, "github", UMConfigure.DEVICE_TYPE_PHONE, null); // } // // mMyApplication = this; // mContext = getApplicationContext(); // // //数据库初始化 // DBHelper devOpenHelper = new DBHelper(getApplicationContext(), "leanote.db"); // DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb()); // mDaoSession = daoMaster.newSession(); // // //loading初始化 // LoadSir.beginBuilder() // .addCallback(new ErrorCallback()) // .addCallback(new EmptyCallback()) // .addCallback(new LoadingCallback()) // .commit(); // } // // private void initMyOkHttp() { // if(BuildConfig.DEBUG) { // //自定义OkHttp // HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); // logging.setLevel(HttpLoggingInterceptor.Level.BODY); // // OkHttpClient okHttpClient = new OkHttpClient.Builder() // .addInterceptor(logging) //设置开启log // .build(); // mMyOkHttp = new MyOkHttp(okHttpClient); // } else { // mMyOkHttp = new MyOkHttp(); // } // } // // /** // * myokhttp // * @return // */ // public MyOkHttp getMyOkHttp() { // if(mMyOkHttp == null) { // initMyOkHttp(); // } // // return mMyOkHttp; // } // // /** // * 获取全局Application // * @return // */ // public static synchronized MyApplication getInstance() { // return mMyApplication; // } // // /** // * 获取ApplicationContext // * @return // */ // public Context getContext() { // return mContext; // } // // /** // * 获取dao session // * @return // */ // public DaoSession getDaoSession() { // return mDaoSession; // } // // public UserInfo getUserInfo() { // return mUserInfo; // } // // public void setUserInfo(UserInfo userInfo) { // mUserInfo = userInfo; // } // } // Path: app/src/main/java/com/tsy/leanote/base/BaseActivity.java import android.annotation.SuppressLint; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import com.tsy.leanote.MyApplication; import com.tsy.leanote.R; import com.umeng.analytics.MobclickAgent; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import pub.devrel.easypermissions.AppSettingsDialog; import pub.devrel.easypermissions.EasyPermissions; * alert AppSet Permission * @param rationale alert setting rationale * @param requestCode onActivityResult requestCode */ protected void alertAppSetPermission(String rationale, int requestCode) { new AppSettingsDialog.Builder(this, rationale) .setTitle(getString(R.string.permission_deny_again_title)) .setPositiveButton(getString(R.string.permission_deny_again_positive)) .setNegativeButton(getString(R.string.permission_deny_again_nagative), null) .setRequestCode(requestCode) .build() .show(); } @Override protected void onResume() { super.onResume(); MobclickAgent.onResume(this); } @Override protected void onPause() { super.onPause(); MobclickAgent.onPause(this); } @Override protected void onDestroy() { super.onDestroy();
MyApplication.getInstance().getMyOkHttp().cancel(this);
tsy12321/LeanoteAndroid
app/src/main/java/com/tsy/leanote/feature/user/contract/UserContract.java
// Path: app/src/main/java/com/tsy/leanote/base/BaseInteractorCallback.java // public interface BaseInteractorCallback { // void onFailure(String msg); // } // // Path: app/src/main/java/com/tsy/leanote/base/NormalInteractorCallback.java // public interface NormalInteractorCallback extends BaseInteractorCallback { // void onSuccess(); // } // // Path: app/src/main/java/com/tsy/leanote/feature/user/bean/UserInfo.java // @Entity // public class UserInfo { // @Id // private Long id; // @Unique // private String uid; // private String username; // private String email; // private String logo; // private String token; // private boolean verified; //邮箱是否认证 // private int last_usn; //上次同步usn // // @Generated(hash = 1860533007) // public UserInfo(Long id, String uid, String username, String email, String logo, // String token, boolean verified, int last_usn) { // this.id = id; // this.uid = uid; // this.username = username; // this.email = email; // this.logo = logo; // this.token = token; // this.verified = verified; // this.last_usn = last_usn; // } // // @Generated(hash = 1279772520) // public UserInfo() { // } // // @Override // public String toString() { // return "UserInfo{" + // "id=" + id + // ", uid='" + uid + '\'' + // ", username='" + username + '\'' + // ", email='" + email + '\'' + // ", logo='" + logo + '\'' + // ", token='" + token + '\'' + // ", verified=" + verified + // ", last_usn=" + last_usn + // '}'; // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUid() { // return this.uid; // } // // public void setUid(String uid) { // this.uid = uid; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return this.email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getLogo() { // return this.logo; // } // // public void setLogo(String logo) { // this.logo = logo; // } // // public String getToken() { // return this.token; // } // // public void setToken(String token) { // this.token = token; // } // // public boolean getVerified() { // return this.verified; // } // // public void setVerified(boolean verified) { // this.verified = verified; // } // // public int getLast_usn() { // return this.last_usn; // } // // public void setLast_usn(int last_usn) { // this.last_usn = last_usn; // } // }
import com.tsy.leanote.base.BaseInteractorCallback; import com.tsy.leanote.base.NormalInteractorCallback; import com.tsy.leanote.feature.user.bean.UserInfo;
package com.tsy.leanote.feature.user.contract; /** * Created by tsy on 2016/12/13. */ public interface UserContract { interface Interactor { /** * 登录 * @param host * @param email * @param pwd * @param callback */ void login(String host, String email, String pwd, UserCallback callback); /** * 获取用户信息 * @param uid * @param token * @param callback */ void getUserInfo(String uid, String token, UserContract.UserCallback callback); /** * 获取当前用户 * @return */
// Path: app/src/main/java/com/tsy/leanote/base/BaseInteractorCallback.java // public interface BaseInteractorCallback { // void onFailure(String msg); // } // // Path: app/src/main/java/com/tsy/leanote/base/NormalInteractorCallback.java // public interface NormalInteractorCallback extends BaseInteractorCallback { // void onSuccess(); // } // // Path: app/src/main/java/com/tsy/leanote/feature/user/bean/UserInfo.java // @Entity // public class UserInfo { // @Id // private Long id; // @Unique // private String uid; // private String username; // private String email; // private String logo; // private String token; // private boolean verified; //邮箱是否认证 // private int last_usn; //上次同步usn // // @Generated(hash = 1860533007) // public UserInfo(Long id, String uid, String username, String email, String logo, // String token, boolean verified, int last_usn) { // this.id = id; // this.uid = uid; // this.username = username; // this.email = email; // this.logo = logo; // this.token = token; // this.verified = verified; // this.last_usn = last_usn; // } // // @Generated(hash = 1279772520) // public UserInfo() { // } // // @Override // public String toString() { // return "UserInfo{" + // "id=" + id + // ", uid='" + uid + '\'' + // ", username='" + username + '\'' + // ", email='" + email + '\'' + // ", logo='" + logo + '\'' + // ", token='" + token + '\'' + // ", verified=" + verified + // ", last_usn=" + last_usn + // '}'; // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUid() { // return this.uid; // } // // public void setUid(String uid) { // this.uid = uid; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return this.email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getLogo() { // return this.logo; // } // // public void setLogo(String logo) { // this.logo = logo; // } // // public String getToken() { // return this.token; // } // // public void setToken(String token) { // this.token = token; // } // // public boolean getVerified() { // return this.verified; // } // // public void setVerified(boolean verified) { // this.verified = verified; // } // // public int getLast_usn() { // return this.last_usn; // } // // public void setLast_usn(int last_usn) { // this.last_usn = last_usn; // } // } // Path: app/src/main/java/com/tsy/leanote/feature/user/contract/UserContract.java import com.tsy.leanote.base.BaseInteractorCallback; import com.tsy.leanote.base.NormalInteractorCallback; import com.tsy.leanote.feature.user.bean.UserInfo; package com.tsy.leanote.feature.user.contract; /** * Created by tsy on 2016/12/13. */ public interface UserContract { interface Interactor { /** * 登录 * @param host * @param email * @param pwd * @param callback */ void login(String host, String email, String pwd, UserCallback callback); /** * 获取用户信息 * @param uid * @param token * @param callback */ void getUserInfo(String uid, String token, UserContract.UserCallback callback); /** * 获取当前用户 * @return */
UserInfo getCurUser();
tsy12321/LeanoteAndroid
app/src/main/java/com/tsy/leanote/feature/user/contract/UserContract.java
// Path: app/src/main/java/com/tsy/leanote/base/BaseInteractorCallback.java // public interface BaseInteractorCallback { // void onFailure(String msg); // } // // Path: app/src/main/java/com/tsy/leanote/base/NormalInteractorCallback.java // public interface NormalInteractorCallback extends BaseInteractorCallback { // void onSuccess(); // } // // Path: app/src/main/java/com/tsy/leanote/feature/user/bean/UserInfo.java // @Entity // public class UserInfo { // @Id // private Long id; // @Unique // private String uid; // private String username; // private String email; // private String logo; // private String token; // private boolean verified; //邮箱是否认证 // private int last_usn; //上次同步usn // // @Generated(hash = 1860533007) // public UserInfo(Long id, String uid, String username, String email, String logo, // String token, boolean verified, int last_usn) { // this.id = id; // this.uid = uid; // this.username = username; // this.email = email; // this.logo = logo; // this.token = token; // this.verified = verified; // this.last_usn = last_usn; // } // // @Generated(hash = 1279772520) // public UserInfo() { // } // // @Override // public String toString() { // return "UserInfo{" + // "id=" + id + // ", uid='" + uid + '\'' + // ", username='" + username + '\'' + // ", email='" + email + '\'' + // ", logo='" + logo + '\'' + // ", token='" + token + '\'' + // ", verified=" + verified + // ", last_usn=" + last_usn + // '}'; // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUid() { // return this.uid; // } // // public void setUid(String uid) { // this.uid = uid; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return this.email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getLogo() { // return this.logo; // } // // public void setLogo(String logo) { // this.logo = logo; // } // // public String getToken() { // return this.token; // } // // public void setToken(String token) { // this.token = token; // } // // public boolean getVerified() { // return this.verified; // } // // public void setVerified(boolean verified) { // this.verified = verified; // } // // public int getLast_usn() { // return this.last_usn; // } // // public void setLast_usn(int last_usn) { // this.last_usn = last_usn; // } // }
import com.tsy.leanote.base.BaseInteractorCallback; import com.tsy.leanote.base.NormalInteractorCallback; import com.tsy.leanote.feature.user.bean.UserInfo;
package com.tsy.leanote.feature.user.contract; /** * Created by tsy on 2016/12/13. */ public interface UserContract { interface Interactor { /** * 登录 * @param host * @param email * @param pwd * @param callback */ void login(String host, String email, String pwd, UserCallback callback); /** * 获取用户信息 * @param uid * @param token * @param callback */ void getUserInfo(String uid, String token, UserContract.UserCallback callback); /** * 获取当前用户 * @return */ UserInfo getCurUser(); /** * 注册 * @param host * @param email * @param pwd * @param callback */ void register(String host, String email, String pwd, UserCallback callback); /** * 退出 * @param userInfo 当前登录用户 * @param callback */
// Path: app/src/main/java/com/tsy/leanote/base/BaseInteractorCallback.java // public interface BaseInteractorCallback { // void onFailure(String msg); // } // // Path: app/src/main/java/com/tsy/leanote/base/NormalInteractorCallback.java // public interface NormalInteractorCallback extends BaseInteractorCallback { // void onSuccess(); // } // // Path: app/src/main/java/com/tsy/leanote/feature/user/bean/UserInfo.java // @Entity // public class UserInfo { // @Id // private Long id; // @Unique // private String uid; // private String username; // private String email; // private String logo; // private String token; // private boolean verified; //邮箱是否认证 // private int last_usn; //上次同步usn // // @Generated(hash = 1860533007) // public UserInfo(Long id, String uid, String username, String email, String logo, // String token, boolean verified, int last_usn) { // this.id = id; // this.uid = uid; // this.username = username; // this.email = email; // this.logo = logo; // this.token = token; // this.verified = verified; // this.last_usn = last_usn; // } // // @Generated(hash = 1279772520) // public UserInfo() { // } // // @Override // public String toString() { // return "UserInfo{" + // "id=" + id + // ", uid='" + uid + '\'' + // ", username='" + username + '\'' + // ", email='" + email + '\'' + // ", logo='" + logo + '\'' + // ", token='" + token + '\'' + // ", verified=" + verified + // ", last_usn=" + last_usn + // '}'; // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUid() { // return this.uid; // } // // public void setUid(String uid) { // this.uid = uid; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return this.email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getLogo() { // return this.logo; // } // // public void setLogo(String logo) { // this.logo = logo; // } // // public String getToken() { // return this.token; // } // // public void setToken(String token) { // this.token = token; // } // // public boolean getVerified() { // return this.verified; // } // // public void setVerified(boolean verified) { // this.verified = verified; // } // // public int getLast_usn() { // return this.last_usn; // } // // public void setLast_usn(int last_usn) { // this.last_usn = last_usn; // } // } // Path: app/src/main/java/com/tsy/leanote/feature/user/contract/UserContract.java import com.tsy.leanote.base.BaseInteractorCallback; import com.tsy.leanote.base.NormalInteractorCallback; import com.tsy.leanote.feature.user.bean.UserInfo; package com.tsy.leanote.feature.user.contract; /** * Created by tsy on 2016/12/13. */ public interface UserContract { interface Interactor { /** * 登录 * @param host * @param email * @param pwd * @param callback */ void login(String host, String email, String pwd, UserCallback callback); /** * 获取用户信息 * @param uid * @param token * @param callback */ void getUserInfo(String uid, String token, UserContract.UserCallback callback); /** * 获取当前用户 * @return */ UserInfo getCurUser(); /** * 注册 * @param host * @param email * @param pwd * @param callback */ void register(String host, String email, String pwd, UserCallback callback); /** * 退出 * @param userInfo 当前登录用户 * @param callback */
void logout(UserInfo userInfo, NormalInteractorCallback callback);
tsy12321/LeanoteAndroid
app/src/main/java/com/tsy/leanote/feature/user/contract/UserContract.java
// Path: app/src/main/java/com/tsy/leanote/base/BaseInteractorCallback.java // public interface BaseInteractorCallback { // void onFailure(String msg); // } // // Path: app/src/main/java/com/tsy/leanote/base/NormalInteractorCallback.java // public interface NormalInteractorCallback extends BaseInteractorCallback { // void onSuccess(); // } // // Path: app/src/main/java/com/tsy/leanote/feature/user/bean/UserInfo.java // @Entity // public class UserInfo { // @Id // private Long id; // @Unique // private String uid; // private String username; // private String email; // private String logo; // private String token; // private boolean verified; //邮箱是否认证 // private int last_usn; //上次同步usn // // @Generated(hash = 1860533007) // public UserInfo(Long id, String uid, String username, String email, String logo, // String token, boolean verified, int last_usn) { // this.id = id; // this.uid = uid; // this.username = username; // this.email = email; // this.logo = logo; // this.token = token; // this.verified = verified; // this.last_usn = last_usn; // } // // @Generated(hash = 1279772520) // public UserInfo() { // } // // @Override // public String toString() { // return "UserInfo{" + // "id=" + id + // ", uid='" + uid + '\'' + // ", username='" + username + '\'' + // ", email='" + email + '\'' + // ", logo='" + logo + '\'' + // ", token='" + token + '\'' + // ", verified=" + verified + // ", last_usn=" + last_usn + // '}'; // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUid() { // return this.uid; // } // // public void setUid(String uid) { // this.uid = uid; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return this.email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getLogo() { // return this.logo; // } // // public void setLogo(String logo) { // this.logo = logo; // } // // public String getToken() { // return this.token; // } // // public void setToken(String token) { // this.token = token; // } // // public boolean getVerified() { // return this.verified; // } // // public void setVerified(boolean verified) { // this.verified = verified; // } // // public int getLast_usn() { // return this.last_usn; // } // // public void setLast_usn(int last_usn) { // this.last_usn = last_usn; // } // }
import com.tsy.leanote.base.BaseInteractorCallback; import com.tsy.leanote.base.NormalInteractorCallback; import com.tsy.leanote.feature.user.bean.UserInfo;
package com.tsy.leanote.feature.user.contract; /** * Created by tsy on 2016/12/13. */ public interface UserContract { interface Interactor { /** * 登录 * @param host * @param email * @param pwd * @param callback */ void login(String host, String email, String pwd, UserCallback callback); /** * 获取用户信息 * @param uid * @param token * @param callback */ void getUserInfo(String uid, String token, UserContract.UserCallback callback); /** * 获取当前用户 * @return */ UserInfo getCurUser(); /** * 注册 * @param host * @param email * @param pwd * @param callback */ void register(String host, String email, String pwd, UserCallback callback); /** * 退出 * @param userInfo 当前登录用户 * @param callback */ void logout(UserInfo userInfo, NormalInteractorCallback callback); /** * 获取最新同步状态 * @param userInfo 当前登录用户 * @param callback */ void getSyncState(UserInfo userInfo, GetSyncStateCallback callback); /** * 更新最新的同步信息 * @param userInfo 当前登录用户 * @param lastSyncUsn 最新同步usn */ void updateLastSyncUsn(UserInfo userInfo, int lastSyncUsn); }
// Path: app/src/main/java/com/tsy/leanote/base/BaseInteractorCallback.java // public interface BaseInteractorCallback { // void onFailure(String msg); // } // // Path: app/src/main/java/com/tsy/leanote/base/NormalInteractorCallback.java // public interface NormalInteractorCallback extends BaseInteractorCallback { // void onSuccess(); // } // // Path: app/src/main/java/com/tsy/leanote/feature/user/bean/UserInfo.java // @Entity // public class UserInfo { // @Id // private Long id; // @Unique // private String uid; // private String username; // private String email; // private String logo; // private String token; // private boolean verified; //邮箱是否认证 // private int last_usn; //上次同步usn // // @Generated(hash = 1860533007) // public UserInfo(Long id, String uid, String username, String email, String logo, // String token, boolean verified, int last_usn) { // this.id = id; // this.uid = uid; // this.username = username; // this.email = email; // this.logo = logo; // this.token = token; // this.verified = verified; // this.last_usn = last_usn; // } // // @Generated(hash = 1279772520) // public UserInfo() { // } // // @Override // public String toString() { // return "UserInfo{" + // "id=" + id + // ", uid='" + uid + '\'' + // ", username='" + username + '\'' + // ", email='" + email + '\'' + // ", logo='" + logo + '\'' + // ", token='" + token + '\'' + // ", verified=" + verified + // ", last_usn=" + last_usn + // '}'; // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUid() { // return this.uid; // } // // public void setUid(String uid) { // this.uid = uid; // } // // public String getUsername() { // return this.username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getEmail() { // return this.email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getLogo() { // return this.logo; // } // // public void setLogo(String logo) { // this.logo = logo; // } // // public String getToken() { // return this.token; // } // // public void setToken(String token) { // this.token = token; // } // // public boolean getVerified() { // return this.verified; // } // // public void setVerified(boolean verified) { // this.verified = verified; // } // // public int getLast_usn() { // return this.last_usn; // } // // public void setLast_usn(int last_usn) { // this.last_usn = last_usn; // } // } // Path: app/src/main/java/com/tsy/leanote/feature/user/contract/UserContract.java import com.tsy.leanote.base.BaseInteractorCallback; import com.tsy.leanote.base.NormalInteractorCallback; import com.tsy.leanote.feature.user.bean.UserInfo; package com.tsy.leanote.feature.user.contract; /** * Created by tsy on 2016/12/13. */ public interface UserContract { interface Interactor { /** * 登录 * @param host * @param email * @param pwd * @param callback */ void login(String host, String email, String pwd, UserCallback callback); /** * 获取用户信息 * @param uid * @param token * @param callback */ void getUserInfo(String uid, String token, UserContract.UserCallback callback); /** * 获取当前用户 * @return */ UserInfo getCurUser(); /** * 注册 * @param host * @param email * @param pwd * @param callback */ void register(String host, String email, String pwd, UserCallback callback); /** * 退出 * @param userInfo 当前登录用户 * @param callback */ void logout(UserInfo userInfo, NormalInteractorCallback callback); /** * 获取最新同步状态 * @param userInfo 当前登录用户 * @param callback */ void getSyncState(UserInfo userInfo, GetSyncStateCallback callback); /** * 更新最新的同步信息 * @param userInfo 当前登录用户 * @param lastSyncUsn 最新同步usn */ void updateLastSyncUsn(UserInfo userInfo, int lastSyncUsn); }
interface UserCallback extends BaseInteractorCallback {
tsy12321/LeanoteAndroid
app/src/main/java/com/tsy/leanote/widget/webview/MyWebViewClient.java
// Path: app/src/main/java/com/tsy/leanote/widget/loadsir/ErrorCallback.java // public class ErrorCallback extends Callback { // @Override // protected int onCreateView() { // return R.layout.layout_error; // } // } // // Path: app/src/main/java/com/tsy/leanote/widget/loadsir/LoadingCallback.java // public class LoadingCallback extends Callback { // // @Override // protected int onCreateView() { // return R.layout.layout_loading; // } // // @Override // public boolean getSuccessVisible() { // return super.getSuccessVisible(); // } // // @Override // protected boolean onReloadEvent(Context context, View view) { // return true; // } // }
import android.graphics.Bitmap; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebView; import android.webkit.WebViewClient; import com.kingja.loadsir.core.LoadService; import com.tsy.leanote.widget.loadsir.ErrorCallback; import com.tsy.leanote.widget.loadsir.LoadingCallback;
package com.tsy.leanote.widget.webview; /** * custom webviewcilent * Created by tsy on 16/8/3. */ public class MyWebViewClient extends WebViewClient { private LoadService mLoadService; public MyWebViewClient(LoadService loadService) { mLoadService = loadService; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); view.getSettings().setBlockNetworkImage(false);
// Path: app/src/main/java/com/tsy/leanote/widget/loadsir/ErrorCallback.java // public class ErrorCallback extends Callback { // @Override // protected int onCreateView() { // return R.layout.layout_error; // } // } // // Path: app/src/main/java/com/tsy/leanote/widget/loadsir/LoadingCallback.java // public class LoadingCallback extends Callback { // // @Override // protected int onCreateView() { // return R.layout.layout_loading; // } // // @Override // public boolean getSuccessVisible() { // return super.getSuccessVisible(); // } // // @Override // protected boolean onReloadEvent(Context context, View view) { // return true; // } // } // Path: app/src/main/java/com/tsy/leanote/widget/webview/MyWebViewClient.java import android.graphics.Bitmap; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebView; import android.webkit.WebViewClient; import com.kingja.loadsir.core.LoadService; import com.tsy.leanote.widget.loadsir.ErrorCallback; import com.tsy.leanote.widget.loadsir.LoadingCallback; package com.tsy.leanote.widget.webview; /** * custom webviewcilent * Created by tsy on 16/8/3. */ public class MyWebViewClient extends WebViewClient { private LoadService mLoadService; public MyWebViewClient(LoadService loadService) { mLoadService = loadService; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); view.getSettings().setBlockNetworkImage(false);
if(mLoadService.getCurrentCallback().equals(LoadingCallback.class)) {
tsy12321/LeanoteAndroid
app/src/main/java/com/tsy/leanote/widget/webview/MyWebViewClient.java
// Path: app/src/main/java/com/tsy/leanote/widget/loadsir/ErrorCallback.java // public class ErrorCallback extends Callback { // @Override // protected int onCreateView() { // return R.layout.layout_error; // } // } // // Path: app/src/main/java/com/tsy/leanote/widget/loadsir/LoadingCallback.java // public class LoadingCallback extends Callback { // // @Override // protected int onCreateView() { // return R.layout.layout_loading; // } // // @Override // public boolean getSuccessVisible() { // return super.getSuccessVisible(); // } // // @Override // protected boolean onReloadEvent(Context context, View view) { // return true; // } // }
import android.graphics.Bitmap; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebView; import android.webkit.WebViewClient; import com.kingja.loadsir.core.LoadService; import com.tsy.leanote.widget.loadsir.ErrorCallback; import com.tsy.leanote.widget.loadsir.LoadingCallback;
package com.tsy.leanote.widget.webview; /** * custom webviewcilent * Created by tsy on 16/8/3. */ public class MyWebViewClient extends WebViewClient { private LoadService mLoadService; public MyWebViewClient(LoadService loadService) { mLoadService = loadService; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); view.getSettings().setBlockNetworkImage(false); if(mLoadService.getCurrentCallback().equals(LoadingCallback.class)) { mLoadService.showSuccess(); } } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); view.getSettings().setBlockNetworkImage(true); mLoadService.showCallback(LoadingCallback.class); } @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error);
// Path: app/src/main/java/com/tsy/leanote/widget/loadsir/ErrorCallback.java // public class ErrorCallback extends Callback { // @Override // protected int onCreateView() { // return R.layout.layout_error; // } // } // // Path: app/src/main/java/com/tsy/leanote/widget/loadsir/LoadingCallback.java // public class LoadingCallback extends Callback { // // @Override // protected int onCreateView() { // return R.layout.layout_loading; // } // // @Override // public boolean getSuccessVisible() { // return super.getSuccessVisible(); // } // // @Override // protected boolean onReloadEvent(Context context, View view) { // return true; // } // } // Path: app/src/main/java/com/tsy/leanote/widget/webview/MyWebViewClient.java import android.graphics.Bitmap; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebView; import android.webkit.WebViewClient; import com.kingja.loadsir.core.LoadService; import com.tsy.leanote.widget.loadsir.ErrorCallback; import com.tsy.leanote.widget.loadsir.LoadingCallback; package com.tsy.leanote.widget.webview; /** * custom webviewcilent * Created by tsy on 16/8/3. */ public class MyWebViewClient extends WebViewClient { private LoadService mLoadService; public MyWebViewClient(LoadService loadService) { mLoadService = loadService; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); view.getSettings().setBlockNetworkImage(false); if(mLoadService.getCurrentCallback().equals(LoadingCallback.class)) { mLoadService.showSuccess(); } } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); view.getSettings().setBlockNetworkImage(true); mLoadService.showCallback(LoadingCallback.class); } @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error);
mLoadService.showCallback(ErrorCallback.class);
tsy12321/LeanoteAndroid
app/src/main/java/com/tsy/leanote/widget/MarkdownPreviewView.java
// Path: app/src/main/java/com/tsy/leanote/widget/webview/WebviewActivity.java // public class WebviewActivity extends BaseActivity { // // @BindView(R.id.toolbar) // Toolbar mToolbar; // // private final static String EXTRA_URL_KEY = "url"; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // String url = getIntent().getStringExtra(EXTRA_URL_KEY); // if(StringUtils.isEmpty(url)) { // throw new IllegalArgumentException("empty url"); // } // // setContentView(R.layout.activity_webview); // ButterKnife.bind(this); // // mToolbar.setTitle(""); // setSupportActionBar(mToolbar); // ActionBar actionBar = getSupportActionBar(); // if (actionBar != null) { // getSupportActionBar().setDisplayHomeAsUpEnabled(true); // } // // FragmentManager fragmentManager = getSupportFragmentManager(); // FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); // // WebviewFragment webviewFragment = new WebviewFragment(); // webviewFragment.setArguments(WebviewFragment.createArguments(url)); // fragmentTransaction.add(R.id.fl_content, webviewFragment, "webview"); // fragmentTransaction.commit(); // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // case android.R.id.home: // onExit(); // break; // default: // break; // } // // return true; // } // // @Override // public void onBackPressed() { // onExit(); // } // // private void onExit() { // finish(); // } // // public static Intent createIntent(Context context, String url) { // Intent intent = new Intent(context, WebviewActivity.class); // intent.putExtra(EXTRA_URL_KEY, url); // return intent; // } // }
import com.tsy.leanote.widget.webview.WebviewActivity; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.net.Uri; import android.os.Build.VERSION; import android.support.v4.widget.NestedScrollView; import android.util.AttributeSet; import android.util.Log; import android.webkit.JavascriptInterface; import android.webkit.WebView; import android.webkit.WebViewClient;
private JavaScriptInterface(MarkdownPreviewView markdownPreviewView) { this.a = markdownPreviewView; } @JavascriptInterface public void none() { } } final class MdWebViewClient extends WebViewClient { final MarkdownPreviewView mMarkdownPreviewView; private MdWebViewClient(MarkdownPreviewView markdownPreviewView) { this.mMarkdownPreviewView = markdownPreviewView; } public final void onPageFinished(WebView webView, String str) { if (this.mMarkdownPreviewView.mLoadingFinishListener != null) { this.mMarkdownPreviewView.mLoadingFinishListener.onLoadingFinish(); } } public final void onReceivedError(WebView webView, int i, String str, String str2) { new StringBuilder("onReceivedError :errorCode:").append(i).append("description:").append(str).append("failingUrl").append(str2); } public final boolean shouldOverrideUrlLoading(WebView webView, String url) {
// Path: app/src/main/java/com/tsy/leanote/widget/webview/WebviewActivity.java // public class WebviewActivity extends BaseActivity { // // @BindView(R.id.toolbar) // Toolbar mToolbar; // // private final static String EXTRA_URL_KEY = "url"; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // String url = getIntent().getStringExtra(EXTRA_URL_KEY); // if(StringUtils.isEmpty(url)) { // throw new IllegalArgumentException("empty url"); // } // // setContentView(R.layout.activity_webview); // ButterKnife.bind(this); // // mToolbar.setTitle(""); // setSupportActionBar(mToolbar); // ActionBar actionBar = getSupportActionBar(); // if (actionBar != null) { // getSupportActionBar().setDisplayHomeAsUpEnabled(true); // } // // FragmentManager fragmentManager = getSupportFragmentManager(); // FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); // // WebviewFragment webviewFragment = new WebviewFragment(); // webviewFragment.setArguments(WebviewFragment.createArguments(url)); // fragmentTransaction.add(R.id.fl_content, webviewFragment, "webview"); // fragmentTransaction.commit(); // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // case android.R.id.home: // onExit(); // break; // default: // break; // } // // return true; // } // // @Override // public void onBackPressed() { // onExit(); // } // // private void onExit() { // finish(); // } // // public static Intent createIntent(Context context, String url) { // Intent intent = new Intent(context, WebviewActivity.class); // intent.putExtra(EXTRA_URL_KEY, url); // return intent; // } // } // Path: app/src/main/java/com/tsy/leanote/widget/MarkdownPreviewView.java import com.tsy.leanote.widget.webview.WebviewActivity; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.net.Uri; import android.os.Build.VERSION; import android.support.v4.widget.NestedScrollView; import android.util.AttributeSet; import android.util.Log; import android.webkit.JavascriptInterface; import android.webkit.WebView; import android.webkit.WebViewClient; private JavaScriptInterface(MarkdownPreviewView markdownPreviewView) { this.a = markdownPreviewView; } @JavascriptInterface public void none() { } } final class MdWebViewClient extends WebViewClient { final MarkdownPreviewView mMarkdownPreviewView; private MdWebViewClient(MarkdownPreviewView markdownPreviewView) { this.mMarkdownPreviewView = markdownPreviewView; } public final void onPageFinished(WebView webView, String str) { if (this.mMarkdownPreviewView.mLoadingFinishListener != null) { this.mMarkdownPreviewView.mLoadingFinishListener.onLoadingFinish(); } } public final void onReceivedError(WebView webView, int i, String str, String str2) { new StringBuilder("onReceivedError :errorCode:").append(i).append("description:").append(str).append("failingUrl").append(str2); } public final boolean shouldOverrideUrlLoading(WebView webView, String url) {
mContext.startActivity(WebviewActivity.createIntent(mMarkdownPreviewView.getContext(), url));
jenkinsci/analysis-core-plugin
src/test/java/hudson/plugins/analysis/util/LoggerFactoryTest.java
// Path: src/main/java/hudson/plugins/analysis/core/Settings.java // public interface Settings { // /** // * Returns whether the logger should be quite. If the logger is quite then the output is not shown in the // * console log. // * // * @return on <code>true</code> no logging statements are written to the console log // */ // Boolean getQuietMode(); // // /** // * Returns whether a build should be failed if the parsed input file is invalid or corrupted. // * // * @return on <code>true</code> the build will be failed, on <code>false</code> an error message is reported // */ // Boolean getFailOnCorrupt(); // // /** // * Returns whether author and commit information should be omitted. // * // * @return on <code>true</code> the SCM will not be called to obtain author and commit information, // * on <code>false</code> author and commit information are created // */ // Boolean getNoAuthors(); // }
import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.io.PrintStream; import org.junit.Test; import hudson.plugins.analysis.core.Settings;
package hudson.plugins.analysis.util; /** * TestCases for {@link PluginLogger}. * * @author Sebastian Seidl */ public class LoggerFactoryTest { /** * Tests if a "true" PluginLogger is created, when the Quiet Mode is deactivated. */ @Test public void quietModeDeactivated() { // Given
// Path: src/main/java/hudson/plugins/analysis/core/Settings.java // public interface Settings { // /** // * Returns whether the logger should be quite. If the logger is quite then the output is not shown in the // * console log. // * // * @return on <code>true</code> no logging statements are written to the console log // */ // Boolean getQuietMode(); // // /** // * Returns whether a build should be failed if the parsed input file is invalid or corrupted. // * // * @return on <code>true</code> the build will be failed, on <code>false</code> an error message is reported // */ // Boolean getFailOnCorrupt(); // // /** // * Returns whether author and commit information should be omitted. // * // * @return on <code>true</code> the SCM will not be called to obtain author and commit information, // * on <code>false</code> author and commit information are created // */ // Boolean getNoAuthors(); // } // Path: src/test/java/hudson/plugins/analysis/util/LoggerFactoryTest.java import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.io.PrintStream; import org.junit.Test; import hudson.plugins.analysis.core.Settings; package hudson.plugins.analysis.util; /** * TestCases for {@link PluginLogger}. * * @author Sebastian Seidl */ public class LoggerFactoryTest { /** * Tests if a "true" PluginLogger is created, when the Quiet Mode is deactivated. */ @Test public void quietModeDeactivated() { // Given
Settings settings = mock(Settings.class);
jenkinsci/analysis-core-plugin
src/test/java/hudson/plugins/analysis/core/IsOverriddenTest.java
// Path: src/main/java/hudson/plugins/analysis/util/Compatibility.java // public final class Compatibility { // // /** // * Util.isOverridden does not work on non-public methods, that's why this one is used here. // */ // public static boolean isOverridden(@Nonnull Class base, @Nonnull Class derived, @Nonnull String methodName, @Nonnull Class... types) { // try { // return !getMethod(base, methodName, types).equals(getMethod(derived, methodName, types)); // } catch (NoSuchMethodException e) { // throw new AssertionError(e); // } // } // // private static Method getMethod(@Nonnull Class clazz, @Nonnull String methodName, @Nonnull Class... types) throws NoSuchMethodException { // Method res = null; // try { // res = clazz.getDeclaredMethod(methodName, types); // } catch (NoSuchMethodException e) { // // Method not found in clazz, let's search in superclasses // Class superclass = clazz.getSuperclass(); // if (superclass != null) { // res = getMethod(superclass, methodName, types); // } // } catch (SecurityException e) { // throw new AssertionError(e); // } // if (res == null) { // throw new NoSuchMethodException("Method " + methodName + " not found in " + clazz.getName()); // } // return res; // } // // private Compatibility() {} // }
import static org.junit.Assert.*; import org.junit.Test; import hudson.plugins.analysis.util.Compatibility;
package hudson.plugins.analysis.core; /** * Test for {@link Compatibility.isOverridden} method. */ public class IsOverriddenTest { /** * Test that a method is found by isOverridden even when it is inherited from an intermediate class. */ @Test public void isOverriddenTest() {
// Path: src/main/java/hudson/plugins/analysis/util/Compatibility.java // public final class Compatibility { // // /** // * Util.isOverridden does not work on non-public methods, that's why this one is used here. // */ // public static boolean isOverridden(@Nonnull Class base, @Nonnull Class derived, @Nonnull String methodName, @Nonnull Class... types) { // try { // return !getMethod(base, methodName, types).equals(getMethod(derived, methodName, types)); // } catch (NoSuchMethodException e) { // throw new AssertionError(e); // } // } // // private static Method getMethod(@Nonnull Class clazz, @Nonnull String methodName, @Nonnull Class... types) throws NoSuchMethodException { // Method res = null; // try { // res = clazz.getDeclaredMethod(methodName, types); // } catch (NoSuchMethodException e) { // // Method not found in clazz, let's search in superclasses // Class superclass = clazz.getSuperclass(); // if (superclass != null) { // res = getMethod(superclass, methodName, types); // } // } catch (SecurityException e) { // throw new AssertionError(e); // } // if (res == null) { // throw new NoSuchMethodException("Method " + methodName + " not found in " + clazz.getName()); // } // return res; // } // // private Compatibility() {} // } // Path: src/test/java/hudson/plugins/analysis/core/IsOverriddenTest.java import static org.junit.Assert.*; import org.junit.Test; import hudson.plugins.analysis.util.Compatibility; package hudson.plugins.analysis.core; /** * Test for {@link Compatibility.isOverridden} method. */ public class IsOverriddenTest { /** * Test that a method is found by isOverridden even when it is inherited from an intermediate class. */ @Test public void isOverriddenTest() {
assertTrue(Compatibility.isOverridden(Base.class, Derived.class, "method"));
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerConnector.java
// Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/other/ConnectorType.java // public enum ConnectorType { // JERSEY, // NETTY, // OKHTTP // } // // Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/client/ClientBuilderForConnector.java // public static ClientBuilderForConnector newClientBuilderForConnector() { // return new ClientBuilderForConnector(); // }
import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardCredentials; import com.github.kostyasha.yad.connector.YADockerConnector; import com.github.kostyasha.yad.other.ConnectorType; import com.github.kostyasha.yad.utils.CredentialsListBoxModel; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.DockerClient; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.exception.DockerException; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.Version; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.core.DefaultDockerClientConfig; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.core.RemoteApiVersion; import com.github.kostyasha.yad_docker_java.com.google.common.base.Preconditions; import com.github.kostyasha.yad_docker_java.org.apache.commons.lang.StringUtils; import com.github.kostyasha.yad_docker_java.org.glassfish.jersey.client.ClientProperties; import com.google.common.base.Throwables; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.ItemGroup; import hudson.security.ACL; import hudson.security.AccessControlled; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import jenkins.model.Jenkins; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.interceptor.RequirePOST; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.servlet.ServletException; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Collections; import java.util.List; import static com.github.kostyasha.yad.client.ClientBuilderForConnector.newClientBuilderForConnector; import static com.github.kostyasha.yad.other.ConnectorType.NETTY; import static com.github.kostyasha.yad_docker_java.com.github.dockerjava.core.RemoteApiVersion.parseConfig; import static hudson.util.FormValidation.ok; import static hudson.util.FormValidation.warning; import static org.apache.commons.lang.builder.ToStringBuilder.reflectionToString; import static org.apache.commons.lang.builder.ToStringStyle.MULTI_LINE_STYLE;
package com.github.kostyasha.yad; /** * Settings for connecting to docker via docker-java configured connection. * * @author Kanstantsin Shautsou */ public class DockerConnector extends YADockerConnector { private static final long serialVersionUID = 1L; @CheckForNull private String serverUrl; @CheckForNull private String apiVersion; @CheckForNull private Boolean tlsVerify; @CheckForNull private String credentialsId = null; @CheckForNull
// Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/other/ConnectorType.java // public enum ConnectorType { // JERSEY, // NETTY, // OKHTTP // } // // Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/client/ClientBuilderForConnector.java // public static ClientBuilderForConnector newClientBuilderForConnector() { // return new ClientBuilderForConnector(); // } // Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerConnector.java import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardCredentials; import com.github.kostyasha.yad.connector.YADockerConnector; import com.github.kostyasha.yad.other.ConnectorType; import com.github.kostyasha.yad.utils.CredentialsListBoxModel; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.DockerClient; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.exception.DockerException; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.Version; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.core.DefaultDockerClientConfig; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.core.RemoteApiVersion; import com.github.kostyasha.yad_docker_java.com.google.common.base.Preconditions; import com.github.kostyasha.yad_docker_java.org.apache.commons.lang.StringUtils; import com.github.kostyasha.yad_docker_java.org.glassfish.jersey.client.ClientProperties; import com.google.common.base.Throwables; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.ItemGroup; import hudson.security.ACL; import hudson.security.AccessControlled; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import jenkins.model.Jenkins; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.interceptor.RequirePOST; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.servlet.ServletException; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Collections; import java.util.List; import static com.github.kostyasha.yad.client.ClientBuilderForConnector.newClientBuilderForConnector; import static com.github.kostyasha.yad.other.ConnectorType.NETTY; import static com.github.kostyasha.yad_docker_java.com.github.dockerjava.core.RemoteApiVersion.parseConfig; import static hudson.util.FormValidation.ok; import static hudson.util.FormValidation.warning; import static org.apache.commons.lang.builder.ToStringBuilder.reflectionToString; import static org.apache.commons.lang.builder.ToStringStyle.MULTI_LINE_STYLE; package com.github.kostyasha.yad; /** * Settings for connecting to docker via docker-java configured connection. * * @author Kanstantsin Shautsou */ public class DockerConnector extends YADockerConnector { private static final long serialVersionUID = 1L; @CheckForNull private String serverUrl; @CheckForNull private String apiVersion; @CheckForNull private Boolean tlsVerify; @CheckForNull private String credentialsId = null; @CheckForNull
private ConnectorType connectorType = NETTY;
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerConnector.java
// Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/other/ConnectorType.java // public enum ConnectorType { // JERSEY, // NETTY, // OKHTTP // } // // Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/client/ClientBuilderForConnector.java // public static ClientBuilderForConnector newClientBuilderForConnector() { // return new ClientBuilderForConnector(); // }
import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardCredentials; import com.github.kostyasha.yad.connector.YADockerConnector; import com.github.kostyasha.yad.other.ConnectorType; import com.github.kostyasha.yad.utils.CredentialsListBoxModel; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.DockerClient; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.exception.DockerException; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.Version; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.core.DefaultDockerClientConfig; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.core.RemoteApiVersion; import com.github.kostyasha.yad_docker_java.com.google.common.base.Preconditions; import com.github.kostyasha.yad_docker_java.org.apache.commons.lang.StringUtils; import com.github.kostyasha.yad_docker_java.org.glassfish.jersey.client.ClientProperties; import com.google.common.base.Throwables; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.ItemGroup; import hudson.security.ACL; import hudson.security.AccessControlled; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import jenkins.model.Jenkins; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.interceptor.RequirePOST; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.servlet.ServletException; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Collections; import java.util.List; import static com.github.kostyasha.yad.client.ClientBuilderForConnector.newClientBuilderForConnector; import static com.github.kostyasha.yad.other.ConnectorType.NETTY; import static com.github.kostyasha.yad_docker_java.com.github.dockerjava.core.RemoteApiVersion.parseConfig; import static hudson.util.FormValidation.ok; import static hudson.util.FormValidation.warning; import static org.apache.commons.lang.builder.ToStringBuilder.reflectionToString; import static org.apache.commons.lang.builder.ToStringStyle.MULTI_LINE_STYLE;
} @DataBoundSetter public void setConnectorType(ConnectorType connectorType) { this.connectorType = connectorType; } public Integer getConnectTimeout() { return connectTimeout; } @DataBoundSetter public void setConnectTimeout(Integer connectTimeout) { this.connectTimeout = connectTimeout; } @CheckForNull public Integer getReadTimeout() { return readTimeout; } /** * @see ClientProperties#READ_TIMEOUT */ @DataBoundSetter public void setReadTimeout(Integer readTimeout) { this.readTimeout = readTimeout; } public DockerClient getFreshClient() throws GeneralSecurityException {
// Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/other/ConnectorType.java // public enum ConnectorType { // JERSEY, // NETTY, // OKHTTP // } // // Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/client/ClientBuilderForConnector.java // public static ClientBuilderForConnector newClientBuilderForConnector() { // return new ClientBuilderForConnector(); // } // Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerConnector.java import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardCredentials; import com.github.kostyasha.yad.connector.YADockerConnector; import com.github.kostyasha.yad.other.ConnectorType; import com.github.kostyasha.yad.utils.CredentialsListBoxModel; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.DockerClient; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.exception.DockerException; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.Version; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.core.DefaultDockerClientConfig; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.core.RemoteApiVersion; import com.github.kostyasha.yad_docker_java.com.google.common.base.Preconditions; import com.github.kostyasha.yad_docker_java.org.apache.commons.lang.StringUtils; import com.github.kostyasha.yad_docker_java.org.glassfish.jersey.client.ClientProperties; import com.google.common.base.Throwables; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.ItemGroup; import hudson.security.ACL; import hudson.security.AccessControlled; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import jenkins.model.Jenkins; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.interceptor.RequirePOST; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.servlet.ServletException; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Collections; import java.util.List; import static com.github.kostyasha.yad.client.ClientBuilderForConnector.newClientBuilderForConnector; import static com.github.kostyasha.yad.other.ConnectorType.NETTY; import static com.github.kostyasha.yad_docker_java.com.github.dockerjava.core.RemoteApiVersion.parseConfig; import static hudson.util.FormValidation.ok; import static hudson.util.FormValidation.warning; import static org.apache.commons.lang.builder.ToStringBuilder.reflectionToString; import static org.apache.commons.lang.builder.ToStringStyle.MULTI_LINE_STYLE; } @DataBoundSetter public void setConnectorType(ConnectorType connectorType) { this.connectorType = connectorType; } public Integer getConnectTimeout() { return connectTimeout; } @DataBoundSetter public void setConnectTimeout(Integer connectTimeout) { this.connectTimeout = connectTimeout; } @CheckForNull public Integer getReadTimeout() { return readTimeout; } /** * @see ClientProperties#READ_TIMEOUT */ @DataBoundSetter public void setReadTimeout(Integer readTimeout) { this.readTimeout = readTimeout; } public DockerClient getFreshClient() throws GeneralSecurityException {
client = newClientBuilderForConnector()
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerSimpleBuildWrapper.java
// Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/utils/DockerUtils.java // public static void jenkinsAddNodeWithRetry(DockerSlaveSingle slave) throws IOException, // InterruptedException { // IOException lastException = null; // int retries = 6; // // while (retries >= 0) { // try { // Jenkins.getInstance().addNode(slave); // return; // } catch (IOException ex) { // lastException = ex; // if (retries <= 0) { // throw ex; // } // LOG.trace("Failed to add DockerSlaveSingle node to Jenkins, retrying...", ex); // Thread.sleep(1000); // } finally { // retries--; // } // } // // throw lastException; // }
import com.github.kostyasha.yad.connector.YADockerConnector; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.EnvVars; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractProject; import hudson.model.Computer; import hudson.model.Descriptor; import hudson.model.Node; import hudson.model.Run; import hudson.model.TaskListener; import hudson.slaves.DelegatingComputerLauncher; import hudson.tasks.BuildWrapperDescriptor; import jenkins.model.Jenkins; import jenkins.tasks.SimpleBuildWrapper; import org.jenkinsci.Symbol; import org.jenkinsci.plugins.cloudstats.CloudStatistics; import org.jenkinsci.plugins.cloudstats.ProvisioningActivity; import org.kohsuke.stapler.DataBoundConstructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import java.io.IOException; import java.io.PrintStream; import static com.github.kostyasha.yad.utils.DockerUtils.jenkinsAddNodeWithRetry; import static java.util.Objects.isNull; import static org.jenkinsci.plugins.cloudstats.CloudStatistics.ProvisioningListener.get;
@CheckForNull public String getSlaveName() { return slaveName; } protected void setSlaveName(String slaveName) { this.slaveName = slaveName; } @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") @Override public void setUp(Context context, Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener, EnvVars initialEnvironment) throws IOException, InterruptedException { PrintStream logger = listener.getLogger(); logger.println("Trying to setup env..."); final ProvisioningActivity.Id activityId = new ProvisioningActivity.Id( run.getDisplayName(), getConfig().getDockerContainerLifecycle().getImage() ); try { get().onStarted(activityId); final String futureName = "yadp" + activityId.getFingerprint();
// Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/utils/DockerUtils.java // public static void jenkinsAddNodeWithRetry(DockerSlaveSingle slave) throws IOException, // InterruptedException { // IOException lastException = null; // int retries = 6; // // while (retries >= 0) { // try { // Jenkins.getInstance().addNode(slave); // return; // } catch (IOException ex) { // lastException = ex; // if (retries <= 0) { // throw ex; // } // LOG.trace("Failed to add DockerSlaveSingle node to Jenkins, retrying...", ex); // Thread.sleep(1000); // } finally { // retries--; // } // } // // throw lastException; // } // Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerSimpleBuildWrapper.java import com.github.kostyasha.yad.connector.YADockerConnector; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.EnvVars; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractProject; import hudson.model.Computer; import hudson.model.Descriptor; import hudson.model.Node; import hudson.model.Run; import hudson.model.TaskListener; import hudson.slaves.DelegatingComputerLauncher; import hudson.tasks.BuildWrapperDescriptor; import jenkins.model.Jenkins; import jenkins.tasks.SimpleBuildWrapper; import org.jenkinsci.Symbol; import org.jenkinsci.plugins.cloudstats.CloudStatistics; import org.jenkinsci.plugins.cloudstats.ProvisioningActivity; import org.kohsuke.stapler.DataBoundConstructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import java.io.IOException; import java.io.PrintStream; import static com.github.kostyasha.yad.utils.DockerUtils.jenkinsAddNodeWithRetry; import static java.util.Objects.isNull; import static org.jenkinsci.plugins.cloudstats.CloudStatistics.ProvisioningListener.get; @CheckForNull public String getSlaveName() { return slaveName; } protected void setSlaveName(String slaveName) { this.slaveName = slaveName; } @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") @Override public void setUp(Context context, Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener, EnvVars initialEnvironment) throws IOException, InterruptedException { PrintStream logger = listener.getLogger(); logger.println("Trying to setup env..."); final ProvisioningActivity.Id activityId = new ProvisioningActivity.Id( run.getDisplayName(), getConfig().getDockerContainerLifecycle().getImage() ); try { get().onStarted(activityId); final String futureName = "yadp" + activityId.getFingerprint();
jenkinsAddNodeWithRetry(getDockerSlaveSingleWithRetry(run, activityId, futureName));
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerGlobalConfiguration.java
// Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/other/cloudorder/DockerCloudOrder.java // public abstract class DockerCloudOrder extends AbstractDescribableImpl<DockerCloudOrder> // implements ExtensionPoint { // // /** // * List of clouds that will be used for provisioning attempt one by one. // */ // @Nonnull // public abstract List<DockerCloud> getDockerClouds(Label label); // // @Override // public DockerCloudOrderDescriptor getDescriptor() { // return (DockerCloudOrderDescriptor) super.getDescriptor(); // } // // public abstract static class DockerCloudOrderDescriptor extends Descriptor<DockerCloudOrder> { // public static DescriptorExtensionList<DockerCloudOrder, DockerCloudOrderDescriptor> allDockerCloudOrderDescriptors() { // return Jenkins.getInstance().getDescriptorList(DockerCloudOrder.class); // } // } // // }
import com.github.kostyasha.yad.other.cloudorder.DockerCloudOrder; import hudson.Extension; import jenkins.model.GlobalConfiguration; import jenkins.model.Jenkins; import org.jenkinsci.Symbol; import javax.annotation.CheckForNull;
package com.github.kostyasha.yad; @Extension @Symbol("dockerSettings") public class DockerGlobalConfiguration extends GlobalConfiguration {
// Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/other/cloudorder/DockerCloudOrder.java // public abstract class DockerCloudOrder extends AbstractDescribableImpl<DockerCloudOrder> // implements ExtensionPoint { // // /** // * List of clouds that will be used for provisioning attempt one by one. // */ // @Nonnull // public abstract List<DockerCloud> getDockerClouds(Label label); // // @Override // public DockerCloudOrderDescriptor getDescriptor() { // return (DockerCloudOrderDescriptor) super.getDescriptor(); // } // // public abstract static class DockerCloudOrderDescriptor extends Descriptor<DockerCloudOrder> { // public static DescriptorExtensionList<DockerCloudOrder, DockerCloudOrderDescriptor> allDockerCloudOrderDescriptors() { // return Jenkins.getInstance().getDescriptorList(DockerCloudOrder.class); // } // } // // } // Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerGlobalConfiguration.java import com.github.kostyasha.yad.other.cloudorder.DockerCloudOrder; import hudson.Extension; import jenkins.model.GlobalConfiguration; import jenkins.model.Jenkins; import org.jenkinsci.Symbol; import javax.annotation.CheckForNull; package com.github.kostyasha.yad; @Extension @Symbol("dockerSettings") public class DockerGlobalConfiguration extends GlobalConfiguration {
private DockerCloudOrder cloudOrder;
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/commons/DockerPullImage.java
// Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/client/ClientBuilderForConnector.java // public static Credentials lookupSystemCredentials(String credentialsId) { // return firstOrNull( // lookupCredentials( // Credentials.class, // Jenkins.getInstance(), // ACL.SYSTEM, // emptyList() // ), // withId(credentialsId) // ); // }
import com.cloudbees.plugins.credentials.Credentials; import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardListBoxModel; import com.github.kostyasha.yad.NoStapler; import com.github.kostyasha.yad.connector.YADockerConnector; import com.github.kostyasha.yad.credentials.DockerRegistryAuthCredentials; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.DockerClient; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.command.PullImageCmd; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.exception.DockerClientException; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.exception.NotFoundException; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.Image; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.core.NameParser; import com.github.kostyasha.yad_docker_java.org.apache.commons.lang.StringUtils; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.model.Descriptor; import hudson.model.ItemGroup; import hudson.model.TaskListener; import hudson.security.ACL; import hudson.util.ListBoxModel; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import java.io.IOException; import java.io.PrintStream; import java.util.Arrays; import java.util.Collections; import java.util.List; import static com.github.kostyasha.yad.client.ClientBuilderForConnector.lookupSystemCredentials; import static java.util.Collections.emptyList; import static java.util.Objects.isNull; import static java.util.Objects.nonNull; import static org.apache.commons.lang.builder.ToStringStyle.SHORT_PREFIX_STYLE;
if (nonNull(connector)) { try (DockerClient altClient = connector.getClient()) { if (nonNull(altClient)) { LOG.debug("Using alternative client {} for {}", client, imageName); execInternal(altClient, imageName, listener); return; } } } execInternal(client, imageName, listener); } /** * Action around image with defined configuration */ public void execInternal(@Nonnull final DockerClient client, @Nonnull final String imageName, TaskListener listener) throws IOException { PrintStream llog = listener.getLogger(); if (shouldPullImage(client, imageName)) { LOG.info("Pulling image '{}'. This may take awhile...", imageName); llog.println(String.format("Pulling image '%s'. This may take awhile...", imageName)); long startTime = System.currentTimeMillis(); final PullImageCmd pullImageCmd = client.pullImageCmd(imageName); // final AuthConfig authConfig = pullImageCmd.getAuthConfig(); for (DockerRegistryCredential cred : getRegistriesCreds()) { // hostname requirements?
// Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/client/ClientBuilderForConnector.java // public static Credentials lookupSystemCredentials(String credentialsId) { // return firstOrNull( // lookupCredentials( // Credentials.class, // Jenkins.getInstance(), // ACL.SYSTEM, // emptyList() // ), // withId(credentialsId) // ); // } // Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/commons/DockerPullImage.java import com.cloudbees.plugins.credentials.Credentials; import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardListBoxModel; import com.github.kostyasha.yad.NoStapler; import com.github.kostyasha.yad.connector.YADockerConnector; import com.github.kostyasha.yad.credentials.DockerRegistryAuthCredentials; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.DockerClient; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.command.PullImageCmd; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.exception.DockerClientException; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.exception.NotFoundException; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.Image; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.core.NameParser; import com.github.kostyasha.yad_docker_java.org.apache.commons.lang.StringUtils; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.model.Descriptor; import hudson.model.ItemGroup; import hudson.model.TaskListener; import hudson.security.ACL; import hudson.util.ListBoxModel; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import java.io.IOException; import java.io.PrintStream; import java.util.Arrays; import java.util.Collections; import java.util.List; import static com.github.kostyasha.yad.client.ClientBuilderForConnector.lookupSystemCredentials; import static java.util.Collections.emptyList; import static java.util.Objects.isNull; import static java.util.Objects.nonNull; import static org.apache.commons.lang.builder.ToStringStyle.SHORT_PREFIX_STYLE; if (nonNull(connector)) { try (DockerClient altClient = connector.getClient()) { if (nonNull(altClient)) { LOG.debug("Using alternative client {} for {}", client, imageName); execInternal(altClient, imageName, listener); return; } } } execInternal(client, imageName, listener); } /** * Action around image with defined configuration */ public void execInternal(@Nonnull final DockerClient client, @Nonnull final String imageName, TaskListener listener) throws IOException { PrintStream llog = listener.getLogger(); if (shouldPullImage(client, imageName)) { LOG.info("Pulling image '{}'. This may take awhile...", imageName); llog.println(String.format("Pulling image '%s'. This may take awhile...", imageName)); long startTime = System.currentTimeMillis(); final PullImageCmd pullImageCmd = client.pullImageCmd(imageName); // final AuthConfig authConfig = pullImageCmd.getAuthConfig(); for (DockerRegistryCredential cred : getRegistriesCreds()) { // hostname requirements?
Credentials credentials = lookupSystemCredentials(cred.getCredentialsId());
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/utils/DockerUtils.java
// Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerSlaveSingle.java // @SuppressFBWarnings(value = "SE_BAD_FIELD", // justification = "Broken serialization https://issues.jenkins-ci.org/browse/JENKINS-31916") // public class DockerSlaveSingle extends AbstractCloudSlave implements TrackedItem { // private static final long serialVersionUID = 1L; // // private static final Logger LOG = LoggerFactory.getLogger(DockerSlaveSingle.class); // // private final YADockerConnector connector; // private final ProvisioningActivity.Id activityId; // private final DockerSlaveConfig config; // // private transient TaskListener listener = null; // // public DockerSlaveSingle(@Nonnull String name, // @Nonnull String nodeDescription, // @Nonnull DockerSlaveConfig config, // @Nonnull YADockerConnector connector, // @Nonnull ProvisioningActivity.Id activityId) // throws IOException, Descriptor.FormException { // super(name, nodeDescription, // config.getRemoteFs(), config.getNumExecutors(), config.getMode(), // "", // config.getLauncher(), config.getRetentionStrategy(), config.getNodeProperties()); // this.connector = connector; // this.activityId = activityId; // this.config = config; // // } // // public YADockerConnector getConnector() { // return connector; // } // // public DockerSlaveConfig getConfig() { // return config; // } // // @Override // public DelegatingComputerLauncher getLauncher() { // return (DelegatingComputerLauncher) super.getLauncher(); // } // // private String getContainerId() { // return ((DockerComputerSingleJNLPLauncher) getLauncher().getLauncher()).getContainerId(); // } // // @Nonnull // public TaskListener getListener() { // return nonNull(listener) ? listener : new StreamTaskListener(System.out, Charset.forName("UTF-8")); // } // // /** // * Set listener that will be used for printing out messages instead default listener. // */ // public void setListener(TaskListener listener) { // this.listener = listener; // } // // @Override // public AbstractCloudComputer createComputer() { // return new DockerComputerSingle(this, activityId); // } // // // @Override // public void terminate() throws InterruptedException, IOException { // try { // _terminate(getListener()); // } finally { // try { // Jenkins.getInstance().removeNode(this); // } catch (IOException e) { // LOG.warn("Failed to remove {}", name, e); // getListener().error("Failed to remove " + name); // } // } // } // // @Override // protected void _terminate(TaskListener listener) throws IOException, InterruptedException { // final DockerContainerLifecycle dockerContainerLifecycle = config.getDockerContainerLifecycle(); // try { // LOG.info("Requesting disconnect for computer: '{}'", name); // final Computer toComputer = toComputer(); // if (toComputer != null) { // toComputer.disconnect(new DockerOfflineCause("Terminating from _terminate.")); // } // } catch (Exception e) { // LOG.error("Can't disconnect computer: '{}'", name, e); // listener.error("Can't disconnect computer: " + name); // } // // if (StringUtils.isNotBlank(getContainerId())) { // try { // dockerContainerLifecycle.getStopContainer().exec(connector.getClient(), getContainerId()); // LOG.info("Stopped container {}", getContainerId()); // listener.getLogger().println("Stopped container " + getContainerId()); // } catch (NotModifiedException ex) { // LOG.info("Container '{}' is already stopped.", getContainerId()); // } catch (Exception ex) { // LOG.error("Failed to stop instance '{}' for slave '{}' due to exception: {}", // getContainerId(), name, ex.getMessage()); // } // // final Computer computer = toComputer(); // if (computer instanceof DockerComputerSingle) { // final DockerComputerSingle dockerComputer = (DockerComputerSingle) computer; // for (DockerTerminateCmdAction a : dockerComputer.getActions(DockerTerminateCmdAction.class)) { // try { // a.exec(connector.getClient(), getContainerId()); // } catch (Exception e) { // LOG.error("Failed execute action {}", a, e); // listener.error("Failed execute " + a.getDisplayName()); // } // } // } else { // LOG.error("Computer '{}' is not DockerComputerSingle", computer); // listener.error("Computer ' " + computer + "' is not DockerComputerSingle", computer); // } // // try { // dockerContainerLifecycle.getRemoveContainer().exec(connector.getClient(), getContainerId()); // LOG.info("Removed container {}", getContainerId()); // listener.getLogger().println("Removed container " + getContainerId()); // } catch (Exception ex) { // String inProgress = "removal of container " + getContainerId() + " is already in progress"; // if (ex.getMessage().contains(inProgress)) { // LOG.debug("Removing", ex); // listener.getLogger().println(inProgress); // } else { // LOG.error("Failed to remove instance '{}' for slave '{}' due to exception: {}", // getContainerId(), name, ex.getMessage()); // listener.error("failed to remove " + getContainerId()); // } // } // } else { // LOG.error("ContainerId is absent, no way to remove/stop container"); // listener.error("ContainerId is absent, no way to remove/stop container"); // } // // ProvisioningActivity activity = CloudStatistics.get().getActivityFor(this); // if (nonNull(activity)) { // activity.enterIfNotAlready(ProvisioningActivity.Phase.COMPLETED); // } // } // // @Nonnull // @Override // public ProvisioningActivity.Id getId() { // return activityId; // } // }
import com.github.kostyasha.yad.DockerSlaveSingle; import jenkins.model.Jenkins; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException;
package com.github.kostyasha.yad.utils; public class DockerUtils { private static final Logger LOG = LoggerFactory.getLogger(DockerUtils.class); private DockerUtils() { }
// Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerSlaveSingle.java // @SuppressFBWarnings(value = "SE_BAD_FIELD", // justification = "Broken serialization https://issues.jenkins-ci.org/browse/JENKINS-31916") // public class DockerSlaveSingle extends AbstractCloudSlave implements TrackedItem { // private static final long serialVersionUID = 1L; // // private static final Logger LOG = LoggerFactory.getLogger(DockerSlaveSingle.class); // // private final YADockerConnector connector; // private final ProvisioningActivity.Id activityId; // private final DockerSlaveConfig config; // // private transient TaskListener listener = null; // // public DockerSlaveSingle(@Nonnull String name, // @Nonnull String nodeDescription, // @Nonnull DockerSlaveConfig config, // @Nonnull YADockerConnector connector, // @Nonnull ProvisioningActivity.Id activityId) // throws IOException, Descriptor.FormException { // super(name, nodeDescription, // config.getRemoteFs(), config.getNumExecutors(), config.getMode(), // "", // config.getLauncher(), config.getRetentionStrategy(), config.getNodeProperties()); // this.connector = connector; // this.activityId = activityId; // this.config = config; // // } // // public YADockerConnector getConnector() { // return connector; // } // // public DockerSlaveConfig getConfig() { // return config; // } // // @Override // public DelegatingComputerLauncher getLauncher() { // return (DelegatingComputerLauncher) super.getLauncher(); // } // // private String getContainerId() { // return ((DockerComputerSingleJNLPLauncher) getLauncher().getLauncher()).getContainerId(); // } // // @Nonnull // public TaskListener getListener() { // return nonNull(listener) ? listener : new StreamTaskListener(System.out, Charset.forName("UTF-8")); // } // // /** // * Set listener that will be used for printing out messages instead default listener. // */ // public void setListener(TaskListener listener) { // this.listener = listener; // } // // @Override // public AbstractCloudComputer createComputer() { // return new DockerComputerSingle(this, activityId); // } // // // @Override // public void terminate() throws InterruptedException, IOException { // try { // _terminate(getListener()); // } finally { // try { // Jenkins.getInstance().removeNode(this); // } catch (IOException e) { // LOG.warn("Failed to remove {}", name, e); // getListener().error("Failed to remove " + name); // } // } // } // // @Override // protected void _terminate(TaskListener listener) throws IOException, InterruptedException { // final DockerContainerLifecycle dockerContainerLifecycle = config.getDockerContainerLifecycle(); // try { // LOG.info("Requesting disconnect for computer: '{}'", name); // final Computer toComputer = toComputer(); // if (toComputer != null) { // toComputer.disconnect(new DockerOfflineCause("Terminating from _terminate.")); // } // } catch (Exception e) { // LOG.error("Can't disconnect computer: '{}'", name, e); // listener.error("Can't disconnect computer: " + name); // } // // if (StringUtils.isNotBlank(getContainerId())) { // try { // dockerContainerLifecycle.getStopContainer().exec(connector.getClient(), getContainerId()); // LOG.info("Stopped container {}", getContainerId()); // listener.getLogger().println("Stopped container " + getContainerId()); // } catch (NotModifiedException ex) { // LOG.info("Container '{}' is already stopped.", getContainerId()); // } catch (Exception ex) { // LOG.error("Failed to stop instance '{}' for slave '{}' due to exception: {}", // getContainerId(), name, ex.getMessage()); // } // // final Computer computer = toComputer(); // if (computer instanceof DockerComputerSingle) { // final DockerComputerSingle dockerComputer = (DockerComputerSingle) computer; // for (DockerTerminateCmdAction a : dockerComputer.getActions(DockerTerminateCmdAction.class)) { // try { // a.exec(connector.getClient(), getContainerId()); // } catch (Exception e) { // LOG.error("Failed execute action {}", a, e); // listener.error("Failed execute " + a.getDisplayName()); // } // } // } else { // LOG.error("Computer '{}' is not DockerComputerSingle", computer); // listener.error("Computer ' " + computer + "' is not DockerComputerSingle", computer); // } // // try { // dockerContainerLifecycle.getRemoveContainer().exec(connector.getClient(), getContainerId()); // LOG.info("Removed container {}", getContainerId()); // listener.getLogger().println("Removed container " + getContainerId()); // } catch (Exception ex) { // String inProgress = "removal of container " + getContainerId() + " is already in progress"; // if (ex.getMessage().contains(inProgress)) { // LOG.debug("Removing", ex); // listener.getLogger().println(inProgress); // } else { // LOG.error("Failed to remove instance '{}' for slave '{}' due to exception: {}", // getContainerId(), name, ex.getMessage()); // listener.error("failed to remove " + getContainerId()); // } // } // } else { // LOG.error("ContainerId is absent, no way to remove/stop container"); // listener.error("ContainerId is absent, no way to remove/stop container"); // } // // ProvisioningActivity activity = CloudStatistics.get().getActivityFor(this); // if (nonNull(activity)) { // activity.enterIfNotAlready(ProvisioningActivity.Phase.COMPLETED); // } // } // // @Nonnull // @Override // public ProvisioningActivity.Id getId() { // return activityId; // } // } // Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/utils/DockerUtils.java import com.github.kostyasha.yad.DockerSlaveSingle; import jenkins.model.Jenkins; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; package com.github.kostyasha.yad.utils; public class DockerUtils { private static final Logger LOG = LoggerFactory.getLogger(DockerUtils.class); private DockerUtils() { }
public static void jenkinsAddNodeWithRetry(DockerSlaveSingle slave) throws IOException,
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/commons/DockerCreateContainer.java
// Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/utils/BindUtils.java // @Nonnull // public static String joinToStr(List<String> joinList) { // // with null check // if (CollectionUtils.isEmpty(joinList)) { // return ""; // } // // return Joiner.on("\n").join(joinList); // } // // Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/utils/BindUtils.java // @Nonnull // public static List<String> splitAndFilterEmpty(@Nonnull String s) { // return splitAndFilterEmpty(s, "\n"); // }
import com.cloudbees.jenkins.plugins.sshcredentials.SSHAuthenticator; import com.cloudbees.jenkins.plugins.sshcredentials.SSHUserListBoxModel; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.command.CreateContainerCmd; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.Bind; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.Device; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.HostConfig; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.Link; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.PortBinding; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.Volume; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.VolumesFrom; import com.github.kostyasha.yad_docker_java.com.google.common.base.Function; import com.github.kostyasha.yad_docker_java.com.google.common.base.Splitter; import com.github.kostyasha.yad_docker_java.com.google.common.base.Strings; import com.github.kostyasha.yad_docker_java.com.google.common.collect.Iterables; import com.trilead.ssh2.Connection; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.model.Descriptor; import hudson.model.ItemGroup; import hudson.plugins.sshslaves.SSHLauncher; import hudson.security.ACL; import hudson.security.AccessControlled; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import jenkins.model.Jenkins; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.QueryParameter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.CheckForNull; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import static com.github.kostyasha.yad.commons.DockerContainerRestartPolicyName.NO; import static com.github.kostyasha.yad.utils.BindUtils.joinToStr; import static com.github.kostyasha.yad.utils.BindUtils.splitAndFilterEmpty; import static java.util.Objects.isNull; import static java.util.Objects.nonNull; import static org.apache.commons.lang.StringUtils.trimToNull; import static org.apache.commons.lang.builder.ToStringStyle.SHORT_PREFIX_STYLE;
.omitEmptyStrings() .split(bindPorts), new PortBindingFunction() ); } private static class PortBindingFunction implements Function<String, PortBinding> { @Nullable public PortBinding apply(String s) { return PortBinding.parse(s); } } @DataBoundSetter public void setBindPorts(String bindPorts) { this.bindPorts = bindPorts; } // dns hosts @CheckForNull public List<String> getDnsHosts() { return dnsHosts; } public void setDnsHosts(List<String> dnsHosts) { this.dnsHosts = dnsHosts; } @Nonnull public String getDnsString() {
// Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/utils/BindUtils.java // @Nonnull // public static String joinToStr(List<String> joinList) { // // with null check // if (CollectionUtils.isEmpty(joinList)) { // return ""; // } // // return Joiner.on("\n").join(joinList); // } // // Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/utils/BindUtils.java // @Nonnull // public static List<String> splitAndFilterEmpty(@Nonnull String s) { // return splitAndFilterEmpty(s, "\n"); // } // Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/commons/DockerCreateContainer.java import com.cloudbees.jenkins.plugins.sshcredentials.SSHAuthenticator; import com.cloudbees.jenkins.plugins.sshcredentials.SSHUserListBoxModel; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.command.CreateContainerCmd; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.Bind; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.Device; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.HostConfig; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.Link; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.PortBinding; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.Volume; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.VolumesFrom; import com.github.kostyasha.yad_docker_java.com.google.common.base.Function; import com.github.kostyasha.yad_docker_java.com.google.common.base.Splitter; import com.github.kostyasha.yad_docker_java.com.google.common.base.Strings; import com.github.kostyasha.yad_docker_java.com.google.common.collect.Iterables; import com.trilead.ssh2.Connection; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.model.Descriptor; import hudson.model.ItemGroup; import hudson.plugins.sshslaves.SSHLauncher; import hudson.security.ACL; import hudson.security.AccessControlled; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import jenkins.model.Jenkins; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.QueryParameter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.CheckForNull; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import static com.github.kostyasha.yad.commons.DockerContainerRestartPolicyName.NO; import static com.github.kostyasha.yad.utils.BindUtils.joinToStr; import static com.github.kostyasha.yad.utils.BindUtils.splitAndFilterEmpty; import static java.util.Objects.isNull; import static java.util.Objects.nonNull; import static org.apache.commons.lang.StringUtils.trimToNull; import static org.apache.commons.lang.builder.ToStringStyle.SHORT_PREFIX_STYLE; .omitEmptyStrings() .split(bindPorts), new PortBindingFunction() ); } private static class PortBindingFunction implements Function<String, PortBinding> { @Nullable public PortBinding apply(String s) { return PortBinding.parse(s); } } @DataBoundSetter public void setBindPorts(String bindPorts) { this.bindPorts = bindPorts; } // dns hosts @CheckForNull public List<String> getDnsHosts() { return dnsHosts; } public void setDnsHosts(List<String> dnsHosts) { this.dnsHosts = dnsHosts; } @Nonnull public String getDnsString() {
return joinToStr(dnsHosts);
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/commons/DockerCreateContainer.java
// Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/utils/BindUtils.java // @Nonnull // public static String joinToStr(List<String> joinList) { // // with null check // if (CollectionUtils.isEmpty(joinList)) { // return ""; // } // // return Joiner.on("\n").join(joinList); // } // // Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/utils/BindUtils.java // @Nonnull // public static List<String> splitAndFilterEmpty(@Nonnull String s) { // return splitAndFilterEmpty(s, "\n"); // }
import com.cloudbees.jenkins.plugins.sshcredentials.SSHAuthenticator; import com.cloudbees.jenkins.plugins.sshcredentials.SSHUserListBoxModel; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.command.CreateContainerCmd; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.Bind; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.Device; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.HostConfig; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.Link; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.PortBinding; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.Volume; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.VolumesFrom; import com.github.kostyasha.yad_docker_java.com.google.common.base.Function; import com.github.kostyasha.yad_docker_java.com.google.common.base.Splitter; import com.github.kostyasha.yad_docker_java.com.google.common.base.Strings; import com.github.kostyasha.yad_docker_java.com.google.common.collect.Iterables; import com.trilead.ssh2.Connection; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.model.Descriptor; import hudson.model.ItemGroup; import hudson.plugins.sshslaves.SSHLauncher; import hudson.security.ACL; import hudson.security.AccessControlled; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import jenkins.model.Jenkins; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.QueryParameter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.CheckForNull; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import static com.github.kostyasha.yad.commons.DockerContainerRestartPolicyName.NO; import static com.github.kostyasha.yad.utils.BindUtils.joinToStr; import static com.github.kostyasha.yad.utils.BindUtils.splitAndFilterEmpty; import static java.util.Objects.isNull; import static java.util.Objects.nonNull; import static org.apache.commons.lang.StringUtils.trimToNull; import static org.apache.commons.lang.builder.ToStringStyle.SHORT_PREFIX_STYLE;
private static class PortBindingFunction implements Function<String, PortBinding> { @Nullable public PortBinding apply(String s) { return PortBinding.parse(s); } } @DataBoundSetter public void setBindPorts(String bindPorts) { this.bindPorts = bindPorts; } // dns hosts @CheckForNull public List<String> getDnsHosts() { return dnsHosts; } public void setDnsHosts(List<String> dnsHosts) { this.dnsHosts = dnsHosts; } @Nonnull public String getDnsString() { return joinToStr(dnsHosts); } @DataBoundSetter public void setDnsString(String dnsString) {
// Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/utils/BindUtils.java // @Nonnull // public static String joinToStr(List<String> joinList) { // // with null check // if (CollectionUtils.isEmpty(joinList)) { // return ""; // } // // return Joiner.on("\n").join(joinList); // } // // Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/utils/BindUtils.java // @Nonnull // public static List<String> splitAndFilterEmpty(@Nonnull String s) { // return splitAndFilterEmpty(s, "\n"); // } // Path: yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/commons/DockerCreateContainer.java import com.cloudbees.jenkins.plugins.sshcredentials.SSHAuthenticator; import com.cloudbees.jenkins.plugins.sshcredentials.SSHUserListBoxModel; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.command.CreateContainerCmd; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.Bind; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.Device; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.HostConfig; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.Link; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.PortBinding; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.Volume; import com.github.kostyasha.yad_docker_java.com.github.dockerjava.api.model.VolumesFrom; import com.github.kostyasha.yad_docker_java.com.google.common.base.Function; import com.github.kostyasha.yad_docker_java.com.google.common.base.Splitter; import com.github.kostyasha.yad_docker_java.com.google.common.base.Strings; import com.github.kostyasha.yad_docker_java.com.google.common.collect.Iterables; import com.trilead.ssh2.Connection; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.model.Descriptor; import hudson.model.ItemGroup; import hudson.plugins.sshslaves.SSHLauncher; import hudson.security.ACL; import hudson.security.AccessControlled; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import jenkins.model.Jenkins; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.QueryParameter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.CheckForNull; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import static com.github.kostyasha.yad.commons.DockerContainerRestartPolicyName.NO; import static com.github.kostyasha.yad.utils.BindUtils.joinToStr; import static com.github.kostyasha.yad.utils.BindUtils.splitAndFilterEmpty; import static java.util.Objects.isNull; import static java.util.Objects.nonNull; import static org.apache.commons.lang.StringUtils.trimToNull; import static org.apache.commons.lang.builder.ToStringStyle.SHORT_PREFIX_STYLE; private static class PortBindingFunction implements Function<String, PortBinding> { @Nullable public PortBinding apply(String s) { return PortBinding.parse(s); } } @DataBoundSetter public void setBindPorts(String bindPorts) { this.bindPorts = bindPorts; } // dns hosts @CheckForNull public List<String> getDnsHosts() { return dnsHosts; } public void setDnsHosts(List<String> dnsHosts) { this.dnsHosts = dnsHosts; } @Nonnull public String getDnsString() { return joinToStr(dnsHosts); } @DataBoundSetter public void setDnsString(String dnsString) {
setDnsHosts(splitAndFilterEmpty(dnsString));
tomikaa87/gree-remote
GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/MyDeviceItemRecyclerViewAdapter.java
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/DeviceItemFragment.java // public interface OnListFragmentInteractionListener { // // TODO: Update argument type and name // void onListFragmentInteraction(DeviceItem item); // }
import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import java.util.List; import tomikaa.greeremote.DeviceItemFragment.OnListFragmentInteractionListener;
package tomikaa.greeremote; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-10-23. */ /** * {@link RecyclerView.Adapter} that can display a {@link DeviceItem} and makes a call to the * specified {@link OnListFragmentInteractionListener}. * TODO: Replace the implementation with code for your data type. */ public class MyDeviceItemRecyclerViewAdapter extends RecyclerView.Adapter<MyDeviceItemRecyclerViewAdapter.ViewHolder> { private final List<DeviceItem> mValues;
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/DeviceItemFragment.java // public interface OnListFragmentInteractionListener { // // TODO: Update argument type and name // void onListFragmentInteraction(DeviceItem item); // } // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/MyDeviceItemRecyclerViewAdapter.java import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import java.util.List; import tomikaa.greeremote.DeviceItemFragment.OnListFragmentInteractionListener; package tomikaa.greeremote; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-10-23. */ /** * {@link RecyclerView.Adapter} that can display a {@link DeviceItem} and makes a call to the * specified {@link OnListFragmentInteractionListener}. * TODO: Replace the implementation with code for your data type. */ public class MyDeviceItemRecyclerViewAdapter extends RecyclerView.Adapter<MyDeviceItemRecyclerViewAdapter.ViewHolder> { private final List<DeviceItem> mValues;
private final OnListFragmentInteractionListener mListener;
tomikaa87/gree-remote
GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Deserializers/PackDeserializer.java
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindOkPack.java // public class BindOkPack extends Pack { // public static String TYPE = "bindok"; // // public String key; // // @SerializedName("r") // public int resultCode; // // public BindOkPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindPack.java // public class BindPack extends Pack { // public static String TYPE = "bind"; // // public int uid; // // public BindPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DevicePack.java // public class DevicePack extends Pack { // public static String TYPE = "dev"; // // public String cid; // public String bc; // public String brand; // public String catalog; // public String mid; // public String model; // public String name; // public String series; // public String ver; // public Integer lock; // // @SerializedName("vender") // public String vendor; // // public DevicePack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/ResultPack.java // public class ResultPack extends Pack { // public static String TYPE = "res"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("opt") // public String[] keys; // // @SerializedName("p") // public Integer[] values; // // public ResultPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/StatusPack.java // public class StatusPack extends Pack { // public static String TYPE = "status"; // // @SerializedName("cols") // public String[] keys; // // public StatusPack() { // type = TYPE; // } // }
import tomikaa.greeremote.Gree.Packs.BindOkPack; import tomikaa.greeremote.Gree.Packs.BindPack; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.DevicePack; import tomikaa.greeremote.Gree.Packs.Pack; import tomikaa.greeremote.Gree.Packs.ResultPack; import tomikaa.greeremote.Gree.Packs.StatusPack; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import java.lang.reflect.Type;
package tomikaa.greeremote.Gree.Deserializers; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-11-26. */ public class PackDeserializer implements JsonDeserializer<Pack> { @Override public Pack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject jsonObject = jsonElement.getAsJsonObject(); String packType = jsonObject.get("t").getAsString();
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindOkPack.java // public class BindOkPack extends Pack { // public static String TYPE = "bindok"; // // public String key; // // @SerializedName("r") // public int resultCode; // // public BindOkPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindPack.java // public class BindPack extends Pack { // public static String TYPE = "bind"; // // public int uid; // // public BindPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DevicePack.java // public class DevicePack extends Pack { // public static String TYPE = "dev"; // // public String cid; // public String bc; // public String brand; // public String catalog; // public String mid; // public String model; // public String name; // public String series; // public String ver; // public Integer lock; // // @SerializedName("vender") // public String vendor; // // public DevicePack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/ResultPack.java // public class ResultPack extends Pack { // public static String TYPE = "res"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("opt") // public String[] keys; // // @SerializedName("p") // public Integer[] values; // // public ResultPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/StatusPack.java // public class StatusPack extends Pack { // public static String TYPE = "status"; // // @SerializedName("cols") // public String[] keys; // // public StatusPack() { // type = TYPE; // } // } // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Deserializers/PackDeserializer.java import tomikaa.greeremote.Gree.Packs.BindOkPack; import tomikaa.greeremote.Gree.Packs.BindPack; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.DevicePack; import tomikaa.greeremote.Gree.Packs.Pack; import tomikaa.greeremote.Gree.Packs.ResultPack; import tomikaa.greeremote.Gree.Packs.StatusPack; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import java.lang.reflect.Type; package tomikaa.greeremote.Gree.Deserializers; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-11-26. */ public class PackDeserializer implements JsonDeserializer<Pack> { @Override public Pack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject jsonObject = jsonElement.getAsJsonObject(); String packType = jsonObject.get("t").getAsString();
if (packType.equalsIgnoreCase(BindOkPack.TYPE)) {
tomikaa87/gree-remote
GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Deserializers/PackDeserializer.java
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindOkPack.java // public class BindOkPack extends Pack { // public static String TYPE = "bindok"; // // public String key; // // @SerializedName("r") // public int resultCode; // // public BindOkPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindPack.java // public class BindPack extends Pack { // public static String TYPE = "bind"; // // public int uid; // // public BindPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DevicePack.java // public class DevicePack extends Pack { // public static String TYPE = "dev"; // // public String cid; // public String bc; // public String brand; // public String catalog; // public String mid; // public String model; // public String name; // public String series; // public String ver; // public Integer lock; // // @SerializedName("vender") // public String vendor; // // public DevicePack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/ResultPack.java // public class ResultPack extends Pack { // public static String TYPE = "res"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("opt") // public String[] keys; // // @SerializedName("p") // public Integer[] values; // // public ResultPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/StatusPack.java // public class StatusPack extends Pack { // public static String TYPE = "status"; // // @SerializedName("cols") // public String[] keys; // // public StatusPack() { // type = TYPE; // } // }
import tomikaa.greeremote.Gree.Packs.BindOkPack; import tomikaa.greeremote.Gree.Packs.BindPack; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.DevicePack; import tomikaa.greeremote.Gree.Packs.Pack; import tomikaa.greeremote.Gree.Packs.ResultPack; import tomikaa.greeremote.Gree.Packs.StatusPack; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import java.lang.reflect.Type;
package tomikaa.greeremote.Gree.Deserializers; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-11-26. */ public class PackDeserializer implements JsonDeserializer<Pack> { @Override public Pack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject jsonObject = jsonElement.getAsJsonObject(); String packType = jsonObject.get("t").getAsString(); if (packType.equalsIgnoreCase(BindOkPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, BindOkPack.class);
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindOkPack.java // public class BindOkPack extends Pack { // public static String TYPE = "bindok"; // // public String key; // // @SerializedName("r") // public int resultCode; // // public BindOkPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindPack.java // public class BindPack extends Pack { // public static String TYPE = "bind"; // // public int uid; // // public BindPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DevicePack.java // public class DevicePack extends Pack { // public static String TYPE = "dev"; // // public String cid; // public String bc; // public String brand; // public String catalog; // public String mid; // public String model; // public String name; // public String series; // public String ver; // public Integer lock; // // @SerializedName("vender") // public String vendor; // // public DevicePack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/ResultPack.java // public class ResultPack extends Pack { // public static String TYPE = "res"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("opt") // public String[] keys; // // @SerializedName("p") // public Integer[] values; // // public ResultPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/StatusPack.java // public class StatusPack extends Pack { // public static String TYPE = "status"; // // @SerializedName("cols") // public String[] keys; // // public StatusPack() { // type = TYPE; // } // } // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Deserializers/PackDeserializer.java import tomikaa.greeremote.Gree.Packs.BindOkPack; import tomikaa.greeremote.Gree.Packs.BindPack; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.DevicePack; import tomikaa.greeremote.Gree.Packs.Pack; import tomikaa.greeremote.Gree.Packs.ResultPack; import tomikaa.greeremote.Gree.Packs.StatusPack; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import java.lang.reflect.Type; package tomikaa.greeremote.Gree.Deserializers; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-11-26. */ public class PackDeserializer implements JsonDeserializer<Pack> { @Override public Pack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject jsonObject = jsonElement.getAsJsonObject(); String packType = jsonObject.get("t").getAsString(); if (packType.equalsIgnoreCase(BindOkPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, BindOkPack.class);
} else if (packType.equalsIgnoreCase(BindPack.TYPE)) {
tomikaa87/gree-remote
GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Deserializers/PackDeserializer.java
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindOkPack.java // public class BindOkPack extends Pack { // public static String TYPE = "bindok"; // // public String key; // // @SerializedName("r") // public int resultCode; // // public BindOkPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindPack.java // public class BindPack extends Pack { // public static String TYPE = "bind"; // // public int uid; // // public BindPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DevicePack.java // public class DevicePack extends Pack { // public static String TYPE = "dev"; // // public String cid; // public String bc; // public String brand; // public String catalog; // public String mid; // public String model; // public String name; // public String series; // public String ver; // public Integer lock; // // @SerializedName("vender") // public String vendor; // // public DevicePack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/ResultPack.java // public class ResultPack extends Pack { // public static String TYPE = "res"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("opt") // public String[] keys; // // @SerializedName("p") // public Integer[] values; // // public ResultPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/StatusPack.java // public class StatusPack extends Pack { // public static String TYPE = "status"; // // @SerializedName("cols") // public String[] keys; // // public StatusPack() { // type = TYPE; // } // }
import tomikaa.greeremote.Gree.Packs.BindOkPack; import tomikaa.greeremote.Gree.Packs.BindPack; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.DevicePack; import tomikaa.greeremote.Gree.Packs.Pack; import tomikaa.greeremote.Gree.Packs.ResultPack; import tomikaa.greeremote.Gree.Packs.StatusPack; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import java.lang.reflect.Type;
package tomikaa.greeremote.Gree.Deserializers; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-11-26. */ public class PackDeserializer implements JsonDeserializer<Pack> { @Override public Pack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject jsonObject = jsonElement.getAsJsonObject(); String packType = jsonObject.get("t").getAsString(); if (packType.equalsIgnoreCase(BindOkPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, BindOkPack.class); } else if (packType.equalsIgnoreCase(BindPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, BindPack.class);
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindOkPack.java // public class BindOkPack extends Pack { // public static String TYPE = "bindok"; // // public String key; // // @SerializedName("r") // public int resultCode; // // public BindOkPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindPack.java // public class BindPack extends Pack { // public static String TYPE = "bind"; // // public int uid; // // public BindPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DevicePack.java // public class DevicePack extends Pack { // public static String TYPE = "dev"; // // public String cid; // public String bc; // public String brand; // public String catalog; // public String mid; // public String model; // public String name; // public String series; // public String ver; // public Integer lock; // // @SerializedName("vender") // public String vendor; // // public DevicePack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/ResultPack.java // public class ResultPack extends Pack { // public static String TYPE = "res"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("opt") // public String[] keys; // // @SerializedName("p") // public Integer[] values; // // public ResultPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/StatusPack.java // public class StatusPack extends Pack { // public static String TYPE = "status"; // // @SerializedName("cols") // public String[] keys; // // public StatusPack() { // type = TYPE; // } // } // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Deserializers/PackDeserializer.java import tomikaa.greeremote.Gree.Packs.BindOkPack; import tomikaa.greeremote.Gree.Packs.BindPack; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.DevicePack; import tomikaa.greeremote.Gree.Packs.Pack; import tomikaa.greeremote.Gree.Packs.ResultPack; import tomikaa.greeremote.Gree.Packs.StatusPack; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import java.lang.reflect.Type; package tomikaa.greeremote.Gree.Deserializers; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-11-26. */ public class PackDeserializer implements JsonDeserializer<Pack> { @Override public Pack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject jsonObject = jsonElement.getAsJsonObject(); String packType = jsonObject.get("t").getAsString(); if (packType.equalsIgnoreCase(BindOkPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, BindOkPack.class); } else if (packType.equalsIgnoreCase(BindPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, BindPack.class);
} else if (packType.equalsIgnoreCase(DatPack.TYPE)) {
tomikaa87/gree-remote
GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Deserializers/PackDeserializer.java
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindOkPack.java // public class BindOkPack extends Pack { // public static String TYPE = "bindok"; // // public String key; // // @SerializedName("r") // public int resultCode; // // public BindOkPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindPack.java // public class BindPack extends Pack { // public static String TYPE = "bind"; // // public int uid; // // public BindPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DevicePack.java // public class DevicePack extends Pack { // public static String TYPE = "dev"; // // public String cid; // public String bc; // public String brand; // public String catalog; // public String mid; // public String model; // public String name; // public String series; // public String ver; // public Integer lock; // // @SerializedName("vender") // public String vendor; // // public DevicePack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/ResultPack.java // public class ResultPack extends Pack { // public static String TYPE = "res"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("opt") // public String[] keys; // // @SerializedName("p") // public Integer[] values; // // public ResultPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/StatusPack.java // public class StatusPack extends Pack { // public static String TYPE = "status"; // // @SerializedName("cols") // public String[] keys; // // public StatusPack() { // type = TYPE; // } // }
import tomikaa.greeremote.Gree.Packs.BindOkPack; import tomikaa.greeremote.Gree.Packs.BindPack; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.DevicePack; import tomikaa.greeremote.Gree.Packs.Pack; import tomikaa.greeremote.Gree.Packs.ResultPack; import tomikaa.greeremote.Gree.Packs.StatusPack; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import java.lang.reflect.Type;
package tomikaa.greeremote.Gree.Deserializers; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-11-26. */ public class PackDeserializer implements JsonDeserializer<Pack> { @Override public Pack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject jsonObject = jsonElement.getAsJsonObject(); String packType = jsonObject.get("t").getAsString(); if (packType.equalsIgnoreCase(BindOkPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, BindOkPack.class); } else if (packType.equalsIgnoreCase(BindPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, BindPack.class); } else if (packType.equalsIgnoreCase(DatPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, DatPack.class);
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindOkPack.java // public class BindOkPack extends Pack { // public static String TYPE = "bindok"; // // public String key; // // @SerializedName("r") // public int resultCode; // // public BindOkPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindPack.java // public class BindPack extends Pack { // public static String TYPE = "bind"; // // public int uid; // // public BindPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DevicePack.java // public class DevicePack extends Pack { // public static String TYPE = "dev"; // // public String cid; // public String bc; // public String brand; // public String catalog; // public String mid; // public String model; // public String name; // public String series; // public String ver; // public Integer lock; // // @SerializedName("vender") // public String vendor; // // public DevicePack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/ResultPack.java // public class ResultPack extends Pack { // public static String TYPE = "res"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("opt") // public String[] keys; // // @SerializedName("p") // public Integer[] values; // // public ResultPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/StatusPack.java // public class StatusPack extends Pack { // public static String TYPE = "status"; // // @SerializedName("cols") // public String[] keys; // // public StatusPack() { // type = TYPE; // } // } // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Deserializers/PackDeserializer.java import tomikaa.greeremote.Gree.Packs.BindOkPack; import tomikaa.greeremote.Gree.Packs.BindPack; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.DevicePack; import tomikaa.greeremote.Gree.Packs.Pack; import tomikaa.greeremote.Gree.Packs.ResultPack; import tomikaa.greeremote.Gree.Packs.StatusPack; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import java.lang.reflect.Type; package tomikaa.greeremote.Gree.Deserializers; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-11-26. */ public class PackDeserializer implements JsonDeserializer<Pack> { @Override public Pack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject jsonObject = jsonElement.getAsJsonObject(); String packType = jsonObject.get("t").getAsString(); if (packType.equalsIgnoreCase(BindOkPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, BindOkPack.class); } else if (packType.equalsIgnoreCase(BindPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, BindPack.class); } else if (packType.equalsIgnoreCase(DatPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, DatPack.class);
} else if (packType.equalsIgnoreCase(ResultPack.TYPE)) {
tomikaa87/gree-remote
GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Deserializers/PackDeserializer.java
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindOkPack.java // public class BindOkPack extends Pack { // public static String TYPE = "bindok"; // // public String key; // // @SerializedName("r") // public int resultCode; // // public BindOkPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindPack.java // public class BindPack extends Pack { // public static String TYPE = "bind"; // // public int uid; // // public BindPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DevicePack.java // public class DevicePack extends Pack { // public static String TYPE = "dev"; // // public String cid; // public String bc; // public String brand; // public String catalog; // public String mid; // public String model; // public String name; // public String series; // public String ver; // public Integer lock; // // @SerializedName("vender") // public String vendor; // // public DevicePack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/ResultPack.java // public class ResultPack extends Pack { // public static String TYPE = "res"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("opt") // public String[] keys; // // @SerializedName("p") // public Integer[] values; // // public ResultPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/StatusPack.java // public class StatusPack extends Pack { // public static String TYPE = "status"; // // @SerializedName("cols") // public String[] keys; // // public StatusPack() { // type = TYPE; // } // }
import tomikaa.greeremote.Gree.Packs.BindOkPack; import tomikaa.greeremote.Gree.Packs.BindPack; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.DevicePack; import tomikaa.greeremote.Gree.Packs.Pack; import tomikaa.greeremote.Gree.Packs.ResultPack; import tomikaa.greeremote.Gree.Packs.StatusPack; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import java.lang.reflect.Type;
package tomikaa.greeremote.Gree.Deserializers; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-11-26. */ public class PackDeserializer implements JsonDeserializer<Pack> { @Override public Pack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject jsonObject = jsonElement.getAsJsonObject(); String packType = jsonObject.get("t").getAsString(); if (packType.equalsIgnoreCase(BindOkPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, BindOkPack.class); } else if (packType.equalsIgnoreCase(BindPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, BindPack.class); } else if (packType.equalsIgnoreCase(DatPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, DatPack.class); } else if (packType.equalsIgnoreCase(ResultPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, ResultPack.class);
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindOkPack.java // public class BindOkPack extends Pack { // public static String TYPE = "bindok"; // // public String key; // // @SerializedName("r") // public int resultCode; // // public BindOkPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindPack.java // public class BindPack extends Pack { // public static String TYPE = "bind"; // // public int uid; // // public BindPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DevicePack.java // public class DevicePack extends Pack { // public static String TYPE = "dev"; // // public String cid; // public String bc; // public String brand; // public String catalog; // public String mid; // public String model; // public String name; // public String series; // public String ver; // public Integer lock; // // @SerializedName("vender") // public String vendor; // // public DevicePack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/ResultPack.java // public class ResultPack extends Pack { // public static String TYPE = "res"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("opt") // public String[] keys; // // @SerializedName("p") // public Integer[] values; // // public ResultPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/StatusPack.java // public class StatusPack extends Pack { // public static String TYPE = "status"; // // @SerializedName("cols") // public String[] keys; // // public StatusPack() { // type = TYPE; // } // } // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Deserializers/PackDeserializer.java import tomikaa.greeremote.Gree.Packs.BindOkPack; import tomikaa.greeremote.Gree.Packs.BindPack; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.DevicePack; import tomikaa.greeremote.Gree.Packs.Pack; import tomikaa.greeremote.Gree.Packs.ResultPack; import tomikaa.greeremote.Gree.Packs.StatusPack; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import java.lang.reflect.Type; package tomikaa.greeremote.Gree.Deserializers; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-11-26. */ public class PackDeserializer implements JsonDeserializer<Pack> { @Override public Pack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject jsonObject = jsonElement.getAsJsonObject(); String packType = jsonObject.get("t").getAsString(); if (packType.equalsIgnoreCase(BindOkPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, BindOkPack.class); } else if (packType.equalsIgnoreCase(BindPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, BindPack.class); } else if (packType.equalsIgnoreCase(DatPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, DatPack.class); } else if (packType.equalsIgnoreCase(ResultPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, ResultPack.class);
} else if (packType.equalsIgnoreCase(StatusPack.TYPE)) {
tomikaa87/gree-remote
GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Deserializers/PackDeserializer.java
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindOkPack.java // public class BindOkPack extends Pack { // public static String TYPE = "bindok"; // // public String key; // // @SerializedName("r") // public int resultCode; // // public BindOkPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindPack.java // public class BindPack extends Pack { // public static String TYPE = "bind"; // // public int uid; // // public BindPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DevicePack.java // public class DevicePack extends Pack { // public static String TYPE = "dev"; // // public String cid; // public String bc; // public String brand; // public String catalog; // public String mid; // public String model; // public String name; // public String series; // public String ver; // public Integer lock; // // @SerializedName("vender") // public String vendor; // // public DevicePack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/ResultPack.java // public class ResultPack extends Pack { // public static String TYPE = "res"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("opt") // public String[] keys; // // @SerializedName("p") // public Integer[] values; // // public ResultPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/StatusPack.java // public class StatusPack extends Pack { // public static String TYPE = "status"; // // @SerializedName("cols") // public String[] keys; // // public StatusPack() { // type = TYPE; // } // }
import tomikaa.greeremote.Gree.Packs.BindOkPack; import tomikaa.greeremote.Gree.Packs.BindPack; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.DevicePack; import tomikaa.greeremote.Gree.Packs.Pack; import tomikaa.greeremote.Gree.Packs.ResultPack; import tomikaa.greeremote.Gree.Packs.StatusPack; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import java.lang.reflect.Type;
package tomikaa.greeremote.Gree.Deserializers; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-11-26. */ public class PackDeserializer implements JsonDeserializer<Pack> { @Override public Pack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject jsonObject = jsonElement.getAsJsonObject(); String packType = jsonObject.get("t").getAsString(); if (packType.equalsIgnoreCase(BindOkPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, BindOkPack.class); } else if (packType.equalsIgnoreCase(BindPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, BindPack.class); } else if (packType.equalsIgnoreCase(DatPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, DatPack.class); } else if (packType.equalsIgnoreCase(ResultPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, ResultPack.class); } else if (packType.equalsIgnoreCase(StatusPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, StatusPack.class);
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindOkPack.java // public class BindOkPack extends Pack { // public static String TYPE = "bindok"; // // public String key; // // @SerializedName("r") // public int resultCode; // // public BindOkPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/BindPack.java // public class BindPack extends Pack { // public static String TYPE = "bind"; // // public int uid; // // public BindPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DevicePack.java // public class DevicePack extends Pack { // public static String TYPE = "dev"; // // public String cid; // public String bc; // public String brand; // public String catalog; // public String mid; // public String model; // public String name; // public String series; // public String ver; // public Integer lock; // // @SerializedName("vender") // public String vendor; // // public DevicePack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/ResultPack.java // public class ResultPack extends Pack { // public static String TYPE = "res"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("opt") // public String[] keys; // // @SerializedName("p") // public Integer[] values; // // public ResultPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/StatusPack.java // public class StatusPack extends Pack { // public static String TYPE = "status"; // // @SerializedName("cols") // public String[] keys; // // public StatusPack() { // type = TYPE; // } // } // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Deserializers/PackDeserializer.java import tomikaa.greeremote.Gree.Packs.BindOkPack; import tomikaa.greeremote.Gree.Packs.BindPack; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.DevicePack; import tomikaa.greeremote.Gree.Packs.Pack; import tomikaa.greeremote.Gree.Packs.ResultPack; import tomikaa.greeremote.Gree.Packs.StatusPack; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import java.lang.reflect.Type; package tomikaa.greeremote.Gree.Deserializers; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-11-26. */ public class PackDeserializer implements JsonDeserializer<Pack> { @Override public Pack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject jsonObject = jsonElement.getAsJsonObject(); String packType = jsonObject.get("t").getAsString(); if (packType.equalsIgnoreCase(BindOkPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, BindOkPack.class); } else if (packType.equalsIgnoreCase(BindPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, BindPack.class); } else if (packType.equalsIgnoreCase(DatPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, DatPack.class); } else if (packType.equalsIgnoreCase(ResultPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, ResultPack.class); } else if (packType.equalsIgnoreCase(StatusPack.TYPE)) { return jsonDeserializationContext.deserialize(jsonObject, StatusPack.class);
} else if (packType.equalsIgnoreCase(DevicePack.TYPE)) {
tomikaa87/gree-remote
GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Utils.java
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Deserializers/PackDeserializer.java // public class PackDeserializer implements JsonDeserializer<Pack> { // // @Override // public Pack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { // JsonObject jsonObject = jsonElement.getAsJsonObject(); // // String packType = jsonObject.get("t").getAsString(); // // if (packType.equalsIgnoreCase(BindOkPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, BindOkPack.class); // } else if (packType.equalsIgnoreCase(BindPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, BindPack.class); // } else if (packType.equalsIgnoreCase(DatPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, DatPack.class); // } else if (packType.equalsIgnoreCase(ResultPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, ResultPack.class); // } else if (packType.equalsIgnoreCase(StatusPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, StatusPack.class); // } else if (packType.equalsIgnoreCase(DevicePack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, DevicePack.class); // } // // return null; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Network/DeviceKeyChain.java // public class DeviceKeyChain { // private final HashMap<String, String> mKeys = new HashMap<>(); // // public void addKey(String deviceId, String key) { // mKeys.put(deviceId.toLowerCase(), key); // } // // public String getKey(String deviceId) { // if (deviceId == null) // return null; // // String id = deviceId.toLowerCase(); // // if (!mKeys.containsKey(id)) // return null; // // return mKeys.get(id); // } // // public boolean containsKey(String deviceId) { // if (deviceId == null) // return false; // // return mKeys.containsKey(deviceId.toLowerCase()); // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packets/Packet.java // public class Packet { // @SerializedName("t") // public String type; // // public String tcid; // public Integer i; // public Integer uid; // public String cid; // // @SerializedName("pack") // public String encryptedPack; // // public transient Pack pack; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // }
import android.util.Log; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.HashMap; import java.util.Map; import tomikaa.greeremote.Gree.Deserializers.PackDeserializer; import tomikaa.greeremote.Gree.Network.DeviceKeyChain; import tomikaa.greeremote.Gree.Packets.Packet; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.Pack;
package tomikaa.greeremote.Gree; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-11-26. */ public class Utils { public static class Unzipped { public final String[] keys; public final Integer[] values; public Unzipped(String[] keys, Integer[] values) { this.keys = keys; this.values = values; } } public static Map<String, Integer> zip(String[] keys, Integer[] values) throws IllegalArgumentException { if (keys.length != values.length) throw new IllegalArgumentException("Length of keys and values must match"); Map<String, Integer> zipped = new HashMap<>(); for (int i = 0; i < keys.length; i++) { zipped.put(keys[i], values[i]); } return zipped; } public static Unzipped unzip(Map<String, Integer> map) { return new Unzipped(map.keySet().toArray(new String[0]), map.values().toArray(new Integer[0])); }
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Deserializers/PackDeserializer.java // public class PackDeserializer implements JsonDeserializer<Pack> { // // @Override // public Pack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { // JsonObject jsonObject = jsonElement.getAsJsonObject(); // // String packType = jsonObject.get("t").getAsString(); // // if (packType.equalsIgnoreCase(BindOkPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, BindOkPack.class); // } else if (packType.equalsIgnoreCase(BindPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, BindPack.class); // } else if (packType.equalsIgnoreCase(DatPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, DatPack.class); // } else if (packType.equalsIgnoreCase(ResultPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, ResultPack.class); // } else if (packType.equalsIgnoreCase(StatusPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, StatusPack.class); // } else if (packType.equalsIgnoreCase(DevicePack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, DevicePack.class); // } // // return null; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Network/DeviceKeyChain.java // public class DeviceKeyChain { // private final HashMap<String, String> mKeys = new HashMap<>(); // // public void addKey(String deviceId, String key) { // mKeys.put(deviceId.toLowerCase(), key); // } // // public String getKey(String deviceId) { // if (deviceId == null) // return null; // // String id = deviceId.toLowerCase(); // // if (!mKeys.containsKey(id)) // return null; // // return mKeys.get(id); // } // // public boolean containsKey(String deviceId) { // if (deviceId == null) // return false; // // return mKeys.containsKey(deviceId.toLowerCase()); // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packets/Packet.java // public class Packet { // @SerializedName("t") // public String type; // // public String tcid; // public Integer i; // public Integer uid; // public String cid; // // @SerializedName("pack") // public String encryptedPack; // // public transient Pack pack; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // } // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Utils.java import android.util.Log; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.HashMap; import java.util.Map; import tomikaa.greeremote.Gree.Deserializers.PackDeserializer; import tomikaa.greeremote.Gree.Network.DeviceKeyChain; import tomikaa.greeremote.Gree.Packets.Packet; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.Pack; package tomikaa.greeremote.Gree; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-11-26. */ public class Utils { public static class Unzipped { public final String[] keys; public final Integer[] values; public Unzipped(String[] keys, Integer[] values) { this.keys = keys; this.values = values; } } public static Map<String, Integer> zip(String[] keys, Integer[] values) throws IllegalArgumentException { if (keys.length != values.length) throw new IllegalArgumentException("Length of keys and values must match"); Map<String, Integer> zipped = new HashMap<>(); for (int i = 0; i < keys.length; i++) { zipped.put(keys[i], values[i]); } return zipped; } public static Unzipped unzip(Map<String, Integer> map) { return new Unzipped(map.keySet().toArray(new String[0]), map.values().toArray(new Integer[0])); }
public static Map<String, Integer> getValues(DatPack pack) {
tomikaa87/gree-remote
GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Utils.java
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Deserializers/PackDeserializer.java // public class PackDeserializer implements JsonDeserializer<Pack> { // // @Override // public Pack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { // JsonObject jsonObject = jsonElement.getAsJsonObject(); // // String packType = jsonObject.get("t").getAsString(); // // if (packType.equalsIgnoreCase(BindOkPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, BindOkPack.class); // } else if (packType.equalsIgnoreCase(BindPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, BindPack.class); // } else if (packType.equalsIgnoreCase(DatPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, DatPack.class); // } else if (packType.equalsIgnoreCase(ResultPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, ResultPack.class); // } else if (packType.equalsIgnoreCase(StatusPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, StatusPack.class); // } else if (packType.equalsIgnoreCase(DevicePack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, DevicePack.class); // } // // return null; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Network/DeviceKeyChain.java // public class DeviceKeyChain { // private final HashMap<String, String> mKeys = new HashMap<>(); // // public void addKey(String deviceId, String key) { // mKeys.put(deviceId.toLowerCase(), key); // } // // public String getKey(String deviceId) { // if (deviceId == null) // return null; // // String id = deviceId.toLowerCase(); // // if (!mKeys.containsKey(id)) // return null; // // return mKeys.get(id); // } // // public boolean containsKey(String deviceId) { // if (deviceId == null) // return false; // // return mKeys.containsKey(deviceId.toLowerCase()); // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packets/Packet.java // public class Packet { // @SerializedName("t") // public String type; // // public String tcid; // public Integer i; // public Integer uid; // public String cid; // // @SerializedName("pack") // public String encryptedPack; // // public transient Pack pack; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // }
import android.util.Log; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.HashMap; import java.util.Map; import tomikaa.greeremote.Gree.Deserializers.PackDeserializer; import tomikaa.greeremote.Gree.Network.DeviceKeyChain; import tomikaa.greeremote.Gree.Packets.Packet; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.Pack;
package tomikaa.greeremote.Gree; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-11-26. */ public class Utils { public static class Unzipped { public final String[] keys; public final Integer[] values; public Unzipped(String[] keys, Integer[] values) { this.keys = keys; this.values = values; } } public static Map<String, Integer> zip(String[] keys, Integer[] values) throws IllegalArgumentException { if (keys.length != values.length) throw new IllegalArgumentException("Length of keys and values must match"); Map<String, Integer> zipped = new HashMap<>(); for (int i = 0; i < keys.length; i++) { zipped.put(keys[i], values[i]); } return zipped; } public static Unzipped unzip(Map<String, Integer> map) { return new Unzipped(map.keySet().toArray(new String[0]), map.values().toArray(new Integer[0])); } public static Map<String, Integer> getValues(DatPack pack) { return zip(pack.keys, pack.values); }
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Deserializers/PackDeserializer.java // public class PackDeserializer implements JsonDeserializer<Pack> { // // @Override // public Pack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { // JsonObject jsonObject = jsonElement.getAsJsonObject(); // // String packType = jsonObject.get("t").getAsString(); // // if (packType.equalsIgnoreCase(BindOkPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, BindOkPack.class); // } else if (packType.equalsIgnoreCase(BindPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, BindPack.class); // } else if (packType.equalsIgnoreCase(DatPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, DatPack.class); // } else if (packType.equalsIgnoreCase(ResultPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, ResultPack.class); // } else if (packType.equalsIgnoreCase(StatusPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, StatusPack.class); // } else if (packType.equalsIgnoreCase(DevicePack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, DevicePack.class); // } // // return null; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Network/DeviceKeyChain.java // public class DeviceKeyChain { // private final HashMap<String, String> mKeys = new HashMap<>(); // // public void addKey(String deviceId, String key) { // mKeys.put(deviceId.toLowerCase(), key); // } // // public String getKey(String deviceId) { // if (deviceId == null) // return null; // // String id = deviceId.toLowerCase(); // // if (!mKeys.containsKey(id)) // return null; // // return mKeys.get(id); // } // // public boolean containsKey(String deviceId) { // if (deviceId == null) // return false; // // return mKeys.containsKey(deviceId.toLowerCase()); // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packets/Packet.java // public class Packet { // @SerializedName("t") // public String type; // // public String tcid; // public Integer i; // public Integer uid; // public String cid; // // @SerializedName("pack") // public String encryptedPack; // // public transient Pack pack; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // } // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Utils.java import android.util.Log; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.HashMap; import java.util.Map; import tomikaa.greeremote.Gree.Deserializers.PackDeserializer; import tomikaa.greeremote.Gree.Network.DeviceKeyChain; import tomikaa.greeremote.Gree.Packets.Packet; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.Pack; package tomikaa.greeremote.Gree; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-11-26. */ public class Utils { public static class Unzipped { public final String[] keys; public final Integer[] values; public Unzipped(String[] keys, Integer[] values) { this.keys = keys; this.values = values; } } public static Map<String, Integer> zip(String[] keys, Integer[] values) throws IllegalArgumentException { if (keys.length != values.length) throw new IllegalArgumentException("Length of keys and values must match"); Map<String, Integer> zipped = new HashMap<>(); for (int i = 0; i < keys.length; i++) { zipped.put(keys[i], values[i]); } return zipped; } public static Unzipped unzip(Map<String, Integer> map) { return new Unzipped(map.keySet().toArray(new String[0]), map.values().toArray(new Integer[0])); } public static Map<String, Integer> getValues(DatPack pack) { return zip(pack.keys, pack.values); }
public static String serializePacket(Packet packet, DeviceKeyChain deviceKeyChain) {
tomikaa87/gree-remote
GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Utils.java
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Deserializers/PackDeserializer.java // public class PackDeserializer implements JsonDeserializer<Pack> { // // @Override // public Pack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { // JsonObject jsonObject = jsonElement.getAsJsonObject(); // // String packType = jsonObject.get("t").getAsString(); // // if (packType.equalsIgnoreCase(BindOkPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, BindOkPack.class); // } else if (packType.equalsIgnoreCase(BindPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, BindPack.class); // } else if (packType.equalsIgnoreCase(DatPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, DatPack.class); // } else if (packType.equalsIgnoreCase(ResultPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, ResultPack.class); // } else if (packType.equalsIgnoreCase(StatusPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, StatusPack.class); // } else if (packType.equalsIgnoreCase(DevicePack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, DevicePack.class); // } // // return null; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Network/DeviceKeyChain.java // public class DeviceKeyChain { // private final HashMap<String, String> mKeys = new HashMap<>(); // // public void addKey(String deviceId, String key) { // mKeys.put(deviceId.toLowerCase(), key); // } // // public String getKey(String deviceId) { // if (deviceId == null) // return null; // // String id = deviceId.toLowerCase(); // // if (!mKeys.containsKey(id)) // return null; // // return mKeys.get(id); // } // // public boolean containsKey(String deviceId) { // if (deviceId == null) // return false; // // return mKeys.containsKey(deviceId.toLowerCase()); // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packets/Packet.java // public class Packet { // @SerializedName("t") // public String type; // // public String tcid; // public Integer i; // public Integer uid; // public String cid; // // @SerializedName("pack") // public String encryptedPack; // // public transient Pack pack; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // }
import android.util.Log; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.HashMap; import java.util.Map; import tomikaa.greeremote.Gree.Deserializers.PackDeserializer; import tomikaa.greeremote.Gree.Network.DeviceKeyChain; import tomikaa.greeremote.Gree.Packets.Packet; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.Pack;
package tomikaa.greeremote.Gree; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-11-26. */ public class Utils { public static class Unzipped { public final String[] keys; public final Integer[] values; public Unzipped(String[] keys, Integer[] values) { this.keys = keys; this.values = values; } } public static Map<String, Integer> zip(String[] keys, Integer[] values) throws IllegalArgumentException { if (keys.length != values.length) throw new IllegalArgumentException("Length of keys and values must match"); Map<String, Integer> zipped = new HashMap<>(); for (int i = 0; i < keys.length; i++) { zipped.put(keys[i], values[i]); } return zipped; } public static Unzipped unzip(Map<String, Integer> map) { return new Unzipped(map.keySet().toArray(new String[0]), map.values().toArray(new Integer[0])); } public static Map<String, Integer> getValues(DatPack pack) { return zip(pack.keys, pack.values); }
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Deserializers/PackDeserializer.java // public class PackDeserializer implements JsonDeserializer<Pack> { // // @Override // public Pack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { // JsonObject jsonObject = jsonElement.getAsJsonObject(); // // String packType = jsonObject.get("t").getAsString(); // // if (packType.equalsIgnoreCase(BindOkPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, BindOkPack.class); // } else if (packType.equalsIgnoreCase(BindPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, BindPack.class); // } else if (packType.equalsIgnoreCase(DatPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, DatPack.class); // } else if (packType.equalsIgnoreCase(ResultPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, ResultPack.class); // } else if (packType.equalsIgnoreCase(StatusPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, StatusPack.class); // } else if (packType.equalsIgnoreCase(DevicePack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, DevicePack.class); // } // // return null; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Network/DeviceKeyChain.java // public class DeviceKeyChain { // private final HashMap<String, String> mKeys = new HashMap<>(); // // public void addKey(String deviceId, String key) { // mKeys.put(deviceId.toLowerCase(), key); // } // // public String getKey(String deviceId) { // if (deviceId == null) // return null; // // String id = deviceId.toLowerCase(); // // if (!mKeys.containsKey(id)) // return null; // // return mKeys.get(id); // } // // public boolean containsKey(String deviceId) { // if (deviceId == null) // return false; // // return mKeys.containsKey(deviceId.toLowerCase()); // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packets/Packet.java // public class Packet { // @SerializedName("t") // public String type; // // public String tcid; // public Integer i; // public Integer uid; // public String cid; // // @SerializedName("pack") // public String encryptedPack; // // public transient Pack pack; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // } // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Utils.java import android.util.Log; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.HashMap; import java.util.Map; import tomikaa.greeremote.Gree.Deserializers.PackDeserializer; import tomikaa.greeremote.Gree.Network.DeviceKeyChain; import tomikaa.greeremote.Gree.Packets.Packet; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.Pack; package tomikaa.greeremote.Gree; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-11-26. */ public class Utils { public static class Unzipped { public final String[] keys; public final Integer[] values; public Unzipped(String[] keys, Integer[] values) { this.keys = keys; this.values = values; } } public static Map<String, Integer> zip(String[] keys, Integer[] values) throws IllegalArgumentException { if (keys.length != values.length) throw new IllegalArgumentException("Length of keys and values must match"); Map<String, Integer> zipped = new HashMap<>(); for (int i = 0; i < keys.length; i++) { zipped.put(keys[i], values[i]); } return zipped; } public static Unzipped unzip(Map<String, Integer> map) { return new Unzipped(map.keySet().toArray(new String[0]), map.values().toArray(new Integer[0])); } public static Map<String, Integer> getValues(DatPack pack) { return zip(pack.keys, pack.values); }
public static String serializePacket(Packet packet, DeviceKeyChain deviceKeyChain) {
tomikaa87/gree-remote
GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Utils.java
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Deserializers/PackDeserializer.java // public class PackDeserializer implements JsonDeserializer<Pack> { // // @Override // public Pack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { // JsonObject jsonObject = jsonElement.getAsJsonObject(); // // String packType = jsonObject.get("t").getAsString(); // // if (packType.equalsIgnoreCase(BindOkPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, BindOkPack.class); // } else if (packType.equalsIgnoreCase(BindPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, BindPack.class); // } else if (packType.equalsIgnoreCase(DatPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, DatPack.class); // } else if (packType.equalsIgnoreCase(ResultPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, ResultPack.class); // } else if (packType.equalsIgnoreCase(StatusPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, StatusPack.class); // } else if (packType.equalsIgnoreCase(DevicePack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, DevicePack.class); // } // // return null; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Network/DeviceKeyChain.java // public class DeviceKeyChain { // private final HashMap<String, String> mKeys = new HashMap<>(); // // public void addKey(String deviceId, String key) { // mKeys.put(deviceId.toLowerCase(), key); // } // // public String getKey(String deviceId) { // if (deviceId == null) // return null; // // String id = deviceId.toLowerCase(); // // if (!mKeys.containsKey(id)) // return null; // // return mKeys.get(id); // } // // public boolean containsKey(String deviceId) { // if (deviceId == null) // return false; // // return mKeys.containsKey(deviceId.toLowerCase()); // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packets/Packet.java // public class Packet { // @SerializedName("t") // public String type; // // public String tcid; // public Integer i; // public Integer uid; // public String cid; // // @SerializedName("pack") // public String encryptedPack; // // public transient Pack pack; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // }
import android.util.Log; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.HashMap; import java.util.Map; import tomikaa.greeremote.Gree.Deserializers.PackDeserializer; import tomikaa.greeremote.Gree.Network.DeviceKeyChain; import tomikaa.greeremote.Gree.Packets.Packet; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.Pack;
for (int i = 0; i < keys.length; i++) { zipped.put(keys[i], values[i]); } return zipped; } public static Unzipped unzip(Map<String, Integer> map) { return new Unzipped(map.keySet().toArray(new String[0]), map.values().toArray(new Integer[0])); } public static Map<String, Integer> getValues(DatPack pack) { return zip(pack.keys, pack.values); } public static String serializePacket(Packet packet, DeviceKeyChain deviceKeyChain) { GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); if (packet.pack != null) { String key = getKey(deviceKeyChain, packet); String plainPack = gson.toJson(packet.pack); packet.encryptedPack = tomikaa.greeremote.Gree.Crypto.encrypt(plainPack, key); } return gson.toJson(packet); } public static Packet deserializePacket(String jsonString, DeviceKeyChain deviceKeyChain) { GsonBuilder gsonBuilder = new GsonBuilder();
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Deserializers/PackDeserializer.java // public class PackDeserializer implements JsonDeserializer<Pack> { // // @Override // public Pack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { // JsonObject jsonObject = jsonElement.getAsJsonObject(); // // String packType = jsonObject.get("t").getAsString(); // // if (packType.equalsIgnoreCase(BindOkPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, BindOkPack.class); // } else if (packType.equalsIgnoreCase(BindPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, BindPack.class); // } else if (packType.equalsIgnoreCase(DatPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, DatPack.class); // } else if (packType.equalsIgnoreCase(ResultPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, ResultPack.class); // } else if (packType.equalsIgnoreCase(StatusPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, StatusPack.class); // } else if (packType.equalsIgnoreCase(DevicePack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, DevicePack.class); // } // // return null; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Network/DeviceKeyChain.java // public class DeviceKeyChain { // private final HashMap<String, String> mKeys = new HashMap<>(); // // public void addKey(String deviceId, String key) { // mKeys.put(deviceId.toLowerCase(), key); // } // // public String getKey(String deviceId) { // if (deviceId == null) // return null; // // String id = deviceId.toLowerCase(); // // if (!mKeys.containsKey(id)) // return null; // // return mKeys.get(id); // } // // public boolean containsKey(String deviceId) { // if (deviceId == null) // return false; // // return mKeys.containsKey(deviceId.toLowerCase()); // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packets/Packet.java // public class Packet { // @SerializedName("t") // public String type; // // public String tcid; // public Integer i; // public Integer uid; // public String cid; // // @SerializedName("pack") // public String encryptedPack; // // public transient Pack pack; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // } // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Utils.java import android.util.Log; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.HashMap; import java.util.Map; import tomikaa.greeremote.Gree.Deserializers.PackDeserializer; import tomikaa.greeremote.Gree.Network.DeviceKeyChain; import tomikaa.greeremote.Gree.Packets.Packet; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.Pack; for (int i = 0; i < keys.length; i++) { zipped.put(keys[i], values[i]); } return zipped; } public static Unzipped unzip(Map<String, Integer> map) { return new Unzipped(map.keySet().toArray(new String[0]), map.values().toArray(new Integer[0])); } public static Map<String, Integer> getValues(DatPack pack) { return zip(pack.keys, pack.values); } public static String serializePacket(Packet packet, DeviceKeyChain deviceKeyChain) { GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); if (packet.pack != null) { String key = getKey(deviceKeyChain, packet); String plainPack = gson.toJson(packet.pack); packet.encryptedPack = tomikaa.greeremote.Gree.Crypto.encrypt(plainPack, key); } return gson.toJson(packet); } public static Packet deserializePacket(String jsonString, DeviceKeyChain deviceKeyChain) { GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Pack.class, new PackDeserializer());
tomikaa87/gree-remote
GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Utils.java
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Deserializers/PackDeserializer.java // public class PackDeserializer implements JsonDeserializer<Pack> { // // @Override // public Pack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { // JsonObject jsonObject = jsonElement.getAsJsonObject(); // // String packType = jsonObject.get("t").getAsString(); // // if (packType.equalsIgnoreCase(BindOkPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, BindOkPack.class); // } else if (packType.equalsIgnoreCase(BindPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, BindPack.class); // } else if (packType.equalsIgnoreCase(DatPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, DatPack.class); // } else if (packType.equalsIgnoreCase(ResultPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, ResultPack.class); // } else if (packType.equalsIgnoreCase(StatusPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, StatusPack.class); // } else if (packType.equalsIgnoreCase(DevicePack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, DevicePack.class); // } // // return null; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Network/DeviceKeyChain.java // public class DeviceKeyChain { // private final HashMap<String, String> mKeys = new HashMap<>(); // // public void addKey(String deviceId, String key) { // mKeys.put(deviceId.toLowerCase(), key); // } // // public String getKey(String deviceId) { // if (deviceId == null) // return null; // // String id = deviceId.toLowerCase(); // // if (!mKeys.containsKey(id)) // return null; // // return mKeys.get(id); // } // // public boolean containsKey(String deviceId) { // if (deviceId == null) // return false; // // return mKeys.containsKey(deviceId.toLowerCase()); // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packets/Packet.java // public class Packet { // @SerializedName("t") // public String type; // // public String tcid; // public Integer i; // public Integer uid; // public String cid; // // @SerializedName("pack") // public String encryptedPack; // // public transient Pack pack; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // }
import android.util.Log; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.HashMap; import java.util.Map; import tomikaa.greeremote.Gree.Deserializers.PackDeserializer; import tomikaa.greeremote.Gree.Network.DeviceKeyChain; import tomikaa.greeremote.Gree.Packets.Packet; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.Pack;
for (int i = 0; i < keys.length; i++) { zipped.put(keys[i], values[i]); } return zipped; } public static Unzipped unzip(Map<String, Integer> map) { return new Unzipped(map.keySet().toArray(new String[0]), map.values().toArray(new Integer[0])); } public static Map<String, Integer> getValues(DatPack pack) { return zip(pack.keys, pack.values); } public static String serializePacket(Packet packet, DeviceKeyChain deviceKeyChain) { GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); if (packet.pack != null) { String key = getKey(deviceKeyChain, packet); String plainPack = gson.toJson(packet.pack); packet.encryptedPack = tomikaa.greeremote.Gree.Crypto.encrypt(plainPack, key); } return gson.toJson(packet); } public static Packet deserializePacket(String jsonString, DeviceKeyChain deviceKeyChain) { GsonBuilder gsonBuilder = new GsonBuilder();
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Deserializers/PackDeserializer.java // public class PackDeserializer implements JsonDeserializer<Pack> { // // @Override // public Pack deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { // JsonObject jsonObject = jsonElement.getAsJsonObject(); // // String packType = jsonObject.get("t").getAsString(); // // if (packType.equalsIgnoreCase(BindOkPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, BindOkPack.class); // } else if (packType.equalsIgnoreCase(BindPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, BindPack.class); // } else if (packType.equalsIgnoreCase(DatPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, DatPack.class); // } else if (packType.equalsIgnoreCase(ResultPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, ResultPack.class); // } else if (packType.equalsIgnoreCase(StatusPack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, StatusPack.class); // } else if (packType.equalsIgnoreCase(DevicePack.TYPE)) { // return jsonDeserializationContext.deserialize(jsonObject, DevicePack.class); // } // // return null; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Network/DeviceKeyChain.java // public class DeviceKeyChain { // private final HashMap<String, String> mKeys = new HashMap<>(); // // public void addKey(String deviceId, String key) { // mKeys.put(deviceId.toLowerCase(), key); // } // // public String getKey(String deviceId) { // if (deviceId == null) // return null; // // String id = deviceId.toLowerCase(); // // if (!mKeys.containsKey(id)) // return null; // // return mKeys.get(id); // } // // public boolean containsKey(String deviceId) { // if (deviceId == null) // return false; // // return mKeys.containsKey(deviceId.toLowerCase()); // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packets/Packet.java // public class Packet { // @SerializedName("t") // public String type; // // public String tcid; // public Integer i; // public Integer uid; // public String cid; // // @SerializedName("pack") // public String encryptedPack; // // public transient Pack pack; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // } // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Utils.java import android.util.Log; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.HashMap; import java.util.Map; import tomikaa.greeremote.Gree.Deserializers.PackDeserializer; import tomikaa.greeremote.Gree.Network.DeviceKeyChain; import tomikaa.greeremote.Gree.Packets.Packet; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.Pack; for (int i = 0; i < keys.length; i++) { zipped.put(keys[i], values[i]); } return zipped; } public static Unzipped unzip(Map<String, Integer> map) { return new Unzipped(map.keySet().toArray(new String[0]), map.values().toArray(new Integer[0])); } public static Map<String, Integer> getValues(DatPack pack) { return zip(pack.keys, pack.values); } public static String serializePacket(Packet packet, DeviceKeyChain deviceKeyChain) { GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); if (packet.pack != null) { String key = getKey(deviceKeyChain, packet); String plainPack = gson.toJson(packet.pack); packet.encryptedPack = tomikaa.greeremote.Gree.Crypto.encrypt(plainPack, key); } return gson.toJson(packet); } public static Packet deserializePacket(String jsonString, DeviceKeyChain deviceKeyChain) { GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Pack.class, new PackDeserializer());
tomikaa87/gree-remote
GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/DeviceItem.java
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Device/Device.java // public interface Device { // // enum Mode { // AUTO, // COOL, // DRY, // FAN, // HEAT // } // // enum FanSpeed { // AUTO, // LOW, // MEDIUM_LOW, // MEDIUM, // MEDIUM_HIGH, // HIGH // } // // enum TemperatureUnit { // CELSIUS, // FAHRENHEIT // } // // enum VerticalSwingMode { // DEFAULT, // FULL, // FIXED_TOP, // FIXED_MIDDLE_TOP, // FIXED_MIDDLE, // FIXED_MIDDLE_BOTTOM, // FIXED_BOTTOM, // SWING_BOTTOM, // SWING_MIDDLE_BOTTOM, // SWING_MIDDLE, // SWING_MIDDLE_TOP, // SWING_TOP // } // // String getId(); // // String getName(); // // void setName(String name); // // Mode getMode(); // // void setMode(Mode mode); // // FanSpeed getFanSpeed(); // // void setFanSpeed(FanSpeed fanSpeed); // // int getTemperature(); // // void setTemperature(int value, TemperatureUnit unit); // // boolean isPoweredOn(); // // void setPoweredOn(boolean poweredOn); // // boolean isLightEnabled(); // // void setLightEnabled(boolean enabled); // // boolean isQuietModeEnabled(); // // void setQuietModeEnabled(boolean enabled); // // boolean isTurboModeEnabled(); // // void setTurboModeEnabled(boolean enabled); // // boolean isHealthModeEnabled(); // // void setHealthModeEnabled(boolean enabled); // // boolean isAirModeEnabled(); // // void setAirModeEnabled(boolean enabled); // // boolean isXfanModeEnabled(); // // void setXfanModeEnabled(boolean enabled); // // boolean isSavingModeEnabled(); // // void setSavingModeEnabled(boolean enabled); // // boolean isSleepModeEnabled(); // // void setSleepModeEnabled(boolean enabled); // // VerticalSwingMode getVerticalSwingMode(); // // void setVerticalSwingMode(VerticalSwingMode mode); // // int getParameter(String name); // // void setParameter(String name, int value); // // void setWifiSsidPassword(String ssid, String psw); // }
import java.io.Serializable; import tomikaa.greeremote.Gree.Device.Device;
package tomikaa.greeremote; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-10-22. */ public class DeviceItem implements Serializable { public String mId = "ID"; public String mName = "Name";
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Device/Device.java // public interface Device { // // enum Mode { // AUTO, // COOL, // DRY, // FAN, // HEAT // } // // enum FanSpeed { // AUTO, // LOW, // MEDIUM_LOW, // MEDIUM, // MEDIUM_HIGH, // HIGH // } // // enum TemperatureUnit { // CELSIUS, // FAHRENHEIT // } // // enum VerticalSwingMode { // DEFAULT, // FULL, // FIXED_TOP, // FIXED_MIDDLE_TOP, // FIXED_MIDDLE, // FIXED_MIDDLE_BOTTOM, // FIXED_BOTTOM, // SWING_BOTTOM, // SWING_MIDDLE_BOTTOM, // SWING_MIDDLE, // SWING_MIDDLE_TOP, // SWING_TOP // } // // String getId(); // // String getName(); // // void setName(String name); // // Mode getMode(); // // void setMode(Mode mode); // // FanSpeed getFanSpeed(); // // void setFanSpeed(FanSpeed fanSpeed); // // int getTemperature(); // // void setTemperature(int value, TemperatureUnit unit); // // boolean isPoweredOn(); // // void setPoweredOn(boolean poweredOn); // // boolean isLightEnabled(); // // void setLightEnabled(boolean enabled); // // boolean isQuietModeEnabled(); // // void setQuietModeEnabled(boolean enabled); // // boolean isTurboModeEnabled(); // // void setTurboModeEnabled(boolean enabled); // // boolean isHealthModeEnabled(); // // void setHealthModeEnabled(boolean enabled); // // boolean isAirModeEnabled(); // // void setAirModeEnabled(boolean enabled); // // boolean isXfanModeEnabled(); // // void setXfanModeEnabled(boolean enabled); // // boolean isSavingModeEnabled(); // // void setSavingModeEnabled(boolean enabled); // // boolean isSleepModeEnabled(); // // void setSleepModeEnabled(boolean enabled); // // VerticalSwingMode getVerticalSwingMode(); // // void setVerticalSwingMode(VerticalSwingMode mode); // // int getParameter(String name); // // void setParameter(String name, int value); // // void setWifiSsidPassword(String ssid, String psw); // } // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/DeviceItem.java import java.io.Serializable; import tomikaa.greeremote.Gree.Device.Device; package tomikaa.greeremote; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-10-22. */ public class DeviceItem implements Serializable { public String mId = "ID"; public String mName = "Name";
public Device.Mode mMode = Device.Mode.AUTO;
tomikaa87/gree-remote
GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packets/Packet.java
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // }
import tomikaa.greeremote.Gree.Packs.Pack; import com.google.gson.annotations.SerializedName;
package tomikaa.greeremote.Gree.Packets; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-11-26. */ public class Packet { @SerializedName("t") public String type; public String tcid; public Integer i; public Integer uid; public String cid; @SerializedName("pack") public String encryptedPack;
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/Pack.java // public class Pack { // @SerializedName("t") // public String type; // // public String mac; // } // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packets/Packet.java import tomikaa.greeremote.Gree.Packs.Pack; import com.google.gson.annotations.SerializedName; package tomikaa.greeremote.Gree.Packets; /* * This file is part of GreeRemoteAndroid. * * GreeRemoteAndroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GreeRemoteAndroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GreeRemoteAndroid. If not, see <http://www.gnu.org/licenses/>. */ /** * Created by tomikaa87 <https://github.com/tomikaa87> on 2017-11-26. */ public class Packet { @SerializedName("t") public String type; public String tcid; public Integer i; public Integer uid; public String cid; @SerializedName("pack") public String encryptedPack;
public transient Pack pack;
tomikaa87/gree-remote
GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Network/AsyncCommunicator.java
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packets/AppPacket.java // public class AppPacket extends Packet { // public static String CID = "app"; // public static String TYPE = "pack"; // // public AppPacket() { // cid = CID; // type = TYPE; // uid = 0; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packets/Packet.java // public class Packet { // @SerializedName("t") // public String type; // // public String tcid; // public Integer i; // public Integer uid; // public String cid; // // @SerializedName("pack") // public String encryptedPack; // // public transient Pack pack; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Utils.java // public class Utils { // // public static class Unzipped { // public final String[] keys; // public final Integer[] values; // // public Unzipped(String[] keys, Integer[] values) { // this.keys = keys; // this.values = values; // } // } // // public static Map<String, Integer> zip(String[] keys, Integer[] values) throws IllegalArgumentException { // if (keys.length != values.length) // throw new IllegalArgumentException("Length of keys and values must match"); // // Map<String, Integer> zipped = new HashMap<>(); // for (int i = 0; i < keys.length; i++) { // zipped.put(keys[i], values[i]); // } // // return zipped; // } // // public static Unzipped unzip(Map<String, Integer> map) { // return new Unzipped(map.keySet().toArray(new String[0]), map.values().toArray(new Integer[0])); // } // // public static Map<String, Integer> getValues(DatPack pack) { // return zip(pack.keys, pack.values); // } // // public static String serializePacket(Packet packet, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // Gson gson = gsonBuilder.create(); // // if (packet.pack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = gson.toJson(packet.pack); // packet.encryptedPack = tomikaa.greeremote.Gree.Crypto.encrypt(plainPack, key); // } // // return gson.toJson(packet); // } // // public static Packet deserializePacket(String jsonString, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.registerTypeAdapter(Pack.class, new PackDeserializer()); // // Gson gson = gsonBuilder.create(); // // Packet packet = gson.fromJson(jsonString, Packet.class); // // if (packet.encryptedPack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = Crypto.decrypt(packet.encryptedPack, key); // packet.pack = gson.fromJson(plainPack, Pack.class); // } // // return packet; // } // // private static String getKey(DeviceKeyChain keyChain, Packet packet) { // String key = Crypto.GENERIC_KEY; // // Log.i("getKey", String.format("packet.cid: %s, packet.tcid: %s", packet.cid, packet.tcid)); // // if (keyChain != null) { // if (keyChain.containsKey(packet.cid)) { // key = keyChain.getKey(packet.cid); // } else if (keyChain.containsKey(packet.tcid)) { // key = keyChain.getKey(packet.tcid); // } // } // // return key; // } // }
import android.os.AsyncTask; import android.provider.ContactsContract; import android.util.Log; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketException; import java.util.ArrayList; import tomikaa.greeremote.Gree.Packets.AppPacket; import tomikaa.greeremote.Gree.Packets.Packet; import tomikaa.greeremote.Gree.Utils;
Packet[] responses = new Packet[0]; if (requests == null || requests.length == 0) return responses; if (!createSocket()) return responses; try { for (Packet request : requests) broadcastPacket(request); responses = receivePackets(TIMEOUT_MS); } catch (Exception e) { Log.e(LOG_TAG, "Error: " + e.getMessage()); } finally { closeSocket(); } return responses; } @Override protected void onPostExecute(Packet[] responses) { super.onPostExecute(responses); if (mCommunicationFinishedListener != null) mCommunicationFinishedListener.onFinished(); } private void broadcastPacket(Packet packet) throws IOException {
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packets/AppPacket.java // public class AppPacket extends Packet { // public static String CID = "app"; // public static String TYPE = "pack"; // // public AppPacket() { // cid = CID; // type = TYPE; // uid = 0; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packets/Packet.java // public class Packet { // @SerializedName("t") // public String type; // // public String tcid; // public Integer i; // public Integer uid; // public String cid; // // @SerializedName("pack") // public String encryptedPack; // // public transient Pack pack; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Utils.java // public class Utils { // // public static class Unzipped { // public final String[] keys; // public final Integer[] values; // // public Unzipped(String[] keys, Integer[] values) { // this.keys = keys; // this.values = values; // } // } // // public static Map<String, Integer> zip(String[] keys, Integer[] values) throws IllegalArgumentException { // if (keys.length != values.length) // throw new IllegalArgumentException("Length of keys and values must match"); // // Map<String, Integer> zipped = new HashMap<>(); // for (int i = 0; i < keys.length; i++) { // zipped.put(keys[i], values[i]); // } // // return zipped; // } // // public static Unzipped unzip(Map<String, Integer> map) { // return new Unzipped(map.keySet().toArray(new String[0]), map.values().toArray(new Integer[0])); // } // // public static Map<String, Integer> getValues(DatPack pack) { // return zip(pack.keys, pack.values); // } // // public static String serializePacket(Packet packet, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // Gson gson = gsonBuilder.create(); // // if (packet.pack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = gson.toJson(packet.pack); // packet.encryptedPack = tomikaa.greeremote.Gree.Crypto.encrypt(plainPack, key); // } // // return gson.toJson(packet); // } // // public static Packet deserializePacket(String jsonString, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.registerTypeAdapter(Pack.class, new PackDeserializer()); // // Gson gson = gsonBuilder.create(); // // Packet packet = gson.fromJson(jsonString, Packet.class); // // if (packet.encryptedPack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = Crypto.decrypt(packet.encryptedPack, key); // packet.pack = gson.fromJson(plainPack, Pack.class); // } // // return packet; // } // // private static String getKey(DeviceKeyChain keyChain, Packet packet) { // String key = Crypto.GENERIC_KEY; // // Log.i("getKey", String.format("packet.cid: %s, packet.tcid: %s", packet.cid, packet.tcid)); // // if (keyChain != null) { // if (keyChain.containsKey(packet.cid)) { // key = keyChain.getKey(packet.cid); // } else if (keyChain.containsKey(packet.tcid)) { // key = keyChain.getKey(packet.tcid); // } // } // // return key; // } // } // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Network/AsyncCommunicator.java import android.os.AsyncTask; import android.provider.ContactsContract; import android.util.Log; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketException; import java.util.ArrayList; import tomikaa.greeremote.Gree.Packets.AppPacket; import tomikaa.greeremote.Gree.Packets.Packet; import tomikaa.greeremote.Gree.Utils; Packet[] responses = new Packet[0]; if (requests == null || requests.length == 0) return responses; if (!createSocket()) return responses; try { for (Packet request : requests) broadcastPacket(request); responses = receivePackets(TIMEOUT_MS); } catch (Exception e) { Log.e(LOG_TAG, "Error: " + e.getMessage()); } finally { closeSocket(); } return responses; } @Override protected void onPostExecute(Packet[] responses) { super.onPostExecute(responses); if (mCommunicationFinishedListener != null) mCommunicationFinishedListener.onFinished(); } private void broadcastPacket(Packet packet) throws IOException {
String data = Utils.serializePacket(packet, mKeyChain);
tomikaa87/gree-remote
GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Network/AsyncCommunicator.java
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packets/AppPacket.java // public class AppPacket extends Packet { // public static String CID = "app"; // public static String TYPE = "pack"; // // public AppPacket() { // cid = CID; // type = TYPE; // uid = 0; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packets/Packet.java // public class Packet { // @SerializedName("t") // public String type; // // public String tcid; // public Integer i; // public Integer uid; // public String cid; // // @SerializedName("pack") // public String encryptedPack; // // public transient Pack pack; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Utils.java // public class Utils { // // public static class Unzipped { // public final String[] keys; // public final Integer[] values; // // public Unzipped(String[] keys, Integer[] values) { // this.keys = keys; // this.values = values; // } // } // // public static Map<String, Integer> zip(String[] keys, Integer[] values) throws IllegalArgumentException { // if (keys.length != values.length) // throw new IllegalArgumentException("Length of keys and values must match"); // // Map<String, Integer> zipped = new HashMap<>(); // for (int i = 0; i < keys.length; i++) { // zipped.put(keys[i], values[i]); // } // // return zipped; // } // // public static Unzipped unzip(Map<String, Integer> map) { // return new Unzipped(map.keySet().toArray(new String[0]), map.values().toArray(new Integer[0])); // } // // public static Map<String, Integer> getValues(DatPack pack) { // return zip(pack.keys, pack.values); // } // // public static String serializePacket(Packet packet, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // Gson gson = gsonBuilder.create(); // // if (packet.pack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = gson.toJson(packet.pack); // packet.encryptedPack = tomikaa.greeremote.Gree.Crypto.encrypt(plainPack, key); // } // // return gson.toJson(packet); // } // // public static Packet deserializePacket(String jsonString, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.registerTypeAdapter(Pack.class, new PackDeserializer()); // // Gson gson = gsonBuilder.create(); // // Packet packet = gson.fromJson(jsonString, Packet.class); // // if (packet.encryptedPack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = Crypto.decrypt(packet.encryptedPack, key); // packet.pack = gson.fromJson(plainPack, Pack.class); // } // // return packet; // } // // private static String getKey(DeviceKeyChain keyChain, Packet packet) { // String key = Crypto.GENERIC_KEY; // // Log.i("getKey", String.format("packet.cid: %s, packet.tcid: %s", packet.cid, packet.tcid)); // // if (keyChain != null) { // if (keyChain.containsKey(packet.cid)) { // key = keyChain.getKey(packet.cid); // } else if (keyChain.containsKey(packet.tcid)) { // key = keyChain.getKey(packet.tcid); // } // } // // return key; // } // }
import android.os.AsyncTask; import android.provider.ContactsContract; import android.util.Log; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketException; import java.util.ArrayList; import tomikaa.greeremote.Gree.Packets.AppPacket; import tomikaa.greeremote.Gree.Packets.Packet; import tomikaa.greeremote.Gree.Utils;
} private Packet[] receivePackets(int timeout) throws IOException { mSocket.setSoTimeout(timeout); ArrayList<Packet> responses = new ArrayList<>(); ArrayList<DatagramPacket> datagramPackets = new ArrayList<>(); try { while (true) { byte[] buffer = new byte[65536]; DatagramPacket datagramPacket = new DatagramPacket(buffer, 65536); mSocket.receive(datagramPacket); datagramPackets.add(datagramPacket); } } catch (Exception e) { Log.w(LOG_TAG, "Exception: " + e.getMessage()); } for (DatagramPacket p : datagramPackets) { String data = new String(p.getData(), 0, p.getLength()); InetAddress address = p.getAddress(); Log.d(LOG_TAG, String.format("Received response from %s: %s", address.getHostAddress(), data)); Packet response = Utils.deserializePacket(data, mKeyChain); // Filter out packets sent by us
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packets/AppPacket.java // public class AppPacket extends Packet { // public static String CID = "app"; // public static String TYPE = "pack"; // // public AppPacket() { // cid = CID; // type = TYPE; // uid = 0; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packets/Packet.java // public class Packet { // @SerializedName("t") // public String type; // // public String tcid; // public Integer i; // public Integer uid; // public String cid; // // @SerializedName("pack") // public String encryptedPack; // // public transient Pack pack; // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Utils.java // public class Utils { // // public static class Unzipped { // public final String[] keys; // public final Integer[] values; // // public Unzipped(String[] keys, Integer[] values) { // this.keys = keys; // this.values = values; // } // } // // public static Map<String, Integer> zip(String[] keys, Integer[] values) throws IllegalArgumentException { // if (keys.length != values.length) // throw new IllegalArgumentException("Length of keys and values must match"); // // Map<String, Integer> zipped = new HashMap<>(); // for (int i = 0; i < keys.length; i++) { // zipped.put(keys[i], values[i]); // } // // return zipped; // } // // public static Unzipped unzip(Map<String, Integer> map) { // return new Unzipped(map.keySet().toArray(new String[0]), map.values().toArray(new Integer[0])); // } // // public static Map<String, Integer> getValues(DatPack pack) { // return zip(pack.keys, pack.values); // } // // public static String serializePacket(Packet packet, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // Gson gson = gsonBuilder.create(); // // if (packet.pack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = gson.toJson(packet.pack); // packet.encryptedPack = tomikaa.greeremote.Gree.Crypto.encrypt(plainPack, key); // } // // return gson.toJson(packet); // } // // public static Packet deserializePacket(String jsonString, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.registerTypeAdapter(Pack.class, new PackDeserializer()); // // Gson gson = gsonBuilder.create(); // // Packet packet = gson.fromJson(jsonString, Packet.class); // // if (packet.encryptedPack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = Crypto.decrypt(packet.encryptedPack, key); // packet.pack = gson.fromJson(plainPack, Pack.class); // } // // return packet; // } // // private static String getKey(DeviceKeyChain keyChain, Packet packet) { // String key = Crypto.GENERIC_KEY; // // Log.i("getKey", String.format("packet.cid: %s, packet.tcid: %s", packet.cid, packet.tcid)); // // if (keyChain != null) { // if (keyChain.containsKey(packet.cid)) { // key = keyChain.getKey(packet.cid); // } else if (keyChain.containsKey(packet.tcid)) { // key = keyChain.getKey(packet.tcid); // } // } // // return key; // } // } // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Network/AsyncCommunicator.java import android.os.AsyncTask; import android.provider.ContactsContract; import android.util.Log; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketException; import java.util.ArrayList; import tomikaa.greeremote.Gree.Packets.AppPacket; import tomikaa.greeremote.Gree.Packets.Packet; import tomikaa.greeremote.Gree.Utils; } private Packet[] receivePackets(int timeout) throws IOException { mSocket.setSoTimeout(timeout); ArrayList<Packet> responses = new ArrayList<>(); ArrayList<DatagramPacket> datagramPackets = new ArrayList<>(); try { while (true) { byte[] buffer = new byte[65536]; DatagramPacket datagramPacket = new DatagramPacket(buffer, 65536); mSocket.receive(datagramPacket); datagramPackets.add(datagramPacket); } } catch (Exception e) { Log.w(LOG_TAG, "Exception: " + e.getMessage()); } for (DatagramPacket p : datagramPackets) { String data = new String(p.getData(), 0, p.getLength()); InetAddress address = p.getAddress(); Log.d(LOG_TAG, String.format("Received response from %s: %s", address.getHostAddress(), data)); Packet response = Utils.deserializePacket(data, mKeyChain); // Filter out packets sent by us
if (response.cid != null && response.cid != AppPacket.CID)
tomikaa87/gree-remote
GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Device/DeviceImpl.java
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DevicePack.java // public class DevicePack extends Pack { // public static String TYPE = "dev"; // // public String cid; // public String bc; // public String brand; // public String catalog; // public String mid; // public String model; // public String name; // public String series; // public String ver; // public Integer lock; // // @SerializedName("vender") // public String vendor; // // public DevicePack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/ResultPack.java // public class ResultPack extends Pack { // public static String TYPE = "res"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("opt") // public String[] keys; // // @SerializedName("p") // public Integer[] values; // // public ResultPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Utils.java // public class Utils { // // public static class Unzipped { // public final String[] keys; // public final Integer[] values; // // public Unzipped(String[] keys, Integer[] values) { // this.keys = keys; // this.values = values; // } // } // // public static Map<String, Integer> zip(String[] keys, Integer[] values) throws IllegalArgumentException { // if (keys.length != values.length) // throw new IllegalArgumentException("Length of keys and values must match"); // // Map<String, Integer> zipped = new HashMap<>(); // for (int i = 0; i < keys.length; i++) { // zipped.put(keys[i], values[i]); // } // // return zipped; // } // // public static Unzipped unzip(Map<String, Integer> map) { // return new Unzipped(map.keySet().toArray(new String[0]), map.values().toArray(new Integer[0])); // } // // public static Map<String, Integer> getValues(DatPack pack) { // return zip(pack.keys, pack.values); // } // // public static String serializePacket(Packet packet, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // Gson gson = gsonBuilder.create(); // // if (packet.pack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = gson.toJson(packet.pack); // packet.encryptedPack = tomikaa.greeremote.Gree.Crypto.encrypt(plainPack, key); // } // // return gson.toJson(packet); // } // // public static Packet deserializePacket(String jsonString, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.registerTypeAdapter(Pack.class, new PackDeserializer()); // // Gson gson = gsonBuilder.create(); // // Packet packet = gson.fromJson(jsonString, Packet.class); // // if (packet.encryptedPack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = Crypto.decrypt(packet.encryptedPack, key); // packet.pack = gson.fromJson(plainPack, Pack.class); // } // // return packet; // } // // private static String getKey(DeviceKeyChain keyChain, Packet packet) { // String key = Crypto.GENERIC_KEY; // // Log.i("getKey", String.format("packet.cid: %s, packet.tcid: %s", packet.cid, packet.tcid)); // // if (keyChain != null) { // if (keyChain.containsKey(packet.cid)) { // key = keyChain.getKey(packet.cid); // } else if (keyChain.containsKey(packet.tcid)) { // key = keyChain.getKey(packet.tcid); // } // } // // return key; // } // }
import android.util.Log; import java.util.Map; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.DevicePack; import tomikaa.greeremote.Gree.Packs.ResultPack; import tomikaa.greeremote.Gree.Utils;
@Override public String toString() { return mParam; } } private String mName = ""; private Mode mMode = Mode.AUTO; private FanSpeed mFanSpeed = FanSpeed.AUTO; private int mTemperature = 0; private TemperatureUnit mTemperatureUnit = TemperatureUnit.CELSIUS; private boolean mPoweredOn; private boolean mLightEnabled; private boolean mQuietModeEnabled; private boolean mTurboModeEnabled; private boolean mHealthModeEnabled; private boolean mAirModeEnabled; private boolean mXfanModeEnabled; private boolean mSavingModeEnabled; private boolean mSleepModeEnabled; private VerticalSwingMode mVerticalSwingMode = VerticalSwingMode.DEFAULT; public DeviceImpl(String deviceId, DeviceManager deviceManager) { mDeviceId = deviceId; mDeviceManager = deviceManager; mLogTag = String.format("DeviceImpl(%s)", deviceId); Log.i(mLogTag, "Created"); }
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DevicePack.java // public class DevicePack extends Pack { // public static String TYPE = "dev"; // // public String cid; // public String bc; // public String brand; // public String catalog; // public String mid; // public String model; // public String name; // public String series; // public String ver; // public Integer lock; // // @SerializedName("vender") // public String vendor; // // public DevicePack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/ResultPack.java // public class ResultPack extends Pack { // public static String TYPE = "res"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("opt") // public String[] keys; // // @SerializedName("p") // public Integer[] values; // // public ResultPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Utils.java // public class Utils { // // public static class Unzipped { // public final String[] keys; // public final Integer[] values; // // public Unzipped(String[] keys, Integer[] values) { // this.keys = keys; // this.values = values; // } // } // // public static Map<String, Integer> zip(String[] keys, Integer[] values) throws IllegalArgumentException { // if (keys.length != values.length) // throw new IllegalArgumentException("Length of keys and values must match"); // // Map<String, Integer> zipped = new HashMap<>(); // for (int i = 0; i < keys.length; i++) { // zipped.put(keys[i], values[i]); // } // // return zipped; // } // // public static Unzipped unzip(Map<String, Integer> map) { // return new Unzipped(map.keySet().toArray(new String[0]), map.values().toArray(new Integer[0])); // } // // public static Map<String, Integer> getValues(DatPack pack) { // return zip(pack.keys, pack.values); // } // // public static String serializePacket(Packet packet, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // Gson gson = gsonBuilder.create(); // // if (packet.pack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = gson.toJson(packet.pack); // packet.encryptedPack = tomikaa.greeremote.Gree.Crypto.encrypt(plainPack, key); // } // // return gson.toJson(packet); // } // // public static Packet deserializePacket(String jsonString, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.registerTypeAdapter(Pack.class, new PackDeserializer()); // // Gson gson = gsonBuilder.create(); // // Packet packet = gson.fromJson(jsonString, Packet.class); // // if (packet.encryptedPack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = Crypto.decrypt(packet.encryptedPack, key); // packet.pack = gson.fromJson(plainPack, Pack.class); // } // // return packet; // } // // private static String getKey(DeviceKeyChain keyChain, Packet packet) { // String key = Crypto.GENERIC_KEY; // // Log.i("getKey", String.format("packet.cid: %s, packet.tcid: %s", packet.cid, packet.tcid)); // // if (keyChain != null) { // if (keyChain.containsKey(packet.cid)) { // key = keyChain.getKey(packet.cid); // } else if (keyChain.containsKey(packet.tcid)) { // key = keyChain.getKey(packet.tcid); // } // } // // return key; // } // } // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Device/DeviceImpl.java import android.util.Log; import java.util.Map; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.DevicePack; import tomikaa.greeremote.Gree.Packs.ResultPack; import tomikaa.greeremote.Gree.Utils; @Override public String toString() { return mParam; } } private String mName = ""; private Mode mMode = Mode.AUTO; private FanSpeed mFanSpeed = FanSpeed.AUTO; private int mTemperature = 0; private TemperatureUnit mTemperatureUnit = TemperatureUnit.CELSIUS; private boolean mPoweredOn; private boolean mLightEnabled; private boolean mQuietModeEnabled; private boolean mTurboModeEnabled; private boolean mHealthModeEnabled; private boolean mAirModeEnabled; private boolean mXfanModeEnabled; private boolean mSavingModeEnabled; private boolean mSleepModeEnabled; private VerticalSwingMode mVerticalSwingMode = VerticalSwingMode.DEFAULT; public DeviceImpl(String deviceId, DeviceManager deviceManager) { mDeviceId = deviceId; mDeviceManager = deviceManager; mLogTag = String.format("DeviceImpl(%s)", deviceId); Log.i(mLogTag, "Created"); }
public void updateWithDatPack(DatPack pack) {
tomikaa87/gree-remote
GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Device/DeviceImpl.java
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DevicePack.java // public class DevicePack extends Pack { // public static String TYPE = "dev"; // // public String cid; // public String bc; // public String brand; // public String catalog; // public String mid; // public String model; // public String name; // public String series; // public String ver; // public Integer lock; // // @SerializedName("vender") // public String vendor; // // public DevicePack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/ResultPack.java // public class ResultPack extends Pack { // public static String TYPE = "res"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("opt") // public String[] keys; // // @SerializedName("p") // public Integer[] values; // // public ResultPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Utils.java // public class Utils { // // public static class Unzipped { // public final String[] keys; // public final Integer[] values; // // public Unzipped(String[] keys, Integer[] values) { // this.keys = keys; // this.values = values; // } // } // // public static Map<String, Integer> zip(String[] keys, Integer[] values) throws IllegalArgumentException { // if (keys.length != values.length) // throw new IllegalArgumentException("Length of keys and values must match"); // // Map<String, Integer> zipped = new HashMap<>(); // for (int i = 0; i < keys.length; i++) { // zipped.put(keys[i], values[i]); // } // // return zipped; // } // // public static Unzipped unzip(Map<String, Integer> map) { // return new Unzipped(map.keySet().toArray(new String[0]), map.values().toArray(new Integer[0])); // } // // public static Map<String, Integer> getValues(DatPack pack) { // return zip(pack.keys, pack.values); // } // // public static String serializePacket(Packet packet, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // Gson gson = gsonBuilder.create(); // // if (packet.pack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = gson.toJson(packet.pack); // packet.encryptedPack = tomikaa.greeremote.Gree.Crypto.encrypt(plainPack, key); // } // // return gson.toJson(packet); // } // // public static Packet deserializePacket(String jsonString, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.registerTypeAdapter(Pack.class, new PackDeserializer()); // // Gson gson = gsonBuilder.create(); // // Packet packet = gson.fromJson(jsonString, Packet.class); // // if (packet.encryptedPack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = Crypto.decrypt(packet.encryptedPack, key); // packet.pack = gson.fromJson(plainPack, Pack.class); // } // // return packet; // } // // private static String getKey(DeviceKeyChain keyChain, Packet packet) { // String key = Crypto.GENERIC_KEY; // // Log.i("getKey", String.format("packet.cid: %s, packet.tcid: %s", packet.cid, packet.tcid)); // // if (keyChain != null) { // if (keyChain.containsKey(packet.cid)) { // key = keyChain.getKey(packet.cid); // } else if (keyChain.containsKey(packet.tcid)) { // key = keyChain.getKey(packet.tcid); // } // } // // return key; // } // }
import android.util.Log; import java.util.Map; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.DevicePack; import tomikaa.greeremote.Gree.Packs.ResultPack; import tomikaa.greeremote.Gree.Utils;
public String toString() { return mParam; } } private String mName = ""; private Mode mMode = Mode.AUTO; private FanSpeed mFanSpeed = FanSpeed.AUTO; private int mTemperature = 0; private TemperatureUnit mTemperatureUnit = TemperatureUnit.CELSIUS; private boolean mPoweredOn; private boolean mLightEnabled; private boolean mQuietModeEnabled; private boolean mTurboModeEnabled; private boolean mHealthModeEnabled; private boolean mAirModeEnabled; private boolean mXfanModeEnabled; private boolean mSavingModeEnabled; private boolean mSleepModeEnabled; private VerticalSwingMode mVerticalSwingMode = VerticalSwingMode.DEFAULT; public DeviceImpl(String deviceId, DeviceManager deviceManager) { mDeviceId = deviceId; mDeviceManager = deviceManager; mLogTag = String.format("DeviceImpl(%s)", deviceId); Log.i(mLogTag, "Created"); } public void updateWithDatPack(DatPack pack) {
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DevicePack.java // public class DevicePack extends Pack { // public static String TYPE = "dev"; // // public String cid; // public String bc; // public String brand; // public String catalog; // public String mid; // public String model; // public String name; // public String series; // public String ver; // public Integer lock; // // @SerializedName("vender") // public String vendor; // // public DevicePack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/ResultPack.java // public class ResultPack extends Pack { // public static String TYPE = "res"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("opt") // public String[] keys; // // @SerializedName("p") // public Integer[] values; // // public ResultPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Utils.java // public class Utils { // // public static class Unzipped { // public final String[] keys; // public final Integer[] values; // // public Unzipped(String[] keys, Integer[] values) { // this.keys = keys; // this.values = values; // } // } // // public static Map<String, Integer> zip(String[] keys, Integer[] values) throws IllegalArgumentException { // if (keys.length != values.length) // throw new IllegalArgumentException("Length of keys and values must match"); // // Map<String, Integer> zipped = new HashMap<>(); // for (int i = 0; i < keys.length; i++) { // zipped.put(keys[i], values[i]); // } // // return zipped; // } // // public static Unzipped unzip(Map<String, Integer> map) { // return new Unzipped(map.keySet().toArray(new String[0]), map.values().toArray(new Integer[0])); // } // // public static Map<String, Integer> getValues(DatPack pack) { // return zip(pack.keys, pack.values); // } // // public static String serializePacket(Packet packet, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // Gson gson = gsonBuilder.create(); // // if (packet.pack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = gson.toJson(packet.pack); // packet.encryptedPack = tomikaa.greeremote.Gree.Crypto.encrypt(plainPack, key); // } // // return gson.toJson(packet); // } // // public static Packet deserializePacket(String jsonString, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.registerTypeAdapter(Pack.class, new PackDeserializer()); // // Gson gson = gsonBuilder.create(); // // Packet packet = gson.fromJson(jsonString, Packet.class); // // if (packet.encryptedPack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = Crypto.decrypt(packet.encryptedPack, key); // packet.pack = gson.fromJson(plainPack, Pack.class); // } // // return packet; // } // // private static String getKey(DeviceKeyChain keyChain, Packet packet) { // String key = Crypto.GENERIC_KEY; // // Log.i("getKey", String.format("packet.cid: %s, packet.tcid: %s", packet.cid, packet.tcid)); // // if (keyChain != null) { // if (keyChain.containsKey(packet.cid)) { // key = keyChain.getKey(packet.cid); // } else if (keyChain.containsKey(packet.tcid)) { // key = keyChain.getKey(packet.tcid); // } // } // // return key; // } // } // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Device/DeviceImpl.java import android.util.Log; import java.util.Map; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.DevicePack; import tomikaa.greeremote.Gree.Packs.ResultPack; import tomikaa.greeremote.Gree.Utils; public String toString() { return mParam; } } private String mName = ""; private Mode mMode = Mode.AUTO; private FanSpeed mFanSpeed = FanSpeed.AUTO; private int mTemperature = 0; private TemperatureUnit mTemperatureUnit = TemperatureUnit.CELSIUS; private boolean mPoweredOn; private boolean mLightEnabled; private boolean mQuietModeEnabled; private boolean mTurboModeEnabled; private boolean mHealthModeEnabled; private boolean mAirModeEnabled; private boolean mXfanModeEnabled; private boolean mSavingModeEnabled; private boolean mSleepModeEnabled; private VerticalSwingMode mVerticalSwingMode = VerticalSwingMode.DEFAULT; public DeviceImpl(String deviceId, DeviceManager deviceManager) { mDeviceId = deviceId; mDeviceManager = deviceManager; mLogTag = String.format("DeviceImpl(%s)", deviceId); Log.i(mLogTag, "Created"); } public void updateWithDatPack(DatPack pack) {
updateParameters(Utils.zip(pack.keys, pack.values));
tomikaa87/gree-remote
GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Device/DeviceImpl.java
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DevicePack.java // public class DevicePack extends Pack { // public static String TYPE = "dev"; // // public String cid; // public String bc; // public String brand; // public String catalog; // public String mid; // public String model; // public String name; // public String series; // public String ver; // public Integer lock; // // @SerializedName("vender") // public String vendor; // // public DevicePack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/ResultPack.java // public class ResultPack extends Pack { // public static String TYPE = "res"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("opt") // public String[] keys; // // @SerializedName("p") // public Integer[] values; // // public ResultPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Utils.java // public class Utils { // // public static class Unzipped { // public final String[] keys; // public final Integer[] values; // // public Unzipped(String[] keys, Integer[] values) { // this.keys = keys; // this.values = values; // } // } // // public static Map<String, Integer> zip(String[] keys, Integer[] values) throws IllegalArgumentException { // if (keys.length != values.length) // throw new IllegalArgumentException("Length of keys and values must match"); // // Map<String, Integer> zipped = new HashMap<>(); // for (int i = 0; i < keys.length; i++) { // zipped.put(keys[i], values[i]); // } // // return zipped; // } // // public static Unzipped unzip(Map<String, Integer> map) { // return new Unzipped(map.keySet().toArray(new String[0]), map.values().toArray(new Integer[0])); // } // // public static Map<String, Integer> getValues(DatPack pack) { // return zip(pack.keys, pack.values); // } // // public static String serializePacket(Packet packet, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // Gson gson = gsonBuilder.create(); // // if (packet.pack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = gson.toJson(packet.pack); // packet.encryptedPack = tomikaa.greeremote.Gree.Crypto.encrypt(plainPack, key); // } // // return gson.toJson(packet); // } // // public static Packet deserializePacket(String jsonString, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.registerTypeAdapter(Pack.class, new PackDeserializer()); // // Gson gson = gsonBuilder.create(); // // Packet packet = gson.fromJson(jsonString, Packet.class); // // if (packet.encryptedPack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = Crypto.decrypt(packet.encryptedPack, key); // packet.pack = gson.fromJson(plainPack, Pack.class); // } // // return packet; // } // // private static String getKey(DeviceKeyChain keyChain, Packet packet) { // String key = Crypto.GENERIC_KEY; // // Log.i("getKey", String.format("packet.cid: %s, packet.tcid: %s", packet.cid, packet.tcid)); // // if (keyChain != null) { // if (keyChain.containsKey(packet.cid)) { // key = keyChain.getKey(packet.cid); // } else if (keyChain.containsKey(packet.tcid)) { // key = keyChain.getKey(packet.tcid); // } // } // // return key; // } // }
import android.util.Log; import java.util.Map; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.DevicePack; import tomikaa.greeremote.Gree.Packs.ResultPack; import tomikaa.greeremote.Gree.Utils;
} private String mName = ""; private Mode mMode = Mode.AUTO; private FanSpeed mFanSpeed = FanSpeed.AUTO; private int mTemperature = 0; private TemperatureUnit mTemperatureUnit = TemperatureUnit.CELSIUS; private boolean mPoweredOn; private boolean mLightEnabled; private boolean mQuietModeEnabled; private boolean mTurboModeEnabled; private boolean mHealthModeEnabled; private boolean mAirModeEnabled; private boolean mXfanModeEnabled; private boolean mSavingModeEnabled; private boolean mSleepModeEnabled; private VerticalSwingMode mVerticalSwingMode = VerticalSwingMode.DEFAULT; public DeviceImpl(String deviceId, DeviceManager deviceManager) { mDeviceId = deviceId; mDeviceManager = deviceManager; mLogTag = String.format("DeviceImpl(%s)", deviceId); Log.i(mLogTag, "Created"); } public void updateWithDatPack(DatPack pack) { updateParameters(Utils.zip(pack.keys, pack.values)); }
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DevicePack.java // public class DevicePack extends Pack { // public static String TYPE = "dev"; // // public String cid; // public String bc; // public String brand; // public String catalog; // public String mid; // public String model; // public String name; // public String series; // public String ver; // public Integer lock; // // @SerializedName("vender") // public String vendor; // // public DevicePack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/ResultPack.java // public class ResultPack extends Pack { // public static String TYPE = "res"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("opt") // public String[] keys; // // @SerializedName("p") // public Integer[] values; // // public ResultPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Utils.java // public class Utils { // // public static class Unzipped { // public final String[] keys; // public final Integer[] values; // // public Unzipped(String[] keys, Integer[] values) { // this.keys = keys; // this.values = values; // } // } // // public static Map<String, Integer> zip(String[] keys, Integer[] values) throws IllegalArgumentException { // if (keys.length != values.length) // throw new IllegalArgumentException("Length of keys and values must match"); // // Map<String, Integer> zipped = new HashMap<>(); // for (int i = 0; i < keys.length; i++) { // zipped.put(keys[i], values[i]); // } // // return zipped; // } // // public static Unzipped unzip(Map<String, Integer> map) { // return new Unzipped(map.keySet().toArray(new String[0]), map.values().toArray(new Integer[0])); // } // // public static Map<String, Integer> getValues(DatPack pack) { // return zip(pack.keys, pack.values); // } // // public static String serializePacket(Packet packet, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // Gson gson = gsonBuilder.create(); // // if (packet.pack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = gson.toJson(packet.pack); // packet.encryptedPack = tomikaa.greeremote.Gree.Crypto.encrypt(plainPack, key); // } // // return gson.toJson(packet); // } // // public static Packet deserializePacket(String jsonString, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.registerTypeAdapter(Pack.class, new PackDeserializer()); // // Gson gson = gsonBuilder.create(); // // Packet packet = gson.fromJson(jsonString, Packet.class); // // if (packet.encryptedPack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = Crypto.decrypt(packet.encryptedPack, key); // packet.pack = gson.fromJson(plainPack, Pack.class); // } // // return packet; // } // // private static String getKey(DeviceKeyChain keyChain, Packet packet) { // String key = Crypto.GENERIC_KEY; // // Log.i("getKey", String.format("packet.cid: %s, packet.tcid: %s", packet.cid, packet.tcid)); // // if (keyChain != null) { // if (keyChain.containsKey(packet.cid)) { // key = keyChain.getKey(packet.cid); // } else if (keyChain.containsKey(packet.tcid)) { // key = keyChain.getKey(packet.tcid); // } // } // // return key; // } // } // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Device/DeviceImpl.java import android.util.Log; import java.util.Map; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.DevicePack; import tomikaa.greeremote.Gree.Packs.ResultPack; import tomikaa.greeremote.Gree.Utils; } private String mName = ""; private Mode mMode = Mode.AUTO; private FanSpeed mFanSpeed = FanSpeed.AUTO; private int mTemperature = 0; private TemperatureUnit mTemperatureUnit = TemperatureUnit.CELSIUS; private boolean mPoweredOn; private boolean mLightEnabled; private boolean mQuietModeEnabled; private boolean mTurboModeEnabled; private boolean mHealthModeEnabled; private boolean mAirModeEnabled; private boolean mXfanModeEnabled; private boolean mSavingModeEnabled; private boolean mSleepModeEnabled; private VerticalSwingMode mVerticalSwingMode = VerticalSwingMode.DEFAULT; public DeviceImpl(String deviceId, DeviceManager deviceManager) { mDeviceId = deviceId; mDeviceManager = deviceManager; mLogTag = String.format("DeviceImpl(%s)", deviceId); Log.i(mLogTag, "Created"); } public void updateWithDatPack(DatPack pack) { updateParameters(Utils.zip(pack.keys, pack.values)); }
public void updateWithResultPack(ResultPack pack) {
tomikaa87/gree-remote
GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Device/DeviceImpl.java
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DevicePack.java // public class DevicePack extends Pack { // public static String TYPE = "dev"; // // public String cid; // public String bc; // public String brand; // public String catalog; // public String mid; // public String model; // public String name; // public String series; // public String ver; // public Integer lock; // // @SerializedName("vender") // public String vendor; // // public DevicePack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/ResultPack.java // public class ResultPack extends Pack { // public static String TYPE = "res"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("opt") // public String[] keys; // // @SerializedName("p") // public Integer[] values; // // public ResultPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Utils.java // public class Utils { // // public static class Unzipped { // public final String[] keys; // public final Integer[] values; // // public Unzipped(String[] keys, Integer[] values) { // this.keys = keys; // this.values = values; // } // } // // public static Map<String, Integer> zip(String[] keys, Integer[] values) throws IllegalArgumentException { // if (keys.length != values.length) // throw new IllegalArgumentException("Length of keys and values must match"); // // Map<String, Integer> zipped = new HashMap<>(); // for (int i = 0; i < keys.length; i++) { // zipped.put(keys[i], values[i]); // } // // return zipped; // } // // public static Unzipped unzip(Map<String, Integer> map) { // return new Unzipped(map.keySet().toArray(new String[0]), map.values().toArray(new Integer[0])); // } // // public static Map<String, Integer> getValues(DatPack pack) { // return zip(pack.keys, pack.values); // } // // public static String serializePacket(Packet packet, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // Gson gson = gsonBuilder.create(); // // if (packet.pack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = gson.toJson(packet.pack); // packet.encryptedPack = tomikaa.greeremote.Gree.Crypto.encrypt(plainPack, key); // } // // return gson.toJson(packet); // } // // public static Packet deserializePacket(String jsonString, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.registerTypeAdapter(Pack.class, new PackDeserializer()); // // Gson gson = gsonBuilder.create(); // // Packet packet = gson.fromJson(jsonString, Packet.class); // // if (packet.encryptedPack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = Crypto.decrypt(packet.encryptedPack, key); // packet.pack = gson.fromJson(plainPack, Pack.class); // } // // return packet; // } // // private static String getKey(DeviceKeyChain keyChain, Packet packet) { // String key = Crypto.GENERIC_KEY; // // Log.i("getKey", String.format("packet.cid: %s, packet.tcid: %s", packet.cid, packet.tcid)); // // if (keyChain != null) { // if (keyChain.containsKey(packet.cid)) { // key = keyChain.getKey(packet.cid); // } else if (keyChain.containsKey(packet.tcid)) { // key = keyChain.getKey(packet.tcid); // } // } // // return key; // } // }
import android.util.Log; import java.util.Map; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.DevicePack; import tomikaa.greeremote.Gree.Packs.ResultPack; import tomikaa.greeremote.Gree.Utils;
private FanSpeed mFanSpeed = FanSpeed.AUTO; private int mTemperature = 0; private TemperatureUnit mTemperatureUnit = TemperatureUnit.CELSIUS; private boolean mPoweredOn; private boolean mLightEnabled; private boolean mQuietModeEnabled; private boolean mTurboModeEnabled; private boolean mHealthModeEnabled; private boolean mAirModeEnabled; private boolean mXfanModeEnabled; private boolean mSavingModeEnabled; private boolean mSleepModeEnabled; private VerticalSwingMode mVerticalSwingMode = VerticalSwingMode.DEFAULT; public DeviceImpl(String deviceId, DeviceManager deviceManager) { mDeviceId = deviceId; mDeviceManager = deviceManager; mLogTag = String.format("DeviceImpl(%s)", deviceId); Log.i(mLogTag, "Created"); } public void updateWithDatPack(DatPack pack) { updateParameters(Utils.zip(pack.keys, pack.values)); } public void updateWithResultPack(ResultPack pack) { updateParameters(Utils.zip(pack.keys, pack.values)); }
// Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DatPack.java // public class DatPack extends Pack { // public static String TYPE = "dat"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("cols") // public String[] keys; // // @SerializedName("dat") // public Integer[] values; // // public DatPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/DevicePack.java // public class DevicePack extends Pack { // public static String TYPE = "dev"; // // public String cid; // public String bc; // public String brand; // public String catalog; // public String mid; // public String model; // public String name; // public String series; // public String ver; // public Integer lock; // // @SerializedName("vender") // public String vendor; // // public DevicePack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Packs/ResultPack.java // public class ResultPack extends Pack { // public static String TYPE = "res"; // // @SerializedName("r") // public int resultCode; // // @SerializedName("opt") // public String[] keys; // // @SerializedName("p") // public Integer[] values; // // public ResultPack() { // type = TYPE; // } // } // // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Utils.java // public class Utils { // // public static class Unzipped { // public final String[] keys; // public final Integer[] values; // // public Unzipped(String[] keys, Integer[] values) { // this.keys = keys; // this.values = values; // } // } // // public static Map<String, Integer> zip(String[] keys, Integer[] values) throws IllegalArgumentException { // if (keys.length != values.length) // throw new IllegalArgumentException("Length of keys and values must match"); // // Map<String, Integer> zipped = new HashMap<>(); // for (int i = 0; i < keys.length; i++) { // zipped.put(keys[i], values[i]); // } // // return zipped; // } // // public static Unzipped unzip(Map<String, Integer> map) { // return new Unzipped(map.keySet().toArray(new String[0]), map.values().toArray(new Integer[0])); // } // // public static Map<String, Integer> getValues(DatPack pack) { // return zip(pack.keys, pack.values); // } // // public static String serializePacket(Packet packet, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // Gson gson = gsonBuilder.create(); // // if (packet.pack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = gson.toJson(packet.pack); // packet.encryptedPack = tomikaa.greeremote.Gree.Crypto.encrypt(plainPack, key); // } // // return gson.toJson(packet); // } // // public static Packet deserializePacket(String jsonString, DeviceKeyChain deviceKeyChain) { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.registerTypeAdapter(Pack.class, new PackDeserializer()); // // Gson gson = gsonBuilder.create(); // // Packet packet = gson.fromJson(jsonString, Packet.class); // // if (packet.encryptedPack != null) { // String key = getKey(deviceKeyChain, packet); // String plainPack = Crypto.decrypt(packet.encryptedPack, key); // packet.pack = gson.fromJson(plainPack, Pack.class); // } // // return packet; // } // // private static String getKey(DeviceKeyChain keyChain, Packet packet) { // String key = Crypto.GENERIC_KEY; // // Log.i("getKey", String.format("packet.cid: %s, packet.tcid: %s", packet.cid, packet.tcid)); // // if (keyChain != null) { // if (keyChain.containsKey(packet.cid)) { // key = keyChain.getKey(packet.cid); // } else if (keyChain.containsKey(packet.tcid)) { // key = keyChain.getKey(packet.tcid); // } // } // // return key; // } // } // Path: GreeRemoteAndroid/app/src/main/java/tomikaa/greeremote/Gree/Device/DeviceImpl.java import android.util.Log; import java.util.Map; import tomikaa.greeremote.Gree.Packs.DatPack; import tomikaa.greeremote.Gree.Packs.DevicePack; import tomikaa.greeremote.Gree.Packs.ResultPack; import tomikaa.greeremote.Gree.Utils; private FanSpeed mFanSpeed = FanSpeed.AUTO; private int mTemperature = 0; private TemperatureUnit mTemperatureUnit = TemperatureUnit.CELSIUS; private boolean mPoweredOn; private boolean mLightEnabled; private boolean mQuietModeEnabled; private boolean mTurboModeEnabled; private boolean mHealthModeEnabled; private boolean mAirModeEnabled; private boolean mXfanModeEnabled; private boolean mSavingModeEnabled; private boolean mSleepModeEnabled; private VerticalSwingMode mVerticalSwingMode = VerticalSwingMode.DEFAULT; public DeviceImpl(String deviceId, DeviceManager deviceManager) { mDeviceId = deviceId; mDeviceManager = deviceManager; mLogTag = String.format("DeviceImpl(%s)", deviceId); Log.i(mLogTag, "Created"); } public void updateWithDatPack(DatPack pack) { updateParameters(Utils.zip(pack.keys, pack.values)); } public void updateWithResultPack(ResultPack pack) { updateParameters(Utils.zip(pack.keys, pack.values)); }
public void updateWithDevicePack(DevicePack pack) {
ssseasonnn/PracticalRecyclerView
app/src/main/java/zlc/season/demo/expand/ParentBean.java
// Path: app/src/main/java/zlc/season/demo/RecyclerItemType.java // public enum RecyclerItemType { // NORMAL(0), TYPE1(1), TYPE2(2), TYPE3(3), PARENT(4), CHILD(5); // // // 定义私有变量 // private int nCode; // // RecyclerItemType(int _nCode) { // this.nCode = _nCode; // } // // public int getValue() { // return this.nCode; // } // } // // Path: practicalrecyclerview/src/main/java/zlc/season/practicalrecyclerview/ItemType.java // public interface ItemType { // int itemType(); // }
import com.google.gson.annotations.SerializedName; import java.util.List; import zlc.season.demo.RecyclerItemType; import zlc.season.practicalrecyclerview.ItemType;
package zlc.season.demo.expand; /** * Author: Season(ssseasonnn@gmail.com) * Date: 2016/10/17 * Time: 15:28 * FIXME */ class ParentBean implements ItemType { @SerializedName("text") int text; @SerializedName("child") List<ChildBean> mChild; /** * 是否展开 */ boolean isExpand; @Override public int itemType() {
// Path: app/src/main/java/zlc/season/demo/RecyclerItemType.java // public enum RecyclerItemType { // NORMAL(0), TYPE1(1), TYPE2(2), TYPE3(3), PARENT(4), CHILD(5); // // // 定义私有变量 // private int nCode; // // RecyclerItemType(int _nCode) { // this.nCode = _nCode; // } // // public int getValue() { // return this.nCode; // } // } // // Path: practicalrecyclerview/src/main/java/zlc/season/practicalrecyclerview/ItemType.java // public interface ItemType { // int itemType(); // } // Path: app/src/main/java/zlc/season/demo/expand/ParentBean.java import com.google.gson.annotations.SerializedName; import java.util.List; import zlc.season.demo.RecyclerItemType; import zlc.season.practicalrecyclerview.ItemType; package zlc.season.demo.expand; /** * Author: Season(ssseasonnn@gmail.com) * Date: 2016/10/17 * Time: 15:28 * FIXME */ class ParentBean implements ItemType { @SerializedName("text") int text; @SerializedName("child") List<ChildBean> mChild; /** * 是否展开 */ boolean isExpand; @Override public int itemType() {
return RecyclerItemType.PARENT.getValue();
ssseasonnn/PracticalRecyclerView
app/src/main/java/zlc/season/demo/multipleitem/MultiItemPresenter.java
// Path: practicalrecyclerview/src/main/java/zlc/season/practicalrecyclerview/ItemType.java // public interface ItemType { // int itemType(); // }
import android.content.Context; import android.util.Log; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import rx.Observable; import rx.Observer; import rx.Subscriber; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import rx.subscriptions.CompositeSubscription; import zlc.season.practicalrecyclerview.ItemType;
package zlc.season.demo.multipleitem; /** * Author: Season(ssseasonnn@gmail.com) * Date: 2016/10/10 * Time: 12:07 * FIXME */ public class MultiItemPresenter { private static int count = -1; private CompositeSubscription mSubscriptions; private MultiItemView mView; private Context mContext; MultiItemPresenter(Context context) { mContext = context; mSubscriptions = new CompositeSubscription(); } void setDataLoadCallBack(MultiItemView itemView) { mView = itemView; } void unsubscribeAll() { mSubscriptions.clear(); } void loadData(final boolean isRefresh) { Subscription subscription = createObservable() .subscribeOn(Schedulers.io()) .delay(2, TimeUnit.SECONDS) .observeOn(AndroidSchedulers.mainThread())
// Path: practicalrecyclerview/src/main/java/zlc/season/practicalrecyclerview/ItemType.java // public interface ItemType { // int itemType(); // } // Path: app/src/main/java/zlc/season/demo/multipleitem/MultiItemPresenter.java import android.content.Context; import android.util.Log; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import rx.Observable; import rx.Observer; import rx.Subscriber; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import rx.subscriptions.CompositeSubscription; import zlc.season.practicalrecyclerview.ItemType; package zlc.season.demo.multipleitem; /** * Author: Season(ssseasonnn@gmail.com) * Date: 2016/10/10 * Time: 12:07 * FIXME */ public class MultiItemPresenter { private static int count = -1; private CompositeSubscription mSubscriptions; private MultiItemView mView; private Context mContext; MultiItemPresenter(Context context) { mContext = context; mSubscriptions = new CompositeSubscription(); } void setDataLoadCallBack(MultiItemView itemView) { mView = itemView; } void unsubscribeAll() { mSubscriptions.clear(); } void loadData(final boolean isRefresh) { Subscription subscription = createObservable() .subscribeOn(Schedulers.io()) .delay(2, TimeUnit.SECONDS) .observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<List<ItemType>>() {
ssseasonnn/PracticalRecyclerView
app/src/main/java/zlc/season/demo/multipleitem/TypeOneBean.java
// Path: app/src/main/java/zlc/season/demo/RecyclerItemType.java // public enum RecyclerItemType { // NORMAL(0), TYPE1(1), TYPE2(2), TYPE3(3), PARENT(4), CHILD(5); // // // 定义私有变量 // private int nCode; // // RecyclerItemType(int _nCode) { // this.nCode = _nCode; // } // // public int getValue() { // return this.nCode; // } // } // // Path: practicalrecyclerview/src/main/java/zlc/season/practicalrecyclerview/ItemType.java // public interface ItemType { // int itemType(); // }
import zlc.season.demo.RecyclerItemType; import zlc.season.practicalrecyclerview.ItemType;
package zlc.season.demo.multipleitem; /** * Author: Season(ssseasonnn@gmail.com) * Date: 2016/9/21 * Time: 15:11 * FIXME */ class TypeOneBean implements ItemType { public String text; public TypeOneBean(String text) { this.text = text; } @Override public int itemType() {
// Path: app/src/main/java/zlc/season/demo/RecyclerItemType.java // public enum RecyclerItemType { // NORMAL(0), TYPE1(1), TYPE2(2), TYPE3(3), PARENT(4), CHILD(5); // // // 定义私有变量 // private int nCode; // // RecyclerItemType(int _nCode) { // this.nCode = _nCode; // } // // public int getValue() { // return this.nCode; // } // } // // Path: practicalrecyclerview/src/main/java/zlc/season/practicalrecyclerview/ItemType.java // public interface ItemType { // int itemType(); // } // Path: app/src/main/java/zlc/season/demo/multipleitem/TypeOneBean.java import zlc.season.demo.RecyclerItemType; import zlc.season.practicalrecyclerview.ItemType; package zlc.season.demo.multipleitem; /** * Author: Season(ssseasonnn@gmail.com) * Date: 2016/9/21 * Time: 15:11 * FIXME */ class TypeOneBean implements ItemType { public String text; public TypeOneBean(String text) { this.text = text; } @Override public int itemType() {
return RecyclerItemType.TYPE1.getValue();
ssseasonnn/PracticalRecyclerView
app/src/main/java/zlc/season/demo/expand/ChildBean.java
// Path: app/src/main/java/zlc/season/demo/RecyclerItemType.java // public enum RecyclerItemType { // NORMAL(0), TYPE1(1), TYPE2(2), TYPE3(3), PARENT(4), CHILD(5); // // // 定义私有变量 // private int nCode; // // RecyclerItemType(int _nCode) { // this.nCode = _nCode; // } // // public int getValue() { // return this.nCode; // } // } // // Path: practicalrecyclerview/src/main/java/zlc/season/practicalrecyclerview/ItemType.java // public interface ItemType { // int itemType(); // }
import com.google.gson.annotations.SerializedName; import zlc.season.demo.RecyclerItemType; import zlc.season.practicalrecyclerview.ItemType;
package zlc.season.demo.expand; /** * Author: Season(ssseasonnn@gmail.com) * Date: 2016/10/17 * Time: 15:29 * FIXME */ class ChildBean implements ItemType { @SerializedName("text") int text; @Override public int itemType() {
// Path: app/src/main/java/zlc/season/demo/RecyclerItemType.java // public enum RecyclerItemType { // NORMAL(0), TYPE1(1), TYPE2(2), TYPE3(3), PARENT(4), CHILD(5); // // // 定义私有变量 // private int nCode; // // RecyclerItemType(int _nCode) { // this.nCode = _nCode; // } // // public int getValue() { // return this.nCode; // } // } // // Path: practicalrecyclerview/src/main/java/zlc/season/practicalrecyclerview/ItemType.java // public interface ItemType { // int itemType(); // } // Path: app/src/main/java/zlc/season/demo/expand/ChildBean.java import com.google.gson.annotations.SerializedName; import zlc.season.demo.RecyclerItemType; import zlc.season.practicalrecyclerview.ItemType; package zlc.season.demo.expand; /** * Author: Season(ssseasonnn@gmail.com) * Date: 2016/10/17 * Time: 15:29 * FIXME */ class ChildBean implements ItemType { @SerializedName("text") int text; @Override public int itemType() {
return RecyclerItemType.CHILD.getValue();
ssseasonnn/PracticalRecyclerView
app/src/main/java/zlc/season/demo/multipleitem/TypeTwoBean.java
// Path: app/src/main/java/zlc/season/demo/RecyclerItemType.java // public enum RecyclerItemType { // NORMAL(0), TYPE1(1), TYPE2(2), TYPE3(3), PARENT(4), CHILD(5); // // // 定义私有变量 // private int nCode; // // RecyclerItemType(int _nCode) { // this.nCode = _nCode; // } // // public int getValue() { // return this.nCode; // } // } // // Path: practicalrecyclerview/src/main/java/zlc/season/practicalrecyclerview/ItemType.java // public interface ItemType { // int itemType(); // }
import zlc.season.demo.RecyclerItemType; import zlc.season.practicalrecyclerview.ItemType;
package zlc.season.demo.multipleitem; /** * Author: Season(ssseasonnn@gmail.com) * Date: 2016/10/10 * Time: 11:56 * FIXME */ public class TypeTwoBean implements ItemType { String text; public TypeTwoBean(String text) { this.text = text; } @Override public int itemType() {
// Path: app/src/main/java/zlc/season/demo/RecyclerItemType.java // public enum RecyclerItemType { // NORMAL(0), TYPE1(1), TYPE2(2), TYPE3(3), PARENT(4), CHILD(5); // // // 定义私有变量 // private int nCode; // // RecyclerItemType(int _nCode) { // this.nCode = _nCode; // } // // public int getValue() { // return this.nCode; // } // } // // Path: practicalrecyclerview/src/main/java/zlc/season/practicalrecyclerview/ItemType.java // public interface ItemType { // int itemType(); // } // Path: app/src/main/java/zlc/season/demo/multipleitem/TypeTwoBean.java import zlc.season.demo.RecyclerItemType; import zlc.season.practicalrecyclerview.ItemType; package zlc.season.demo.multipleitem; /** * Author: Season(ssseasonnn@gmail.com) * Date: 2016/10/10 * Time: 11:56 * FIXME */ public class TypeTwoBean implements ItemType { String text; public TypeTwoBean(String text) { this.text = text; } @Override public int itemType() {
return RecyclerItemType.TYPE2.getValue();
luminis-ams/elastic-rest-spring-wrapper
src/main/java/eu/luminis/elastic/index/SingleClusterIndexService.java
// Path: src/main/java/eu/luminis/elastic/SingleClusterRestClientFactoryBean.java // public static final String DEFAULT_CLUSTER_NAME = "default-cluster";
import static eu.luminis.elastic.SingleClusterRestClientFactoryBean.DEFAULT_CLUSTER_NAME;
package eu.luminis.elastic.index; /** * Wrapper for the {@code IndexService} without the option to work with multiple clusters. Only the default cluster * is available. */ public class SingleClusterIndexService { private IndexService indexService; /** * Default constructor * * @param indexService wrapped index service */ public SingleClusterIndexService(IndexService indexService) { this.indexService = indexService; } /** * Checks if the cluster with the provided cluster name contains an index with the provided index name * * @param indexName The name of the index to check for existence * @return True if the index exists in the cluster with the provided name */ public Boolean indexExist(String indexName) {
// Path: src/main/java/eu/luminis/elastic/SingleClusterRestClientFactoryBean.java // public static final String DEFAULT_CLUSTER_NAME = "default-cluster"; // Path: src/main/java/eu/luminis/elastic/index/SingleClusterIndexService.java import static eu.luminis.elastic.SingleClusterRestClientFactoryBean.DEFAULT_CLUSTER_NAME; package eu.luminis.elastic.index; /** * Wrapper for the {@code IndexService} without the option to work with multiple clusters. Only the default cluster * is available. */ public class SingleClusterIndexService { private IndexService indexService; /** * Default constructor * * @param indexService wrapped index service */ public SingleClusterIndexService(IndexService indexService) { this.indexService = indexService; } /** * Checks if the cluster with the provided cluster name contains an index with the provided index name * * @param indexName The name of the index to check for existence * @return True if the index exists in the cluster with the provided name */ public Boolean indexExist(String indexName) {
return indexService.indexExist(DEFAULT_CLUSTER_NAME, indexName);
luminis-ams/elastic-rest-spring-wrapper
src/main/java/eu/luminis/elastic/search/response/HitsAggsResponse.java
// Path: src/main/java/eu/luminis/elastic/search/response/aggregations/Aggregation.java // public class Aggregation { // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: src/main/java/eu/luminis/elastic/search/response/aggregations/AggregationKeyDeserializer.java // public class AggregationKeyDeserializer extends KeyDeserializer { // @Override // public String deserializeKey(String key, DeserializationContext ctxt) throws IOException { // int position = key.indexOf('#'); // if (position == -1) { // throw ctxt.mappingException(String.format("Key %s should have structure type#key for aggregations", key)); // } // return key.substring(position + 1); // } // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import eu.luminis.elastic.search.response.aggregations.Aggregation; import eu.luminis.elastic.search.response.aggregations.AggregationKeyDeserializer; import java.util.Map;
package eu.luminis.elastic.search.response; /** * Main response class for aggregations response. Can contain hits and aggregations */ public class HitsAggsResponse<T> extends HitsResponse<T> { @JsonProperty
// Path: src/main/java/eu/luminis/elastic/search/response/aggregations/Aggregation.java // public class Aggregation { // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: src/main/java/eu/luminis/elastic/search/response/aggregations/AggregationKeyDeserializer.java // public class AggregationKeyDeserializer extends KeyDeserializer { // @Override // public String deserializeKey(String key, DeserializationContext ctxt) throws IOException { // int position = key.indexOf('#'); // if (position == -1) { // throw ctxt.mappingException(String.format("Key %s should have structure type#key for aggregations", key)); // } // return key.substring(position + 1); // } // } // Path: src/main/java/eu/luminis/elastic/search/response/HitsAggsResponse.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import eu.luminis.elastic.search.response.aggregations.Aggregation; import eu.luminis.elastic.search.response.aggregations.AggregationKeyDeserializer; import java.util.Map; package eu.luminis.elastic.search.response; /** * Main response class for aggregations response. Can contain hits and aggregations */ public class HitsAggsResponse<T> extends HitsResponse<T> { @JsonProperty
@JsonDeserialize(keyUsing = AggregationKeyDeserializer.class)
luminis-ams/elastic-rest-spring-wrapper
src/main/java/eu/luminis/elastic/search/response/HitsAggsResponse.java
// Path: src/main/java/eu/luminis/elastic/search/response/aggregations/Aggregation.java // public class Aggregation { // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: src/main/java/eu/luminis/elastic/search/response/aggregations/AggregationKeyDeserializer.java // public class AggregationKeyDeserializer extends KeyDeserializer { // @Override // public String deserializeKey(String key, DeserializationContext ctxt) throws IOException { // int position = key.indexOf('#'); // if (position == -1) { // throw ctxt.mappingException(String.format("Key %s should have structure type#key for aggregations", key)); // } // return key.substring(position + 1); // } // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import eu.luminis.elastic.search.response.aggregations.Aggregation; import eu.luminis.elastic.search.response.aggregations.AggregationKeyDeserializer; import java.util.Map;
package eu.luminis.elastic.search.response; /** * Main response class for aggregations response. Can contain hits and aggregations */ public class HitsAggsResponse<T> extends HitsResponse<T> { @JsonProperty @JsonDeserialize(keyUsing = AggregationKeyDeserializer.class)
// Path: src/main/java/eu/luminis/elastic/search/response/aggregations/Aggregation.java // public class Aggregation { // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: src/main/java/eu/luminis/elastic/search/response/aggregations/AggregationKeyDeserializer.java // public class AggregationKeyDeserializer extends KeyDeserializer { // @Override // public String deserializeKey(String key, DeserializationContext ctxt) throws IOException { // int position = key.indexOf('#'); // if (position == -1) { // throw ctxt.mappingException(String.format("Key %s should have structure type#key for aggregations", key)); // } // return key.substring(position + 1); // } // } // Path: src/main/java/eu/luminis/elastic/search/response/HitsAggsResponse.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import eu.luminis.elastic.search.response.aggregations.Aggregation; import eu.luminis.elastic.search.response.aggregations.AggregationKeyDeserializer; import java.util.Map; package eu.luminis.elastic.search.response; /** * Main response class for aggregations response. Can contain hits and aggregations */ public class HitsAggsResponse<T> extends HitsResponse<T> { @JsonProperty @JsonDeserialize(keyUsing = AggregationKeyDeserializer.class)
private Map<String, Aggregation> aggregations;
luminis-ams/elastic-rest-spring-wrapper
src/main/java/eu/luminis/elastic/search/response/aggregations/metric/MetricResponse.java
// Path: src/main/java/eu/luminis/elastic/document/response/Shards.java // public class Shards { // private Integer total; // // private Integer successful; // // private Integer failed; // // private Integer skipped; // // public Integer getFailed() { // return failed; // } // // public void setFailed(Integer failed) { // this.failed = failed; // } // // public Integer getSuccessful() { // return successful; // } // // public void setSuccessful(Integer successful) { // this.successful = successful; // } // // public Integer getTotal() { // return total; // } // // public void setTotal(Integer total) { // this.total = total; // } // // public Integer getSkipped() { // return skipped; // } // // public void setSkipped(Integer skipped) { // this.skipped = skipped; // } // }
import com.fasterxml.jackson.annotation.JsonProperty; import eu.luminis.elastic.document.response.Shards;
package eu.luminis.elastic.search.response.aggregations.metric; public class MetricResponse { @JsonProperty(value = "_shards")
// Path: src/main/java/eu/luminis/elastic/document/response/Shards.java // public class Shards { // private Integer total; // // private Integer successful; // // private Integer failed; // // private Integer skipped; // // public Integer getFailed() { // return failed; // } // // public void setFailed(Integer failed) { // this.failed = failed; // } // // public Integer getSuccessful() { // return successful; // } // // public void setSuccessful(Integer successful) { // this.successful = successful; // } // // public Integer getTotal() { // return total; // } // // public void setTotal(Integer total) { // this.total = total; // } // // public Integer getSkipped() { // return skipped; // } // // public void setSkipped(Integer skipped) { // this.skipped = skipped; // } // } // Path: src/main/java/eu/luminis/elastic/search/response/aggregations/metric/MetricResponse.java import com.fasterxml.jackson.annotation.JsonProperty; import eu.luminis.elastic.document.response.Shards; package eu.luminis.elastic.search.response.aggregations.metric; public class MetricResponse { @JsonProperty(value = "_shards")
private Shards shards;
luminis-ams/elastic-rest-spring-wrapper
src/main/java/eu/luminis/elastic/search/SingleClusterSearchService.java
// Path: src/main/java/eu/luminis/elastic/search/response/HitsAggsResponse.java // public class HitsAggsResponse<T> extends HitsResponse<T> { // // @JsonProperty // @JsonDeserialize(keyUsing = AggregationKeyDeserializer.class) // private Map<String, Aggregation> aggregations; // // public Map<String, Aggregation> getAggregations() { // return aggregations; // } // // public void setAggregations(Map<String, Aggregation> aggregations) { // this.aggregations = aggregations; // } // } // // Path: src/main/java/eu/luminis/elastic/search/response/HitsResponse.java // public class HitsResponse<T> { // private List<T> hits; // private long totalHits; // private long responseTime; // private Boolean timedOut; // // public List<T> getHits() { // return hits; // } // // public void setHits(List<T> hits) { // this.hits = hits; // } // // public long getTotalHits() { // return totalHits; // } // // public void setTotalHits(long totalHits) { // this.totalHits = totalHits; // } // // public long getResponseTime() { // return responseTime; // } // // public void setResponseTime(long responseTime) { // this.responseTime = responseTime; // } // // public Boolean getTimedOut() { // return timedOut; // } // // public void setTimedOut(Boolean timedOut) { // this.timedOut = timedOut; // } // } // // Path: src/main/java/eu/luminis/elastic/SingleClusterRestClientFactoryBean.java // public static final String DEFAULT_CLUSTER_NAME = "default-cluster";
import eu.luminis.elastic.search.response.HitsAggsResponse; import eu.luminis.elastic.search.response.HitsResponse; import static eu.luminis.elastic.SingleClusterRestClientFactoryBean.DEFAULT_CLUSTER_NAME;
package eu.luminis.elastic.search; public class SingleClusterSearchService { private SearchService searchService; public SingleClusterSearchService(SearchService searchService) { this.searchService = searchService; }
// Path: src/main/java/eu/luminis/elastic/search/response/HitsAggsResponse.java // public class HitsAggsResponse<T> extends HitsResponse<T> { // // @JsonProperty // @JsonDeserialize(keyUsing = AggregationKeyDeserializer.class) // private Map<String, Aggregation> aggregations; // // public Map<String, Aggregation> getAggregations() { // return aggregations; // } // // public void setAggregations(Map<String, Aggregation> aggregations) { // this.aggregations = aggregations; // } // } // // Path: src/main/java/eu/luminis/elastic/search/response/HitsResponse.java // public class HitsResponse<T> { // private List<T> hits; // private long totalHits; // private long responseTime; // private Boolean timedOut; // // public List<T> getHits() { // return hits; // } // // public void setHits(List<T> hits) { // this.hits = hits; // } // // public long getTotalHits() { // return totalHits; // } // // public void setTotalHits(long totalHits) { // this.totalHits = totalHits; // } // // public long getResponseTime() { // return responseTime; // } // // public void setResponseTime(long responseTime) { // this.responseTime = responseTime; // } // // public Boolean getTimedOut() { // return timedOut; // } // // public void setTimedOut(Boolean timedOut) { // this.timedOut = timedOut; // } // } // // Path: src/main/java/eu/luminis/elastic/SingleClusterRestClientFactoryBean.java // public static final String DEFAULT_CLUSTER_NAME = "default-cluster"; // Path: src/main/java/eu/luminis/elastic/search/SingleClusterSearchService.java import eu.luminis.elastic.search.response.HitsAggsResponse; import eu.luminis.elastic.search.response.HitsResponse; import static eu.luminis.elastic.SingleClusterRestClientFactoryBean.DEFAULT_CLUSTER_NAME; package eu.luminis.elastic.search; public class SingleClusterSearchService { private SearchService searchService; public SingleClusterSearchService(SearchService searchService) { this.searchService = searchService; }
public <T> HitsResponse<T> queryByTemplate(SearchByTemplateRequest request) {
luminis-ams/elastic-rest-spring-wrapper
src/main/java/eu/luminis/elastic/search/SingleClusterSearchService.java
// Path: src/main/java/eu/luminis/elastic/search/response/HitsAggsResponse.java // public class HitsAggsResponse<T> extends HitsResponse<T> { // // @JsonProperty // @JsonDeserialize(keyUsing = AggregationKeyDeserializer.class) // private Map<String, Aggregation> aggregations; // // public Map<String, Aggregation> getAggregations() { // return aggregations; // } // // public void setAggregations(Map<String, Aggregation> aggregations) { // this.aggregations = aggregations; // } // } // // Path: src/main/java/eu/luminis/elastic/search/response/HitsResponse.java // public class HitsResponse<T> { // private List<T> hits; // private long totalHits; // private long responseTime; // private Boolean timedOut; // // public List<T> getHits() { // return hits; // } // // public void setHits(List<T> hits) { // this.hits = hits; // } // // public long getTotalHits() { // return totalHits; // } // // public void setTotalHits(long totalHits) { // this.totalHits = totalHits; // } // // public long getResponseTime() { // return responseTime; // } // // public void setResponseTime(long responseTime) { // this.responseTime = responseTime; // } // // public Boolean getTimedOut() { // return timedOut; // } // // public void setTimedOut(Boolean timedOut) { // this.timedOut = timedOut; // } // } // // Path: src/main/java/eu/luminis/elastic/SingleClusterRestClientFactoryBean.java // public static final String DEFAULT_CLUSTER_NAME = "default-cluster";
import eu.luminis.elastic.search.response.HitsAggsResponse; import eu.luminis.elastic.search.response.HitsResponse; import static eu.luminis.elastic.SingleClusterRestClientFactoryBean.DEFAULT_CLUSTER_NAME;
package eu.luminis.elastic.search; public class SingleClusterSearchService { private SearchService searchService; public SingleClusterSearchService(SearchService searchService) { this.searchService = searchService; } public <T> HitsResponse<T> queryByTemplate(SearchByTemplateRequest request) {
// Path: src/main/java/eu/luminis/elastic/search/response/HitsAggsResponse.java // public class HitsAggsResponse<T> extends HitsResponse<T> { // // @JsonProperty // @JsonDeserialize(keyUsing = AggregationKeyDeserializer.class) // private Map<String, Aggregation> aggregations; // // public Map<String, Aggregation> getAggregations() { // return aggregations; // } // // public void setAggregations(Map<String, Aggregation> aggregations) { // this.aggregations = aggregations; // } // } // // Path: src/main/java/eu/luminis/elastic/search/response/HitsResponse.java // public class HitsResponse<T> { // private List<T> hits; // private long totalHits; // private long responseTime; // private Boolean timedOut; // // public List<T> getHits() { // return hits; // } // // public void setHits(List<T> hits) { // this.hits = hits; // } // // public long getTotalHits() { // return totalHits; // } // // public void setTotalHits(long totalHits) { // this.totalHits = totalHits; // } // // public long getResponseTime() { // return responseTime; // } // // public void setResponseTime(long responseTime) { // this.responseTime = responseTime; // } // // public Boolean getTimedOut() { // return timedOut; // } // // public void setTimedOut(Boolean timedOut) { // this.timedOut = timedOut; // } // } // // Path: src/main/java/eu/luminis/elastic/SingleClusterRestClientFactoryBean.java // public static final String DEFAULT_CLUSTER_NAME = "default-cluster"; // Path: src/main/java/eu/luminis/elastic/search/SingleClusterSearchService.java import eu.luminis.elastic.search.response.HitsAggsResponse; import eu.luminis.elastic.search.response.HitsResponse; import static eu.luminis.elastic.SingleClusterRestClientFactoryBean.DEFAULT_CLUSTER_NAME; package eu.luminis.elastic.search; public class SingleClusterSearchService { private SearchService searchService; public SingleClusterSearchService(SearchService searchService) { this.searchService = searchService; } public <T> HitsResponse<T> queryByTemplate(SearchByTemplateRequest request) {
return this.searchService.queryByTemplate(DEFAULT_CLUSTER_NAME,request);
luminis-ams/elastic-rest-spring-wrapper
src/main/java/eu/luminis/elastic/search/SingleClusterSearchService.java
// Path: src/main/java/eu/luminis/elastic/search/response/HitsAggsResponse.java // public class HitsAggsResponse<T> extends HitsResponse<T> { // // @JsonProperty // @JsonDeserialize(keyUsing = AggregationKeyDeserializer.class) // private Map<String, Aggregation> aggregations; // // public Map<String, Aggregation> getAggregations() { // return aggregations; // } // // public void setAggregations(Map<String, Aggregation> aggregations) { // this.aggregations = aggregations; // } // } // // Path: src/main/java/eu/luminis/elastic/search/response/HitsResponse.java // public class HitsResponse<T> { // private List<T> hits; // private long totalHits; // private long responseTime; // private Boolean timedOut; // // public List<T> getHits() { // return hits; // } // // public void setHits(List<T> hits) { // this.hits = hits; // } // // public long getTotalHits() { // return totalHits; // } // // public void setTotalHits(long totalHits) { // this.totalHits = totalHits; // } // // public long getResponseTime() { // return responseTime; // } // // public void setResponseTime(long responseTime) { // this.responseTime = responseTime; // } // // public Boolean getTimedOut() { // return timedOut; // } // // public void setTimedOut(Boolean timedOut) { // this.timedOut = timedOut; // } // } // // Path: src/main/java/eu/luminis/elastic/SingleClusterRestClientFactoryBean.java // public static final String DEFAULT_CLUSTER_NAME = "default-cluster";
import eu.luminis.elastic.search.response.HitsAggsResponse; import eu.luminis.elastic.search.response.HitsResponse; import static eu.luminis.elastic.SingleClusterRestClientFactoryBean.DEFAULT_CLUSTER_NAME;
package eu.luminis.elastic.search; public class SingleClusterSearchService { private SearchService searchService; public SingleClusterSearchService(SearchService searchService) { this.searchService = searchService; } public <T> HitsResponse<T> queryByTemplate(SearchByTemplateRequest request) { return this.searchService.queryByTemplate(DEFAULT_CLUSTER_NAME,request); }
// Path: src/main/java/eu/luminis/elastic/search/response/HitsAggsResponse.java // public class HitsAggsResponse<T> extends HitsResponse<T> { // // @JsonProperty // @JsonDeserialize(keyUsing = AggregationKeyDeserializer.class) // private Map<String, Aggregation> aggregations; // // public Map<String, Aggregation> getAggregations() { // return aggregations; // } // // public void setAggregations(Map<String, Aggregation> aggregations) { // this.aggregations = aggregations; // } // } // // Path: src/main/java/eu/luminis/elastic/search/response/HitsResponse.java // public class HitsResponse<T> { // private List<T> hits; // private long totalHits; // private long responseTime; // private Boolean timedOut; // // public List<T> getHits() { // return hits; // } // // public void setHits(List<T> hits) { // this.hits = hits; // } // // public long getTotalHits() { // return totalHits; // } // // public void setTotalHits(long totalHits) { // this.totalHits = totalHits; // } // // public long getResponseTime() { // return responseTime; // } // // public void setResponseTime(long responseTime) { // this.responseTime = responseTime; // } // // public Boolean getTimedOut() { // return timedOut; // } // // public void setTimedOut(Boolean timedOut) { // this.timedOut = timedOut; // } // } // // Path: src/main/java/eu/luminis/elastic/SingleClusterRestClientFactoryBean.java // public static final String DEFAULT_CLUSTER_NAME = "default-cluster"; // Path: src/main/java/eu/luminis/elastic/search/SingleClusterSearchService.java import eu.luminis.elastic.search.response.HitsAggsResponse; import eu.luminis.elastic.search.response.HitsResponse; import static eu.luminis.elastic.SingleClusterRestClientFactoryBean.DEFAULT_CLUSTER_NAME; package eu.luminis.elastic.search; public class SingleClusterSearchService { private SearchService searchService; public SingleClusterSearchService(SearchService searchService) { this.searchService = searchService; } public <T> HitsResponse<T> queryByTemplate(SearchByTemplateRequest request) { return this.searchService.queryByTemplate(DEFAULT_CLUSTER_NAME,request); }
public <T> HitsAggsResponse<T> aggsByTemplate(SearchByTemplateRequest request) {
luminis-ams/elastic-rest-spring-wrapper
src/main/java/eu/luminis/elastic/search/response/aggregations/bucket/DateHistogramBucket.java
// Path: src/main/java/eu/luminis/elastic/search/response/aggregations/Aggregation.java // public class Aggregation { // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: src/main/java/eu/luminis/elastic/search/response/aggregations/bucket/Bucket.java // public interface Bucket { // }
import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonProperty; import eu.luminis.elastic.search.response.aggregations.Aggregation; import eu.luminis.elastic.search.response.aggregations.bucket.Bucket; import java.util.HashMap; import java.util.Map;
package eu.luminis.elastic.search.response.aggregations.bucket; /** * Specific bucket implementation for Date Histogram Aggregations. */ public class DateHistogramBucket implements Bucket { @JsonProperty("key_as_string") private String keyAsString; private Long key; @JsonProperty("doc_count") private Long docCount; public String getKeyAsString() { return keyAsString; } public void setKeyAsString(String keyAsString) { this.keyAsString = keyAsString; } public Long getKey() { return key; } public void setKey(Long key) { this.key = key; } public Long getDocCount() { return docCount; } public void setDocCount(Long docCount) { this.docCount = docCount; }
// Path: src/main/java/eu/luminis/elastic/search/response/aggregations/Aggregation.java // public class Aggregation { // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // // Path: src/main/java/eu/luminis/elastic/search/response/aggregations/bucket/Bucket.java // public interface Bucket { // } // Path: src/main/java/eu/luminis/elastic/search/response/aggregations/bucket/DateHistogramBucket.java import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonProperty; import eu.luminis.elastic.search.response.aggregations.Aggregation; import eu.luminis.elastic.search.response.aggregations.bucket.Bucket; import java.util.HashMap; import java.util.Map; package eu.luminis.elastic.search.response.aggregations.bucket; /** * Specific bucket implementation for Date Histogram Aggregations. */ public class DateHistogramBucket implements Bucket { @JsonProperty("key_as_string") private String keyAsString; private Long key; @JsonProperty("doc_count") private Long docCount; public String getKeyAsString() { return keyAsString; } public void setKeyAsString(String keyAsString) { this.keyAsString = keyAsString; } public Long getKey() { return key; } public void setKey(Long key) { this.key = key; } public Long getDocCount() { return docCount; } public void setDocCount(Long docCount) { this.docCount = docCount; }
private Map<String, Aggregation> aggregations = new HashMap<>();
luminis-ams/elastic-rest-spring-wrapper
src/main/java/eu/luminis/elastic/document/SingleClusterDocumentService.java
// Path: src/main/java/eu/luminis/elastic/SingleClusterRestClientFactoryBean.java // public static final String DEFAULT_CLUSTER_NAME = "default-cluster";
import static eu.luminis.elastic.SingleClusterRestClientFactoryBean.DEFAULT_CLUSTER_NAME;
package eu.luminis.elastic.document; /** * Wrapper for the {@code DocumentService} without the option to work with multiple clusters. Only the default cluster * is available. */ public class SingleClusterDocumentService { private DocumentService documentService; /** * Default constructor * * @param documentService Wrapped document service */ public SingleClusterDocumentService(DocumentService documentService) { this.documentService = documentService; } /** * By specifying the unique identification of an object we can return only that object. If we cannot find the object * we throw an {@link QueryByIdNotFoundException}. * * @param request Object containing the required parameters * @param <T> Type of the object to be mapped to * @return Found object of type T */ public <T> T queryById(QueryByIdRequest request) {
// Path: src/main/java/eu/luminis/elastic/SingleClusterRestClientFactoryBean.java // public static final String DEFAULT_CLUSTER_NAME = "default-cluster"; // Path: src/main/java/eu/luminis/elastic/document/SingleClusterDocumentService.java import static eu.luminis.elastic.SingleClusterRestClientFactoryBean.DEFAULT_CLUSTER_NAME; package eu.luminis.elastic.document; /** * Wrapper for the {@code DocumentService} without the option to work with multiple clusters. Only the default cluster * is available. */ public class SingleClusterDocumentService { private DocumentService documentService; /** * Default constructor * * @param documentService Wrapped document service */ public SingleClusterDocumentService(DocumentService documentService) { this.documentService = documentService; } /** * By specifying the unique identification of an object we can return only that object. If we cannot find the object * we throw an {@link QueryByIdNotFoundException}. * * @param request Object containing the required parameters * @param <T> Type of the object to be mapped to * @return Found object of type T */ public <T> T queryById(QueryByIdRequest request) {
return documentService.queryById(DEFAULT_CLUSTER_NAME, request);
luminis-ams/elastic-rest-spring-wrapper
src/main/java/eu/luminis/elastic/cluster/ClusterManagementService.java
// Path: src/main/java/eu/luminis/elastic/LoggingFailureListener.java // public class LoggingFailureListener extends RestClient.FailureListener { // private static final Logger logger = LoggerFactory.getLogger(LoggingFailureListener.class); // // @Override // public void onFailure(HttpHost host) { // logger.warn("The following host just failed {}:{}", host.getHostName(), host.getPort()); // } // }
import eu.luminis.elastic.LoggingFailureListener; import org.apache.http.Header; import org.apache.http.HttpHost; import org.apache.http.message.BasicHeader; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.sniff.Sniffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.annotation.PreDestroy; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set;
Cluster cluster = closeCluster(clusterName); clusters.remove(clusterName); return cluster; } /** * Returns the names of all registered clusters. * * @return The names of the registered clusters */ public Set<String> listAvailableClusters() { return clusters.keySet(); } @PreDestroy protected void tearDown() { clusters.keySet().forEach(this::closeCluster); clusters.clear(); } private boolean exists(String clusterName) { return clusters.get(clusterName) != null; } private Cluster createCluster(List<String> hosts, boolean enableSniffer) { HttpHost[] nodes = hosts.stream().map(HttpHost::create).toArray(HttpHost[]::new); Header[] defaultHeaders = new Header[]{new BasicHeader(HEADER_CONTENT_TYPE_KEY, DEFAULT_HEADER_CONTENT_TYPE)}; RestClient client = RestClient.builder(nodes) .setDefaultHeaders(defaultHeaders)
// Path: src/main/java/eu/luminis/elastic/LoggingFailureListener.java // public class LoggingFailureListener extends RestClient.FailureListener { // private static final Logger logger = LoggerFactory.getLogger(LoggingFailureListener.class); // // @Override // public void onFailure(HttpHost host) { // logger.warn("The following host just failed {}:{}", host.getHostName(), host.getPort()); // } // } // Path: src/main/java/eu/luminis/elastic/cluster/ClusterManagementService.java import eu.luminis.elastic.LoggingFailureListener; import org.apache.http.Header; import org.apache.http.HttpHost; import org.apache.http.message.BasicHeader; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.sniff.Sniffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.annotation.PreDestroy; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; Cluster cluster = closeCluster(clusterName); clusters.remove(clusterName); return cluster; } /** * Returns the names of all registered clusters. * * @return The names of the registered clusters */ public Set<String> listAvailableClusters() { return clusters.keySet(); } @PreDestroy protected void tearDown() { clusters.keySet().forEach(this::closeCluster); clusters.clear(); } private boolean exists(String clusterName) { return clusters.get(clusterName) != null; } private Cluster createCluster(List<String> hosts, boolean enableSniffer) { HttpHost[] nodes = hosts.stream().map(HttpHost::create).toArray(HttpHost[]::new); Header[] defaultHeaders = new Header[]{new BasicHeader(HEADER_CONTENT_TYPE_KEY, DEFAULT_HEADER_CONTENT_TYPE)}; RestClient client = RestClient.builder(nodes) .setDefaultHeaders(defaultHeaders)
.setFailureListener(new LoggingFailureListener())
luminis-ams/elastic-rest-spring-wrapper
src/main/java/eu/luminis/elastic/search/response/query/ElasticQueryResponse.java
// Path: src/main/java/eu/luminis/elastic/document/response/Hits.java // public class Hits<T> { // // private List<Hit<T>> hits; // // @JsonProperty("total") // private Long total; // // @JsonProperty("max_score") // private Double maxScore; // // public List<Hit<T>> getHits() { // return hits; // } // // public void setHits(List<Hit<T>> hits) { // this.hits = hits; // } // // public Long getTotal() { // return total; // } // // public void setTotal(Long total) { // this.total = total; // } // // public Double getMaxScore() { // return maxScore; // } // // public void setMaxScore(Double maxScore) { // this.maxScore = maxScore; // } // } // // Path: src/main/java/eu/luminis/elastic/document/response/Shards.java // public class Shards { // private Integer total; // // private Integer successful; // // private Integer failed; // // private Integer skipped; // // public Integer getFailed() { // return failed; // } // // public void setFailed(Integer failed) { // this.failed = failed; // } // // public Integer getSuccessful() { // return successful; // } // // public void setSuccessful(Integer successful) { // this.successful = successful; // } // // public Integer getTotal() { // return total; // } // // public void setTotal(Integer total) { // this.total = total; // } // // public Integer getSkipped() { // return skipped; // } // // public void setSkipped(Integer skipped) { // this.skipped = skipped; // } // } // // Path: src/main/java/eu/luminis/elastic/search/response/aggregations/Aggregation.java // public class Aggregation { // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import com.fasterxml.jackson.annotation.JsonProperty; import eu.luminis.elastic.document.response.Hits; import eu.luminis.elastic.document.response.Shards; import eu.luminis.elastic.search.response.aggregations.Aggregation; import java.util.Map;
package eu.luminis.elastic.search.response.query; public class ElasticQueryResponse<T> { private Long took; @JsonProperty(value = "timed_out") private Boolean timedOut; @JsonProperty(value = "_shards")
// Path: src/main/java/eu/luminis/elastic/document/response/Hits.java // public class Hits<T> { // // private List<Hit<T>> hits; // // @JsonProperty("total") // private Long total; // // @JsonProperty("max_score") // private Double maxScore; // // public List<Hit<T>> getHits() { // return hits; // } // // public void setHits(List<Hit<T>> hits) { // this.hits = hits; // } // // public Long getTotal() { // return total; // } // // public void setTotal(Long total) { // this.total = total; // } // // public Double getMaxScore() { // return maxScore; // } // // public void setMaxScore(Double maxScore) { // this.maxScore = maxScore; // } // } // // Path: src/main/java/eu/luminis/elastic/document/response/Shards.java // public class Shards { // private Integer total; // // private Integer successful; // // private Integer failed; // // private Integer skipped; // // public Integer getFailed() { // return failed; // } // // public void setFailed(Integer failed) { // this.failed = failed; // } // // public Integer getSuccessful() { // return successful; // } // // public void setSuccessful(Integer successful) { // this.successful = successful; // } // // public Integer getTotal() { // return total; // } // // public void setTotal(Integer total) { // this.total = total; // } // // public Integer getSkipped() { // return skipped; // } // // public void setSkipped(Integer skipped) { // this.skipped = skipped; // } // } // // Path: src/main/java/eu/luminis/elastic/search/response/aggregations/Aggregation.java // public class Aggregation { // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: src/main/java/eu/luminis/elastic/search/response/query/ElasticQueryResponse.java import com.fasterxml.jackson.annotation.JsonProperty; import eu.luminis.elastic.document.response.Hits; import eu.luminis.elastic.document.response.Shards; import eu.luminis.elastic.search.response.aggregations.Aggregation; import java.util.Map; package eu.luminis.elastic.search.response.query; public class ElasticQueryResponse<T> { private Long took; @JsonProperty(value = "timed_out") private Boolean timedOut; @JsonProperty(value = "_shards")
private Shards shards;
luminis-ams/elastic-rest-spring-wrapper
src/main/java/eu/luminis/elastic/search/response/query/ElasticQueryResponse.java
// Path: src/main/java/eu/luminis/elastic/document/response/Hits.java // public class Hits<T> { // // private List<Hit<T>> hits; // // @JsonProperty("total") // private Long total; // // @JsonProperty("max_score") // private Double maxScore; // // public List<Hit<T>> getHits() { // return hits; // } // // public void setHits(List<Hit<T>> hits) { // this.hits = hits; // } // // public Long getTotal() { // return total; // } // // public void setTotal(Long total) { // this.total = total; // } // // public Double getMaxScore() { // return maxScore; // } // // public void setMaxScore(Double maxScore) { // this.maxScore = maxScore; // } // } // // Path: src/main/java/eu/luminis/elastic/document/response/Shards.java // public class Shards { // private Integer total; // // private Integer successful; // // private Integer failed; // // private Integer skipped; // // public Integer getFailed() { // return failed; // } // // public void setFailed(Integer failed) { // this.failed = failed; // } // // public Integer getSuccessful() { // return successful; // } // // public void setSuccessful(Integer successful) { // this.successful = successful; // } // // public Integer getTotal() { // return total; // } // // public void setTotal(Integer total) { // this.total = total; // } // // public Integer getSkipped() { // return skipped; // } // // public void setSkipped(Integer skipped) { // this.skipped = skipped; // } // } // // Path: src/main/java/eu/luminis/elastic/search/response/aggregations/Aggregation.java // public class Aggregation { // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import com.fasterxml.jackson.annotation.JsonProperty; import eu.luminis.elastic.document.response.Hits; import eu.luminis.elastic.document.response.Shards; import eu.luminis.elastic.search.response.aggregations.Aggregation; import java.util.Map;
package eu.luminis.elastic.search.response.query; public class ElasticQueryResponse<T> { private Long took; @JsonProperty(value = "timed_out") private Boolean timedOut; @JsonProperty(value = "_shards") private Shards shards;
// Path: src/main/java/eu/luminis/elastic/document/response/Hits.java // public class Hits<T> { // // private List<Hit<T>> hits; // // @JsonProperty("total") // private Long total; // // @JsonProperty("max_score") // private Double maxScore; // // public List<Hit<T>> getHits() { // return hits; // } // // public void setHits(List<Hit<T>> hits) { // this.hits = hits; // } // // public Long getTotal() { // return total; // } // // public void setTotal(Long total) { // this.total = total; // } // // public Double getMaxScore() { // return maxScore; // } // // public void setMaxScore(Double maxScore) { // this.maxScore = maxScore; // } // } // // Path: src/main/java/eu/luminis/elastic/document/response/Shards.java // public class Shards { // private Integer total; // // private Integer successful; // // private Integer failed; // // private Integer skipped; // // public Integer getFailed() { // return failed; // } // // public void setFailed(Integer failed) { // this.failed = failed; // } // // public Integer getSuccessful() { // return successful; // } // // public void setSuccessful(Integer successful) { // this.successful = successful; // } // // public Integer getTotal() { // return total; // } // // public void setTotal(Integer total) { // this.total = total; // } // // public Integer getSkipped() { // return skipped; // } // // public void setSkipped(Integer skipped) { // this.skipped = skipped; // } // } // // Path: src/main/java/eu/luminis/elastic/search/response/aggregations/Aggregation.java // public class Aggregation { // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: src/main/java/eu/luminis/elastic/search/response/query/ElasticQueryResponse.java import com.fasterxml.jackson.annotation.JsonProperty; import eu.luminis.elastic.document.response.Hits; import eu.luminis.elastic.document.response.Shards; import eu.luminis.elastic.search.response.aggregations.Aggregation; import java.util.Map; package eu.luminis.elastic.search.response.query; public class ElasticQueryResponse<T> { private Long took; @JsonProperty(value = "timed_out") private Boolean timedOut; @JsonProperty(value = "_shards") private Shards shards;
private Hits<T> hits;
luminis-ams/elastic-rest-spring-wrapper
src/main/java/eu/luminis/elastic/search/response/query/ElasticQueryResponse.java
// Path: src/main/java/eu/luminis/elastic/document/response/Hits.java // public class Hits<T> { // // private List<Hit<T>> hits; // // @JsonProperty("total") // private Long total; // // @JsonProperty("max_score") // private Double maxScore; // // public List<Hit<T>> getHits() { // return hits; // } // // public void setHits(List<Hit<T>> hits) { // this.hits = hits; // } // // public Long getTotal() { // return total; // } // // public void setTotal(Long total) { // this.total = total; // } // // public Double getMaxScore() { // return maxScore; // } // // public void setMaxScore(Double maxScore) { // this.maxScore = maxScore; // } // } // // Path: src/main/java/eu/luminis/elastic/document/response/Shards.java // public class Shards { // private Integer total; // // private Integer successful; // // private Integer failed; // // private Integer skipped; // // public Integer getFailed() { // return failed; // } // // public void setFailed(Integer failed) { // this.failed = failed; // } // // public Integer getSuccessful() { // return successful; // } // // public void setSuccessful(Integer successful) { // this.successful = successful; // } // // public Integer getTotal() { // return total; // } // // public void setTotal(Integer total) { // this.total = total; // } // // public Integer getSkipped() { // return skipped; // } // // public void setSkipped(Integer skipped) { // this.skipped = skipped; // } // } // // Path: src/main/java/eu/luminis/elastic/search/response/aggregations/Aggregation.java // public class Aggregation { // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import com.fasterxml.jackson.annotation.JsonProperty; import eu.luminis.elastic.document.response.Hits; import eu.luminis.elastic.document.response.Shards; import eu.luminis.elastic.search.response.aggregations.Aggregation; import java.util.Map;
package eu.luminis.elastic.search.response.query; public class ElasticQueryResponse<T> { private Long took; @JsonProperty(value = "timed_out") private Boolean timedOut; @JsonProperty(value = "_shards") private Shards shards; private Hits<T> hits;
// Path: src/main/java/eu/luminis/elastic/document/response/Hits.java // public class Hits<T> { // // private List<Hit<T>> hits; // // @JsonProperty("total") // private Long total; // // @JsonProperty("max_score") // private Double maxScore; // // public List<Hit<T>> getHits() { // return hits; // } // // public void setHits(List<Hit<T>> hits) { // this.hits = hits; // } // // public Long getTotal() { // return total; // } // // public void setTotal(Long total) { // this.total = total; // } // // public Double getMaxScore() { // return maxScore; // } // // public void setMaxScore(Double maxScore) { // this.maxScore = maxScore; // } // } // // Path: src/main/java/eu/luminis/elastic/document/response/Shards.java // public class Shards { // private Integer total; // // private Integer successful; // // private Integer failed; // // private Integer skipped; // // public Integer getFailed() { // return failed; // } // // public void setFailed(Integer failed) { // this.failed = failed; // } // // public Integer getSuccessful() { // return successful; // } // // public void setSuccessful(Integer successful) { // this.successful = successful; // } // // public Integer getTotal() { // return total; // } // // public void setTotal(Integer total) { // this.total = total; // } // // public Integer getSkipped() { // return skipped; // } // // public void setSkipped(Integer skipped) { // this.skipped = skipped; // } // } // // Path: src/main/java/eu/luminis/elastic/search/response/aggregations/Aggregation.java // public class Aggregation { // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: src/main/java/eu/luminis/elastic/search/response/query/ElasticQueryResponse.java import com.fasterxml.jackson.annotation.JsonProperty; import eu.luminis.elastic.document.response.Hits; import eu.luminis.elastic.document.response.Shards; import eu.luminis.elastic.search.response.aggregations.Aggregation; import java.util.Map; package eu.luminis.elastic.search.response.query; public class ElasticQueryResponse<T> { private Long took; @JsonProperty(value = "timed_out") private Boolean timedOut; @JsonProperty(value = "_shards") private Shards shards; private Hits<T> hits;
private Map<String,Aggregation> aggregations;
luminis-ams/elastic-rest-spring-wrapper
src/main/java/eu/luminis/elastic/search/response/aggregations/bucket/BaseBucket.java
// Path: src/main/java/eu/luminis/elastic/search/response/aggregations/Aggregation.java // public class Aggregation { // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonProperty; import eu.luminis.elastic.search.response.aggregations.Aggregation; import java.util.HashMap; import java.util.Map;
package eu.luminis.elastic.search.response.aggregations.bucket; /** * Default Bucket that can be used by most other buckets besides the ones with a non-string key. */ public class BaseBucket implements Bucket { @JsonProperty("key") private String key; @JsonProperty("doc_count") private Long docCount; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public Long getDocCount() { return docCount; } public void setDocCount(Long docCount) { this.docCount = docCount; }
// Path: src/main/java/eu/luminis/elastic/search/response/aggregations/Aggregation.java // public class Aggregation { // private String name; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: src/main/java/eu/luminis/elastic/search/response/aggregations/bucket/BaseBucket.java import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonProperty; import eu.luminis.elastic.search.response.aggregations.Aggregation; import java.util.HashMap; import java.util.Map; package eu.luminis.elastic.search.response.aggregations.bucket; /** * Default Bucket that can be used by most other buckets besides the ones with a non-string key. */ public class BaseBucket implements Bucket { @JsonProperty("key") private String key; @JsonProperty("doc_count") private Long docCount; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public Long getDocCount() { return docCount; } public void setDocCount(Long docCount) { this.docCount = docCount; }
private Map<String, Aggregation> aggregations = new HashMap<>();
luminis-ams/elastic-rest-spring-wrapper
src/main/java/eu/luminis/elastic/SingleClusterRestClientFactoryBean.java
// Path: src/main/java/eu/luminis/elastic/cluster/ClusterManagementService.java // @Component // public class ClusterManagementService { // // private static final Logger LOGGER = LoggerFactory.getLogger(ClusterManagementService.class); // private static final String HEADER_CONTENT_TYPE_KEY = "Content-Type"; // private static final String DEFAULT_HEADER_CONTENT_TYPE = "application/json"; // // private Map<String, Cluster> clusters = new HashMap<>(); // // /** // * Return the cluster with the provided name. If the name cannot be found a ClusterApiException is thrown // * // * @param clusterName Name of the cluster to return // * @return The found cluster // */ // public Cluster getCluster(String clusterName) { // Cluster cluster = clusters.get(clusterName); // // if (cluster == null) { // LOGGER.warn("Requested cluster with name {} is unknown.", clusterName); // throw new ClusterApiException("The provided cluster name does not result in a valid cluster"); // } // // return cluster; // } // // /** // * Return the client that maintains the actual connection to the cluster with the provided name // * // * @param clusterName The name of the cluster to find the client for. // * @return The rest client belonging to the cluster with the provided name // */ // public RestClient getRestClientForCluster(String clusterName) { // return this.getCluster(clusterName).getClient(); // } // // /** // * Add a new cluster to be managed. // * // * @param clusterName the name of the cluster. // * @param hosts the hosts within that cluster. // * @return the cluster that has just been added, or null if the clusterName was already present. // */ // public Cluster addCluster(String clusterName, List<String> hosts, boolean enableSniffer) { // if (!exists(clusterName)) { // Cluster cluster = createCluster(hosts, enableSniffer); // clusters.put(clusterName, cluster); // return cluster; // } else { // return null; // } // } // // /** // * Delete a cluster. Also closes any active connections that may exist with this cluster. // * // * @param clusterName the name of the cluster. // * @return the closed cluster. // */ // public Cluster deleteCluster(String clusterName) { // Cluster cluster = closeCluster(clusterName); // clusters.remove(clusterName); // return cluster; // } // // /** // * Returns the names of all registered clusters. // * // * @return The names of the registered clusters // */ // public Set<String> listAvailableClusters() { // return clusters.keySet(); // } // // @PreDestroy // protected void tearDown() { // clusters.keySet().forEach(this::closeCluster); // clusters.clear(); // } // // private boolean exists(String clusterName) { // return clusters.get(clusterName) != null; // } // // private Cluster createCluster(List<String> hosts, boolean enableSniffer) { // HttpHost[] nodes = hosts.stream().map(HttpHost::create).toArray(HttpHost[]::new); // Header[] defaultHeaders = new Header[]{new BasicHeader(HEADER_CONTENT_TYPE_KEY, DEFAULT_HEADER_CONTENT_TYPE)}; // // RestClient client = RestClient.builder(nodes) // .setDefaultHeaders(defaultHeaders) // .setFailureListener(new LoggingFailureListener()) // .build(); // // if (enableSniffer) { // return new Cluster(client, Sniffer.builder(client).build()); // } else { // return new Cluster(client); // } // } // // private Cluster closeCluster(String clusterName) { // Cluster cluster = clusters.get(clusterName); // if (cluster != null) { // try { // if (cluster.getSniffer() != null) { // cluster.getSniffer().close(); // } // cluster.getClient().close(); // } catch (IOException ex) { // String error = String.format("Could not close connection to cluster: %s", clusterName); // LOGGER.error(error, ex); // throw new ClusterApiException(error, ex); // } // return cluster; // } else { // return null; // } // } // }
import eu.luminis.elastic.cluster.ClusterManagementService; import org.elasticsearch.client.RestClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.AbstractFactoryBean; import java.util.Arrays;
package eu.luminis.elastic; /** * Factory bean for creating the RestClient instance when working with a single cluster. */ public class SingleClusterRestClientFactoryBean extends AbstractFactoryBean<RestClient> { public static final String DEFAULT_CLUSTER_NAME = "default-cluster";
// Path: src/main/java/eu/luminis/elastic/cluster/ClusterManagementService.java // @Component // public class ClusterManagementService { // // private static final Logger LOGGER = LoggerFactory.getLogger(ClusterManagementService.class); // private static final String HEADER_CONTENT_TYPE_KEY = "Content-Type"; // private static final String DEFAULT_HEADER_CONTENT_TYPE = "application/json"; // // private Map<String, Cluster> clusters = new HashMap<>(); // // /** // * Return the cluster with the provided name. If the name cannot be found a ClusterApiException is thrown // * // * @param clusterName Name of the cluster to return // * @return The found cluster // */ // public Cluster getCluster(String clusterName) { // Cluster cluster = clusters.get(clusterName); // // if (cluster == null) { // LOGGER.warn("Requested cluster with name {} is unknown.", clusterName); // throw new ClusterApiException("The provided cluster name does not result in a valid cluster"); // } // // return cluster; // } // // /** // * Return the client that maintains the actual connection to the cluster with the provided name // * // * @param clusterName The name of the cluster to find the client for. // * @return The rest client belonging to the cluster with the provided name // */ // public RestClient getRestClientForCluster(String clusterName) { // return this.getCluster(clusterName).getClient(); // } // // /** // * Add a new cluster to be managed. // * // * @param clusterName the name of the cluster. // * @param hosts the hosts within that cluster. // * @return the cluster that has just been added, or null if the clusterName was already present. // */ // public Cluster addCluster(String clusterName, List<String> hosts, boolean enableSniffer) { // if (!exists(clusterName)) { // Cluster cluster = createCluster(hosts, enableSniffer); // clusters.put(clusterName, cluster); // return cluster; // } else { // return null; // } // } // // /** // * Delete a cluster. Also closes any active connections that may exist with this cluster. // * // * @param clusterName the name of the cluster. // * @return the closed cluster. // */ // public Cluster deleteCluster(String clusterName) { // Cluster cluster = closeCluster(clusterName); // clusters.remove(clusterName); // return cluster; // } // // /** // * Returns the names of all registered clusters. // * // * @return The names of the registered clusters // */ // public Set<String> listAvailableClusters() { // return clusters.keySet(); // } // // @PreDestroy // protected void tearDown() { // clusters.keySet().forEach(this::closeCluster); // clusters.clear(); // } // // private boolean exists(String clusterName) { // return clusters.get(clusterName) != null; // } // // private Cluster createCluster(List<String> hosts, boolean enableSniffer) { // HttpHost[] nodes = hosts.stream().map(HttpHost::create).toArray(HttpHost[]::new); // Header[] defaultHeaders = new Header[]{new BasicHeader(HEADER_CONTENT_TYPE_KEY, DEFAULT_HEADER_CONTENT_TYPE)}; // // RestClient client = RestClient.builder(nodes) // .setDefaultHeaders(defaultHeaders) // .setFailureListener(new LoggingFailureListener()) // .build(); // // if (enableSniffer) { // return new Cluster(client, Sniffer.builder(client).build()); // } else { // return new Cluster(client); // } // } // // private Cluster closeCluster(String clusterName) { // Cluster cluster = clusters.get(clusterName); // if (cluster != null) { // try { // if (cluster.getSniffer() != null) { // cluster.getSniffer().close(); // } // cluster.getClient().close(); // } catch (IOException ex) { // String error = String.format("Could not close connection to cluster: %s", clusterName); // LOGGER.error(error, ex); // throw new ClusterApiException(error, ex); // } // return cluster; // } else { // return null; // } // } // } // Path: src/main/java/eu/luminis/elastic/SingleClusterRestClientFactoryBean.java import eu.luminis.elastic.cluster.ClusterManagementService; import org.elasticsearch.client.RestClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.AbstractFactoryBean; import java.util.Arrays; package eu.luminis.elastic; /** * Factory bean for creating the RestClient instance when working with a single cluster. */ public class SingleClusterRestClientFactoryBean extends AbstractFactoryBean<RestClient> { public static final String DEFAULT_CLUSTER_NAME = "default-cluster";
private final ClusterManagementService clusterManagementService;
luminis-ams/elastic-rest-spring-wrapper
src/main/java/eu/luminis/elastic/index/response/RefreshResponse.java
// Path: src/main/java/eu/luminis/elastic/document/response/Shards.java // public class Shards { // private Integer total; // // private Integer successful; // // private Integer failed; // // private Integer skipped; // // public Integer getFailed() { // return failed; // } // // public void setFailed(Integer failed) { // this.failed = failed; // } // // public Integer getSuccessful() { // return successful; // } // // public void setSuccessful(Integer successful) { // this.successful = successful; // } // // public Integer getTotal() { // return total; // } // // public void setTotal(Integer total) { // this.total = total; // } // // public Integer getSkipped() { // return skipped; // } // // public void setSkipped(Integer skipped) { // this.skipped = skipped; // } // }
import com.fasterxml.jackson.annotation.JsonProperty; import eu.luminis.elastic.document.response.Shards;
package eu.luminis.elastic.index.response; public class RefreshResponse { @JsonProperty(value = "_shards")
// Path: src/main/java/eu/luminis/elastic/document/response/Shards.java // public class Shards { // private Integer total; // // private Integer successful; // // private Integer failed; // // private Integer skipped; // // public Integer getFailed() { // return failed; // } // // public void setFailed(Integer failed) { // this.failed = failed; // } // // public Integer getSuccessful() { // return successful; // } // // public void setSuccessful(Integer successful) { // this.successful = successful; // } // // public Integer getTotal() { // return total; // } // // public void setTotal(Integer total) { // this.total = total; // } // // public Integer getSkipped() { // return skipped; // } // // public void setSkipped(Integer skipped) { // this.skipped = skipped; // } // } // Path: src/main/java/eu/luminis/elastic/index/response/RefreshResponse.java import com.fasterxml.jackson.annotation.JsonProperty; import eu.luminis.elastic.document.response.Shards; package eu.luminis.elastic.index.response; public class RefreshResponse { @JsonProperty(value = "_shards")
private Shards shards;
barancev/testng_samples
src/test/java/ru/stqa/trainings/testng/tricky1/sample26/MyFactory.java
// Path: src/test/java/ru/stqa/trainings/testng/simple5/sample22/DataProviders.java // public class DataProviders { // // @DataProvider // public static Iterator<Object[]> loadUserFromFile() throws IOException { // BufferedReader in = new BufferedReader(new InputStreamReader( // DataProviders.class.getResourceAsStream("/user.data"))); // // List<Object[]> userData = new ArrayList<Object[]>(); // String line = in.readLine(); // while (line != null) { // userData.add(line.split(";")); // line = in.readLine(); // } // // in.close(); // // return userData.iterator(); // } // // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.testng.annotations.Factory; import ru.stqa.trainings.testng.simple5.sample22.DataProviders;
package ru.stqa.trainings.testng.tricky1.sample26; public class MyFactory { @Factory public Object[] tf() throws IOException { List<Object> tests = new ArrayList<Object>(); List<String[]> data = loadUserFromResource("/user.data"); for (String[] dataItem : data) { tests.add(new CreateUser(dataItem[0], dataItem[1])); tests.add(new DeleteUser(dataItem[0])); } return (Object[]) tests.toArray(new Object[tests.size()]); } public List<String[]> loadUserFromResource(String resource) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(
// Path: src/test/java/ru/stqa/trainings/testng/simple5/sample22/DataProviders.java // public class DataProviders { // // @DataProvider // public static Iterator<Object[]> loadUserFromFile() throws IOException { // BufferedReader in = new BufferedReader(new InputStreamReader( // DataProviders.class.getResourceAsStream("/user.data"))); // // List<Object[]> userData = new ArrayList<Object[]>(); // String line = in.readLine(); // while (line != null) { // userData.add(line.split(";")); // line = in.readLine(); // } // // in.close(); // // return userData.iterator(); // } // // } // Path: src/test/java/ru/stqa/trainings/testng/tricky1/sample26/MyFactory.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.testng.annotations.Factory; import ru.stqa.trainings.testng.simple5.sample22.DataProviders; package ru.stqa.trainings.testng.tricky1.sample26; public class MyFactory { @Factory public Object[] tf() throws IOException { List<Object> tests = new ArrayList<Object>(); List<String[]> data = loadUserFromResource("/user.data"); for (String[] dataItem : data) { tests.add(new CreateUser(dataItem[0], dataItem[1])); tests.add(new DeleteUser(dataItem[0])); } return (Object[]) tests.toArray(new Object[tests.size()]); } public List<String[]> loadUserFromResource(String resource) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(
DataProviders.class.getResourceAsStream(resource)));
barancev/testng_samples
src/test/java/ru/stqa/trainings/testng/tricky4/sample37/MyFactory.java
// Path: src/test/java/ru/stqa/trainings/testng/simple5/sample22/DataProviders.java // public class DataProviders { // // @DataProvider // public static Iterator<Object[]> loadUserFromFile() throws IOException { // BufferedReader in = new BufferedReader(new InputStreamReader( // DataProviders.class.getResourceAsStream("/user.data"))); // // List<Object[]> userData = new ArrayList<Object[]>(); // String line = in.readLine(); // while (line != null) { // userData.add(line.split(";")); // line = in.readLine(); // } // // in.close(); // // return userData.iterator(); // } // // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.testng.annotations.Factory; import org.testng.annotations.Listeners; import ru.stqa.trainings.testng.simple5.sample22.DataProviders;
package ru.stqa.trainings.testng.tricky4.sample37; @Listeners(OrderByPriority.class) public class MyFactory { @Factory public Object[] tf() throws IOException { List<Object> tests = new ArrayList<Object>(); List<String[]> data = loadUserFromResource("/user.data"); int p = 0; for (String[] dataItem : data) { CreateUser create = new CreateUser(dataItem[0], dataItem[1]); create.setPriority(p++); tests.add(create); DeleteUser delete = new DeleteUser(dataItem[0]); delete.setPriority(p++); tests.add(delete); } return (Object[]) tests.toArray(new Object[tests.size()]); } public List<String[]> loadUserFromResource(String resource) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(
// Path: src/test/java/ru/stqa/trainings/testng/simple5/sample22/DataProviders.java // public class DataProviders { // // @DataProvider // public static Iterator<Object[]> loadUserFromFile() throws IOException { // BufferedReader in = new BufferedReader(new InputStreamReader( // DataProviders.class.getResourceAsStream("/user.data"))); // // List<Object[]> userData = new ArrayList<Object[]>(); // String line = in.readLine(); // while (line != null) { // userData.add(line.split(";")); // line = in.readLine(); // } // // in.close(); // // return userData.iterator(); // } // // } // Path: src/test/java/ru/stqa/trainings/testng/tricky4/sample37/MyFactory.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.testng.annotations.Factory; import org.testng.annotations.Listeners; import ru.stqa.trainings.testng.simple5.sample22.DataProviders; package ru.stqa.trainings.testng.tricky4.sample37; @Listeners(OrderByPriority.class) public class MyFactory { @Factory public Object[] tf() throws IOException { List<Object> tests = new ArrayList<Object>(); List<String[]> data = loadUserFromResource("/user.data"); int p = 0; for (String[] dataItem : data) { CreateUser create = new CreateUser(dataItem[0], dataItem[1]); create.setPriority(p++); tests.add(create); DeleteUser delete = new DeleteUser(dataItem[0]); delete.setPriority(p++); tests.add(delete); } return (Object[]) tests.toArray(new Object[tests.size()]); } public List<String[]> loadUserFromResource(String resource) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(
DataProviders.class.getResourceAsStream(resource)));
wso2/product-es
modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/es/integration/common/utils/lifecycle/LifecycleUtil.java
// Path: modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/es/integration/common/utils/subscription/WorkItemClient.java // public class WorkItemClient { // private static Log log = LogFactory.getLog(WorkItemClient.class); // // private WorkItemClient() { // } // // /** // * get the existing management console notifications // * // * @param humanTaskAdminClient // * @return // * @throws java.rmi.RemoteException // * @throws IllegalStateFault // * @throws IllegalAccessFault // * @throws IllegalArgumentFault // * @throws InterruptedException // */ // public static WorkItem[] getWorkItems(HumanTaskAdminClient humanTaskAdminClient) // throws RemoteException, IllegalStateFault, IllegalAccessFault, IllegalArgumentFault, // InterruptedException { // long startTime = new Date().getTime(); // long endTime = startTime + 2 * 60 * 1000; // WorkItem[] workItems = null; // // try for a minute to get all the notifications // while ((new Date().getTime()) < endTime) { // workItems = humanTaskAdminClient.getWorkItems(); // if (workItems.length > 0) { // break; // } // Thread.sleep(5000); // } // return workItems; // } // // public static WorkItem[] waitForWorkItems(HumanTaskAdminClient humanTaskAdminClient) // throws RemoteException, InterruptedException, // SearchAdminServiceRegistryExceptionException { // Calendar startTime = Calendar.getInstance(); // WorkItem[] workItems = null; // while (((Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < 30000) { // log.info("waiting for work items ..... "); // try { // workItems = WorkItemClient.getWorkItems(humanTaskAdminClient); // } catch (Exception e) { // log.error("Error while getting work items... ", e); // return workItems; // } // if (workItems != null) { // return workItems; // } // Thread.sleep(5000); // } // return workItems; // } // // }
import org.wso2.carbon.automation.engine.context.AutomationContext; import org.wso2.carbon.automation.engine.frameworkutils.FrameworkPathUtil; import org.wso2.carbon.automation.test.utils.common.FileManager; import org.wso2.carbon.governance.custom.lifecycles.checklist.stub.CustomLifecyclesChecklistAdminServiceExceptionException; import org.wso2.carbon.governance.custom.lifecycles.checklist.stub.beans.xsd.LifecycleBean; import org.wso2.carbon.governance.custom.lifecycles.checklist.stub.util.xsd.Property; import org.wso2.carbon.humantask.stub.ui.task.client.api.IllegalAccessFault; import org.wso2.carbon.humantask.stub.ui.task.client.api.IllegalArgumentFault; import org.wso2.carbon.humantask.stub.ui.task.client.api.IllegalStateFault; import org.wso2.carbon.integration.common.admin.client.UserManagementClient; import org.wso2.carbon.integration.common.utils.LoginLogoutClient; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.info.stub.beans.xsd.SubscriptionBean; import org.wso2.carbon.registry.properties.stub.PropertiesAdminServiceRegistryExceptionException; import org.wso2.carbon.registry.resource.stub.ResourceAdminServiceExceptionException; import org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient; import org.wso2.es.integration.common.clients.*; import org.wso2.es.integration.common.utils.RegistryProviderUtil; import org.wso2.es.integration.common.utils.subscription.WorkItemClient; import javax.activation.DataHandler; import java.io.File; import java.net.URL; import java.rmi.RemoteException;
*/ private boolean consoleSubscribe(String path, String eventType) throws RemoteException, RegistryException { // subscribe for management console notifications SubscriptionBean bean = infoServiceAdminClient.subscribe(path, "work://RoleSubscriptionTest", eventType, sessionCookie); return bean.getSubscriptionInstances() != null; } /** * get management console subscriptions * * @param type type of the element * @return true if the required notification is generated, false otherwise * @throws java.rmi.RemoteException * @throws IllegalStateFault * @throws IllegalAccessFault * @throws IllegalArgumentFault * @throws InterruptedException */ private boolean getNotification(String type) throws RemoteException, IllegalStateFault, IllegalAccessFault, IllegalArgumentFault, InterruptedException { boolean success = false; Thread.sleep(3000);//force delay otherwise getWorkItems return null // get all the management console notifications
// Path: modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/es/integration/common/utils/subscription/WorkItemClient.java // public class WorkItemClient { // private static Log log = LogFactory.getLog(WorkItemClient.class); // // private WorkItemClient() { // } // // /** // * get the existing management console notifications // * // * @param humanTaskAdminClient // * @return // * @throws java.rmi.RemoteException // * @throws IllegalStateFault // * @throws IllegalAccessFault // * @throws IllegalArgumentFault // * @throws InterruptedException // */ // public static WorkItem[] getWorkItems(HumanTaskAdminClient humanTaskAdminClient) // throws RemoteException, IllegalStateFault, IllegalAccessFault, IllegalArgumentFault, // InterruptedException { // long startTime = new Date().getTime(); // long endTime = startTime + 2 * 60 * 1000; // WorkItem[] workItems = null; // // try for a minute to get all the notifications // while ((new Date().getTime()) < endTime) { // workItems = humanTaskAdminClient.getWorkItems(); // if (workItems.length > 0) { // break; // } // Thread.sleep(5000); // } // return workItems; // } // // public static WorkItem[] waitForWorkItems(HumanTaskAdminClient humanTaskAdminClient) // throws RemoteException, InterruptedException, // SearchAdminServiceRegistryExceptionException { // Calendar startTime = Calendar.getInstance(); // WorkItem[] workItems = null; // while (((Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < 30000) { // log.info("waiting for work items ..... "); // try { // workItems = WorkItemClient.getWorkItems(humanTaskAdminClient); // } catch (Exception e) { // log.error("Error while getting work items... ", e); // return workItems; // } // if (workItems != null) { // return workItems; // } // Thread.sleep(5000); // } // return workItems; // } // // } // Path: modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/es/integration/common/utils/lifecycle/LifecycleUtil.java import org.wso2.carbon.automation.engine.context.AutomationContext; import org.wso2.carbon.automation.engine.frameworkutils.FrameworkPathUtil; import org.wso2.carbon.automation.test.utils.common.FileManager; import org.wso2.carbon.governance.custom.lifecycles.checklist.stub.CustomLifecyclesChecklistAdminServiceExceptionException; import org.wso2.carbon.governance.custom.lifecycles.checklist.stub.beans.xsd.LifecycleBean; import org.wso2.carbon.governance.custom.lifecycles.checklist.stub.util.xsd.Property; import org.wso2.carbon.humantask.stub.ui.task.client.api.IllegalAccessFault; import org.wso2.carbon.humantask.stub.ui.task.client.api.IllegalArgumentFault; import org.wso2.carbon.humantask.stub.ui.task.client.api.IllegalStateFault; import org.wso2.carbon.integration.common.admin.client.UserManagementClient; import org.wso2.carbon.integration.common.utils.LoginLogoutClient; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.info.stub.beans.xsd.SubscriptionBean; import org.wso2.carbon.registry.properties.stub.PropertiesAdminServiceRegistryExceptionException; import org.wso2.carbon.registry.resource.stub.ResourceAdminServiceExceptionException; import org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient; import org.wso2.es.integration.common.clients.*; import org.wso2.es.integration.common.utils.RegistryProviderUtil; import org.wso2.es.integration.common.utils.subscription.WorkItemClient; import javax.activation.DataHandler; import java.io.File; import java.net.URL; import java.rmi.RemoteException; */ private boolean consoleSubscribe(String path, String eventType) throws RemoteException, RegistryException { // subscribe for management console notifications SubscriptionBean bean = infoServiceAdminClient.subscribe(path, "work://RoleSubscriptionTest", eventType, sessionCookie); return bean.getSubscriptionInstances() != null; } /** * get management console subscriptions * * @param type type of the element * @return true if the required notification is generated, false otherwise * @throws java.rmi.RemoteException * @throws IllegalStateFault * @throws IllegalAccessFault * @throws IllegalArgumentFault * @throws InterruptedException */ private boolean getNotification(String type) throws RemoteException, IllegalStateFault, IllegalAccessFault, IllegalArgumentFault, InterruptedException { boolean success = false; Thread.sleep(3000);//force delay otherwise getWorkItems return null // get all the management console notifications
WorkItem[] workItems = WorkItemClient.getWorkItems(humanTaskAdminClient);
wso2/product-es
modules/distribution/src/resources/es-migration-client/src/main/java/org/wso2/carbon/es/migration/MigrationDatabaseCreator.java
// Path: modules/distribution/src/resources/es-migration-client/src/main/java/org/wso2/carbon/es/migration/util/Constants.java // public class Constants { // // public static final String VERSION_210 = "2.1.0"; // //Constants for email username migration client // public static final String METADATA_NAMESPACE = "http://www.wso2.org/governance/metadata"; // public static final String OLD_EMAIL_AT_SIGN = ":"; // public static final String NEW_EMAIL_AT_SIGN = "-at-"; // public static final String CARBON_HOME = System.getProperty("carbon.home"); // public static final String REGISTRY_XML_PATH = Constants.CARBON_HOME + File.separator + "repository" + File.separator // + "conf" + File.separator + "registry.xml"; // public static final String UM_MIGRATION_SCRIPT = "/migration-scripts/um_migration.sql"; // public static final String REGISTRY_MIGRATION_SCRIPT = "/migration-scripts/reg_migration.sql"; // public static final String GOV_PATH = "/_system/governance"; // public static final String RESOURCETYPES_RXT_PATH = // GOV_PATH + "/repository/components/org.wso2.carbon.governance/types"; // public static final String ARTIFACT_TYPE = "artifactType"; // public static final String FILE_EXTENSION = "fileExtension"; // public static final String TYPE = "type"; // public static final String STORAGE_PATH = "storagePath"; // public static final String CONTENT = "content"; // public static final String TABLE = "table"; // public static final String NAME = "name"; // public static final String FIELD = "field"; // public static final String OVERVIEW = "overview"; // public static final String PROVIDER = "provider"; // public static final String OVERVIEW_PROVIDER = "@{overview_provider}"; // public static final String DB_CONFIG = "dbConfig"; // public static final String DATASOURCE = "dataSource"; // //registry path for store.json file at config registry // public static final String STORE_CONFIG_PATH = "/store/configs/store.json"; // // public static final String PUBLISHER_CONFIG_PATH = "/publisher/configs/publisher.json"; // public static final String LOGIN_PERMISSION = "\"/permission/admin/login\":"; // // public static final String PERMISSION_ACTION = "[\"ui.execute\"]"; // public static final String LOGIN_SCRIPT = "\"/permission/admin/login\":[\"ui.execute\"]"; // public static final String USER_PERMISSION_FIX_SCRIPT = "/migration-scripts/user_permission_fix.sql"; // // // }
import java.sql.SQLWarning; import java.sql.Statement; import java.util.StringTokenizer; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.es.migration.util.Constants; import org.wso2.carbon.utils.dbcreator.DatabaseCreator; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException;
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.es.migration; /** * This class initilzes the datsources and contains methods which executes the migration scripts on registry database * and um tables. */ public class MigrationDatabaseCreator { private static Log log = LogFactory.getLog(MigrationDatabaseCreator.class); private Connection conn = null; private Statement statement; private DataSource dataSource; private DataSource umDataSource; public MigrationDatabaseCreator(DataSource dataSource, DataSource umDataSource) { this.dataSource = dataSource; this.umDataSource = umDataSource; } public MigrationDatabaseCreator(DataSource dataSource) { this.dataSource = dataSource; } /** * Execute Migration Script * * @throws SQLException,IOException */ public void executeRegistryMigrationScript() throws SQLException, IOException { try { conn = dataSource.getConnection(); if (conn != null) { conn.setAutoCommit(false); statement = conn.createStatement();
// Path: modules/distribution/src/resources/es-migration-client/src/main/java/org/wso2/carbon/es/migration/util/Constants.java // public class Constants { // // public static final String VERSION_210 = "2.1.0"; // //Constants for email username migration client // public static final String METADATA_NAMESPACE = "http://www.wso2.org/governance/metadata"; // public static final String OLD_EMAIL_AT_SIGN = ":"; // public static final String NEW_EMAIL_AT_SIGN = "-at-"; // public static final String CARBON_HOME = System.getProperty("carbon.home"); // public static final String REGISTRY_XML_PATH = Constants.CARBON_HOME + File.separator + "repository" + File.separator // + "conf" + File.separator + "registry.xml"; // public static final String UM_MIGRATION_SCRIPT = "/migration-scripts/um_migration.sql"; // public static final String REGISTRY_MIGRATION_SCRIPT = "/migration-scripts/reg_migration.sql"; // public static final String GOV_PATH = "/_system/governance"; // public static final String RESOURCETYPES_RXT_PATH = // GOV_PATH + "/repository/components/org.wso2.carbon.governance/types"; // public static final String ARTIFACT_TYPE = "artifactType"; // public static final String FILE_EXTENSION = "fileExtension"; // public static final String TYPE = "type"; // public static final String STORAGE_PATH = "storagePath"; // public static final String CONTENT = "content"; // public static final String TABLE = "table"; // public static final String NAME = "name"; // public static final String FIELD = "field"; // public static final String OVERVIEW = "overview"; // public static final String PROVIDER = "provider"; // public static final String OVERVIEW_PROVIDER = "@{overview_provider}"; // public static final String DB_CONFIG = "dbConfig"; // public static final String DATASOURCE = "dataSource"; // //registry path for store.json file at config registry // public static final String STORE_CONFIG_PATH = "/store/configs/store.json"; // // public static final String PUBLISHER_CONFIG_PATH = "/publisher/configs/publisher.json"; // public static final String LOGIN_PERMISSION = "\"/permission/admin/login\":"; // // public static final String PERMISSION_ACTION = "[\"ui.execute\"]"; // public static final String LOGIN_SCRIPT = "\"/permission/admin/login\":[\"ui.execute\"]"; // public static final String USER_PERMISSION_FIX_SCRIPT = "/migration-scripts/user_permission_fix.sql"; // // // } // Path: modules/distribution/src/resources/es-migration-client/src/main/java/org/wso2/carbon/es/migration/MigrationDatabaseCreator.java import java.sql.SQLWarning; import java.sql.Statement; import java.util.StringTokenizer; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.es.migration.util.Constants; import org.wso2.carbon.utils.dbcreator.DatabaseCreator; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; /* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.es.migration; /** * This class initilzes the datsources and contains methods which executes the migration scripts on registry database * and um tables. */ public class MigrationDatabaseCreator { private static Log log = LogFactory.getLog(MigrationDatabaseCreator.class); private Connection conn = null; private Statement statement; private DataSource dataSource; private DataSource umDataSource; public MigrationDatabaseCreator(DataSource dataSource, DataSource umDataSource) { this.dataSource = dataSource; this.umDataSource = umDataSource; } public MigrationDatabaseCreator(DataSource dataSource) { this.dataSource = dataSource; } /** * Execute Migration Script * * @throws SQLException,IOException */ public void executeRegistryMigrationScript() throws SQLException, IOException { try { conn = dataSource.getConnection(); if (conn != null) { conn.setAutoCommit(false); statement = conn.createStatement();
String dbscriptName = Constants.REGISTRY_MIGRATION_SCRIPT;
wso2/product-es
modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/es/integration/common/utils/subscription/WorkItemClient.java
// Path: modules/integration/tests-common/admin-clients/src/main/java/org/wso2/es/integration/common/clients/HumanTaskAdminClient.java // public class HumanTaskAdminClient { // // private HumanTaskClientAPIAdminStub htStub; // private UserAdminStub umStub; // private WorkListServiceStub wlStub; // // public HumanTaskAdminClient(String backEndUrl, String sessionCookie) throws AxisFault { // htStub = new HumanTaskClientAPIAdminStub(backEndUrl + "HumanTaskClientAPIAdmin"); // AuthenticateStub.authenticateStub(sessionCookie, htStub); // // umStub = new UserAdminStub(backEndUrl + "UserAdmin"); // AuthenticateStub.authenticateStub(sessionCookie, umStub); // // wlStub = new WorkListServiceStub(backEndUrl + "WorkListService"); // AuthenticateStub.authenticateStub(sessionCookie, wlStub); // } // // public HumanTaskAdminClient(String backEndUrl, String userName, String password) throws AxisFault { // // htStub = new HumanTaskClientAPIAdminStub(backEndUrl + "HumanTaskClientAPIAdmin"); // AuthenticateStub.authenticateStub(userName, password, htStub); // // umStub = new UserAdminStub(backEndUrl + "UserAdmin"); // AuthenticateStub.authenticateStub(userName, password, umStub); // // wlStub = new WorkListServiceStub(backEndUrl + "WorkListService"); // AuthenticateStub.authenticateStub(userName, password, wlStub); // } // // // public WorkItem[] getWorkItems() // throws IllegalStateFault, IllegalAccessFault, RemoteException, IllegalArgumentFault { // // TSimpleQueryInput queryInput = new TSimpleQueryInput(); // queryInput.setPageNumber(0); // queryInput.setSimpleQueryCategory(TSimpleQueryCategory.ALL_TASKS); // // TTaskSimpleQueryResultSet resultSet = htStub.simpleQuery(queryInput); // if (resultSet == null || resultSet.getRow() == null || resultSet.getRow().length == 0) { // return new WorkItem[0]; // } // List<WorkItem> workItems = new LinkedList<>(); // for (TTaskSimpleQueryResultRow row : resultSet.getRow()) { // URI id = row.getId(); // String taskUser = ""; // //Ready state notification doesn't have taskUser // if (htStub.loadTask(id) != null && htStub.loadTask(id).getActualOwner() != null) { // taskUser = htStub.loadTask(id).getActualOwner().getTUser(); // } // // workItems.add(new WorkItem(id, row.getPresentationSubject(), // row.getPresentationName(), row.getPriority(), row.getStatus(), // row.getCreatedTime(), taskUser)); // } // return workItems.toArray(new WorkItem[workItems.size()]); // } // // /** // * change the workItem status to Complete. it will hide from the management console // * // * @param id // * @throws RemoteException // * @throws IllegalStateFault // * @throws IllegalOperationFault // * @throws IllegalArgumentFault // * @throws IllegalAccessFault // */ // public void completeTask(URI id) throws RemoteException, IllegalStateFault, // IllegalOperationFault, IllegalArgumentFault, IllegalAccessFault { // htStub.start(id); // htStub.complete(id, "<WorkResponse>true</WorkResponse>"); // } // }
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.humantask.stub.ui.task.client.api.IllegalAccessFault; import org.wso2.carbon.humantask.stub.ui.task.client.api.IllegalArgumentFault; import org.wso2.carbon.humantask.stub.ui.task.client.api.IllegalStateFault; import org.wso2.carbon.registry.search.stub.SearchAdminServiceRegistryExceptionException; import org.wso2.es.integration.common.clients.HumanTaskAdminClient; import org.wso2.es.integration.common.clients.WorkItem; import java.rmi.RemoteException; import java.util.Calendar; import java.util.Date;
/* * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.es.integration.common.utils.subscription; public class WorkItemClient { private static Log log = LogFactory.getLog(WorkItemClient.class); private WorkItemClient() { } /** * get the existing management console notifications * * @param humanTaskAdminClient * @return * @throws java.rmi.RemoteException * @throws IllegalStateFault * @throws IllegalAccessFault * @throws IllegalArgumentFault * @throws InterruptedException */
// Path: modules/integration/tests-common/admin-clients/src/main/java/org/wso2/es/integration/common/clients/HumanTaskAdminClient.java // public class HumanTaskAdminClient { // // private HumanTaskClientAPIAdminStub htStub; // private UserAdminStub umStub; // private WorkListServiceStub wlStub; // // public HumanTaskAdminClient(String backEndUrl, String sessionCookie) throws AxisFault { // htStub = new HumanTaskClientAPIAdminStub(backEndUrl + "HumanTaskClientAPIAdmin"); // AuthenticateStub.authenticateStub(sessionCookie, htStub); // // umStub = new UserAdminStub(backEndUrl + "UserAdmin"); // AuthenticateStub.authenticateStub(sessionCookie, umStub); // // wlStub = new WorkListServiceStub(backEndUrl + "WorkListService"); // AuthenticateStub.authenticateStub(sessionCookie, wlStub); // } // // public HumanTaskAdminClient(String backEndUrl, String userName, String password) throws AxisFault { // // htStub = new HumanTaskClientAPIAdminStub(backEndUrl + "HumanTaskClientAPIAdmin"); // AuthenticateStub.authenticateStub(userName, password, htStub); // // umStub = new UserAdminStub(backEndUrl + "UserAdmin"); // AuthenticateStub.authenticateStub(userName, password, umStub); // // wlStub = new WorkListServiceStub(backEndUrl + "WorkListService"); // AuthenticateStub.authenticateStub(userName, password, wlStub); // } // // // public WorkItem[] getWorkItems() // throws IllegalStateFault, IllegalAccessFault, RemoteException, IllegalArgumentFault { // // TSimpleQueryInput queryInput = new TSimpleQueryInput(); // queryInput.setPageNumber(0); // queryInput.setSimpleQueryCategory(TSimpleQueryCategory.ALL_TASKS); // // TTaskSimpleQueryResultSet resultSet = htStub.simpleQuery(queryInput); // if (resultSet == null || resultSet.getRow() == null || resultSet.getRow().length == 0) { // return new WorkItem[0]; // } // List<WorkItem> workItems = new LinkedList<>(); // for (TTaskSimpleQueryResultRow row : resultSet.getRow()) { // URI id = row.getId(); // String taskUser = ""; // //Ready state notification doesn't have taskUser // if (htStub.loadTask(id) != null && htStub.loadTask(id).getActualOwner() != null) { // taskUser = htStub.loadTask(id).getActualOwner().getTUser(); // } // // workItems.add(new WorkItem(id, row.getPresentationSubject(), // row.getPresentationName(), row.getPriority(), row.getStatus(), // row.getCreatedTime(), taskUser)); // } // return workItems.toArray(new WorkItem[workItems.size()]); // } // // /** // * change the workItem status to Complete. it will hide from the management console // * // * @param id // * @throws RemoteException // * @throws IllegalStateFault // * @throws IllegalOperationFault // * @throws IllegalArgumentFault // * @throws IllegalAccessFault // */ // public void completeTask(URI id) throws RemoteException, IllegalStateFault, // IllegalOperationFault, IllegalArgumentFault, IllegalAccessFault { // htStub.start(id); // htStub.complete(id, "<WorkResponse>true</WorkResponse>"); // } // } // Path: modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/es/integration/common/utils/subscription/WorkItemClient.java import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.humantask.stub.ui.task.client.api.IllegalAccessFault; import org.wso2.carbon.humantask.stub.ui.task.client.api.IllegalArgumentFault; import org.wso2.carbon.humantask.stub.ui.task.client.api.IllegalStateFault; import org.wso2.carbon.registry.search.stub.SearchAdminServiceRegistryExceptionException; import org.wso2.es.integration.common.clients.HumanTaskAdminClient; import org.wso2.es.integration.common.clients.WorkItem; import java.rmi.RemoteException; import java.util.Calendar; import java.util.Date; /* * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.es.integration.common.utils.subscription; public class WorkItemClient { private static Log log = LogFactory.getLog(WorkItemClient.class); private WorkItemClient() { } /** * get the existing management console notifications * * @param humanTaskAdminClient * @return * @throws java.rmi.RemoteException * @throws IllegalStateFault * @throws IllegalAccessFault * @throws IllegalArgumentFault * @throws InterruptedException */
public static WorkItem[] getWorkItems(HumanTaskAdminClient humanTaskAdminClient)
wso2/product-es
modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/es/integration/common/utils/ManifestUtils.java
// Path: modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/es/integration/common/utils/domain/InstallationManifest.java // public class InstallationManifest { // //private Collection<ResourcePackage> packages; // private Map<String,ResourcePackage> packages; // // public InstallationManifest() { // this.packages = new HashMap<>(); //new ArrayList<ResourcePackage>(); // } // // /** // * Returns a string list of package names // * @return // */ // public Collection<String> getResourcePackageNames() { // return packages.keySet(); // } // // /** // * Returns the ResourcePackage instance with the provided package name // * @param packageName The name of the package to be returned // * @return // */ // public ResourcePackage getResourcePackage(String packageName){ // ResourcePackage resourcePackage=null; // if(this.packages.containsKey(packageName)){ // resourcePackage = this.packages.get(packageName); // } // return resourcePackage; // } // // /** // * Returns the list of packages to be installed // * @return // */ // public Collection<ResourcePackage> getResourcePackages() { // return packages.values(); // //return packages; // } // }
import com.google.gson.Gson; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.es.integration.common.utils.domain.InstallationManifest; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException;
/* * Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.es.integration.common.utils; /** * Encapsulates all actions related to reading installation * manifest file */ public class ManifestUtils { private static final Log log = LogFactory.getLog(ManifestUtils.class); private ManifestUtils() { } /** * Reads the manifest file and then converts the JSON content to an instance of the InstallationManifest * DAO * @param manifestPath The path to manifest file * @return An instance of the InstallationManfiest DAO * @throws IOException Thrown if the manifest file cannot be found */
// Path: modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/es/integration/common/utils/domain/InstallationManifest.java // public class InstallationManifest { // //private Collection<ResourcePackage> packages; // private Map<String,ResourcePackage> packages; // // public InstallationManifest() { // this.packages = new HashMap<>(); //new ArrayList<ResourcePackage>(); // } // // /** // * Returns a string list of package names // * @return // */ // public Collection<String> getResourcePackageNames() { // return packages.keySet(); // } // // /** // * Returns the ResourcePackage instance with the provided package name // * @param packageName The name of the package to be returned // * @return // */ // public ResourcePackage getResourcePackage(String packageName){ // ResourcePackage resourcePackage=null; // if(this.packages.containsKey(packageName)){ // resourcePackage = this.packages.get(packageName); // } // return resourcePackage; // } // // /** // * Returns the list of packages to be installed // * @return // */ // public Collection<ResourcePackage> getResourcePackages() { // return packages.values(); // //return packages; // } // } // Path: modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/es/integration/common/utils/ManifestUtils.java import com.google.gson.Gson; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.es.integration.common.utils.domain.InstallationManifest; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; /* * Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.es.integration.common.utils; /** * Encapsulates all actions related to reading installation * manifest file */ public class ManifestUtils { private static final Log log = LogFactory.getLog(ManifestUtils.class); private ManifestUtils() { } /** * Reads the manifest file and then converts the JSON content to an instance of the InstallationManifest * DAO * @param manifestPath The path to manifest file * @return An instance of the InstallationManfiest DAO * @throws IOException Thrown if the manifest file cannot be found */
public static InstallationManifest load(String manifestPath) throws IOException {
wso2/product-es
modules/integration/tests-common/ui-pages/src/main/java/org/wso2/es/integration/common/ui/page/main/HomePage.java
// Path: modules/integration/tests-common/ui-pages/src/main/java/org/wso2/es/integration/common/ui/page/LoginPage.java // public class LoginPage { // private static final Log log = LogFactory.getLog(LoginPage.class); // private WebDriver driver; // private boolean isCloudEnvironment = false; // // public LoginPage(WebDriver driver) throws IOException { // this.driver = driver; // // // Check that we're on the right page. // if (!driver.getCurrentUrl().contains("login.jsp")) { // // Alternatively, we could navigate to the login page, perhaps logging out first // throw new IllegalStateException("This is not the login page"); // } // } // // public LoginPage(WebDriver driver, boolean isCloudEnvironment) throws IOException { // this.driver = driver; // this.isCloudEnvironment = isCloudEnvironment; // // Check that we're on the right page. // if (this.isCloudEnvironment) { // if (!driver.getCurrentUrl().contains("home/index.html")) { // // Alternatively, we could navigate to the login page, perhaps logging out first // throw new IllegalStateException("This is not the cloud login page"); // } // driver.findElement(By.xpath("//*[@id=\"content\"]/div[1]/div/a[2]/img")).click(); // } else { // if (!(driver.getCurrentUrl().contains("login.jsp"))) { // // Alternatively, we could navigate to the login page, perhaps logging out first // throw new IllegalStateException("This is not the product login page"); // } // } // } // // public HomePage loginAs(String userName, String password, boolean isTenant) // throws IOException { // log.info("login as " + userName + ":Tenant"); // WebElement userNameField = driver.findElement(By.name(UIElementMapper.getInstance().getElement("login.username.name"))); // WebElement passwordField = driver.findElement(By.name(UIElementMapper.getInstance().getElement("login.password"))); // // userNameField.sendKeys(userName); // passwordField.sendKeys(password); // if (isCloudEnvironment) { // driver.findElement( // By.xpath("//*[@id=\"loginForm\"]/table/tbody/tr[4]/td[2]/input")) // .click(); // return new HomePage(isTenant, driver); // } else { // driver.findElement( // By.className(UIElementMapper.getInstance() // .getElement("login.sign.in.button"))).click(); // return new HomePage(isTenant, driver); // } // } // // public HomePage loginAs(String userName, String password) throws IOException { // log.info("login as " + userName); // WebElement userNameField = driver.findElement(By.name(UIElementMapper.getInstance().getElement("login.username.name"))); // WebElement passwordField = driver.findElement(By.name(UIElementMapper.getInstance().getElement("login.password"))); // // userNameField.sendKeys(userName); // passwordField.sendKeys(password); // if (isCloudEnvironment) { // driver.findElement(By.xpath("//*[@id=\"loginForm\"]/table/tbody/tr[4]/td[2]/input")).click(); // return new HomePage(driver, isCloudEnvironment); // } else { // driver.findElement(By.className(UIElementMapper.getInstance().getElement("login.sign.in.button"))).click(); // return new HomePage(driver); // } // } // // }
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.wso2.es.integration.common.ui.page.LoginPage; import org.wso2.es.integration.common.ui.page.util.UIElementMapper; import java.io.IOException; import java.util.Arrays; import java.util.List;
.getText().toLowerCase().contains("home")) { throw new IllegalStateException("This is not the home page"); } } public HomePage(WebDriver driver, boolean isCloudEnvironment) throws IOException { this.driver = driver; this.isCloudEnvironment = isCloudEnvironment; if (isCloudEnvironment) { if (!driver.findElement(By.className("dashboard-title")).getText().toLowerCase().contains("quick start dashboard")) { throw new IllegalStateException("This is not the cloud home page"); } } else { // Check that we're on the right page. if (!driver.findElement(By.id(UIElementMapper.getInstance().getElement("home.dashboard.middle.text"))) .getText().toLowerCase().contains("home")) { throw new IllegalStateException("This is not the home page"); } } } public HomePage(boolean isTenant, WebDriver driver) throws IOException { this.isTenant = isTenant; if (this.isTenant) { if (!driver.getCurrentUrl().contains("loginStatus=true")) { throw new IllegalStateException("This is not the home page"); } } }
// Path: modules/integration/tests-common/ui-pages/src/main/java/org/wso2/es/integration/common/ui/page/LoginPage.java // public class LoginPage { // private static final Log log = LogFactory.getLog(LoginPage.class); // private WebDriver driver; // private boolean isCloudEnvironment = false; // // public LoginPage(WebDriver driver) throws IOException { // this.driver = driver; // // // Check that we're on the right page. // if (!driver.getCurrentUrl().contains("login.jsp")) { // // Alternatively, we could navigate to the login page, perhaps logging out first // throw new IllegalStateException("This is not the login page"); // } // } // // public LoginPage(WebDriver driver, boolean isCloudEnvironment) throws IOException { // this.driver = driver; // this.isCloudEnvironment = isCloudEnvironment; // // Check that we're on the right page. // if (this.isCloudEnvironment) { // if (!driver.getCurrentUrl().contains("home/index.html")) { // // Alternatively, we could navigate to the login page, perhaps logging out first // throw new IllegalStateException("This is not the cloud login page"); // } // driver.findElement(By.xpath("//*[@id=\"content\"]/div[1]/div/a[2]/img")).click(); // } else { // if (!(driver.getCurrentUrl().contains("login.jsp"))) { // // Alternatively, we could navigate to the login page, perhaps logging out first // throw new IllegalStateException("This is not the product login page"); // } // } // } // // public HomePage loginAs(String userName, String password, boolean isTenant) // throws IOException { // log.info("login as " + userName + ":Tenant"); // WebElement userNameField = driver.findElement(By.name(UIElementMapper.getInstance().getElement("login.username.name"))); // WebElement passwordField = driver.findElement(By.name(UIElementMapper.getInstance().getElement("login.password"))); // // userNameField.sendKeys(userName); // passwordField.sendKeys(password); // if (isCloudEnvironment) { // driver.findElement( // By.xpath("//*[@id=\"loginForm\"]/table/tbody/tr[4]/td[2]/input")) // .click(); // return new HomePage(isTenant, driver); // } else { // driver.findElement( // By.className(UIElementMapper.getInstance() // .getElement("login.sign.in.button"))).click(); // return new HomePage(isTenant, driver); // } // } // // public HomePage loginAs(String userName, String password) throws IOException { // log.info("login as " + userName); // WebElement userNameField = driver.findElement(By.name(UIElementMapper.getInstance().getElement("login.username.name"))); // WebElement passwordField = driver.findElement(By.name(UIElementMapper.getInstance().getElement("login.password"))); // // userNameField.sendKeys(userName); // passwordField.sendKeys(password); // if (isCloudEnvironment) { // driver.findElement(By.xpath("//*[@id=\"loginForm\"]/table/tbody/tr[4]/td[2]/input")).click(); // return new HomePage(driver, isCloudEnvironment); // } else { // driver.findElement(By.className(UIElementMapper.getInstance().getElement("login.sign.in.button"))).click(); // return new HomePage(driver); // } // } // // } // Path: modules/integration/tests-common/ui-pages/src/main/java/org/wso2/es/integration/common/ui/page/main/HomePage.java import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.wso2.es.integration.common.ui.page.LoginPage; import org.wso2.es.integration.common.ui.page.util.UIElementMapper; import java.io.IOException; import java.util.Arrays; import java.util.List; .getText().toLowerCase().contains("home")) { throw new IllegalStateException("This is not the home page"); } } public HomePage(WebDriver driver, boolean isCloudEnvironment) throws IOException { this.driver = driver; this.isCloudEnvironment = isCloudEnvironment; if (isCloudEnvironment) { if (!driver.findElement(By.className("dashboard-title")).getText().toLowerCase().contains("quick start dashboard")) { throw new IllegalStateException("This is not the cloud home page"); } } else { // Check that we're on the right page. if (!driver.findElement(By.id(UIElementMapper.getInstance().getElement("home.dashboard.middle.text"))) .getText().toLowerCase().contains("home")) { throw new IllegalStateException("This is not the home page"); } } } public HomePage(boolean isTenant, WebDriver driver) throws IOException { this.isTenant = isTenant; if (this.isTenant) { if (!driver.getCurrentUrl().contains("loginStatus=true")) { throw new IllegalStateException("This is not the home page"); } } }
public LoginPage logout() throws IOException {
wso2/product-es
modules/integration/tests-common/ui-pages/src/main/java/org/wso2/es/integration/common/ui/page/LoginPage.java
// Path: modules/integration/tests-common/ui-pages/src/main/java/org/wso2/es/integration/common/ui/page/main/HomePage.java // public class HomePage { // // // private static final Log log = LogFactory.getLog(HomePage.class); // private WebDriver driver; // private boolean isCloudEnvironment = false; // private boolean isTenant = false; // // public HomePage(WebDriver driver) throws IOException { // this.driver = driver; // // Check that we're on the right page. // if (!driver.findElement(By.id(UIElementMapper.getInstance().getElement("home.dashboard.middle.text"))) // .getText().toLowerCase().contains("home")) { // throw new IllegalStateException("This is not the home page"); // } // } // // public HomePage(WebDriver driver, boolean isCloudEnvironment) throws IOException { // this.driver = driver; // this.isCloudEnvironment = isCloudEnvironment; // if (isCloudEnvironment) { // if (!driver.findElement(By.className("dashboard-title")).getText().toLowerCase().contains("quick start dashboard")) { // throw new IllegalStateException("This is not the cloud home page"); // } // } else { // // Check that we're on the right page. // if (!driver.findElement(By.id(UIElementMapper.getInstance().getElement("home.dashboard.middle.text"))) // .getText().toLowerCase().contains("home")) { // throw new IllegalStateException("This is not the home page"); // } // } // } // // public HomePage(boolean isTenant, WebDriver driver) throws IOException { // this.isTenant = isTenant; // if (this.isTenant) { // if (!driver.getCurrentUrl().contains("loginStatus=true")) { // throw new IllegalStateException("This is not the home page"); // } // } // } // // public LoginPage logout() throws IOException { // driver.findElement(By.xpath(UIElementMapper.getInstance().getElement("home.greg.sign.out.xpath"))).click(); // return new LoginPage(driver, isCloudEnvironment); // } // // private int findMenuItem(int startIndex, String name, List<WebElement> menuItems){ // for (int i = startIndex; i < menuItems.size(); i++) { // WebElement item = menuItems.get(i); // if (name.equals(item.getText())) { // return i; // } // } // return menuItems.size(); // } // // public WebDriver clickMenu(String... itemNames) { // List<WebElement> menuItems = driver.findElements(By.cssSelector(".main li")); // int index = 0; // for (String itemName : itemNames) { // index = findMenuItem(index, itemName, menuItems); // // } // // if (index < menuItems.size()) { // menuItems.get(index).findElement(By.tagName("a")).click(); // } else { // throw new IllegalStateException("Menu item with text '" + Arrays.toString(itemNames) + "' does not exits."); // } // return driver; // } // }
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.wso2.es.integration.common.ui.page.main.HomePage; import org.wso2.es.integration.common.ui.page.util.UIElementMapper; import java.io.IOException;
/* *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * *WSO2 Inc. licenses this file to you under the Apache License, *Version 2.0 (the "License"); you may not use this file except *in compliance with the License. *You may obtain a copy of the License at * *http://www.apache.org/licenses/LICENSE-2.0 * *Unless required by applicable law or agreed to in writing, *software distributed under the License is distributed on an *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *KIND, either express or implied. See the License for the *specific language governing permissions and limitations *under the License. */ package org.wso2.es.integration.common.ui.page; /** * login page class - contains methods to login to wso2 products. */ public class LoginPage { private static final Log log = LogFactory.getLog(LoginPage.class); private WebDriver driver; private boolean isCloudEnvironment = false; public LoginPage(WebDriver driver) throws IOException { this.driver = driver; // Check that we're on the right page. if (!driver.getCurrentUrl().contains("login.jsp")) { // Alternatively, we could navigate to the login page, perhaps logging out first throw new IllegalStateException("This is not the login page"); } } public LoginPage(WebDriver driver, boolean isCloudEnvironment) throws IOException { this.driver = driver; this.isCloudEnvironment = isCloudEnvironment; // Check that we're on the right page. if (this.isCloudEnvironment) { if (!driver.getCurrentUrl().contains("home/index.html")) { // Alternatively, we could navigate to the login page, perhaps logging out first throw new IllegalStateException("This is not the cloud login page"); } driver.findElement(By.xpath("//*[@id=\"content\"]/div[1]/div/a[2]/img")).click(); } else { if (!(driver.getCurrentUrl().contains("login.jsp"))) { // Alternatively, we could navigate to the login page, perhaps logging out first throw new IllegalStateException("This is not the product login page"); } } }
// Path: modules/integration/tests-common/ui-pages/src/main/java/org/wso2/es/integration/common/ui/page/main/HomePage.java // public class HomePage { // // // private static final Log log = LogFactory.getLog(HomePage.class); // private WebDriver driver; // private boolean isCloudEnvironment = false; // private boolean isTenant = false; // // public HomePage(WebDriver driver) throws IOException { // this.driver = driver; // // Check that we're on the right page. // if (!driver.findElement(By.id(UIElementMapper.getInstance().getElement("home.dashboard.middle.text"))) // .getText().toLowerCase().contains("home")) { // throw new IllegalStateException("This is not the home page"); // } // } // // public HomePage(WebDriver driver, boolean isCloudEnvironment) throws IOException { // this.driver = driver; // this.isCloudEnvironment = isCloudEnvironment; // if (isCloudEnvironment) { // if (!driver.findElement(By.className("dashboard-title")).getText().toLowerCase().contains("quick start dashboard")) { // throw new IllegalStateException("This is not the cloud home page"); // } // } else { // // Check that we're on the right page. // if (!driver.findElement(By.id(UIElementMapper.getInstance().getElement("home.dashboard.middle.text"))) // .getText().toLowerCase().contains("home")) { // throw new IllegalStateException("This is not the home page"); // } // } // } // // public HomePage(boolean isTenant, WebDriver driver) throws IOException { // this.isTenant = isTenant; // if (this.isTenant) { // if (!driver.getCurrentUrl().contains("loginStatus=true")) { // throw new IllegalStateException("This is not the home page"); // } // } // } // // public LoginPage logout() throws IOException { // driver.findElement(By.xpath(UIElementMapper.getInstance().getElement("home.greg.sign.out.xpath"))).click(); // return new LoginPage(driver, isCloudEnvironment); // } // // private int findMenuItem(int startIndex, String name, List<WebElement> menuItems){ // for (int i = startIndex; i < menuItems.size(); i++) { // WebElement item = menuItems.get(i); // if (name.equals(item.getText())) { // return i; // } // } // return menuItems.size(); // } // // public WebDriver clickMenu(String... itemNames) { // List<WebElement> menuItems = driver.findElements(By.cssSelector(".main li")); // int index = 0; // for (String itemName : itemNames) { // index = findMenuItem(index, itemName, menuItems); // // } // // if (index < menuItems.size()) { // menuItems.get(index).findElement(By.tagName("a")).click(); // } else { // throw new IllegalStateException("Menu item with text '" + Arrays.toString(itemNames) + "' does not exits."); // } // return driver; // } // } // Path: modules/integration/tests-common/ui-pages/src/main/java/org/wso2/es/integration/common/ui/page/LoginPage.java import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.wso2.es.integration.common.ui.page.main.HomePage; import org.wso2.es.integration.common.ui.page.util.UIElementMapper; import java.io.IOException; /* *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * *WSO2 Inc. licenses this file to you under the Apache License, *Version 2.0 (the "License"); you may not use this file except *in compliance with the License. *You may obtain a copy of the License at * *http://www.apache.org/licenses/LICENSE-2.0 * *Unless required by applicable law or agreed to in writing, *software distributed under the License is distributed on an *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *KIND, either express or implied. See the License for the *specific language governing permissions and limitations *under the License. */ package org.wso2.es.integration.common.ui.page; /** * login page class - contains methods to login to wso2 products. */ public class LoginPage { private static final Log log = LogFactory.getLog(LoginPage.class); private WebDriver driver; private boolean isCloudEnvironment = false; public LoginPage(WebDriver driver) throws IOException { this.driver = driver; // Check that we're on the right page. if (!driver.getCurrentUrl().contains("login.jsp")) { // Alternatively, we could navigate to the login page, perhaps logging out first throw new IllegalStateException("This is not the login page"); } } public LoginPage(WebDriver driver, boolean isCloudEnvironment) throws IOException { this.driver = driver; this.isCloudEnvironment = isCloudEnvironment; // Check that we're on the right page. if (this.isCloudEnvironment) { if (!driver.getCurrentUrl().contains("home/index.html")) { // Alternatively, we could navigate to the login page, perhaps logging out first throw new IllegalStateException("This is not the cloud login page"); } driver.findElement(By.xpath("//*[@id=\"content\"]/div[1]/div/a[2]/img")).click(); } else { if (!(driver.getCurrentUrl().contains("login.jsp"))) { // Alternatively, we could navigate to the login page, perhaps logging out first throw new IllegalStateException("This is not the product login page"); } } }
public HomePage loginAs(String userName, String password, boolean isTenant)
Apereo-Learning-Analytics-Initiative/Larissa
src/test/java/nl/uva/larissa/repository/couchdb/DbKey.java
// Path: src/main/java/nl/uva/larissa/json/model/Activity.java // public class Activity implements StatementObject { // // private String objectType; // @NotNull // private IRI id; // @Valid // private ActivityDefinition definition; // // public String getObjectType() { // return objectType; // } // // public void setObjectType(String objectType) { // this.objectType = objectType; // } // // public IRI getId() { // return id; // } // // public void setId(IRI id) { // this.id = id; // } // // public ActivityDefinition getDefinition() { // return definition; // } // // public void setDefinition(ActivityDefinition definition) { // this.definition = definition; // } // // } // // Path: src/main/java/nl/uva/larissa/json/model/Agent.java // @JsonInclude(Include.NON_NULL) // public class Agent implements Actor, Authority, Instructor, StatementObject { // // private String objectType; // private String name; // @JsonUnwrapped // @Valid // @NotNull // private IFI identifier; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public IFI getIdentifier() { // return identifier; // } // // public void setIdentifier(IFI identifier) { // this.identifier = identifier; // } // // public String getObjectType() { // return objectType; // } // // public void setObjectType(String objectType) { // this.objectType = objectType; // } // } // // Path: src/main/java/nl/uva/larissa/json/model/Statement.java // @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context", // "timestamp", "stored", "authority", "version" }) // @ValidRevisionUsage // @ValidPlatformUsage // public class Statement { // @JsonProperty(required = false) // @IsUUID // private String id; // @NotNull // @Valid // private Actor actor; // @NotNull // @Valid // private Verb verb; // @NotNull // @Valid // @JsonProperty("object") // private StatementObject statementObject; // private Result result; // @Valid // private Context context; // // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it // // is outside of a Sub-Statement. // @Past // private Date timestamp; // // // should be set by the LRS, not the client // @Null // private Date stored; // private Authority authority; // private String version; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public Actor getActor() { // return actor; // } // // public void setActor(Actor actor) { // this.actor = actor; // } // // public Verb getVerb() { // return verb; // } // // public void setVerb(Verb verb) { // this.verb = verb; // } // // public StatementObject getStatementObject() { // return statementObject; // } // // public void setStatementObject(StatementObject statementObject) { // this.statementObject = statementObject; // } // // public Result getResult() { // return result; // } // // public void setResult(Result result) { // this.result = result; // } // // public Date getTimestamp() { // return timestamp; // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public Date getStored() { // return stored; // } // // public void setStored(Date stored) { // this.stored = stored; // } // // public Authority getAuthority() { // return authority; // } // // public void setAuthority(Authority authority) { // this.authority = authority; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public Context getContext() { // return context; // } // // public void setContext(Context context) { // this.context = context; // } // } // // Path: src/main/java/nl/uva/larissa/json/model/Verb.java // public class Verb { // @NotNull // private IRI id; // @LanguageMap // private Map<String, String> display; // // public IRI getId() { // return id; // } // // public void setId(IRI id) { // this.id = id; // } // // public Map<String, String> getDisplay() { // return display; // } // // public void setDisplay(Map<String, String> display) { // this.display = display; // } // }
import java.util.UUID; import nl.uva.larissa.json.model.Activity; import nl.uva.larissa.json.model.Agent; import nl.uva.larissa.json.model.Statement; import nl.uva.larissa.json.model.Verb; import org.apache.abdera.i18n.iri.IRI;
package nl.uva.larissa.repository.couchdb; class DbKey { private Statement statement; public DbKey(String email, String verbName) {
// Path: src/main/java/nl/uva/larissa/json/model/Activity.java // public class Activity implements StatementObject { // // private String objectType; // @NotNull // private IRI id; // @Valid // private ActivityDefinition definition; // // public String getObjectType() { // return objectType; // } // // public void setObjectType(String objectType) { // this.objectType = objectType; // } // // public IRI getId() { // return id; // } // // public void setId(IRI id) { // this.id = id; // } // // public ActivityDefinition getDefinition() { // return definition; // } // // public void setDefinition(ActivityDefinition definition) { // this.definition = definition; // } // // } // // Path: src/main/java/nl/uva/larissa/json/model/Agent.java // @JsonInclude(Include.NON_NULL) // public class Agent implements Actor, Authority, Instructor, StatementObject { // // private String objectType; // private String name; // @JsonUnwrapped // @Valid // @NotNull // private IFI identifier; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public IFI getIdentifier() { // return identifier; // } // // public void setIdentifier(IFI identifier) { // this.identifier = identifier; // } // // public String getObjectType() { // return objectType; // } // // public void setObjectType(String objectType) { // this.objectType = objectType; // } // } // // Path: src/main/java/nl/uva/larissa/json/model/Statement.java // @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context", // "timestamp", "stored", "authority", "version" }) // @ValidRevisionUsage // @ValidPlatformUsage // public class Statement { // @JsonProperty(required = false) // @IsUUID // private String id; // @NotNull // @Valid // private Actor actor; // @NotNull // @Valid // private Verb verb; // @NotNull // @Valid // @JsonProperty("object") // private StatementObject statementObject; // private Result result; // @Valid // private Context context; // // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it // // is outside of a Sub-Statement. // @Past // private Date timestamp; // // // should be set by the LRS, not the client // @Null // private Date stored; // private Authority authority; // private String version; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public Actor getActor() { // return actor; // } // // public void setActor(Actor actor) { // this.actor = actor; // } // // public Verb getVerb() { // return verb; // } // // public void setVerb(Verb verb) { // this.verb = verb; // } // // public StatementObject getStatementObject() { // return statementObject; // } // // public void setStatementObject(StatementObject statementObject) { // this.statementObject = statementObject; // } // // public Result getResult() { // return result; // } // // public void setResult(Result result) { // this.result = result; // } // // public Date getTimestamp() { // return timestamp; // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public Date getStored() { // return stored; // } // // public void setStored(Date stored) { // this.stored = stored; // } // // public Authority getAuthority() { // return authority; // } // // public void setAuthority(Authority authority) { // this.authority = authority; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public Context getContext() { // return context; // } // // public void setContext(Context context) { // this.context = context; // } // } // // Path: src/main/java/nl/uva/larissa/json/model/Verb.java // public class Verb { // @NotNull // private IRI id; // @LanguageMap // private Map<String, String> display; // // public IRI getId() { // return id; // } // // public void setId(IRI id) { // this.id = id; // } // // public Map<String, String> getDisplay() { // return display; // } // // public void setDisplay(Map<String, String> display) { // this.display = display; // } // } // Path: src/test/java/nl/uva/larissa/repository/couchdb/DbKey.java import java.util.UUID; import nl.uva.larissa.json.model.Activity; import nl.uva.larissa.json.model.Agent; import nl.uva.larissa.json.model.Statement; import nl.uva.larissa.json.model.Verb; import org.apache.abdera.i18n.iri.IRI; package nl.uva.larissa.repository.couchdb; class DbKey { private Statement statement; public DbKey(String email, String verbName) {
Agent agent = ITAgentQuery.getAgent(email);
Apereo-Learning-Analytics-Initiative/Larissa
src/test/java/nl/uva/larissa/repository/couchdb/DbKey.java
// Path: src/main/java/nl/uva/larissa/json/model/Activity.java // public class Activity implements StatementObject { // // private String objectType; // @NotNull // private IRI id; // @Valid // private ActivityDefinition definition; // // public String getObjectType() { // return objectType; // } // // public void setObjectType(String objectType) { // this.objectType = objectType; // } // // public IRI getId() { // return id; // } // // public void setId(IRI id) { // this.id = id; // } // // public ActivityDefinition getDefinition() { // return definition; // } // // public void setDefinition(ActivityDefinition definition) { // this.definition = definition; // } // // } // // Path: src/main/java/nl/uva/larissa/json/model/Agent.java // @JsonInclude(Include.NON_NULL) // public class Agent implements Actor, Authority, Instructor, StatementObject { // // private String objectType; // private String name; // @JsonUnwrapped // @Valid // @NotNull // private IFI identifier; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public IFI getIdentifier() { // return identifier; // } // // public void setIdentifier(IFI identifier) { // this.identifier = identifier; // } // // public String getObjectType() { // return objectType; // } // // public void setObjectType(String objectType) { // this.objectType = objectType; // } // } // // Path: src/main/java/nl/uva/larissa/json/model/Statement.java // @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context", // "timestamp", "stored", "authority", "version" }) // @ValidRevisionUsage // @ValidPlatformUsage // public class Statement { // @JsonProperty(required = false) // @IsUUID // private String id; // @NotNull // @Valid // private Actor actor; // @NotNull // @Valid // private Verb verb; // @NotNull // @Valid // @JsonProperty("object") // private StatementObject statementObject; // private Result result; // @Valid // private Context context; // // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it // // is outside of a Sub-Statement. // @Past // private Date timestamp; // // // should be set by the LRS, not the client // @Null // private Date stored; // private Authority authority; // private String version; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public Actor getActor() { // return actor; // } // // public void setActor(Actor actor) { // this.actor = actor; // } // // public Verb getVerb() { // return verb; // } // // public void setVerb(Verb verb) { // this.verb = verb; // } // // public StatementObject getStatementObject() { // return statementObject; // } // // public void setStatementObject(StatementObject statementObject) { // this.statementObject = statementObject; // } // // public Result getResult() { // return result; // } // // public void setResult(Result result) { // this.result = result; // } // // public Date getTimestamp() { // return timestamp; // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public Date getStored() { // return stored; // } // // public void setStored(Date stored) { // this.stored = stored; // } // // public Authority getAuthority() { // return authority; // } // // public void setAuthority(Authority authority) { // this.authority = authority; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public Context getContext() { // return context; // } // // public void setContext(Context context) { // this.context = context; // } // } // // Path: src/main/java/nl/uva/larissa/json/model/Verb.java // public class Verb { // @NotNull // private IRI id; // @LanguageMap // private Map<String, String> display; // // public IRI getId() { // return id; // } // // public void setId(IRI id) { // this.id = id; // } // // public Map<String, String> getDisplay() { // return display; // } // // public void setDisplay(Map<String, String> display) { // this.display = display; // } // }
import java.util.UUID; import nl.uva.larissa.json.model.Activity; import nl.uva.larissa.json.model.Agent; import nl.uva.larissa.json.model.Statement; import nl.uva.larissa.json.model.Verb; import org.apache.abdera.i18n.iri.IRI;
package nl.uva.larissa.repository.couchdb; class DbKey { private Statement statement; public DbKey(String email, String verbName) { Agent agent = ITAgentQuery.getAgent(email);
// Path: src/main/java/nl/uva/larissa/json/model/Activity.java // public class Activity implements StatementObject { // // private String objectType; // @NotNull // private IRI id; // @Valid // private ActivityDefinition definition; // // public String getObjectType() { // return objectType; // } // // public void setObjectType(String objectType) { // this.objectType = objectType; // } // // public IRI getId() { // return id; // } // // public void setId(IRI id) { // this.id = id; // } // // public ActivityDefinition getDefinition() { // return definition; // } // // public void setDefinition(ActivityDefinition definition) { // this.definition = definition; // } // // } // // Path: src/main/java/nl/uva/larissa/json/model/Agent.java // @JsonInclude(Include.NON_NULL) // public class Agent implements Actor, Authority, Instructor, StatementObject { // // private String objectType; // private String name; // @JsonUnwrapped // @Valid // @NotNull // private IFI identifier; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public IFI getIdentifier() { // return identifier; // } // // public void setIdentifier(IFI identifier) { // this.identifier = identifier; // } // // public String getObjectType() { // return objectType; // } // // public void setObjectType(String objectType) { // this.objectType = objectType; // } // } // // Path: src/main/java/nl/uva/larissa/json/model/Statement.java // @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context", // "timestamp", "stored", "authority", "version" }) // @ValidRevisionUsage // @ValidPlatformUsage // public class Statement { // @JsonProperty(required = false) // @IsUUID // private String id; // @NotNull // @Valid // private Actor actor; // @NotNull // @Valid // private Verb verb; // @NotNull // @Valid // @JsonProperty("object") // private StatementObject statementObject; // private Result result; // @Valid // private Context context; // // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it // // is outside of a Sub-Statement. // @Past // private Date timestamp; // // // should be set by the LRS, not the client // @Null // private Date stored; // private Authority authority; // private String version; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public Actor getActor() { // return actor; // } // // public void setActor(Actor actor) { // this.actor = actor; // } // // public Verb getVerb() { // return verb; // } // // public void setVerb(Verb verb) { // this.verb = verb; // } // // public StatementObject getStatementObject() { // return statementObject; // } // // public void setStatementObject(StatementObject statementObject) { // this.statementObject = statementObject; // } // // public Result getResult() { // return result; // } // // public void setResult(Result result) { // this.result = result; // } // // public Date getTimestamp() { // return timestamp; // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public Date getStored() { // return stored; // } // // public void setStored(Date stored) { // this.stored = stored; // } // // public Authority getAuthority() { // return authority; // } // // public void setAuthority(Authority authority) { // this.authority = authority; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public Context getContext() { // return context; // } // // public void setContext(Context context) { // this.context = context; // } // } // // Path: src/main/java/nl/uva/larissa/json/model/Verb.java // public class Verb { // @NotNull // private IRI id; // @LanguageMap // private Map<String, String> display; // // public IRI getId() { // return id; // } // // public void setId(IRI id) { // this.id = id; // } // // public Map<String, String> getDisplay() { // return display; // } // // public void setDisplay(Map<String, String> display) { // this.display = display; // } // } // Path: src/test/java/nl/uva/larissa/repository/couchdb/DbKey.java import java.util.UUID; import nl.uva.larissa.json.model.Activity; import nl.uva.larissa.json.model.Agent; import nl.uva.larissa.json.model.Statement; import nl.uva.larissa.json.model.Verb; import org.apache.abdera.i18n.iri.IRI; package nl.uva.larissa.repository.couchdb; class DbKey { private Statement statement; public DbKey(String email, String verbName) { Agent agent = ITAgentQuery.getAgent(email);
Verb verb = new Verb();
Apereo-Learning-Analytics-Initiative/Larissa
src/test/java/nl/uva/larissa/json/TestPrinter.java
// Path: src/main/java/nl/uva/larissa/json/model/Statement.java // @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context", // "timestamp", "stored", "authority", "version" }) // @ValidRevisionUsage // @ValidPlatformUsage // public class Statement { // @JsonProperty(required = false) // @IsUUID // private String id; // @NotNull // @Valid // private Actor actor; // @NotNull // @Valid // private Verb verb; // @NotNull // @Valid // @JsonProperty("object") // private StatementObject statementObject; // private Result result; // @Valid // private Context context; // // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it // // is outside of a Sub-Statement. // @Past // private Date timestamp; // // // should be set by the LRS, not the client // @Null // private Date stored; // private Authority authority; // private String version; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public Actor getActor() { // return actor; // } // // public void setActor(Actor actor) { // this.actor = actor; // } // // public Verb getVerb() { // return verb; // } // // public void setVerb(Verb verb) { // this.verb = verb; // } // // public StatementObject getStatementObject() { // return statementObject; // } // // public void setStatementObject(StatementObject statementObject) { // this.statementObject = statementObject; // } // // public Result getResult() { // return result; // } // // public void setResult(Result result) { // this.result = result; // } // // public Date getTimestamp() { // return timestamp; // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public Date getStored() { // return stored; // } // // public void setStored(Date stored) { // this.stored = stored; // } // // public Authority getAuthority() { // return authority; // } // // public void setAuthority(Authority authority) { // this.authority = authority; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public Context getContext() { // return context; // } // // public void setContext(Context context) { // this.context = context; // } // } // // Path: src/test/java/nl/uva/test/Util.java // public class Util { // public static String readJsonFile(File textFile) throws IOException { // try (BufferedReader reader = new BufferedReader( // new FileReader(textFile))) { // final StringBuilder result = new StringBuilder(); // String line; // while ((line = reader.readLine()) != null) { // line = line.replaceAll(" ", ""); // result.append(line); // } // return result.toString(); // } // } // }
import java.io.File; import java.io.IOException; import nl.uva.larissa.json.model.Statement; import nl.uva.test.Util; import static org.junit.Assert.*; import org.junit.BeforeClass; import org.junit.Test;
package nl.uva.larissa.json; public class TestPrinter { private static final File BASEDIR = new File("src/test/resources"); private static final File EXPECTED_DIR = new File(BASEDIR, "expectedIds"); private static StatementParser parser; @BeforeClass public static void beforeClass() { parser = new StatementParserImpl(); } @Test public void testPrintIds() throws IOException, ParseException { StatementPrinter printer = new StatementPrinterImpl(); String file = "testLongExampleStatement.json";
// Path: src/main/java/nl/uva/larissa/json/model/Statement.java // @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context", // "timestamp", "stored", "authority", "version" }) // @ValidRevisionUsage // @ValidPlatformUsage // public class Statement { // @JsonProperty(required = false) // @IsUUID // private String id; // @NotNull // @Valid // private Actor actor; // @NotNull // @Valid // private Verb verb; // @NotNull // @Valid // @JsonProperty("object") // private StatementObject statementObject; // private Result result; // @Valid // private Context context; // // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it // // is outside of a Sub-Statement. // @Past // private Date timestamp; // // // should be set by the LRS, not the client // @Null // private Date stored; // private Authority authority; // private String version; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public Actor getActor() { // return actor; // } // // public void setActor(Actor actor) { // this.actor = actor; // } // // public Verb getVerb() { // return verb; // } // // public void setVerb(Verb verb) { // this.verb = verb; // } // // public StatementObject getStatementObject() { // return statementObject; // } // // public void setStatementObject(StatementObject statementObject) { // this.statementObject = statementObject; // } // // public Result getResult() { // return result; // } // // public void setResult(Result result) { // this.result = result; // } // // public Date getTimestamp() { // return timestamp; // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public Date getStored() { // return stored; // } // // public void setStored(Date stored) { // this.stored = stored; // } // // public Authority getAuthority() { // return authority; // } // // public void setAuthority(Authority authority) { // this.authority = authority; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public Context getContext() { // return context; // } // // public void setContext(Context context) { // this.context = context; // } // } // // Path: src/test/java/nl/uva/test/Util.java // public class Util { // public static String readJsonFile(File textFile) throws IOException { // try (BufferedReader reader = new BufferedReader( // new FileReader(textFile))) { // final StringBuilder result = new StringBuilder(); // String line; // while ((line = reader.readLine()) != null) { // line = line.replaceAll(" ", ""); // result.append(line); // } // return result.toString(); // } // } // } // Path: src/test/java/nl/uva/larissa/json/TestPrinter.java import java.io.File; import java.io.IOException; import nl.uva.larissa.json.model.Statement; import nl.uva.test.Util; import static org.junit.Assert.*; import org.junit.BeforeClass; import org.junit.Test; package nl.uva.larissa.json; public class TestPrinter { private static final File BASEDIR = new File("src/test/resources"); private static final File EXPECTED_DIR = new File(BASEDIR, "expectedIds"); private static StatementParser parser; @BeforeClass public static void beforeClass() { parser = new StatementParserImpl(); } @Test public void testPrintIds() throws IOException, ParseException { StatementPrinter printer = new StatementPrinterImpl(); String file = "testLongExampleStatement.json";
String input = Util.readJsonFile(new File(BASEDIR, file));
Apereo-Learning-Analytics-Initiative/Larissa
src/test/java/nl/uva/larissa/json/TestPrinter.java
// Path: src/main/java/nl/uva/larissa/json/model/Statement.java // @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context", // "timestamp", "stored", "authority", "version" }) // @ValidRevisionUsage // @ValidPlatformUsage // public class Statement { // @JsonProperty(required = false) // @IsUUID // private String id; // @NotNull // @Valid // private Actor actor; // @NotNull // @Valid // private Verb verb; // @NotNull // @Valid // @JsonProperty("object") // private StatementObject statementObject; // private Result result; // @Valid // private Context context; // // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it // // is outside of a Sub-Statement. // @Past // private Date timestamp; // // // should be set by the LRS, not the client // @Null // private Date stored; // private Authority authority; // private String version; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public Actor getActor() { // return actor; // } // // public void setActor(Actor actor) { // this.actor = actor; // } // // public Verb getVerb() { // return verb; // } // // public void setVerb(Verb verb) { // this.verb = verb; // } // // public StatementObject getStatementObject() { // return statementObject; // } // // public void setStatementObject(StatementObject statementObject) { // this.statementObject = statementObject; // } // // public Result getResult() { // return result; // } // // public void setResult(Result result) { // this.result = result; // } // // public Date getTimestamp() { // return timestamp; // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public Date getStored() { // return stored; // } // // public void setStored(Date stored) { // this.stored = stored; // } // // public Authority getAuthority() { // return authority; // } // // public void setAuthority(Authority authority) { // this.authority = authority; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public Context getContext() { // return context; // } // // public void setContext(Context context) { // this.context = context; // } // } // // Path: src/test/java/nl/uva/test/Util.java // public class Util { // public static String readJsonFile(File textFile) throws IOException { // try (BufferedReader reader = new BufferedReader( // new FileReader(textFile))) { // final StringBuilder result = new StringBuilder(); // String line; // while ((line = reader.readLine()) != null) { // line = line.replaceAll(" ", ""); // result.append(line); // } // return result.toString(); // } // } // }
import java.io.File; import java.io.IOException; import nl.uva.larissa.json.model.Statement; import nl.uva.test.Util; import static org.junit.Assert.*; import org.junit.BeforeClass; import org.junit.Test;
package nl.uva.larissa.json; public class TestPrinter { private static final File BASEDIR = new File("src/test/resources"); private static final File EXPECTED_DIR = new File(BASEDIR, "expectedIds"); private static StatementParser parser; @BeforeClass public static void beforeClass() { parser = new StatementParserImpl(); } @Test public void testPrintIds() throws IOException, ParseException { StatementPrinter printer = new StatementPrinterImpl(); String file = "testLongExampleStatement.json"; String input = Util.readJsonFile(new File(BASEDIR, file));
// Path: src/main/java/nl/uva/larissa/json/model/Statement.java // @JsonPropertyOrder({ "id", "actor", "verb", "object", "result", "context", // "timestamp", "stored", "authority", "version" }) // @ValidRevisionUsage // @ValidPlatformUsage // public class Statement { // @JsonProperty(required = false) // @IsUUID // private String id; // @NotNull // @Valid // private Actor actor; // @NotNull // @Valid // private Verb verb; // @NotNull // @Valid // @JsonProperty("object") // private StatementObject statementObject; // private Result result; // @Valid // private Context context; // // xAPI 1.0.1 4.1.7 A timestamp SHOULD be the current or a past time when it // // is outside of a Sub-Statement. // @Past // private Date timestamp; // // // should be set by the LRS, not the client // @Null // private Date stored; // private Authority authority; // private String version; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public Actor getActor() { // return actor; // } // // public void setActor(Actor actor) { // this.actor = actor; // } // // public Verb getVerb() { // return verb; // } // // public void setVerb(Verb verb) { // this.verb = verb; // } // // public StatementObject getStatementObject() { // return statementObject; // } // // public void setStatementObject(StatementObject statementObject) { // this.statementObject = statementObject; // } // // public Result getResult() { // return result; // } // // public void setResult(Result result) { // this.result = result; // } // // public Date getTimestamp() { // return timestamp; // } // // public void setTimestamp(Date timestamp) { // this.timestamp = timestamp; // } // // public Date getStored() { // return stored; // } // // public void setStored(Date stored) { // this.stored = stored; // } // // public Authority getAuthority() { // return authority; // } // // public void setAuthority(Authority authority) { // this.authority = authority; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public Context getContext() { // return context; // } // // public void setContext(Context context) { // this.context = context; // } // } // // Path: src/test/java/nl/uva/test/Util.java // public class Util { // public static String readJsonFile(File textFile) throws IOException { // try (BufferedReader reader = new BufferedReader( // new FileReader(textFile))) { // final StringBuilder result = new StringBuilder(); // String line; // while ((line = reader.readLine()) != null) { // line = line.replaceAll(" ", ""); // result.append(line); // } // return result.toString(); // } // } // } // Path: src/test/java/nl/uva/larissa/json/TestPrinter.java import java.io.File; import java.io.IOException; import nl.uva.larissa.json.model.Statement; import nl.uva.test.Util; import static org.junit.Assert.*; import org.junit.BeforeClass; import org.junit.Test; package nl.uva.larissa.json; public class TestPrinter { private static final File BASEDIR = new File("src/test/resources"); private static final File EXPECTED_DIR = new File(BASEDIR, "expectedIds"); private static StatementParser parser; @BeforeClass public static void beforeClass() { parser = new StatementParserImpl(); } @Test public void testPrintIds() throws IOException, ParseException { StatementPrinter printer = new StatementPrinterImpl(); String file = "testLongExampleStatement.json"; String input = Util.readJsonFile(new File(BASEDIR, file));
Statement statement = parser.parseStatement(input);
Apereo-Learning-Analytics-Initiative/Larissa
src/main/java/nl/uva/larissa/repository/couchdb/VerbRegistrationQuery.java
// Path: src/main/java/nl/uva/larissa/repository/StatementFilter.java // public class StatementFilter { // // private String statementId; // private String voidedStatementId; // // TODO or Identified Group! // private Agent agent; // private IRI verb; // private IRI activity; // // UUID // private String registration; // private Boolean relatedActivities; // private Boolean relatedAgents; // private Date since; // private Date until; // private Integer limit; // // TODO enum? // private String format; // private Boolean ascending; // // // for more-URL // @QueryParam("startId") // private String startId; // // public StatementFilter() { // } // // public StatementFilter(StatementFilter filter) { // statementId = filter.getStatementId(); // voidedStatementId = filter.getVoidedStatementid(); // agent = filter.getAgent(); // verb = filter.getVerb(); // activity = filter.getActivity(); // registration = filter.getRegistration(); // relatedActivities = filter.getRelatedActivities(); // relatedAgents = filter.getRelatedAgents(); // since = filter.getSince(); // until = filter.getUntil(); // limit = filter.getLimit(); // format = filter.getFormat(); // ascending= filter.getAscending(); // startId = filter.getStartId(); // } // // public String getStatementId() { // return statementId; // } // // public void setStatementId(String statementId) { // this.statementId = statementId; // } // // public String getVoidedStatementid() { // return voidedStatementId; // } // // public void setVoidedStatementid(String voidedStatementId) { // this.voidedStatementId = voidedStatementId; // } // // public Agent getAgent() { // return agent; // } // // public void setAgent(Agent agent) { // this.agent = agent; // } // // public IRI getVerb() { // return verb; // } // // public void setVerb(IRI verb) { // this.verb = verb; // } // // public IRI getActivity() { // return activity; // } // // public void setActivity(IRI activity) { // this.activity = activity; // } // // public String getRegistration() { // return registration; // } // // public void setRegistration(String registration) { // this.registration = registration; // } // // public Boolean getRelatedActivities() { // return relatedActivities; // } // // public void setRelatedActivities(Boolean relatedActivities) { // this.relatedActivities = relatedActivities; // } // // public Boolean getRelatedAgents() { // return relatedAgents; // } // // public void setRelatedAgents(Boolean relatedAgents) { // this.relatedAgents = relatedAgents; // } // // public String getVoidedStatementId() { // return voidedStatementId; // } // // @Override // public String toString() { // return "StatementFilter [statementId=" + statementId // + ", voidedStatementId=" + voidedStatementId + ", agent=" // + agent + ", verb=" + verb + ", activity=" + activity // + ", registration=" + registration + ", relatedActivities=" // + relatedActivities + ", relatedAgents=" + relatedAgents // + ", since=" + since + ", until=" + until + ", limit=" + limit // + ", format=" + format + ", ascending=" + ascending // + ", startId=" + startId + "]"; // } // // public void setVoidedStatementId(String voidedStatementId) { // this.voidedStatementId = voidedStatementId; // } // // public Date getSince() { // return since; // } // // public void setSince(Date since) { // this.since = since; // } // // public Date getUntil() { // return until; // } // // public void setUntil(Date until) { // this.until = until; // } // // public Integer getLimit() { // return limit; // } // // public void setLimit(Integer limit) { // this.limit = limit; // } // // public String getFormat() { // return format; // } // // public void setFormat(String format) { // this.format = format; // } // // public String getStartId() { // return startId; // } // // public void setStartId(String startId) { // this.startId = startId; // } // // public Boolean getAscending() { // return ascending; // } // // public void setAscending(Boolean ascending) { // this.ascending = ascending; // } // // }
import org.ektorp.ComplexKey; import nl.uva.larissa.repository.StatementFilter;
package nl.uva.larissa.repository.couchdb; /* * targets view-entries of form [authority, verb, registration, stored] * */ public class VerbRegistrationQuery extends MapQuery { static final String VIEWNAME = "verbRegistration"; public VerbRegistrationQuery() { super(VIEWNAME); } @Override
// Path: src/main/java/nl/uva/larissa/repository/StatementFilter.java // public class StatementFilter { // // private String statementId; // private String voidedStatementId; // // TODO or Identified Group! // private Agent agent; // private IRI verb; // private IRI activity; // // UUID // private String registration; // private Boolean relatedActivities; // private Boolean relatedAgents; // private Date since; // private Date until; // private Integer limit; // // TODO enum? // private String format; // private Boolean ascending; // // // for more-URL // @QueryParam("startId") // private String startId; // // public StatementFilter() { // } // // public StatementFilter(StatementFilter filter) { // statementId = filter.getStatementId(); // voidedStatementId = filter.getVoidedStatementid(); // agent = filter.getAgent(); // verb = filter.getVerb(); // activity = filter.getActivity(); // registration = filter.getRegistration(); // relatedActivities = filter.getRelatedActivities(); // relatedAgents = filter.getRelatedAgents(); // since = filter.getSince(); // until = filter.getUntil(); // limit = filter.getLimit(); // format = filter.getFormat(); // ascending= filter.getAscending(); // startId = filter.getStartId(); // } // // public String getStatementId() { // return statementId; // } // // public void setStatementId(String statementId) { // this.statementId = statementId; // } // // public String getVoidedStatementid() { // return voidedStatementId; // } // // public void setVoidedStatementid(String voidedStatementId) { // this.voidedStatementId = voidedStatementId; // } // // public Agent getAgent() { // return agent; // } // // public void setAgent(Agent agent) { // this.agent = agent; // } // // public IRI getVerb() { // return verb; // } // // public void setVerb(IRI verb) { // this.verb = verb; // } // // public IRI getActivity() { // return activity; // } // // public void setActivity(IRI activity) { // this.activity = activity; // } // // public String getRegistration() { // return registration; // } // // public void setRegistration(String registration) { // this.registration = registration; // } // // public Boolean getRelatedActivities() { // return relatedActivities; // } // // public void setRelatedActivities(Boolean relatedActivities) { // this.relatedActivities = relatedActivities; // } // // public Boolean getRelatedAgents() { // return relatedAgents; // } // // public void setRelatedAgents(Boolean relatedAgents) { // this.relatedAgents = relatedAgents; // } // // public String getVoidedStatementId() { // return voidedStatementId; // } // // @Override // public String toString() { // return "StatementFilter [statementId=" + statementId // + ", voidedStatementId=" + voidedStatementId + ", agent=" // + agent + ", verb=" + verb + ", activity=" + activity // + ", registration=" + registration + ", relatedActivities=" // + relatedActivities + ", relatedAgents=" + relatedAgents // + ", since=" + since + ", until=" + until + ", limit=" + limit // + ", format=" + format + ", ascending=" + ascending // + ", startId=" + startId + "]"; // } // // public void setVoidedStatementId(String voidedStatementId) { // this.voidedStatementId = voidedStatementId; // } // // public Date getSince() { // return since; // } // // public void setSince(Date since) { // this.since = since; // } // // public Date getUntil() { // return until; // } // // public void setUntil(Date until) { // this.until = until; // } // // public Integer getLimit() { // return limit; // } // // public void setLimit(Integer limit) { // this.limit = limit; // } // // public String getFormat() { // return format; // } // // public void setFormat(String format) { // this.format = format; // } // // public String getStartId() { // return startId; // } // // public void setStartId(String startId) { // this.startId = startId; // } // // public Boolean getAscending() { // return ascending; // } // // public void setAscending(Boolean ascending) { // this.ascending = ascending; // } // // } // Path: src/main/java/nl/uva/larissa/repository/couchdb/VerbRegistrationQuery.java import org.ektorp.ComplexKey; import nl.uva.larissa.repository.StatementFilter; package nl.uva.larissa.repository.couchdb; /* * targets view-entries of form [authority, verb, registration, stored] * */ public class VerbRegistrationQuery extends MapQuery { static final String VIEWNAME = "verbRegistration"; public VerbRegistrationQuery() { super(VIEWNAME); } @Override
protected void copyStartKeyValuesToFilter(StatementFilter filter,