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
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/presenter/BasePresenterTest.java
// Path: app/src/test/java/com/andrey7mel/stepbystep/other/BaseTest.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(application = TestApplication.class, // constants = BuildConfig.class, // sdk = 21) // @Ignore // public class BaseTest { // // public TestComponent component; // public TestUtils testUtils; // // @Before // public void setUp() throws Exception { // component = (TestComponent) App.getComponent(); // testUtils = new TestUtils(); // } // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestConst.java // public class TestConst { // public static final String TEST_OWNER = "TEST_OWNER"; // public static final String TEST_REPO = "TEST_REPO"; // public static final String TEST_ERROR = "TEST_ERROR"; // public static final String ERROR_RESPONSE_500 = "HTTP 500 OK"; // public static final String ERROR_RESPONSE_404 = "HTTP 404 OK"; // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/RepoListView.java // public interface RepoListView extends View { // // void showRepoList(List<Repository> vo); // // void showEmptyList(); // // String getUserName(); // // void startRepoInfoFragment(Repository repository); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/View.java // public interface View { // // void showError(String error); // // void showLoading(); // // void hideLoading(); // }
import com.andrey7mel.stepbystep.other.BaseTest; import com.andrey7mel.stepbystep.other.TestConst; import com.andrey7mel.stepbystep.view.fragments.RepoListView; import com.andrey7mel.stepbystep.view.fragments.View; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import rx.Subscription; import rx.observers.TestSubscriber; import static junit.framework.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
package com.andrey7mel.stepbystep.presenter; public class BasePresenterTest extends BaseTest { protected View view; private BasePresenter basePresenter; @Override @Before public void setUp() throws Exception { super.setUp();
// Path: app/src/test/java/com/andrey7mel/stepbystep/other/BaseTest.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(application = TestApplication.class, // constants = BuildConfig.class, // sdk = 21) // @Ignore // public class BaseTest { // // public TestComponent component; // public TestUtils testUtils; // // @Before // public void setUp() throws Exception { // component = (TestComponent) App.getComponent(); // testUtils = new TestUtils(); // } // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestConst.java // public class TestConst { // public static final String TEST_OWNER = "TEST_OWNER"; // public static final String TEST_REPO = "TEST_REPO"; // public static final String TEST_ERROR = "TEST_ERROR"; // public static final String ERROR_RESPONSE_500 = "HTTP 500 OK"; // public static final String ERROR_RESPONSE_404 = "HTTP 404 OK"; // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/RepoListView.java // public interface RepoListView extends View { // // void showRepoList(List<Repository> vo); // // void showEmptyList(); // // String getUserName(); // // void startRepoInfoFragment(Repository repository); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/View.java // public interface View { // // void showError(String error); // // void showLoading(); // // void hideLoading(); // } // Path: app/src/test/java/com/andrey7mel/stepbystep/presenter/BasePresenterTest.java import com.andrey7mel.stepbystep.other.BaseTest; import com.andrey7mel.stepbystep.other.TestConst; import com.andrey7mel.stepbystep.view.fragments.RepoListView; import com.andrey7mel.stepbystep.view.fragments.View; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import rx.Subscription; import rx.observers.TestSubscriber; import static junit.framework.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; package com.andrey7mel.stepbystep.presenter; public class BasePresenterTest extends BaseTest { protected View view; private BasePresenter basePresenter; @Override @Before public void setUp() throws Exception { super.setUp();
RepoListView repoListView = mock(RepoListView.class);
andrey7mel/android-step-by-step
app/src/test/java/com/andrey7mel/stepbystep/presenter/BasePresenterTest.java
// Path: app/src/test/java/com/andrey7mel/stepbystep/other/BaseTest.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(application = TestApplication.class, // constants = BuildConfig.class, // sdk = 21) // @Ignore // public class BaseTest { // // public TestComponent component; // public TestUtils testUtils; // // @Before // public void setUp() throws Exception { // component = (TestComponent) App.getComponent(); // testUtils = new TestUtils(); // } // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestConst.java // public class TestConst { // public static final String TEST_OWNER = "TEST_OWNER"; // public static final String TEST_REPO = "TEST_REPO"; // public static final String TEST_ERROR = "TEST_ERROR"; // public static final String ERROR_RESPONSE_500 = "HTTP 500 OK"; // public static final String ERROR_RESPONSE_404 = "HTTP 404 OK"; // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/RepoListView.java // public interface RepoListView extends View { // // void showRepoList(List<Repository> vo); // // void showEmptyList(); // // String getUserName(); // // void startRepoInfoFragment(Repository repository); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/View.java // public interface View { // // void showError(String error); // // void showLoading(); // // void hideLoading(); // }
import com.andrey7mel.stepbystep.other.BaseTest; import com.andrey7mel.stepbystep.other.TestConst; import com.andrey7mel.stepbystep.view.fragments.RepoListView; import com.andrey7mel.stepbystep.view.fragments.View; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import rx.Subscription; import rx.observers.TestSubscriber; import static junit.framework.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
package com.andrey7mel.stepbystep.presenter; public class BasePresenterTest extends BaseTest { protected View view; private BasePresenter basePresenter; @Override @Before public void setUp() throws Exception { super.setUp(); RepoListView repoListView = mock(RepoListView.class); basePresenter = new RepoListPresenter(repoListView); view = repoListView; } @Test public void testShowLoadingState() throws Exception { basePresenter.showLoadingState(); verify(view).showLoading(); } @Test public void testHideLoadingState() throws Exception { basePresenter.hideLoadingState(); verify(view).hideLoading(); } @Test public void testShowError() throws Exception {
// Path: app/src/test/java/com/andrey7mel/stepbystep/other/BaseTest.java // @RunWith(RobolectricGradleTestRunner.class) // @Config(application = TestApplication.class, // constants = BuildConfig.class, // sdk = 21) // @Ignore // public class BaseTest { // // public TestComponent component; // public TestUtils testUtils; // // @Before // public void setUp() throws Exception { // component = (TestComponent) App.getComponent(); // testUtils = new TestUtils(); // } // // } // // Path: app/src/test/java/com/andrey7mel/stepbystep/other/TestConst.java // public class TestConst { // public static final String TEST_OWNER = "TEST_OWNER"; // public static final String TEST_REPO = "TEST_REPO"; // public static final String TEST_ERROR = "TEST_ERROR"; // public static final String ERROR_RESPONSE_500 = "HTTP 500 OK"; // public static final String ERROR_RESPONSE_404 = "HTTP 404 OK"; // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/RepoListView.java // public interface RepoListView extends View { // // void showRepoList(List<Repository> vo); // // void showEmptyList(); // // String getUserName(); // // void startRepoInfoFragment(Repository repository); // // } // // Path: app/src/main/java/com/andrey7mel/stepbystep/view/fragments/View.java // public interface View { // // void showError(String error); // // void showLoading(); // // void hideLoading(); // } // Path: app/src/test/java/com/andrey7mel/stepbystep/presenter/BasePresenterTest.java import com.andrey7mel.stepbystep.other.BaseTest; import com.andrey7mel.stepbystep.other.TestConst; import com.andrey7mel.stepbystep.view.fragments.RepoListView; import com.andrey7mel.stepbystep.view.fragments.View; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import rx.Subscription; import rx.observers.TestSubscriber; import static junit.framework.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; package com.andrey7mel.stepbystep.presenter; public class BasePresenterTest extends BaseTest { protected View view; private BasePresenter basePresenter; @Override @Before public void setUp() throws Exception { super.setUp(); RepoListView repoListView = mock(RepoListView.class); basePresenter = new RepoListPresenter(repoListView); view = repoListView; } @Test public void testShowLoadingState() throws Exception { basePresenter.showLoadingState(); verify(view).showLoading(); } @Test public void testHideLoadingState() throws Exception { basePresenter.hideLoadingState(); verify(view).hideLoading(); } @Test public void testShowError() throws Exception {
Throwable throwable = new Throwable(TestConst.TEST_ERROR);
teivah/TIBreview
src/test/java/com/tibco/exchange/tibreview/parser/RulesParserTest.java
// Path: src/main/java/com/tibco/exchange/tibreview/exception/ParsingException.java // public class ParsingException extends Exception { // // private static final long serialVersionUID = 89526587L; // // public ParsingException() { // super(); // } // // public ParsingException(String message) { // super(message); // } // // public ParsingException(String message, Throwable cause) { // super(message, cause); // } // // public ParsingException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/tibco/exchange/tibreview/model/rules/Resource.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "resource", propOrder = { // "rule" // }) // public class Resource { // // @XmlElement(required = true) // protected List<Resourcerule> rule; // // /** // * Gets the value of the rule property. // * // * <p> // * This accessor method returns a reference to the live list, // * not a snapshot. Therefore any modification you make to the // * returned list will be present inside the JAXB object. // * This is why there is not a <CODE>set</CODE> method for the rule property. // * // * <p> // * For example, to add a new item, do as follows: // * <pre> // * getRule().add(newItem); // * </pre> // * // * // * <p> // * Objects of the following type(s) are allowed in the list // * {@link Resourcerule } // * // * // */ // public List<Resourcerule> getRule() { // if (rule == null) { // rule = new ArrayList<Resourcerule>(); // } // return this.rule; // } // // } // // Path: src/main/java/com/tibco/exchange/tibreview/model/rules/Tibrules.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "tibrules", propOrder = { // "process", // "resource", // "xpathfunctions" // }) // public class Tibrules { // // protected Process process; // protected Resource resource; // protected Xpathfunctions xpathfunctions; // // /** // * Gets the value of the process property. // * // * @return // * possible object is // * {@link Process } // * // */ // public Process getProcess() { // return process; // } // // /** // * Sets the value of the process property. // * // * @param value // * allowed object is // * {@link Process } // * // */ // public void setProcess(Process value) { // this.process = value; // } // // /** // * Gets the value of the resource property. // * // * @return // * possible object is // * {@link Resource } // * // */ // public Resource getResource() { // return resource; // } // // /** // * Sets the value of the resource property. // * // * @param value // * allowed object is // * {@link Resource } // * // */ // public void setResource(Resource value) { // this.resource = value; // } // // /** // * Gets the value of the xpathfunctions property. // * // * @return // * possible object is // * {@link Xpathfunctions } // * // */ // public Xpathfunctions getXpathfunctions() { // return xpathfunctions; // } // // /** // * Sets the value of the xpathfunctions property. // * // * @param value // * allowed object is // * {@link Xpathfunctions } // * // */ // public void setXpathfunctions(Xpathfunctions value) { // this.xpathfunctions = value; // } // // }
import static org.junit.Assert.assertEquals; import org.junit.Test; import com.tibco.exchange.tibreview.exception.ParsingException; import com.tibco.exchange.tibreview.model.rules.Resource; import com.tibco.exchange.tibreview.model.rules.Tibrules;
package com.tibco.exchange.tibreview.parser; public class RulesParserTest { @Test public void testParseFile() { try {
// Path: src/main/java/com/tibco/exchange/tibreview/exception/ParsingException.java // public class ParsingException extends Exception { // // private static final long serialVersionUID = 89526587L; // // public ParsingException() { // super(); // } // // public ParsingException(String message) { // super(message); // } // // public ParsingException(String message, Throwable cause) { // super(message, cause); // } // // public ParsingException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/tibco/exchange/tibreview/model/rules/Resource.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "resource", propOrder = { // "rule" // }) // public class Resource { // // @XmlElement(required = true) // protected List<Resourcerule> rule; // // /** // * Gets the value of the rule property. // * // * <p> // * This accessor method returns a reference to the live list, // * not a snapshot. Therefore any modification you make to the // * returned list will be present inside the JAXB object. // * This is why there is not a <CODE>set</CODE> method for the rule property. // * // * <p> // * For example, to add a new item, do as follows: // * <pre> // * getRule().add(newItem); // * </pre> // * // * // * <p> // * Objects of the following type(s) are allowed in the list // * {@link Resourcerule } // * // * // */ // public List<Resourcerule> getRule() { // if (rule == null) { // rule = new ArrayList<Resourcerule>(); // } // return this.rule; // } // // } // // Path: src/main/java/com/tibco/exchange/tibreview/model/rules/Tibrules.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "tibrules", propOrder = { // "process", // "resource", // "xpathfunctions" // }) // public class Tibrules { // // protected Process process; // protected Resource resource; // protected Xpathfunctions xpathfunctions; // // /** // * Gets the value of the process property. // * // * @return // * possible object is // * {@link Process } // * // */ // public Process getProcess() { // return process; // } // // /** // * Sets the value of the process property. // * // * @param value // * allowed object is // * {@link Process } // * // */ // public void setProcess(Process value) { // this.process = value; // } // // /** // * Gets the value of the resource property. // * // * @return // * possible object is // * {@link Resource } // * // */ // public Resource getResource() { // return resource; // } // // /** // * Sets the value of the resource property. // * // * @param value // * allowed object is // * {@link Resource } // * // */ // public void setResource(Resource value) { // this.resource = value; // } // // /** // * Gets the value of the xpathfunctions property. // * // * @return // * possible object is // * {@link Xpathfunctions } // * // */ // public Xpathfunctions getXpathfunctions() { // return xpathfunctions; // } // // /** // * Sets the value of the xpathfunctions property. // * // * @param value // * allowed object is // * {@link Xpathfunctions } // * // */ // public void setXpathfunctions(Xpathfunctions value) { // this.xpathfunctions = value; // } // // } // Path: src/test/java/com/tibco/exchange/tibreview/parser/RulesParserTest.java import static org.junit.Assert.assertEquals; import org.junit.Test; import com.tibco.exchange.tibreview.exception.ParsingException; import com.tibco.exchange.tibreview.model.rules.Resource; import com.tibco.exchange.tibreview.model.rules.Tibrules; package com.tibco.exchange.tibreview.parser; public class RulesParserTest { @Test public void testParseFile() { try {
Tibrules a = RulesParser.getInstance().parseFile("src/test/resources/tibrules.xml");
teivah/TIBreview
src/test/java/com/tibco/exchange/tibreview/parser/RulesParserTest.java
// Path: src/main/java/com/tibco/exchange/tibreview/exception/ParsingException.java // public class ParsingException extends Exception { // // private static final long serialVersionUID = 89526587L; // // public ParsingException() { // super(); // } // // public ParsingException(String message) { // super(message); // } // // public ParsingException(String message, Throwable cause) { // super(message, cause); // } // // public ParsingException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/tibco/exchange/tibreview/model/rules/Resource.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "resource", propOrder = { // "rule" // }) // public class Resource { // // @XmlElement(required = true) // protected List<Resourcerule> rule; // // /** // * Gets the value of the rule property. // * // * <p> // * This accessor method returns a reference to the live list, // * not a snapshot. Therefore any modification you make to the // * returned list will be present inside the JAXB object. // * This is why there is not a <CODE>set</CODE> method for the rule property. // * // * <p> // * For example, to add a new item, do as follows: // * <pre> // * getRule().add(newItem); // * </pre> // * // * // * <p> // * Objects of the following type(s) are allowed in the list // * {@link Resourcerule } // * // * // */ // public List<Resourcerule> getRule() { // if (rule == null) { // rule = new ArrayList<Resourcerule>(); // } // return this.rule; // } // // } // // Path: src/main/java/com/tibco/exchange/tibreview/model/rules/Tibrules.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "tibrules", propOrder = { // "process", // "resource", // "xpathfunctions" // }) // public class Tibrules { // // protected Process process; // protected Resource resource; // protected Xpathfunctions xpathfunctions; // // /** // * Gets the value of the process property. // * // * @return // * possible object is // * {@link Process } // * // */ // public Process getProcess() { // return process; // } // // /** // * Sets the value of the process property. // * // * @param value // * allowed object is // * {@link Process } // * // */ // public void setProcess(Process value) { // this.process = value; // } // // /** // * Gets the value of the resource property. // * // * @return // * possible object is // * {@link Resource } // * // */ // public Resource getResource() { // return resource; // } // // /** // * Sets the value of the resource property. // * // * @param value // * allowed object is // * {@link Resource } // * // */ // public void setResource(Resource value) { // this.resource = value; // } // // /** // * Gets the value of the xpathfunctions property. // * // * @return // * possible object is // * {@link Xpathfunctions } // * // */ // public Xpathfunctions getXpathfunctions() { // return xpathfunctions; // } // // /** // * Sets the value of the xpathfunctions property. // * // * @param value // * allowed object is // * {@link Xpathfunctions } // * // */ // public void setXpathfunctions(Xpathfunctions value) { // this.xpathfunctions = value; // } // // }
import static org.junit.Assert.assertEquals; import org.junit.Test; import com.tibco.exchange.tibreview.exception.ParsingException; import com.tibco.exchange.tibreview.model.rules.Resource; import com.tibco.exchange.tibreview.model.rules.Tibrules;
package com.tibco.exchange.tibreview.parser; public class RulesParserTest { @Test public void testParseFile() { try { Tibrules a = RulesParser.getInstance().parseFile("src/test/resources/tibrules.xml");
// Path: src/main/java/com/tibco/exchange/tibreview/exception/ParsingException.java // public class ParsingException extends Exception { // // private static final long serialVersionUID = 89526587L; // // public ParsingException() { // super(); // } // // public ParsingException(String message) { // super(message); // } // // public ParsingException(String message, Throwable cause) { // super(message, cause); // } // // public ParsingException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/tibco/exchange/tibreview/model/rules/Resource.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "resource", propOrder = { // "rule" // }) // public class Resource { // // @XmlElement(required = true) // protected List<Resourcerule> rule; // // /** // * Gets the value of the rule property. // * // * <p> // * This accessor method returns a reference to the live list, // * not a snapshot. Therefore any modification you make to the // * returned list will be present inside the JAXB object. // * This is why there is not a <CODE>set</CODE> method for the rule property. // * // * <p> // * For example, to add a new item, do as follows: // * <pre> // * getRule().add(newItem); // * </pre> // * // * // * <p> // * Objects of the following type(s) are allowed in the list // * {@link Resourcerule } // * // * // */ // public List<Resourcerule> getRule() { // if (rule == null) { // rule = new ArrayList<Resourcerule>(); // } // return this.rule; // } // // } // // Path: src/main/java/com/tibco/exchange/tibreview/model/rules/Tibrules.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "tibrules", propOrder = { // "process", // "resource", // "xpathfunctions" // }) // public class Tibrules { // // protected Process process; // protected Resource resource; // protected Xpathfunctions xpathfunctions; // // /** // * Gets the value of the process property. // * // * @return // * possible object is // * {@link Process } // * // */ // public Process getProcess() { // return process; // } // // /** // * Sets the value of the process property. // * // * @param value // * allowed object is // * {@link Process } // * // */ // public void setProcess(Process value) { // this.process = value; // } // // /** // * Gets the value of the resource property. // * // * @return // * possible object is // * {@link Resource } // * // */ // public Resource getResource() { // return resource; // } // // /** // * Sets the value of the resource property. // * // * @param value // * allowed object is // * {@link Resource } // * // */ // public void setResource(Resource value) { // this.resource = value; // } // // /** // * Gets the value of the xpathfunctions property. // * // * @return // * possible object is // * {@link Xpathfunctions } // * // */ // public Xpathfunctions getXpathfunctions() { // return xpathfunctions; // } // // /** // * Sets the value of the xpathfunctions property. // * // * @param value // * allowed object is // * {@link Xpathfunctions } // * // */ // public void setXpathfunctions(Xpathfunctions value) { // this.xpathfunctions = value; // } // // } // Path: src/test/java/com/tibco/exchange/tibreview/parser/RulesParserTest.java import static org.junit.Assert.assertEquals; import org.junit.Test; import com.tibco.exchange.tibreview.exception.ParsingException; import com.tibco.exchange.tibreview.model.rules.Resource; import com.tibco.exchange.tibreview.model.rules.Tibrules; package com.tibco.exchange.tibreview.parser; public class RulesParserTest { @Test public void testParseFile() { try { Tibrules a = RulesParser.getInstance().parseFile("src/test/resources/tibrules.xml");
Resource resource = a.getResource();
teivah/TIBreview
src/test/java/com/tibco/exchange/tibreview/parser/RulesParserTest.java
// Path: src/main/java/com/tibco/exchange/tibreview/exception/ParsingException.java // public class ParsingException extends Exception { // // private static final long serialVersionUID = 89526587L; // // public ParsingException() { // super(); // } // // public ParsingException(String message) { // super(message); // } // // public ParsingException(String message, Throwable cause) { // super(message, cause); // } // // public ParsingException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/tibco/exchange/tibreview/model/rules/Resource.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "resource", propOrder = { // "rule" // }) // public class Resource { // // @XmlElement(required = true) // protected List<Resourcerule> rule; // // /** // * Gets the value of the rule property. // * // * <p> // * This accessor method returns a reference to the live list, // * not a snapshot. Therefore any modification you make to the // * returned list will be present inside the JAXB object. // * This is why there is not a <CODE>set</CODE> method for the rule property. // * // * <p> // * For example, to add a new item, do as follows: // * <pre> // * getRule().add(newItem); // * </pre> // * // * // * <p> // * Objects of the following type(s) are allowed in the list // * {@link Resourcerule } // * // * // */ // public List<Resourcerule> getRule() { // if (rule == null) { // rule = new ArrayList<Resourcerule>(); // } // return this.rule; // } // // } // // Path: src/main/java/com/tibco/exchange/tibreview/model/rules/Tibrules.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "tibrules", propOrder = { // "process", // "resource", // "xpathfunctions" // }) // public class Tibrules { // // protected Process process; // protected Resource resource; // protected Xpathfunctions xpathfunctions; // // /** // * Gets the value of the process property. // * // * @return // * possible object is // * {@link Process } // * // */ // public Process getProcess() { // return process; // } // // /** // * Sets the value of the process property. // * // * @param value // * allowed object is // * {@link Process } // * // */ // public void setProcess(Process value) { // this.process = value; // } // // /** // * Gets the value of the resource property. // * // * @return // * possible object is // * {@link Resource } // * // */ // public Resource getResource() { // return resource; // } // // /** // * Sets the value of the resource property. // * // * @param value // * allowed object is // * {@link Resource } // * // */ // public void setResource(Resource value) { // this.resource = value; // } // // /** // * Gets the value of the xpathfunctions property. // * // * @return // * possible object is // * {@link Xpathfunctions } // * // */ // public Xpathfunctions getXpathfunctions() { // return xpathfunctions; // } // // /** // * Sets the value of the xpathfunctions property. // * // * @param value // * allowed object is // * {@link Xpathfunctions } // * // */ // public void setXpathfunctions(Xpathfunctions value) { // this.xpathfunctions = value; // } // // }
import static org.junit.Assert.assertEquals; import org.junit.Test; import com.tibco.exchange.tibreview.exception.ParsingException; import com.tibco.exchange.tibreview.model.rules.Resource; import com.tibco.exchange.tibreview.model.rules.Tibrules;
package com.tibco.exchange.tibreview.parser; public class RulesParserTest { @Test public void testParseFile() { try { Tibrules a = RulesParser.getInstance().parseFile("src/test/resources/tibrules.xml"); Resource resource = a.getResource(); assertEquals(resource.getRule().size(), 26);
// Path: src/main/java/com/tibco/exchange/tibreview/exception/ParsingException.java // public class ParsingException extends Exception { // // private static final long serialVersionUID = 89526587L; // // public ParsingException() { // super(); // } // // public ParsingException(String message) { // super(message); // } // // public ParsingException(String message, Throwable cause) { // super(message, cause); // } // // public ParsingException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/tibco/exchange/tibreview/model/rules/Resource.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "resource", propOrder = { // "rule" // }) // public class Resource { // // @XmlElement(required = true) // protected List<Resourcerule> rule; // // /** // * Gets the value of the rule property. // * // * <p> // * This accessor method returns a reference to the live list, // * not a snapshot. Therefore any modification you make to the // * returned list will be present inside the JAXB object. // * This is why there is not a <CODE>set</CODE> method for the rule property. // * // * <p> // * For example, to add a new item, do as follows: // * <pre> // * getRule().add(newItem); // * </pre> // * // * // * <p> // * Objects of the following type(s) are allowed in the list // * {@link Resourcerule } // * // * // */ // public List<Resourcerule> getRule() { // if (rule == null) { // rule = new ArrayList<Resourcerule>(); // } // return this.rule; // } // // } // // Path: src/main/java/com/tibco/exchange/tibreview/model/rules/Tibrules.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "tibrules", propOrder = { // "process", // "resource", // "xpathfunctions" // }) // public class Tibrules { // // protected Process process; // protected Resource resource; // protected Xpathfunctions xpathfunctions; // // /** // * Gets the value of the process property. // * // * @return // * possible object is // * {@link Process } // * // */ // public Process getProcess() { // return process; // } // // /** // * Sets the value of the process property. // * // * @param value // * allowed object is // * {@link Process } // * // */ // public void setProcess(Process value) { // this.process = value; // } // // /** // * Gets the value of the resource property. // * // * @return // * possible object is // * {@link Resource } // * // */ // public Resource getResource() { // return resource; // } // // /** // * Sets the value of the resource property. // * // * @param value // * allowed object is // * {@link Resource } // * // */ // public void setResource(Resource value) { // this.resource = value; // } // // /** // * Gets the value of the xpathfunctions property. // * // * @return // * possible object is // * {@link Xpathfunctions } // * // */ // public Xpathfunctions getXpathfunctions() { // return xpathfunctions; // } // // /** // * Sets the value of the xpathfunctions property. // * // * @param value // * allowed object is // * {@link Xpathfunctions } // * // */ // public void setXpathfunctions(Xpathfunctions value) { // this.xpathfunctions = value; // } // // } // Path: src/test/java/com/tibco/exchange/tibreview/parser/RulesParserTest.java import static org.junit.Assert.assertEquals; import org.junit.Test; import com.tibco.exchange.tibreview.exception.ParsingException; import com.tibco.exchange.tibreview.model.rules.Resource; import com.tibco.exchange.tibreview.model.rules.Tibrules; package com.tibco.exchange.tibreview.parser; public class RulesParserTest { @Test public void testParseFile() { try { Tibrules a = RulesParser.getInstance().parseFile("src/test/resources/tibrules.xml"); Resource resource = a.getResource(); assertEquals(resource.getRule().size(), 26);
} catch (ParsingException e) {
teivah/TIBreview
src/main/java/com/tibco/exchange/tibreview/common/TIBProcess.java
// Path: src/main/java/com/tibco/exchange/tibreview/exception/ParsingException.java // public class ParsingException extends Exception { // // private static final long serialVersionUID = 89526587L; // // public ParsingException() { // super(); // } // // public ParsingException(String message) { // super(message); // } // // public ParsingException(String message, Throwable cause) { // super(message, cause); // } // // public ParsingException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/tibco/exchange/tibreview/model/sax/PartnerLinkModel.java // public class PartnerLinkModel { // private String myRole; // private String partnerRole; // private String name; // private boolean dynamic; // private String processName; // private String serviceName; // // public String getMyRole() { // return myRole; // } // // public void setMyRole(String myRole) { // this.myRole = myRole; // } // // public String getPartnerRole() { // return partnerRole; // } // // public void setPartnerRole(String partnerRole) { // this.partnerRole = partnerRole; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public boolean isDynamic() { // return dynamic; // } // // public void setDynamic(boolean dynamic) { // this.dynamic = dynamic; // } // // public String getProcessName() { // return processName; // } // // public void setProcessName(String processName) { // this.processName = processName; // } // // public String getServiceName() { // return serviceName; // } // // public void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // @Override // public String toString() { // return "PartnerLinkModel [myRole=" + myRole + ", partnerRole=" + partnerRole + ", name=" + name + ", dynamic=" // + dynamic + ", processName=" + processName + ", serviceName=" + serviceName + "]"; // } // // } // // Path: src/main/java/com/tibco/exchange/tibreview/parser/ProcessHandler.java // public class ProcessHandler extends DefaultHandler { // // private List<PartnerLinkModel> listPartnerLink; // // private Stack<String> elementStack; // private Stack<Object> objectStack; // // public ProcessHandler() { // listPartnerLink = new ArrayList<>(); // elementStack = new Stack<String>(); // objectStack = new Stack<Object>(); // } // // public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // elementStack.push(qName); // // if("bpws:partnerLink".equals(qName)) { // PartnerLinkModel elem = new PartnerLinkModel(); // objectStack.push(elem); // listPartnerLink.add(elem); // // String myRole = attributes.getValue("myRole"); // String partnerRole = attributes.getValue("partnerRole"); // String name = attributes.getValue("name"); // // elem.setMyRole(myRole); // elem.setPartnerRole(partnerRole); // elem.setName(name); // } else if("tibex:ReferenceWire".equals(qName)) { // if("bpws:partnerLink".equals(currentElementParent())) { // PartnerLinkModel parent = (PartnerLinkModel)objectStack.peek(); // // boolean dynamic = Boolean.valueOf(attributes.getValue("dynamic")); // String processName = attributes.getValue("processName"); // String serviceName = attributes.getValue("serviceName"); // // parent.setDynamic(dynamic); // parent.setProcessName(processName); // parent.setServiceName(serviceName); // } // } // } // // public void endElement(String uri, String localName, String qName) throws SAXException { // // elementStack.pop(); // // if ("bpws:partnerLink".equals(qName)) { // objectStack.pop(); // } // } // // // private String currentElement() { // // return this.elementStack.peek(); // // } // // private String currentElementParent() { // if (this.elementStack.size() < 2) { // return null; // } // return this.elementStack.get(this.elementStack.size() - 2); // } // // public List<PartnerLinkModel> getListPartnerLink() { // return listPartnerLink; // } // }
import java.io.File; import java.util.ArrayList; import java.util.List; import com.tibco.exchange.tibreview.exception.ParsingException; import com.tibco.exchange.tibreview.model.sax.PartnerLinkModel; import com.tibco.exchange.tibreview.parser.ProcessHandler;
package com.tibco.exchange.tibreview.common; public class TIBProcess { private String filePath; private String fullProcessName; private String processName; private String packageName;
// Path: src/main/java/com/tibco/exchange/tibreview/exception/ParsingException.java // public class ParsingException extends Exception { // // private static final long serialVersionUID = 89526587L; // // public ParsingException() { // super(); // } // // public ParsingException(String message) { // super(message); // } // // public ParsingException(String message, Throwable cause) { // super(message, cause); // } // // public ParsingException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/tibco/exchange/tibreview/model/sax/PartnerLinkModel.java // public class PartnerLinkModel { // private String myRole; // private String partnerRole; // private String name; // private boolean dynamic; // private String processName; // private String serviceName; // // public String getMyRole() { // return myRole; // } // // public void setMyRole(String myRole) { // this.myRole = myRole; // } // // public String getPartnerRole() { // return partnerRole; // } // // public void setPartnerRole(String partnerRole) { // this.partnerRole = partnerRole; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public boolean isDynamic() { // return dynamic; // } // // public void setDynamic(boolean dynamic) { // this.dynamic = dynamic; // } // // public String getProcessName() { // return processName; // } // // public void setProcessName(String processName) { // this.processName = processName; // } // // public String getServiceName() { // return serviceName; // } // // public void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // @Override // public String toString() { // return "PartnerLinkModel [myRole=" + myRole + ", partnerRole=" + partnerRole + ", name=" + name + ", dynamic=" // + dynamic + ", processName=" + processName + ", serviceName=" + serviceName + "]"; // } // // } // // Path: src/main/java/com/tibco/exchange/tibreview/parser/ProcessHandler.java // public class ProcessHandler extends DefaultHandler { // // private List<PartnerLinkModel> listPartnerLink; // // private Stack<String> elementStack; // private Stack<Object> objectStack; // // public ProcessHandler() { // listPartnerLink = new ArrayList<>(); // elementStack = new Stack<String>(); // objectStack = new Stack<Object>(); // } // // public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // elementStack.push(qName); // // if("bpws:partnerLink".equals(qName)) { // PartnerLinkModel elem = new PartnerLinkModel(); // objectStack.push(elem); // listPartnerLink.add(elem); // // String myRole = attributes.getValue("myRole"); // String partnerRole = attributes.getValue("partnerRole"); // String name = attributes.getValue("name"); // // elem.setMyRole(myRole); // elem.setPartnerRole(partnerRole); // elem.setName(name); // } else if("tibex:ReferenceWire".equals(qName)) { // if("bpws:partnerLink".equals(currentElementParent())) { // PartnerLinkModel parent = (PartnerLinkModel)objectStack.peek(); // // boolean dynamic = Boolean.valueOf(attributes.getValue("dynamic")); // String processName = attributes.getValue("processName"); // String serviceName = attributes.getValue("serviceName"); // // parent.setDynamic(dynamic); // parent.setProcessName(processName); // parent.setServiceName(serviceName); // } // } // } // // public void endElement(String uri, String localName, String qName) throws SAXException { // // elementStack.pop(); // // if ("bpws:partnerLink".equals(qName)) { // objectStack.pop(); // } // } // // // private String currentElement() { // // return this.elementStack.peek(); // // } // // private String currentElementParent() { // if (this.elementStack.size() < 2) { // return null; // } // return this.elementStack.get(this.elementStack.size() - 2); // } // // public List<PartnerLinkModel> getListPartnerLink() { // return listPartnerLink; // } // } // Path: src/main/java/com/tibco/exchange/tibreview/common/TIBProcess.java import java.io.File; import java.util.ArrayList; import java.util.List; import com.tibco.exchange.tibreview.exception.ParsingException; import com.tibco.exchange.tibreview.model.sax.PartnerLinkModel; import com.tibco.exchange.tibreview.parser.ProcessHandler; package com.tibco.exchange.tibreview.common; public class TIBProcess { private String filePath; private String fullProcessName; private String processName; private String packageName;
private List<PartnerLinkModel> partners;
teivah/TIBreview
src/main/java/com/tibco/exchange/tibreview/common/TIBProcess.java
// Path: src/main/java/com/tibco/exchange/tibreview/exception/ParsingException.java // public class ParsingException extends Exception { // // private static final long serialVersionUID = 89526587L; // // public ParsingException() { // super(); // } // // public ParsingException(String message) { // super(message); // } // // public ParsingException(String message, Throwable cause) { // super(message, cause); // } // // public ParsingException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/tibco/exchange/tibreview/model/sax/PartnerLinkModel.java // public class PartnerLinkModel { // private String myRole; // private String partnerRole; // private String name; // private boolean dynamic; // private String processName; // private String serviceName; // // public String getMyRole() { // return myRole; // } // // public void setMyRole(String myRole) { // this.myRole = myRole; // } // // public String getPartnerRole() { // return partnerRole; // } // // public void setPartnerRole(String partnerRole) { // this.partnerRole = partnerRole; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public boolean isDynamic() { // return dynamic; // } // // public void setDynamic(boolean dynamic) { // this.dynamic = dynamic; // } // // public String getProcessName() { // return processName; // } // // public void setProcessName(String processName) { // this.processName = processName; // } // // public String getServiceName() { // return serviceName; // } // // public void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // @Override // public String toString() { // return "PartnerLinkModel [myRole=" + myRole + ", partnerRole=" + partnerRole + ", name=" + name + ", dynamic=" // + dynamic + ", processName=" + processName + ", serviceName=" + serviceName + "]"; // } // // } // // Path: src/main/java/com/tibco/exchange/tibreview/parser/ProcessHandler.java // public class ProcessHandler extends DefaultHandler { // // private List<PartnerLinkModel> listPartnerLink; // // private Stack<String> elementStack; // private Stack<Object> objectStack; // // public ProcessHandler() { // listPartnerLink = new ArrayList<>(); // elementStack = new Stack<String>(); // objectStack = new Stack<Object>(); // } // // public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // elementStack.push(qName); // // if("bpws:partnerLink".equals(qName)) { // PartnerLinkModel elem = new PartnerLinkModel(); // objectStack.push(elem); // listPartnerLink.add(elem); // // String myRole = attributes.getValue("myRole"); // String partnerRole = attributes.getValue("partnerRole"); // String name = attributes.getValue("name"); // // elem.setMyRole(myRole); // elem.setPartnerRole(partnerRole); // elem.setName(name); // } else if("tibex:ReferenceWire".equals(qName)) { // if("bpws:partnerLink".equals(currentElementParent())) { // PartnerLinkModel parent = (PartnerLinkModel)objectStack.peek(); // // boolean dynamic = Boolean.valueOf(attributes.getValue("dynamic")); // String processName = attributes.getValue("processName"); // String serviceName = attributes.getValue("serviceName"); // // parent.setDynamic(dynamic); // parent.setProcessName(processName); // parent.setServiceName(serviceName); // } // } // } // // public void endElement(String uri, String localName, String qName) throws SAXException { // // elementStack.pop(); // // if ("bpws:partnerLink".equals(qName)) { // objectStack.pop(); // } // } // // // private String currentElement() { // // return this.elementStack.peek(); // // } // // private String currentElementParent() { // if (this.elementStack.size() < 2) { // return null; // } // return this.elementStack.get(this.elementStack.size() - 2); // } // // public List<PartnerLinkModel> getListPartnerLink() { // return listPartnerLink; // } // }
import java.io.File; import java.util.ArrayList; import java.util.List; import com.tibco.exchange.tibreview.exception.ParsingException; import com.tibco.exchange.tibreview.model.sax.PartnerLinkModel; import com.tibco.exchange.tibreview.parser.ProcessHandler;
package com.tibco.exchange.tibreview.common; public class TIBProcess { private String filePath; private String fullProcessName; private String processName; private String packageName; private List<PartnerLinkModel> partners; private static final String PROCESSES_PACKAGE = "Processes"; private static final String PROCESS_EXTENSION = ".bwp"; private static final String PACKAGE_DELIMITER = "."; private static final String PROCESS_PACKAGE_DELIMITER = PACKAGE_DELIMITER + PROCESSES_PACKAGE + PACKAGE_DELIMITER;
// Path: src/main/java/com/tibco/exchange/tibreview/exception/ParsingException.java // public class ParsingException extends Exception { // // private static final long serialVersionUID = 89526587L; // // public ParsingException() { // super(); // } // // public ParsingException(String message) { // super(message); // } // // public ParsingException(String message, Throwable cause) { // super(message, cause); // } // // public ParsingException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/tibco/exchange/tibreview/model/sax/PartnerLinkModel.java // public class PartnerLinkModel { // private String myRole; // private String partnerRole; // private String name; // private boolean dynamic; // private String processName; // private String serviceName; // // public String getMyRole() { // return myRole; // } // // public void setMyRole(String myRole) { // this.myRole = myRole; // } // // public String getPartnerRole() { // return partnerRole; // } // // public void setPartnerRole(String partnerRole) { // this.partnerRole = partnerRole; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public boolean isDynamic() { // return dynamic; // } // // public void setDynamic(boolean dynamic) { // this.dynamic = dynamic; // } // // public String getProcessName() { // return processName; // } // // public void setProcessName(String processName) { // this.processName = processName; // } // // public String getServiceName() { // return serviceName; // } // // public void setServiceName(String serviceName) { // this.serviceName = serviceName; // } // // @Override // public String toString() { // return "PartnerLinkModel [myRole=" + myRole + ", partnerRole=" + partnerRole + ", name=" + name + ", dynamic=" // + dynamic + ", processName=" + processName + ", serviceName=" + serviceName + "]"; // } // // } // // Path: src/main/java/com/tibco/exchange/tibreview/parser/ProcessHandler.java // public class ProcessHandler extends DefaultHandler { // // private List<PartnerLinkModel> listPartnerLink; // // private Stack<String> elementStack; // private Stack<Object> objectStack; // // public ProcessHandler() { // listPartnerLink = new ArrayList<>(); // elementStack = new Stack<String>(); // objectStack = new Stack<Object>(); // } // // public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // elementStack.push(qName); // // if("bpws:partnerLink".equals(qName)) { // PartnerLinkModel elem = new PartnerLinkModel(); // objectStack.push(elem); // listPartnerLink.add(elem); // // String myRole = attributes.getValue("myRole"); // String partnerRole = attributes.getValue("partnerRole"); // String name = attributes.getValue("name"); // // elem.setMyRole(myRole); // elem.setPartnerRole(partnerRole); // elem.setName(name); // } else if("tibex:ReferenceWire".equals(qName)) { // if("bpws:partnerLink".equals(currentElementParent())) { // PartnerLinkModel parent = (PartnerLinkModel)objectStack.peek(); // // boolean dynamic = Boolean.valueOf(attributes.getValue("dynamic")); // String processName = attributes.getValue("processName"); // String serviceName = attributes.getValue("serviceName"); // // parent.setDynamic(dynamic); // parent.setProcessName(processName); // parent.setServiceName(serviceName); // } // } // } // // public void endElement(String uri, String localName, String qName) throws SAXException { // // elementStack.pop(); // // if ("bpws:partnerLink".equals(qName)) { // objectStack.pop(); // } // } // // // private String currentElement() { // // return this.elementStack.peek(); // // } // // private String currentElementParent() { // if (this.elementStack.size() < 2) { // return null; // } // return this.elementStack.get(this.elementStack.size() - 2); // } // // public List<PartnerLinkModel> getListPartnerLink() { // return listPartnerLink; // } // } // Path: src/main/java/com/tibco/exchange/tibreview/common/TIBProcess.java import java.io.File; import java.util.ArrayList; import java.util.List; import com.tibco.exchange.tibreview.exception.ParsingException; import com.tibco.exchange.tibreview.model.sax.PartnerLinkModel; import com.tibco.exchange.tibreview.parser.ProcessHandler; package com.tibco.exchange.tibreview.common; public class TIBProcess { private String filePath; private String fullProcessName; private String processName; private String packageName; private List<PartnerLinkModel> partners; private static final String PROCESSES_PACKAGE = "Processes"; private static final String PROCESS_EXTENSION = ".bwp"; private static final String PACKAGE_DELIMITER = "."; private static final String PROCESS_PACKAGE_DELIMITER = PACKAGE_DELIMITER + PROCESSES_PACKAGE + PACKAGE_DELIMITER;
public TIBProcess(String filePath) throws ParsingException {
teivah/TIBreview
src/main/java/com/tibco/exchange/tibreview/parser/RulesParser.java
// Path: src/main/java/com/tibco/exchange/tibreview/exception/ParsingException.java // public class ParsingException extends Exception { // // private static final long serialVersionUID = 89526587L; // // public ParsingException() { // super(); // } // // public ParsingException(String message) { // super(message); // } // // public ParsingException(String message, Throwable cause) { // super(message, cause); // } // // public ParsingException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/tibco/exchange/tibreview/model/rules/Tibrules.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "tibrules", propOrder = { // "process", // "resource", // "xpathfunctions" // }) // public class Tibrules { // // protected Process process; // protected Resource resource; // protected Xpathfunctions xpathfunctions; // // /** // * Gets the value of the process property. // * // * @return // * possible object is // * {@link Process } // * // */ // public Process getProcess() { // return process; // } // // /** // * Sets the value of the process property. // * // * @param value // * allowed object is // * {@link Process } // * // */ // public void setProcess(Process value) { // this.process = value; // } // // /** // * Gets the value of the resource property. // * // * @return // * possible object is // * {@link Resource } // * // */ // public Resource getResource() { // return resource; // } // // /** // * Sets the value of the resource property. // * // * @param value // * allowed object is // * {@link Resource } // * // */ // public void setResource(Resource value) { // this.resource = value; // } // // /** // * Gets the value of the xpathfunctions property. // * // * @return // * possible object is // * {@link Xpathfunctions } // * // */ // public Xpathfunctions getXpathfunctions() { // return xpathfunctions; // } // // /** // * Sets the value of the xpathfunctions property. // * // * @param value // * allowed object is // * {@link Xpathfunctions } // * // */ // public void setXpathfunctions(Xpathfunctions value) { // this.xpathfunctions = value; // } // // }
import java.io.File; import java.io.FileInputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.Unmarshaller; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import com.tibco.exchange.tibreview.exception.ParsingException; import com.tibco.exchange.tibreview.model.rules.Tibrules;
package com.tibco.exchange.tibreview.parser; public class RulesParser { private static RulesParser instance = null; private static final String SCHEMA_FILE = "schemas/tibrules.xsd"; private RulesParser() { } public static RulesParser getInstance() { if(instance == null) { instance = new RulesParser(); } return instance; }
// Path: src/main/java/com/tibco/exchange/tibreview/exception/ParsingException.java // public class ParsingException extends Exception { // // private static final long serialVersionUID = 89526587L; // // public ParsingException() { // super(); // } // // public ParsingException(String message) { // super(message); // } // // public ParsingException(String message, Throwable cause) { // super(message, cause); // } // // public ParsingException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/tibco/exchange/tibreview/model/rules/Tibrules.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "tibrules", propOrder = { // "process", // "resource", // "xpathfunctions" // }) // public class Tibrules { // // protected Process process; // protected Resource resource; // protected Xpathfunctions xpathfunctions; // // /** // * Gets the value of the process property. // * // * @return // * possible object is // * {@link Process } // * // */ // public Process getProcess() { // return process; // } // // /** // * Sets the value of the process property. // * // * @param value // * allowed object is // * {@link Process } // * // */ // public void setProcess(Process value) { // this.process = value; // } // // /** // * Gets the value of the resource property. // * // * @return // * possible object is // * {@link Resource } // * // */ // public Resource getResource() { // return resource; // } // // /** // * Sets the value of the resource property. // * // * @param value // * allowed object is // * {@link Resource } // * // */ // public void setResource(Resource value) { // this.resource = value; // } // // /** // * Gets the value of the xpathfunctions property. // * // * @return // * possible object is // * {@link Xpathfunctions } // * // */ // public Xpathfunctions getXpathfunctions() { // return xpathfunctions; // } // // /** // * Sets the value of the xpathfunctions property. // * // * @param value // * allowed object is // * {@link Xpathfunctions } // * // */ // public void setXpathfunctions(Xpathfunctions value) { // this.xpathfunctions = value; // } // // } // Path: src/main/java/com/tibco/exchange/tibreview/parser/RulesParser.java import java.io.File; import java.io.FileInputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.Unmarshaller; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import com.tibco.exchange.tibreview.exception.ParsingException; import com.tibco.exchange.tibreview.model.rules.Tibrules; package com.tibco.exchange.tibreview.parser; public class RulesParser { private static RulesParser instance = null; private static final String SCHEMA_FILE = "schemas/tibrules.xsd"; private RulesParser() { } public static RulesParser getInstance() { if(instance == null) { instance = new RulesParser(); } return instance; }
public Tibrules parseFile(String file) throws ParsingException {
teivah/TIBreview
src/main/java/com/tibco/exchange/tibreview/parser/RulesParser.java
// Path: src/main/java/com/tibco/exchange/tibreview/exception/ParsingException.java // public class ParsingException extends Exception { // // private static final long serialVersionUID = 89526587L; // // public ParsingException() { // super(); // } // // public ParsingException(String message) { // super(message); // } // // public ParsingException(String message, Throwable cause) { // super(message, cause); // } // // public ParsingException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/tibco/exchange/tibreview/model/rules/Tibrules.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "tibrules", propOrder = { // "process", // "resource", // "xpathfunctions" // }) // public class Tibrules { // // protected Process process; // protected Resource resource; // protected Xpathfunctions xpathfunctions; // // /** // * Gets the value of the process property. // * // * @return // * possible object is // * {@link Process } // * // */ // public Process getProcess() { // return process; // } // // /** // * Sets the value of the process property. // * // * @param value // * allowed object is // * {@link Process } // * // */ // public void setProcess(Process value) { // this.process = value; // } // // /** // * Gets the value of the resource property. // * // * @return // * possible object is // * {@link Resource } // * // */ // public Resource getResource() { // return resource; // } // // /** // * Sets the value of the resource property. // * // * @param value // * allowed object is // * {@link Resource } // * // */ // public void setResource(Resource value) { // this.resource = value; // } // // /** // * Gets the value of the xpathfunctions property. // * // * @return // * possible object is // * {@link Xpathfunctions } // * // */ // public Xpathfunctions getXpathfunctions() { // return xpathfunctions; // } // // /** // * Sets the value of the xpathfunctions property. // * // * @param value // * allowed object is // * {@link Xpathfunctions } // * // */ // public void setXpathfunctions(Xpathfunctions value) { // this.xpathfunctions = value; // } // // }
import java.io.File; import java.io.FileInputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.Unmarshaller; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import com.tibco.exchange.tibreview.exception.ParsingException; import com.tibco.exchange.tibreview.model.rules.Tibrules;
package com.tibco.exchange.tibreview.parser; public class RulesParser { private static RulesParser instance = null; private static final String SCHEMA_FILE = "schemas/tibrules.xsd"; private RulesParser() { } public static RulesParser getInstance() { if(instance == null) { instance = new RulesParser(); } return instance; }
// Path: src/main/java/com/tibco/exchange/tibreview/exception/ParsingException.java // public class ParsingException extends Exception { // // private static final long serialVersionUID = 89526587L; // // public ParsingException() { // super(); // } // // public ParsingException(String message) { // super(message); // } // // public ParsingException(String message, Throwable cause) { // super(message, cause); // } // // public ParsingException(Throwable cause) { // super(cause); // } // } // // Path: src/main/java/com/tibco/exchange/tibreview/model/rules/Tibrules.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "tibrules", propOrder = { // "process", // "resource", // "xpathfunctions" // }) // public class Tibrules { // // protected Process process; // protected Resource resource; // protected Xpathfunctions xpathfunctions; // // /** // * Gets the value of the process property. // * // * @return // * possible object is // * {@link Process } // * // */ // public Process getProcess() { // return process; // } // // /** // * Sets the value of the process property. // * // * @param value // * allowed object is // * {@link Process } // * // */ // public void setProcess(Process value) { // this.process = value; // } // // /** // * Gets the value of the resource property. // * // * @return // * possible object is // * {@link Resource } // * // */ // public Resource getResource() { // return resource; // } // // /** // * Sets the value of the resource property. // * // * @param value // * allowed object is // * {@link Resource } // * // */ // public void setResource(Resource value) { // this.resource = value; // } // // /** // * Gets the value of the xpathfunctions property. // * // * @return // * possible object is // * {@link Xpathfunctions } // * // */ // public Xpathfunctions getXpathfunctions() { // return xpathfunctions; // } // // /** // * Sets the value of the xpathfunctions property. // * // * @param value // * allowed object is // * {@link Xpathfunctions } // * // */ // public void setXpathfunctions(Xpathfunctions value) { // this.xpathfunctions = value; // } // // } // Path: src/main/java/com/tibco/exchange/tibreview/parser/RulesParser.java import java.io.File; import java.io.FileInputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.Unmarshaller; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import com.tibco.exchange.tibreview.exception.ParsingException; import com.tibco.exchange.tibreview.model.rules.Tibrules; package com.tibco.exchange.tibreview.parser; public class RulesParser { private static RulesParser instance = null; private static final String SCHEMA_FILE = "schemas/tibrules.xsd"; private RulesParser() { } public static RulesParser getInstance() { if(instance == null) { instance = new RulesParser(); } return instance; }
public Tibrules parseFile(String file) throws ParsingException {
TorchPowered/OpenByte
src/main/java/net/openbyte/gui/ClassCreationFrame.java
// Path: src/main/java/net/openbyte/FileUtil.java // public class FileUtil { // // /** // * Sets the content of the file via the format provided. // * // * @param format the format that the file with be formatted // * @param file the file that will be formatted // */ // public static void format(String format, File file){ // byte[] formatBytes = format.getBytes(); // try { // FileOutputStream stream = new FileOutputStream(file); // stream.write(formatBytes); // stream.close(); // } catch (Exception e){ // e.printStackTrace(); // } // } // } // // Path: src/main/java/net/openbyte/Formats.java // public class Formats { // // /** // * Represents the regular class creation format. // * // * @param thePackage the package the class is in // * @param className the class name // * @return the format // */ // public static String classFormat(String thePackage, String className){ // String format = "package " + thePackage + ";" + " \n" + "public class " + className + " {" + " \n" + "}"; // return format; // } // // /** // * Represents the java interface class format. // * // * @param thePackage the package the interface is in // * @param interfaceName the interface name // * @return the format // */ // public static String interfaceFormat(String thePackage, String interfaceName) { // String format = "package " + thePackage + ";" + "\n" + "public interface " + interfaceName + " {" + "\n" + "}"; // return format; // } // }
import java.awt.*; import java.awt.event.*; import java.io.File; import java.io.IOException; import javax.swing.*; import net.openbyte.FileUtil; import net.openbyte.Formats;
String[] splittedName = textField1.getText().split("\\."); if(splittedName.length < 2){ JOptionPane.showMessageDialog(this, "You need to put the class inside of a package to create a class.", "Error", JOptionPane.ERROR_MESSAGE); return; } if(splittedName.length > 4){ JOptionPane.showMessageDialog(this, "You cannot create a class inside of more than 3 packages.", "Error", JOptionPane.ERROR_MESSAGE); return; } if(splittedName.length == 4){ File mainPackageDir = new File(src, splittedName[0]); File secondPackageDir = new File(mainPackageDir, splittedName[1]); File thirdPackageDir = new File(secondPackageDir, splittedName[2]); File theClass = new File(thirdPackageDir, splittedName[3] + ".java"); if(!mainPackageDir.exists()){ mainPackageDir.mkdir(); } if(!secondPackageDir.exists()){ secondPackageDir.mkdir(); } if(!theClass.exists()){ try { theClass.createNewFile(); } catch (IOException e1) { e1.printStackTrace(); } } setVisible(false); tree.updateUI(); if(checkBox1.isSelected()) {
// Path: src/main/java/net/openbyte/FileUtil.java // public class FileUtil { // // /** // * Sets the content of the file via the format provided. // * // * @param format the format that the file with be formatted // * @param file the file that will be formatted // */ // public static void format(String format, File file){ // byte[] formatBytes = format.getBytes(); // try { // FileOutputStream stream = new FileOutputStream(file); // stream.write(formatBytes); // stream.close(); // } catch (Exception e){ // e.printStackTrace(); // } // } // } // // Path: src/main/java/net/openbyte/Formats.java // public class Formats { // // /** // * Represents the regular class creation format. // * // * @param thePackage the package the class is in // * @param className the class name // * @return the format // */ // public static String classFormat(String thePackage, String className){ // String format = "package " + thePackage + ";" + " \n" + "public class " + className + " {" + " \n" + "}"; // return format; // } // // /** // * Represents the java interface class format. // * // * @param thePackage the package the interface is in // * @param interfaceName the interface name // * @return the format // */ // public static String interfaceFormat(String thePackage, String interfaceName) { // String format = "package " + thePackage + ";" + "\n" + "public interface " + interfaceName + " {" + "\n" + "}"; // return format; // } // } // Path: src/main/java/net/openbyte/gui/ClassCreationFrame.java import java.awt.*; import java.awt.event.*; import java.io.File; import java.io.IOException; import javax.swing.*; import net.openbyte.FileUtil; import net.openbyte.Formats; String[] splittedName = textField1.getText().split("\\."); if(splittedName.length < 2){ JOptionPane.showMessageDialog(this, "You need to put the class inside of a package to create a class.", "Error", JOptionPane.ERROR_MESSAGE); return; } if(splittedName.length > 4){ JOptionPane.showMessageDialog(this, "You cannot create a class inside of more than 3 packages.", "Error", JOptionPane.ERROR_MESSAGE); return; } if(splittedName.length == 4){ File mainPackageDir = new File(src, splittedName[0]); File secondPackageDir = new File(mainPackageDir, splittedName[1]); File thirdPackageDir = new File(secondPackageDir, splittedName[2]); File theClass = new File(thirdPackageDir, splittedName[3] + ".java"); if(!mainPackageDir.exists()){ mainPackageDir.mkdir(); } if(!secondPackageDir.exists()){ secondPackageDir.mkdir(); } if(!theClass.exists()){ try { theClass.createNewFile(); } catch (IOException e1) { e1.printStackTrace(); } } setVisible(false); tree.updateUI(); if(checkBox1.isSelected()) {
FileUtil.format(Formats.interfaceFormat(splittedName[0] + "." + splittedName[1] + "." + splittedName[2], splittedName[3]), theClass);
TorchPowered/OpenByte
src/main/java/net/openbyte/gui/ClassCreationFrame.java
// Path: src/main/java/net/openbyte/FileUtil.java // public class FileUtil { // // /** // * Sets the content of the file via the format provided. // * // * @param format the format that the file with be formatted // * @param file the file that will be formatted // */ // public static void format(String format, File file){ // byte[] formatBytes = format.getBytes(); // try { // FileOutputStream stream = new FileOutputStream(file); // stream.write(formatBytes); // stream.close(); // } catch (Exception e){ // e.printStackTrace(); // } // } // } // // Path: src/main/java/net/openbyte/Formats.java // public class Formats { // // /** // * Represents the regular class creation format. // * // * @param thePackage the package the class is in // * @param className the class name // * @return the format // */ // public static String classFormat(String thePackage, String className){ // String format = "package " + thePackage + ";" + " \n" + "public class " + className + " {" + " \n" + "}"; // return format; // } // // /** // * Represents the java interface class format. // * // * @param thePackage the package the interface is in // * @param interfaceName the interface name // * @return the format // */ // public static String interfaceFormat(String thePackage, String interfaceName) { // String format = "package " + thePackage + ";" + "\n" + "public interface " + interfaceName + " {" + "\n" + "}"; // return format; // } // }
import java.awt.*; import java.awt.event.*; import java.io.File; import java.io.IOException; import javax.swing.*; import net.openbyte.FileUtil; import net.openbyte.Formats;
String[] splittedName = textField1.getText().split("\\."); if(splittedName.length < 2){ JOptionPane.showMessageDialog(this, "You need to put the class inside of a package to create a class.", "Error", JOptionPane.ERROR_MESSAGE); return; } if(splittedName.length > 4){ JOptionPane.showMessageDialog(this, "You cannot create a class inside of more than 3 packages.", "Error", JOptionPane.ERROR_MESSAGE); return; } if(splittedName.length == 4){ File mainPackageDir = new File(src, splittedName[0]); File secondPackageDir = new File(mainPackageDir, splittedName[1]); File thirdPackageDir = new File(secondPackageDir, splittedName[2]); File theClass = new File(thirdPackageDir, splittedName[3] + ".java"); if(!mainPackageDir.exists()){ mainPackageDir.mkdir(); } if(!secondPackageDir.exists()){ secondPackageDir.mkdir(); } if(!theClass.exists()){ try { theClass.createNewFile(); } catch (IOException e1) { e1.printStackTrace(); } } setVisible(false); tree.updateUI(); if(checkBox1.isSelected()) {
// Path: src/main/java/net/openbyte/FileUtil.java // public class FileUtil { // // /** // * Sets the content of the file via the format provided. // * // * @param format the format that the file with be formatted // * @param file the file that will be formatted // */ // public static void format(String format, File file){ // byte[] formatBytes = format.getBytes(); // try { // FileOutputStream stream = new FileOutputStream(file); // stream.write(formatBytes); // stream.close(); // } catch (Exception e){ // e.printStackTrace(); // } // } // } // // Path: src/main/java/net/openbyte/Formats.java // public class Formats { // // /** // * Represents the regular class creation format. // * // * @param thePackage the package the class is in // * @param className the class name // * @return the format // */ // public static String classFormat(String thePackage, String className){ // String format = "package " + thePackage + ";" + " \n" + "public class " + className + " {" + " \n" + "}"; // return format; // } // // /** // * Represents the java interface class format. // * // * @param thePackage the package the interface is in // * @param interfaceName the interface name // * @return the format // */ // public static String interfaceFormat(String thePackage, String interfaceName) { // String format = "package " + thePackage + ";" + "\n" + "public interface " + interfaceName + " {" + "\n" + "}"; // return format; // } // } // Path: src/main/java/net/openbyte/gui/ClassCreationFrame.java import java.awt.*; import java.awt.event.*; import java.io.File; import java.io.IOException; import javax.swing.*; import net.openbyte.FileUtil; import net.openbyte.Formats; String[] splittedName = textField1.getText().split("\\."); if(splittedName.length < 2){ JOptionPane.showMessageDialog(this, "You need to put the class inside of a package to create a class.", "Error", JOptionPane.ERROR_MESSAGE); return; } if(splittedName.length > 4){ JOptionPane.showMessageDialog(this, "You cannot create a class inside of more than 3 packages.", "Error", JOptionPane.ERROR_MESSAGE); return; } if(splittedName.length == 4){ File mainPackageDir = new File(src, splittedName[0]); File secondPackageDir = new File(mainPackageDir, splittedName[1]); File thirdPackageDir = new File(secondPackageDir, splittedName[2]); File theClass = new File(thirdPackageDir, splittedName[3] + ".java"); if(!mainPackageDir.exists()){ mainPackageDir.mkdir(); } if(!secondPackageDir.exists()){ secondPackageDir.mkdir(); } if(!theClass.exists()){ try { theClass.createNewFile(); } catch (IOException e1) { e1.printStackTrace(); } } setVisible(false); tree.updateUI(); if(checkBox1.isSelected()) {
FileUtil.format(Formats.interfaceFormat(splittedName[0] + "." + splittedName[1] + "." + splittedName[2], splittedName[3]), theClass);
TorchPowered/OpenByte
src/main/java/net/openbyte/plugin/PluginManager.java
// Path: src/main/java/net/openbyte/data/file/PluginDescriptionFile.java // public class PluginDescriptionFile { // private String mainClassPath; // private String author; // private String logoURL; // private String iconURL; // private String description; // // private PluginDescriptionFile(String mainClassPath, String author, String logoURL, String iconURL, String description) { // this.mainClassPath = mainClassPath; // this.author = author; // this.logoURL = logoURL; // this.iconURL = iconURL; // this.description = description; // } // // public static PluginDescriptionFile getPluginDescription(InputStream file) throws Exception { // Properties properties = new Properties(); // properties.load(file); // // final String main = properties.getProperty("main"); // final String author = properties.getProperty("author"); // final String description = properties.getProperty("description"); // final String iconURL = properties.getProperty("iconurl"); // final String logoURL = properties.getProperty("logourl"); // // return new PluginDescriptionFile(main, author, logoURL, iconURL, description); // } // // public String getAuthor() { // return author; // } // // public String getDescription() { // return description; // } // // public String getIconURL() { // return iconURL; // } // // public String getLogoURL() { // return logoURL; // } // // public String getMainClassPath() { // return mainClassPath; // } // }
import java.net.URLClassLoader; import java.util.ArrayList; import java.util.HashMap; import java.util.Properties; import java.util.jar.JarEntry; import java.util.jar.JarFile; import net.openbyte.data.file.PluginDescriptionFile; import java.io.File; import java.io.FilenameFilter; import java.io.InputStream; import java.net.URL;
/* * This file is part of OpenByte IDE, licensed under the MIT License (MIT). * * Copyright (c) TorchPowered 2016 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.openbyte.plugin; /** * Represents the plugin manager that manages all plugins that are assignable as a AbstractPlugin. * * @since API Version 1.0 */ public class PluginManager { /** * Represents the loaded abstract plugins. */ private static ArrayList<AbstractPlugin> abstractPlugins = new ArrayList<AbstractPlugin>();
// Path: src/main/java/net/openbyte/data/file/PluginDescriptionFile.java // public class PluginDescriptionFile { // private String mainClassPath; // private String author; // private String logoURL; // private String iconURL; // private String description; // // private PluginDescriptionFile(String mainClassPath, String author, String logoURL, String iconURL, String description) { // this.mainClassPath = mainClassPath; // this.author = author; // this.logoURL = logoURL; // this.iconURL = iconURL; // this.description = description; // } // // public static PluginDescriptionFile getPluginDescription(InputStream file) throws Exception { // Properties properties = new Properties(); // properties.load(file); // // final String main = properties.getProperty("main"); // final String author = properties.getProperty("author"); // final String description = properties.getProperty("description"); // final String iconURL = properties.getProperty("iconurl"); // final String logoURL = properties.getProperty("logourl"); // // return new PluginDescriptionFile(main, author, logoURL, iconURL, description); // } // // public String getAuthor() { // return author; // } // // public String getDescription() { // return description; // } // // public String getIconURL() { // return iconURL; // } // // public String getLogoURL() { // return logoURL; // } // // public String getMainClassPath() { // return mainClassPath; // } // } // Path: src/main/java/net/openbyte/plugin/PluginManager.java import java.net.URLClassLoader; import java.util.ArrayList; import java.util.HashMap; import java.util.Properties; import java.util.jar.JarEntry; import java.util.jar.JarFile; import net.openbyte.data.file.PluginDescriptionFile; import java.io.File; import java.io.FilenameFilter; import java.io.InputStream; import java.net.URL; /* * This file is part of OpenByte IDE, licensed under the MIT License (MIT). * * Copyright (c) TorchPowered 2016 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.openbyte.plugin; /** * Represents the plugin manager that manages all plugins that are assignable as a AbstractPlugin. * * @since API Version 1.0 */ public class PluginManager { /** * Represents the loaded abstract plugins. */ private static ArrayList<AbstractPlugin> abstractPlugins = new ArrayList<AbstractPlugin>();
private static HashMap<AbstractPlugin, PluginDescriptionFile> pluginToDescriptionMap = new HashMap<AbstractPlugin, PluginDescriptionFile>();
TorchPowered/OpenByte
src/main/java/net/openbyte/event/handle/EventManager.java
// Path: src/main/java/net/openbyte/event/meta/Event.java // public interface Event { // }
import net.openbyte.event.meta.Event; import net.openbyte.event.meta.EventListener; import java.lang.reflect.Method; import java.util.ArrayList;
/* * This file is part of OpenByte IDE, licensed under the MIT License (MIT). * * Copyright (c) TorchPowered 2016 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.openbyte.event.handle; /** * Handles all events execution and handling. */ public class EventManager { private static EventManager RUNTIME_INSTANCE = null; private ArrayList<Class<?>> listenerClasses = new ArrayList<Class<?>>(); private EventManager(){} public static EventManager init() { if(RUNTIME_INSTANCE == null) { RUNTIME_INSTANCE = new EventManager(); } return getManager(); } public static EventManager getManager() { return RUNTIME_INSTANCE; } public void registerListener(Class<?> listener) { for (Class<?> listenerClass : listenerClasses) { if (listenerClass.getName().equals(listener.getName())) { return; } } if(!listener.isAnnotationPresent(EventListener.class)) { return; } listenerClasses.add(listener); }
// Path: src/main/java/net/openbyte/event/meta/Event.java // public interface Event { // } // Path: src/main/java/net/openbyte/event/handle/EventManager.java import net.openbyte.event.meta.Event; import net.openbyte.event.meta.EventListener; import java.lang.reflect.Method; import java.util.ArrayList; /* * This file is part of OpenByte IDE, licensed under the MIT License (MIT). * * Copyright (c) TorchPowered 2016 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.openbyte.event.handle; /** * Handles all events execution and handling. */ public class EventManager { private static EventManager RUNTIME_INSTANCE = null; private ArrayList<Class<?>> listenerClasses = new ArrayList<Class<?>>(); private EventManager(){} public static EventManager init() { if(RUNTIME_INSTANCE == null) { RUNTIME_INSTANCE = new EventManager(); } return getManager(); } public static EventManager getManager() { return RUNTIME_INSTANCE; } public void registerListener(Class<?> listener) { for (Class<?> listenerClass : listenerClasses) { if (listenerClass.getName().equals(listener.getName())) { return; } } if(!listener.isAnnotationPresent(EventListener.class)) { return; } listenerClasses.add(listener); }
public void callEvent(Event event) throws Exception {
TorchPowered/OpenByte
src/main/java/net/openbyte/gui/SettingsFrame.java
// Path: src/main/java/net/openbyte/data/Files.java // public class Files { // /** // * Represents the current OpenByte workspace directory. // */ // public static File WORKSPACE_DIRECTORY = new File(System.getProperty("user.home"), ".openbyte"); // /** // * Represents the plugins directory inside of the workspace directory. // */ // public static final File PLUGINS_DIRECTORY = new File(WORKSPACE_DIRECTORY, "plugins"); // // /** // * Creates a new file // * @param fileName the file name // * @param parentDirectory the parent directory of the file // * @return the file created // */ // public static File createNewFile(String fileName, File parentDirectory){ // File file = new File(parentDirectory, fileName); // try { // file.createNewFile(); // } catch (IOException e) { // e.printStackTrace(); // } // return file; // } // }
import java.awt.*; import java.awt.event.*; import java.io.File; import javax.swing.*; import net.openbyte.data.Files;
/* * This file is part of OpenByte IDE, licensed under the MIT License (MIT). * * Copyright (c) TorchPowered 2016 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* * Created by JFormDesigner on Sun Feb 14 18:20:40 ICT 2016 */ package net.openbyte.gui; /** * @author Gary Lee */ public class SettingsFrame extends JDialog { public static boolean useSystem = true; public static String email = "example@example.org"; public SettingsFrame(Dialog owner) { super(owner); initComponents();
// Path: src/main/java/net/openbyte/data/Files.java // public class Files { // /** // * Represents the current OpenByte workspace directory. // */ // public static File WORKSPACE_DIRECTORY = new File(System.getProperty("user.home"), ".openbyte"); // /** // * Represents the plugins directory inside of the workspace directory. // */ // public static final File PLUGINS_DIRECTORY = new File(WORKSPACE_DIRECTORY, "plugins"); // // /** // * Creates a new file // * @param fileName the file name // * @param parentDirectory the parent directory of the file // * @return the file created // */ // public static File createNewFile(String fileName, File parentDirectory){ // File file = new File(parentDirectory, fileName); // try { // file.createNewFile(); // } catch (IOException e) { // e.printStackTrace(); // } // return file; // } // } // Path: src/main/java/net/openbyte/gui/SettingsFrame.java import java.awt.*; import java.awt.event.*; import java.io.File; import javax.swing.*; import net.openbyte.data.Files; /* * This file is part of OpenByte IDE, licensed under the MIT License (MIT). * * Copyright (c) TorchPowered 2016 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* * Created by JFormDesigner on Sun Feb 14 18:20:40 ICT 2016 */ package net.openbyte.gui; /** * @author Gary Lee */ public class SettingsFrame extends JDialog { public static boolean useSystem = true; public static String email = "example@example.org"; public SettingsFrame(Dialog owner) { super(owner); initComponents();
this.label2.setText("Current Workspace Location: " + Files.WORKSPACE_DIRECTORY.getAbsolutePath());
TorchPowered/OpenByte
src/main/java/net/openbyte/data/file/OpenProjectSolution.java
// Path: src/main/java/net/openbyte/enums/ModificationAPI.java // public enum ModificationAPI { // MINECRAFT_FORGE, // MCP, // BUKKIT, // }
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Properties; import net.openbyte.enums.ModificationAPI; import javax.swing.*; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream;
/** * Deletes the solution. */ public void deleteSolution(){ System.gc(); saveToFile.delete(); } /** * Sets the project name. * * @param name the project name */ public void setProjectName(String name){ solution.setProperty("name", name); save(); } public String getProjectName(){ return solution.getProperty("name"); } public File getProjectFolder(){ return new File(solution.getProperty("folderPath")); } public void setProjectFolder(File file){ solution.setProperty("folderPath", file.getAbsolutePath()); }
// Path: src/main/java/net/openbyte/enums/ModificationAPI.java // public enum ModificationAPI { // MINECRAFT_FORGE, // MCP, // BUKKIT, // } // Path: src/main/java/net/openbyte/data/file/OpenProjectSolution.java import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Properties; import net.openbyte.enums.ModificationAPI; import javax.swing.*; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; /** * Deletes the solution. */ public void deleteSolution(){ System.gc(); saveToFile.delete(); } /** * Sets the project name. * * @param name the project name */ public void setProjectName(String name){ solution.setProperty("name", name); save(); } public String getProjectName(){ return solution.getProperty("name"); } public File getProjectFolder(){ return new File(solution.getProperty("folderPath")); } public void setProjectFolder(File file){ solution.setProperty("folderPath", file.getAbsolutePath()); }
public void setModificationAPI(ModificationAPI api) {
TorchPowered/OpenByte
src/main/java/net/openbyte/gui/AboutFrame.java
// Path: src/main/java/net/openbyte/Launch.java // public class Launch { // // /** // * The SLF4J logger to the console. // */ // public static final Logger logger = LoggerFactory.getLogger("OpenByte"); // // /** // * The list of project names current loaded into runtime // */ // public static final ArrayList<String> projectNames = new ArrayList<String>(); // // /** // * A map to convert names to solutions. // */ // public static final HashMap<String, OpenProjectSolution> nameToSolution = new HashMap<String, OpenProjectSolution>(); // // /** // * A double that updates every release and contains the current version. // */ // public static final double CURRENT_VERSION = 2.0; // // /** // * This is the main method that allows Java to initiate the program. // * // * @param args the arguments to the Java program, which are ignored // */ // public static void main(String[] args){ // logger.info("Checking for a new version..."); // try { // GitHub gitHub = new GitHubBuilder().withOAuthToken("e5b60cea047a3e44d4fc83adb86ea35bda131744 ").build(); // GHRepository repository = gitHub.getUser("PizzaCrust").getRepository("OpenByte"); // for (GHRelease release : repository.listReleases()) { // double releaseTag = Double.parseDouble(release.getTagName()); // if(CURRENT_VERSION < releaseTag) { // logger.info("Version " + releaseTag + " has been released."); // JOptionPane.showMessageDialog(null, "Please update OpenByte to " + releaseTag + " at https://github.com/PizzaCrust/OpenByte.", "Update", JOptionPane.WARNING_MESSAGE); // } else { // logger.info("OpenByte is at the latest version."); // } // } // } catch (Exception e) { // logger.error("Failed to connect to GitHub."); // e.printStackTrace(); // } // logger.info("Checking for a workspace folder..."); // if(!Files.WORKSPACE_DIRECTORY.exists()){ // logger.info("Workspace directory not found, creating one."); // Files.WORKSPACE_DIRECTORY.mkdir(); // } // logger.info("Checking for a plugins folder..."); // if(!Files.PLUGINS_DIRECTORY.exists()) { // logger.info("Plugins directory not found, creating one."); // Files.PLUGINS_DIRECTORY.mkdir(); // } // try{ // logger.info("Grabbing and applying system look and feel..."); // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // } // catch(ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e){ // logger.info("Something went wrong when applying the look and feel, using the default one..."); // e.printStackTrace(); // } // logger.info("Starting event manager..."); // EventManager.init(); // logger.info("Detecting plugin files..."); // File[] pluginFiles = PluginManager.getPluginFiles(Files.PLUGINS_DIRECTORY); // logger.info("Detected " + pluginFiles.length + " plugin files in the plugins directory!"); // logger.info("Beginning load/register plugin process..."); // for (File pluginFile : pluginFiles) { // logger.info("Loading file " + FilenameUtils.removeExtension(pluginFile.getName()) + "..."); // try { // PluginManager.registerAndLoadPlugin(pluginFile); // } catch (Exception e) { // logger.error("Failed to load file " + FilenameUtils.removeExtension(pluginFile.getName()) + "!"); // e.printStackTrace(); // } // } // logger.info("All plugin files were loaded/registered to OpenByte."); // logger.info("Showing graphical interface to user..."); // WelcomeFrame welcomeFrame = new WelcomeFrame(); // welcomeFrame.setVisible(true); // } // }
import javax.imageio.ImageIO; import javax.swing.*; import net.openbyte.Launch; import org.jdesktop.swingx.*; import java.awt.*; import java.io.IOException;
/* * This file is part of OpenByte IDE, licensed under the MIT License (MIT). * * Copyright (c) TorchPowered 2016 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* * Created by JFormDesigner on Sat Feb 20 09:29:40 WIB 2016 */ package net.openbyte.gui; /** * @author Gary Lee */ public class AboutFrame extends JFrame { public AboutFrame() { initComponents(); try { xImagePanel1.setImage(ImageIO.read(getClass().getClassLoader().getResourceAsStream("openbytelogo.png"))); } catch (IOException e) { e.printStackTrace(); }
// Path: src/main/java/net/openbyte/Launch.java // public class Launch { // // /** // * The SLF4J logger to the console. // */ // public static final Logger logger = LoggerFactory.getLogger("OpenByte"); // // /** // * The list of project names current loaded into runtime // */ // public static final ArrayList<String> projectNames = new ArrayList<String>(); // // /** // * A map to convert names to solutions. // */ // public static final HashMap<String, OpenProjectSolution> nameToSolution = new HashMap<String, OpenProjectSolution>(); // // /** // * A double that updates every release and contains the current version. // */ // public static final double CURRENT_VERSION = 2.0; // // /** // * This is the main method that allows Java to initiate the program. // * // * @param args the arguments to the Java program, which are ignored // */ // public static void main(String[] args){ // logger.info("Checking for a new version..."); // try { // GitHub gitHub = new GitHubBuilder().withOAuthToken("e5b60cea047a3e44d4fc83adb86ea35bda131744 ").build(); // GHRepository repository = gitHub.getUser("PizzaCrust").getRepository("OpenByte"); // for (GHRelease release : repository.listReleases()) { // double releaseTag = Double.parseDouble(release.getTagName()); // if(CURRENT_VERSION < releaseTag) { // logger.info("Version " + releaseTag + " has been released."); // JOptionPane.showMessageDialog(null, "Please update OpenByte to " + releaseTag + " at https://github.com/PizzaCrust/OpenByte.", "Update", JOptionPane.WARNING_MESSAGE); // } else { // logger.info("OpenByte is at the latest version."); // } // } // } catch (Exception e) { // logger.error("Failed to connect to GitHub."); // e.printStackTrace(); // } // logger.info("Checking for a workspace folder..."); // if(!Files.WORKSPACE_DIRECTORY.exists()){ // logger.info("Workspace directory not found, creating one."); // Files.WORKSPACE_DIRECTORY.mkdir(); // } // logger.info("Checking for a plugins folder..."); // if(!Files.PLUGINS_DIRECTORY.exists()) { // logger.info("Plugins directory not found, creating one."); // Files.PLUGINS_DIRECTORY.mkdir(); // } // try{ // logger.info("Grabbing and applying system look and feel..."); // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // } // catch(ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e){ // logger.info("Something went wrong when applying the look and feel, using the default one..."); // e.printStackTrace(); // } // logger.info("Starting event manager..."); // EventManager.init(); // logger.info("Detecting plugin files..."); // File[] pluginFiles = PluginManager.getPluginFiles(Files.PLUGINS_DIRECTORY); // logger.info("Detected " + pluginFiles.length + " plugin files in the plugins directory!"); // logger.info("Beginning load/register plugin process..."); // for (File pluginFile : pluginFiles) { // logger.info("Loading file " + FilenameUtils.removeExtension(pluginFile.getName()) + "..."); // try { // PluginManager.registerAndLoadPlugin(pluginFile); // } catch (Exception e) { // logger.error("Failed to load file " + FilenameUtils.removeExtension(pluginFile.getName()) + "!"); // e.printStackTrace(); // } // } // logger.info("All plugin files were loaded/registered to OpenByte."); // logger.info("Showing graphical interface to user..."); // WelcomeFrame welcomeFrame = new WelcomeFrame(); // welcomeFrame.setVisible(true); // } // } // Path: src/main/java/net/openbyte/gui/AboutFrame.java import javax.imageio.ImageIO; import javax.swing.*; import net.openbyte.Launch; import org.jdesktop.swingx.*; import java.awt.*; import java.io.IOException; /* * This file is part of OpenByte IDE, licensed under the MIT License (MIT). * * Copyright (c) TorchPowered 2016 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* * Created by JFormDesigner on Sat Feb 20 09:29:40 WIB 2016 */ package net.openbyte.gui; /** * @author Gary Lee */ public class AboutFrame extends JFrame { public AboutFrame() { initComponents(); try { xImagePanel1.setImage(ImageIO.read(getClass().getClassLoader().getResourceAsStream("openbytelogo.png"))); } catch (IOException e) { e.printStackTrace(); }
label2.setText("Build: OpenByte IDE v" + Launch.CURRENT_VERSION);
arangodb/arangodb-java-driver-async
src/main/java/com/arangodb/internal/ArangoRouteAsyncImpl.java
// Path: src/main/java/com/arangodb/ArangoRouteAsync.java // public interface ArangoRouteAsync extends ArangoSerializationAccessor { // // /** // * Returns a new {@link ArangoRouteAsync} instance for the given path (relative to the current route) that can be // * used to perform arbitrary requests. // * // * @param path // * The relative URL of the route // * @return {@link ArangoRouteAsync} // */ // ArangoRouteAsync route(String... path); // // /** // * Header that should be sent with each request to the route. // * // * @param key // * Header key // * @param value // * Header value (the <code>toString()</code> method will be called for the value} // * @return {@link ArangoRouteAsync} // */ // ArangoRouteAsync withHeader(String key, Object value); // // /** // * Query parameter that should be sent with each request to the route. // * // * @param key // * Query parameter key // * @param value // * Query parameter value (the <code>toString()</code> method will be called for the value} // * @return {@link ArangoRouteAsync} // */ // ArangoRouteAsync withQueryParam(String key, Object value); // // /** // * The response body. The body will be serialized to {@link VPackSlice}. // * // * @param body // * The response body // * @return {@link ArangoRouteAsync} // */ // ArangoRouteAsync withBody(Object body); // // /** // * Performs a DELETE request to the given URL and returns the server response. // * // * @return server response // */ // CompletableFuture<Response> delete(); // // /** // * Performs a GET request to the given URL and returns the server response. // * // * @return server response // */ // // CompletableFuture<Response> get(); // // /** // * Performs a HEAD request to the given URL and returns the server response. // * // * @return server response // */ // // CompletableFuture<Response> head(); // // /** // * Performs a PATCH request to the given URL and returns the server response. // * // * @return server response // */ // // CompletableFuture<Response> patch(); // // /** // * Performs a POST request to the given URL and returns the server response. // * // * @return server response // */ // // CompletableFuture<Response> post(); // // /** // * Performs a PUT request to the given URL and returns the server response. // * // * @return server response // */ // // CompletableFuture<Response> put(); // // }
import java.util.Map; import java.util.concurrent.CompletableFuture; import com.arangodb.ArangoRouteAsync; import com.arangodb.internal.ArangoExecutor.ResponseDeserializer; import com.arangodb.velocypack.exception.VPackException; import com.arangodb.velocystream.RequestType; import com.arangodb.velocystream.Response;
/* * DISCLAIMER * * Copyright 2018 ArangoDB GmbH, Cologne, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright holder is ArangoDB GmbH, Cologne, Germany */ package com.arangodb.internal; /** * @author Mark Vollmary * */ public class ArangoRouteAsyncImpl extends InternalArangoRoute<ArangoDBAsyncImpl, ArangoDatabaseAsyncImpl, ArangoExecutorAsync>
// Path: src/main/java/com/arangodb/ArangoRouteAsync.java // public interface ArangoRouteAsync extends ArangoSerializationAccessor { // // /** // * Returns a new {@link ArangoRouteAsync} instance for the given path (relative to the current route) that can be // * used to perform arbitrary requests. // * // * @param path // * The relative URL of the route // * @return {@link ArangoRouteAsync} // */ // ArangoRouteAsync route(String... path); // // /** // * Header that should be sent with each request to the route. // * // * @param key // * Header key // * @param value // * Header value (the <code>toString()</code> method will be called for the value} // * @return {@link ArangoRouteAsync} // */ // ArangoRouteAsync withHeader(String key, Object value); // // /** // * Query parameter that should be sent with each request to the route. // * // * @param key // * Query parameter key // * @param value // * Query parameter value (the <code>toString()</code> method will be called for the value} // * @return {@link ArangoRouteAsync} // */ // ArangoRouteAsync withQueryParam(String key, Object value); // // /** // * The response body. The body will be serialized to {@link VPackSlice}. // * // * @param body // * The response body // * @return {@link ArangoRouteAsync} // */ // ArangoRouteAsync withBody(Object body); // // /** // * Performs a DELETE request to the given URL and returns the server response. // * // * @return server response // */ // CompletableFuture<Response> delete(); // // /** // * Performs a GET request to the given URL and returns the server response. // * // * @return server response // */ // // CompletableFuture<Response> get(); // // /** // * Performs a HEAD request to the given URL and returns the server response. // * // * @return server response // */ // // CompletableFuture<Response> head(); // // /** // * Performs a PATCH request to the given URL and returns the server response. // * // * @return server response // */ // // CompletableFuture<Response> patch(); // // /** // * Performs a POST request to the given URL and returns the server response. // * // * @return server response // */ // // CompletableFuture<Response> post(); // // /** // * Performs a PUT request to the given URL and returns the server response. // * // * @return server response // */ // // CompletableFuture<Response> put(); // // } // Path: src/main/java/com/arangodb/internal/ArangoRouteAsyncImpl.java import java.util.Map; import java.util.concurrent.CompletableFuture; import com.arangodb.ArangoRouteAsync; import com.arangodb.internal.ArangoExecutor.ResponseDeserializer; import com.arangodb.velocypack.exception.VPackException; import com.arangodb.velocystream.RequestType; import com.arangodb.velocystream.Response; /* * DISCLAIMER * * Copyright 2018 ArangoDB GmbH, Cologne, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright holder is ArangoDB GmbH, Cologne, Germany */ package com.arangodb.internal; /** * @author Mark Vollmary * */ public class ArangoRouteAsyncImpl extends InternalArangoRoute<ArangoDBAsyncImpl, ArangoDatabaseAsyncImpl, ArangoExecutorAsync>
implements ArangoRouteAsync {
arangodb/arangodb-java-driver-async
src/test/java/com/arangodb/example/graph/GraphTraversalsInAQLExample.java
// Path: src/main/java/com/arangodb/ArangoCursorAsync.java // public interface ArangoCursorAsync<T> extends ArangoCursor<T> { // // Stream<T> streamRemaining(); // // }
import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import java.util.Collection; import java.util.concurrent.ExecutionException; import org.junit.Test; import com.arangodb.ArangoCursorAsync;
/* * DISCLAIMER * * Copyright 2016 ArangoDB GmbH, Cologne, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright holder is ArangoDB GmbH, Cologne, Germany */ package com.arangodb.example.graph; /** * Graph traversals in AQL * * @see <a href="https://docs.arangodb.com/current/AQL/Graphs/Traversals.html">Graph traversals in AQL</a> * * @author a-brandt * */ public class GraphTraversalsInAQLExample extends BaseGraphTest { @Test public void queryAllVertices() throws InterruptedException, ExecutionException { String queryString = "FOR v IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' RETURN v._key";
// Path: src/main/java/com/arangodb/ArangoCursorAsync.java // public interface ArangoCursorAsync<T> extends ArangoCursor<T> { // // Stream<T> streamRemaining(); // // } // Path: src/test/java/com/arangodb/example/graph/GraphTraversalsInAQLExample.java import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import java.util.Collection; import java.util.concurrent.ExecutionException; import org.junit.Test; import com.arangodb.ArangoCursorAsync; /* * DISCLAIMER * * Copyright 2016 ArangoDB GmbH, Cologne, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright holder is ArangoDB GmbH, Cologne, Germany */ package com.arangodb.example.graph; /** * Graph traversals in AQL * * @see <a href="https://docs.arangodb.com/current/AQL/Graphs/Traversals.html">Graph traversals in AQL</a> * * @author a-brandt * */ public class GraphTraversalsInAQLExample extends BaseGraphTest { @Test public void queryAllVertices() throws InterruptedException, ExecutionException { String queryString = "FOR v IN 1..3 OUTBOUND 'circles/A' GRAPH 'traversalGraph' RETURN v._key";
ArangoCursorAsync<String> cursor = db.query(queryString, null, null, String.class).get();
arangodb/arangodb-java-driver-async
src/main/java/com/arangodb/internal/ArangoSearchAsyncImpl.java
// Path: src/main/java/com/arangodb/ArangoSearchAsync.java // public interface ArangoSearchAsync extends ArangoViewAsync { // // /** // * Creates a view, then returns view information from the server. // * // * @see <a href="https://docs.arangodb.com/current/HTTP/Views/ArangoSearch.html#create-arangosearch-view">API // * Documentation</a> // * @return information about the view @ // */ // CompletableFuture<ViewEntity> create(); // // /** // * Creates a view with the given {@code options}, then returns view information from the server. // * // * @see <a href="https://docs.arangodb.com/current/HTTP/Views/ArangoSearch.html#create-arangosearch-view">API // * Documentation</a> // * @param options // * Additional options, can be null // * @return information about the view @ // */ // CompletableFuture<ViewEntity> create(ArangoSearchCreateOptions options); // // /** // * Reads the properties of the specified view. // * // * @see <a href="https://docs.arangodb.com/current/HTTP/Views/Getting.html#read-properties-of-a-view">API // * Documentation</a> // * @return properties of the view @ // */ // CompletableFuture<ArangoSearchPropertiesEntity> getProperties(); // // /** // * Partially changes properties of the view. // * // * @see <a href= // * "https://docs.arangodb.com/current/HTTP/Views/ArangoSearch.html#partially-changes-properties-of-an-arangosearch-view">API // * Documentation</a> // * @param options // * properties to change // * @return properties of the view @ // */ // CompletableFuture<ArangoSearchPropertiesEntity> updateProperties(ArangoSearchPropertiesOptions options); // // /** // * Changes properties of the view. // * // * @see <a href= // * "https://docs.arangodb.com/current/HTTP/Views/ArangoSearch.html#change-properties-of-an-arangosearch-view">API // * Documentation</a> // * @param options // * properties to change // * @return properties of the view @ // */ // CompletableFuture<ArangoSearchPropertiesEntity> replaceProperties(ArangoSearchPropertiesOptions options); // // }
import java.util.concurrent.CompletableFuture; import com.arangodb.ArangoSearchAsync; import com.arangodb.entity.ViewEntity; import com.arangodb.entity.arangosearch.ArangoSearchPropertiesEntity; import com.arangodb.model.arangosearch.ArangoSearchCreateOptions; import com.arangodb.model.arangosearch.ArangoSearchPropertiesOptions;
/* * DISCLAIMER * * Copyright 2018 ArangoDB GmbH, Cologne, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright holder is ArangoDB GmbH, Cologne, Germany */ package com.arangodb.internal; /** * @author Mark Vollmary * */ public class ArangoSearchAsyncImpl extends InternalArangoSearch<ArangoDBAsyncImpl, ArangoDatabaseAsyncImpl, ArangoExecutorAsync>
// Path: src/main/java/com/arangodb/ArangoSearchAsync.java // public interface ArangoSearchAsync extends ArangoViewAsync { // // /** // * Creates a view, then returns view information from the server. // * // * @see <a href="https://docs.arangodb.com/current/HTTP/Views/ArangoSearch.html#create-arangosearch-view">API // * Documentation</a> // * @return information about the view @ // */ // CompletableFuture<ViewEntity> create(); // // /** // * Creates a view with the given {@code options}, then returns view information from the server. // * // * @see <a href="https://docs.arangodb.com/current/HTTP/Views/ArangoSearch.html#create-arangosearch-view">API // * Documentation</a> // * @param options // * Additional options, can be null // * @return information about the view @ // */ // CompletableFuture<ViewEntity> create(ArangoSearchCreateOptions options); // // /** // * Reads the properties of the specified view. // * // * @see <a href="https://docs.arangodb.com/current/HTTP/Views/Getting.html#read-properties-of-a-view">API // * Documentation</a> // * @return properties of the view @ // */ // CompletableFuture<ArangoSearchPropertiesEntity> getProperties(); // // /** // * Partially changes properties of the view. // * // * @see <a href= // * "https://docs.arangodb.com/current/HTTP/Views/ArangoSearch.html#partially-changes-properties-of-an-arangosearch-view">API // * Documentation</a> // * @param options // * properties to change // * @return properties of the view @ // */ // CompletableFuture<ArangoSearchPropertiesEntity> updateProperties(ArangoSearchPropertiesOptions options); // // /** // * Changes properties of the view. // * // * @see <a href= // * "https://docs.arangodb.com/current/HTTP/Views/ArangoSearch.html#change-properties-of-an-arangosearch-view">API // * Documentation</a> // * @param options // * properties to change // * @return properties of the view @ // */ // CompletableFuture<ArangoSearchPropertiesEntity> replaceProperties(ArangoSearchPropertiesOptions options); // // } // Path: src/main/java/com/arangodb/internal/ArangoSearchAsyncImpl.java import java.util.concurrent.CompletableFuture; import com.arangodb.ArangoSearchAsync; import com.arangodb.entity.ViewEntity; import com.arangodb.entity.arangosearch.ArangoSearchPropertiesEntity; import com.arangodb.model.arangosearch.ArangoSearchCreateOptions; import com.arangodb.model.arangosearch.ArangoSearchPropertiesOptions; /* * DISCLAIMER * * Copyright 2018 ArangoDB GmbH, Cologne, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright holder is ArangoDB GmbH, Cologne, Germany */ package com.arangodb.internal; /** * @author Mark Vollmary * */ public class ArangoSearchAsyncImpl extends InternalArangoSearch<ArangoDBAsyncImpl, ArangoDatabaseAsyncImpl, ArangoExecutorAsync>
implements ArangoSearchAsync {
arangodb/arangodb-java-driver-async
src/test/java/com/arangodb/example/graph/ShortestPathInAQLExample.java
// Path: src/main/java/com/arangodb/ArangoCursorAsync.java // public interface ArangoCursorAsync<T> extends ArangoCursor<T> { // // Stream<T> streamRemaining(); // // }
import com.arangodb.ArangoCursorAsync; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.ExecutionException; import org.junit.Test;
/* * DISCLAIMER * * Copyright 2016 ArangoDB GmbH, Cologne, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright holder is ArangoDB GmbH, Cologne, Germany */ package com.arangodb.example.graph; /** * Shortest Path in AQL * * @see <a href="https://docs.arangodb.com/current/AQL/Graphs/ShortestPath.html">Shortest Path in AQL</a> * * @author a-brandt * */ public class ShortestPathInAQLExample extends BaseGraphTest { @SuppressWarnings({"WeakerAccess", "unused"}) public static class Pair { private String vertex; private String edge; public String getVertex() { return vertex; } public void setVertex(final String vertex) { this.vertex = vertex; } public String getEdge() { return edge; } public void setEdge(final String edge) { this.edge = edge; } } @Test public void queryShortestPathFromAToD() throws InterruptedException, ExecutionException { String queryString = "FOR v, e IN OUTBOUND SHORTEST_PATH 'circles/A' TO 'circles/D' GRAPH 'traversalGraph' RETURN {'vertex': v._key, 'edge': e._key}";
// Path: src/main/java/com/arangodb/ArangoCursorAsync.java // public interface ArangoCursorAsync<T> extends ArangoCursor<T> { // // Stream<T> streamRemaining(); // // } // Path: src/test/java/com/arangodb/example/graph/ShortestPathInAQLExample.java import com.arangodb.ArangoCursorAsync; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.ExecutionException; import org.junit.Test; /* * DISCLAIMER * * Copyright 2016 ArangoDB GmbH, Cologne, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright holder is ArangoDB GmbH, Cologne, Germany */ package com.arangodb.example.graph; /** * Shortest Path in AQL * * @see <a href="https://docs.arangodb.com/current/AQL/Graphs/ShortestPath.html">Shortest Path in AQL</a> * * @author a-brandt * */ public class ShortestPathInAQLExample extends BaseGraphTest { @SuppressWarnings({"WeakerAccess", "unused"}) public static class Pair { private String vertex; private String edge; public String getVertex() { return vertex; } public void setVertex(final String vertex) { this.vertex = vertex; } public String getEdge() { return edge; } public void setEdge(final String edge) { this.edge = edge; } } @Test public void queryShortestPathFromAToD() throws InterruptedException, ExecutionException { String queryString = "FOR v, e IN OUTBOUND SHORTEST_PATH 'circles/A' TO 'circles/D' GRAPH 'traversalGraph' RETURN {'vertex': v._key, 'edge': e._key}";
ArangoCursorAsync<Pair> cursor = db.query(queryString, null, null, Pair.class).get();
rapid7/jenkinsci-appspider-plugin
src/test/java/com/rapid7/appspider/EnterpriseClientTestContext.java
// Path: src/main/java/com/rapid7/appspider/Utility.java // public static String[] toStringArray(List<String> source) { // if (Objects.isNull(source)) // throw new IllegalArgumentException("source cannot be null"); // String[] engines = new String[source.size()]; // return source.toArray(engines); // }
import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.json.JSONArray; import org.json.JSONObject; import org.mockito.ArgumentMatcher; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; import static com.rapid7.appspider.Utility.toStringArray; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
} public String getExpectedAuthToken() { return expectedAuthToken; } public ApiSerializer getMockApiSerializer() { return mockApiSerializer; } public LoggerFacade getMockLogger() { return mockLogger; } public ContentHelper getMockContentHelper() { return mockContentHelper; } public Map<String, String> getExpectedEngineGroupsIdsByName() { return expectedEngineGroupsIdsByName; } public Map<String, String> getExpectedEngineGroupsNamesForClient() { return expectedEngineGroupsNamesForClient; } public String getFirstEngineId() { return engineGroupDetails.get(0).getId(); } public String getFirstEngineName() { return engineGroupDetails.get(0).getName(); } public String[] getEngineGroupNames() {
// Path: src/main/java/com/rapid7/appspider/Utility.java // public static String[] toStringArray(List<String> source) { // if (Objects.isNull(source)) // throw new IllegalArgumentException("source cannot be null"); // String[] engines = new String[source.size()]; // return source.toArray(engines); // } // Path: src/test/java/com/rapid7/appspider/EnterpriseClientTestContext.java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.json.JSONArray; import org.json.JSONObject; import org.mockito.ArgumentMatcher; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; import static com.rapid7.appspider.Utility.toStringArray; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; } public String getExpectedAuthToken() { return expectedAuthToken; } public ApiSerializer getMockApiSerializer() { return mockApiSerializer; } public LoggerFacade getMockLogger() { return mockLogger; } public ContentHelper getMockContentHelper() { return mockContentHelper; } public Map<String, String> getExpectedEngineGroupsIdsByName() { return expectedEngineGroupsIdsByName; } public Map<String, String> getExpectedEngineGroupsNamesForClient() { return expectedEngineGroupsNamesForClient; } public String getFirstEngineId() { return engineGroupDetails.get(0).getId(); } public String getFirstEngineName() { return engineGroupDetails.get(0).getName(); } public String[] getEngineGroupNames() {
return toStringArray(engineGroupDetails.stream().map(EngineStub::getName).collect(Collectors.toList()));
rapid7/jenkinsci-appspider-plugin
src/main/java/com/rapid7/appspider/HttpClientService.java
// Path: src/main/java/com/rapid7/appspider/Utility.java // public static boolean isSuccessStatusCode(HttpResponse response) { // if (Objects.isNull(response)) // return false; // // // https://www.w3.org/Protocols/HTTP/HTRESP.html // // while most if not all AppSpider Enterprise endpoints return 200 on success it's // // safer to treat any success code as success // int statusCode = response.getStatusLine().getStatusCode(); // return statusCode >= 200 && statusCode <= 299; // }
import org.apache.http.*; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.utils.URIBuilder; import org.json.JSONObject; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.util.Arrays; import java.util.Objects; import java.util.Optional; import static com.rapid7.appspider.Utility.isSuccessStatusCode;
/* * Copyright © 2003 - 2020 Rapid7, Inc. All rights reserved. */ package com.rapid7.appspider; public class HttpClientService implements ClientService { private final HttpClient httpClient; private final LoggerFacade logger; private final ContentHelper contentHelper; public HttpClientService(HttpClient httpClient, ContentHelper contentHelper, LoggerFacade logger) { if (Objects.isNull(httpClient)) throw new IllegalArgumentException("httpClient cannot be null"); if (Objects.isNull(contentHelper)) throw new IllegalArgumentException("jsonHelper cannot be null"); if (Objects.isNull(logger)) throw new IllegalArgumentException("logger cannot be null"); this.httpClient = httpClient; this.contentHelper = contentHelper; this.logger = logger; } /** * executes the provided HttpRequestBase returning the result as a JSONObject * @param request the request to send/execute * @return on success an Optional containing a JSONObject; otherwise, Optional.empty() */ @Override public Optional<JSONObject> executeJsonRequest(HttpRequestBase request) { try { return contentHelper.responseToJSONObject(httpClient.execute(request), request.getURI().getPath()); } catch (IOException e) { logger.severe(e.toString()); return Optional.empty(); } } /** * executes the provided HttpRequestBase returning the result as a HttpEntity * @param request the request to send/execute * @return on success an Optional containing a HttpEntity; otherwise, Optional.empty() */ public Optional<HttpEntity> executeEntityRequest(HttpRequestBase request) { try { HttpResponse response = httpClient.execute(request);
// Path: src/main/java/com/rapid7/appspider/Utility.java // public static boolean isSuccessStatusCode(HttpResponse response) { // if (Objects.isNull(response)) // return false; // // // https://www.w3.org/Protocols/HTTP/HTRESP.html // // while most if not all AppSpider Enterprise endpoints return 200 on success it's // // safer to treat any success code as success // int statusCode = response.getStatusLine().getStatusCode(); // return statusCode >= 200 && statusCode <= 299; // } // Path: src/main/java/com/rapid7/appspider/HttpClientService.java import org.apache.http.*; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.utils.URIBuilder; import org.json.JSONObject; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.util.Arrays; import java.util.Objects; import java.util.Optional; import static com.rapid7.appspider.Utility.isSuccessStatusCode; /* * Copyright © 2003 - 2020 Rapid7, Inc. All rights reserved. */ package com.rapid7.appspider; public class HttpClientService implements ClientService { private final HttpClient httpClient; private final LoggerFacade logger; private final ContentHelper contentHelper; public HttpClientService(HttpClient httpClient, ContentHelper contentHelper, LoggerFacade logger) { if (Objects.isNull(httpClient)) throw new IllegalArgumentException("httpClient cannot be null"); if (Objects.isNull(contentHelper)) throw new IllegalArgumentException("jsonHelper cannot be null"); if (Objects.isNull(logger)) throw new IllegalArgumentException("logger cannot be null"); this.httpClient = httpClient; this.contentHelper = contentHelper; this.logger = logger; } /** * executes the provided HttpRequestBase returning the result as a JSONObject * @param request the request to send/execute * @return on success an Optional containing a JSONObject; otherwise, Optional.empty() */ @Override public Optional<JSONObject> executeJsonRequest(HttpRequestBase request) { try { return contentHelper.responseToJSONObject(httpClient.execute(request), request.getURI().getPath()); } catch (IOException e) { logger.severe(e.toString()); return Optional.empty(); } } /** * executes the provided HttpRequestBase returning the result as a HttpEntity * @param request the request to send/execute * @return on success an Optional containing a HttpEntity; otherwise, Optional.empty() */ public Optional<HttpEntity> executeEntityRequest(HttpRequestBase request) { try { HttpResponse response = httpClient.execute(request);
return isSuccessStatusCode(response)
rapid7/jenkinsci-appspider-plugin
src/test/java/com/rapid7/appspider/EnterpriseRestClientTest.java
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // }
import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.datatransferobjects.ScanResult; import com.rapid7.appspider.models.AuthenticationModel; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.*; import static org.junit.jupiter.api.Assertions.*;
package com.rapid7.appspider; class EnterpriseRestClientTest { private static final String url = "https://appspider.rapid7.com/AppSpiderEnterprise/rest/v1"; private EnterpriseClientTestContext context; @BeforeEach public void initialize() { context = new EnterpriseClientTestContext(url); } @AfterEach public void cleanup() { context.close(); } @Test void testAuthenticationReturnsTrueWhenCredentialsAreValid() throws IOException { context.arrangeExpectedValues(true).configureLogin(true).configureEnterpriseClient();
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // } // Path: src/test/java/com/rapid7/appspider/EnterpriseRestClientTest.java import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.datatransferobjects.ScanResult; import com.rapid7.appspider.models.AuthenticationModel; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.*; import static org.junit.jupiter.api.Assertions.*; package com.rapid7.appspider; class EnterpriseRestClientTest { private static final String url = "https://appspider.rapid7.com/AppSpiderEnterprise/rest/v1"; private EnterpriseClientTestContext context; @BeforeEach public void initialize() { context = new EnterpriseClientTestContext(url); } @AfterEach public void cleanup() { context.close(); } @Test void testAuthenticationReturnsTrueWhenCredentialsAreValid() throws IOException { context.arrangeExpectedValues(true).configureLogin(true).configureEnterpriseClient();
assertTrue(context.getEnterpriseClient().testAuthentication(new AuthenticationModel("wolf359", "pa55word")));
rapid7/jenkinsci-appspider-plugin
src/test/java/com/rapid7/appspider/EnterpriseRestClientTest.java
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // }
import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.datatransferobjects.ScanResult; import com.rapid7.appspider.models.AuthenticationModel; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.*; import static org.junit.jupiter.api.Assertions.*;
@Test void getEngineGroupNamesForClientCorrectResultReturned() throws IOException { context.arrangeExpectedValues().configureGetEngineGroupsForClient(true).configureEnterpriseClient(); Optional<String[]> engineGroupNames = context.getEnterpriseClient() .getEngineGroupNamesForClient(context.getExpectedAuthToken()); List<String> expected = Arrays.asList(context.getEngineGroupNames()); List<String> actual = Arrays.asList(engineGroupNames.get()); Collections.sort(expected); Collections.sort(actual); assertArrayEquals(expected.toArray(), actual.toArray()); } @Test void getEngineGroupNamesForClientIsNotPresentWhenApiCallFails() throws IOException { context.arrangeExpectedValues().configureGetEngineGroupsForClient(false).configureEnterpriseClient(); Optional<String[]> engineGroupNames = context.getEnterpriseClient() .getEngineGroupNamesForClient(context.getExpectedAuthToken()); assertFalse(engineGroupNames.isPresent()); } @Test void runScanConfigByNameIsSuccessWhenConfigFoundAndScanCreated() throws IOException { context.arrangeExpectedValues().configureGetConfigs(true).configureRunScanByConfigId(true) .configureEnterpriseClient();
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // } // Path: src/test/java/com/rapid7/appspider/EnterpriseRestClientTest.java import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.datatransferobjects.ScanResult; import com.rapid7.appspider.models.AuthenticationModel; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.*; import static org.junit.jupiter.api.Assertions.*; @Test void getEngineGroupNamesForClientCorrectResultReturned() throws IOException { context.arrangeExpectedValues().configureGetEngineGroupsForClient(true).configureEnterpriseClient(); Optional<String[]> engineGroupNames = context.getEnterpriseClient() .getEngineGroupNamesForClient(context.getExpectedAuthToken()); List<String> expected = Arrays.asList(context.getEngineGroupNames()); List<String> actual = Arrays.asList(engineGroupNames.get()); Collections.sort(expected); Collections.sort(actual); assertArrayEquals(expected.toArray(), actual.toArray()); } @Test void getEngineGroupNamesForClientIsNotPresentWhenApiCallFails() throws IOException { context.arrangeExpectedValues().configureGetEngineGroupsForClient(false).configureEnterpriseClient(); Optional<String[]> engineGroupNames = context.getEnterpriseClient() .getEngineGroupNamesForClient(context.getExpectedAuthToken()); assertFalse(engineGroupNames.isPresent()); } @Test void runScanConfigByNameIsSuccessWhenConfigFoundAndScanCreated() throws IOException { context.arrangeExpectedValues().configureGetConfigs(true).configureRunScanByConfigId(true) .configureEnterpriseClient();
ScanResult scanResult = context.getEnterpriseClient().runScanByConfigName(context.getExpectedAuthToken(),
rapid7/jenkinsci-appspider-plugin
src/test/java/com/rapid7/appspider/EnterpriseRestClientTest.java
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // }
import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.datatransferobjects.ScanResult; import com.rapid7.appspider.models.AuthenticationModel; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.*; import static org.junit.jupiter.api.Assertions.*;
Optional<InputStream> maybeInputStream = context.getEnterpriseClient() .getReportZip(context.getExpectedAuthToken(), context.getExpectedScanId()); try (InputStream inputStream = maybeInputStream.orElseThrow(() -> new RuntimeException("test failure"))) { byte[] encodedResponse = new byte[inputStream.available()]; assertEquals(inputStream.available(), inputStream.read(encodedResponse)); String decoded = new String(Base64.getDecoder().decode(encodedResponse)); assertEquals(content, decoded); } } @Test void getReportZipIsNotPresentWhenFails() throws IOException { String content = UUID.randomUUID().toString(); byte[] encodedContent = Base64.getEncoder().encode(content.getBytes()); context.arrangeExpectedValues().configureGetReportZip(false, encodedContent).configureEnterpriseClient(); Optional<InputStream> inputStream = context.getEnterpriseClient().getReportZip(context.getExpectedAuthToken(), context.getExpectedScanId()); assertFalse(inputStream.isPresent()); } @Test void getClientIdNamePairsIsPresentWhenSuccessful() throws IOException { context .arrangeExpectedValues() .configureGetClientIdNamePairs(true) .configureEnterpriseClient();
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // } // Path: src/test/java/com/rapid7/appspider/EnterpriseRestClientTest.java import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.datatransferobjects.ScanResult; import com.rapid7.appspider.models.AuthenticationModel; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.*; import static org.junit.jupiter.api.Assertions.*; Optional<InputStream> maybeInputStream = context.getEnterpriseClient() .getReportZip(context.getExpectedAuthToken(), context.getExpectedScanId()); try (InputStream inputStream = maybeInputStream.orElseThrow(() -> new RuntimeException("test failure"))) { byte[] encodedResponse = new byte[inputStream.available()]; assertEquals(inputStream.available(), inputStream.read(encodedResponse)); String decoded = new String(Base64.getDecoder().decode(encodedResponse)); assertEquals(content, decoded); } } @Test void getReportZipIsNotPresentWhenFails() throws IOException { String content = UUID.randomUUID().toString(); byte[] encodedContent = Base64.getEncoder().encode(content.getBytes()); context.arrangeExpectedValues().configureGetReportZip(false, encodedContent).configureEnterpriseClient(); Optional<InputStream> inputStream = context.getEnterpriseClient().getReportZip(context.getExpectedAuthToken(), context.getExpectedScanId()); assertFalse(inputStream.isPresent()); } @Test void getClientIdNamePairsIsPresentWhenSuccessful() throws IOException { context .arrangeExpectedValues() .configureGetClientIdNamePairs(true) .configureEnterpriseClient();
Optional<List<ClientIdNamePair>> configs = context
rapid7/jenkinsci-appspider-plugin
src/main/java/com/rapid7/appspider/EnterpriseRestClient.java
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // }
import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.datatransferobjects.ScanResult; import com.rapid7.appspider.models.AuthenticationModel; import freemarker.template.Template; import freemarker.template.TemplateException; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional;
/* * Copyright © 2003 - 2020 Rapid7, Inc. All rights reserved. */ package com.rapid7.appspider; /** * Provides methods to communicating with AppSpider Enterprise while obsuring the implementation * details of that communication. */ public final class EnterpriseRestClient implements EnterpriseClient { private final String restEndPointUrl; private final HttpClientService clientService; private final LoggerFacade logger; private final ApiSerializer apiSerializer; private final ContentHelper contentHelper; /** * Instantiates a new instance of the EnterpriseClient class * @param clientService helper that works directly with lower level HttpClient methods * @param restEndPointUrl base endpoint including /rest/v1 or equilvalent path * @param apiSerializer Helper class providing handling of HttpResponse to JSONObject methods * @param contentHelper Helper class providing parsing and encoding methods to support api calls * @param logger logger used for diagnostic output * @throws IllegalArgumentException thrown if any of the arguments are null or if restEntPointUrl is empty */ public EnterpriseRestClient(HttpClientService clientService, String restEndPointUrl, ApiSerializer apiSerializer, ContentHelper contentHelper, LoggerFacade logger) { if (Objects.isNull(restEndPointUrl) || restEndPointUrl.isEmpty()) throw new IllegalArgumentException("restEndPointUrl cannot be null or empty"); if (Objects.isNull(clientService)) throw new IllegalArgumentException("clientHelper cannot be null or empty"); if (Objects.isNull(apiSerializer)) throw new IllegalArgumentException("apiSerializer cannot be null or empty"); if (Objects.isNull(contentHelper)) throw new IllegalArgumentException("jsonHelper cannot be null"); if (Objects.isNull(logger)) throw new IllegalArgumentException("logger cannot be null"); this.restEndPointUrl = restEndPointUrl; this.clientService = clientService; this.apiSerializer = apiSerializer; this.contentHelper = contentHelper; this.logger = logger; } /** * {@inheritDoc} */ @Override public String getUrl() { return restEndPointUrl; } private static final String AUTHENTICATION_LOGIN = "/Authentication/Login"; /** * {@inheritDoc} */ @Override
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // } // Path: src/main/java/com/rapid7/appspider/EnterpriseRestClient.java import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.datatransferobjects.ScanResult; import com.rapid7.appspider.models.AuthenticationModel; import freemarker.template.Template; import freemarker.template.TemplateException; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; /* * Copyright © 2003 - 2020 Rapid7, Inc. All rights reserved. */ package com.rapid7.appspider; /** * Provides methods to communicating with AppSpider Enterprise while obsuring the implementation * details of that communication. */ public final class EnterpriseRestClient implements EnterpriseClient { private final String restEndPointUrl; private final HttpClientService clientService; private final LoggerFacade logger; private final ApiSerializer apiSerializer; private final ContentHelper contentHelper; /** * Instantiates a new instance of the EnterpriseClient class * @param clientService helper that works directly with lower level HttpClient methods * @param restEndPointUrl base endpoint including /rest/v1 or equilvalent path * @param apiSerializer Helper class providing handling of HttpResponse to JSONObject methods * @param contentHelper Helper class providing parsing and encoding methods to support api calls * @param logger logger used for diagnostic output * @throws IllegalArgumentException thrown if any of the arguments are null or if restEntPointUrl is empty */ public EnterpriseRestClient(HttpClientService clientService, String restEndPointUrl, ApiSerializer apiSerializer, ContentHelper contentHelper, LoggerFacade logger) { if (Objects.isNull(restEndPointUrl) || restEndPointUrl.isEmpty()) throw new IllegalArgumentException("restEndPointUrl cannot be null or empty"); if (Objects.isNull(clientService)) throw new IllegalArgumentException("clientHelper cannot be null or empty"); if (Objects.isNull(apiSerializer)) throw new IllegalArgumentException("apiSerializer cannot be null or empty"); if (Objects.isNull(contentHelper)) throw new IllegalArgumentException("jsonHelper cannot be null"); if (Objects.isNull(logger)) throw new IllegalArgumentException("logger cannot be null"); this.restEndPointUrl = restEndPointUrl; this.clientService = clientService; this.apiSerializer = apiSerializer; this.contentHelper = contentHelper; this.logger = logger; } /** * {@inheritDoc} */ @Override public String getUrl() { return restEndPointUrl; } private static final String AUTHENTICATION_LOGIN = "/Authentication/Login"; /** * {@inheritDoc} */ @Override
public Optional<String> login(AuthenticationModel authModel) {
rapid7/jenkinsci-appspider-plugin
src/main/java/com/rapid7/appspider/EnterpriseRestClient.java
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // }
import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.datatransferobjects.ScanResult; import com.rapid7.appspider.models.AuthenticationModel; import freemarker.template.Template; import freemarker.template.TemplateException; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional;
} /** * {@inheritDoc} */ @Override public Optional<String> getEngineGroupIdFromName(String authToken, String engineGroupName) { return getAllEngineGroups(authToken).filter(map -> map.containsKey(engineGroupName)).flatMap(map -> Optional.of(map.get(engineGroupName))); } private static final String GET_ALL_ENGINE_GROUPS = "/EngineGroup/GetAllEngineGroups"; private static final String GET_ENGINE_GROUPS_FOR_CLIENT = "/EngineGroup/GetEngineGroupsForClient"; private Optional<Map<String, String>> getAllEngineGroups(String authToken) { return clientService .buildGetRequestUsingFormUrlEncoding(restEndPointUrl + GET_ALL_ENGINE_GROUPS, authToken) .flatMap(get -> contentHelper.asMapOfStringToString("Name", "Id", clientService.executeJsonRequest(get))); } private Optional<Map<String,String>> getEngineGroupsForClient(String authToken) { return clientService .buildGetRequestUsingFormUrlEncoding(restEndPointUrl + GET_ENGINE_GROUPS_FOR_CLIENT, authToken) .flatMap(get -> contentHelper.asMapOfStringToString("Name", "Id", clientService.executeJsonRequest(get))); } // </editor-fold> // <editor-fold desc="Scan APIs"> /** * {@inheritDoc} */ @Override
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // } // Path: src/main/java/com/rapid7/appspider/EnterpriseRestClient.java import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.datatransferobjects.ScanResult; import com.rapid7.appspider.models.AuthenticationModel; import freemarker.template.Template; import freemarker.template.TemplateException; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; } /** * {@inheritDoc} */ @Override public Optional<String> getEngineGroupIdFromName(String authToken, String engineGroupName) { return getAllEngineGroups(authToken).filter(map -> map.containsKey(engineGroupName)).flatMap(map -> Optional.of(map.get(engineGroupName))); } private static final String GET_ALL_ENGINE_GROUPS = "/EngineGroup/GetAllEngineGroups"; private static final String GET_ENGINE_GROUPS_FOR_CLIENT = "/EngineGroup/GetEngineGroupsForClient"; private Optional<Map<String, String>> getAllEngineGroups(String authToken) { return clientService .buildGetRequestUsingFormUrlEncoding(restEndPointUrl + GET_ALL_ENGINE_GROUPS, authToken) .flatMap(get -> contentHelper.asMapOfStringToString("Name", "Id", clientService.executeJsonRequest(get))); } private Optional<Map<String,String>> getEngineGroupsForClient(String authToken) { return clientService .buildGetRequestUsingFormUrlEncoding(restEndPointUrl + GET_ENGINE_GROUPS_FOR_CLIENT, authToken) .flatMap(get -> contentHelper.asMapOfStringToString("Name", "Id", clientService.executeJsonRequest(get))); } // </editor-fold> // <editor-fold desc="Scan APIs"> /** * {@inheritDoc} */ @Override
public ScanResult runScanByConfigName(String authToken, String configName) {
rapid7/jenkinsci-appspider-plugin
src/main/java/com/rapid7/appspider/EnterpriseRestClient.java
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // }
import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.datatransferobjects.ScanResult; import com.rapid7.appspider.models.AuthenticationModel; import freemarker.template.Template; import freemarker.template.TemplateException; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional;
/** * {@inheritDoc} */ @Override public Optional<String> getVulnerabilitiesSummaryXml(String authToken, String scanId) { return clientService .buildGetRequestUsingFormUrlEncoding(restEndPointUrl + GET_VULNERABILITIES_SUMMARY, authToken, contentHelper.pairFrom(SCAN_ID, scanId)) .flatMap(clientService::executeEntityRequest) .flatMap(contentHelper::getTextHtmlOrXmlContent); } /** * {@inheritDoc} */ @Override public Optional<InputStream> getReportZip(String authToken, String scanId) { return clientService .buildGetRequestUsingFormUrlEncoding(restEndPointUrl + GET_REPORT_ZIP, authToken, contentHelper.pairFrom(SCAN_ID, scanId)) .flatMap(clientService::executeEntityRequest) .flatMap(contentHelper::getInputStream); } // </editor-fold> // <editor-fold desc="Config APIs"> private static final String GET_CLIENTS = "/Client/GetClients"; /** * {@inheritDoc} */
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // } // Path: src/main/java/com/rapid7/appspider/EnterpriseRestClient.java import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.datatransferobjects.ScanResult; import com.rapid7.appspider.models.AuthenticationModel; import freemarker.template.Template; import freemarker.template.TemplateException; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; /** * {@inheritDoc} */ @Override public Optional<String> getVulnerabilitiesSummaryXml(String authToken, String scanId) { return clientService .buildGetRequestUsingFormUrlEncoding(restEndPointUrl + GET_VULNERABILITIES_SUMMARY, authToken, contentHelper.pairFrom(SCAN_ID, scanId)) .flatMap(clientService::executeEntityRequest) .flatMap(contentHelper::getTextHtmlOrXmlContent); } /** * {@inheritDoc} */ @Override public Optional<InputStream> getReportZip(String authToken, String scanId) { return clientService .buildGetRequestUsingFormUrlEncoding(restEndPointUrl + GET_REPORT_ZIP, authToken, contentHelper.pairFrom(SCAN_ID, scanId)) .flatMap(clientService::executeEntityRequest) .flatMap(contentHelper::getInputStream); } // </editor-fold> // <editor-fold desc="Config APIs"> private static final String GET_CLIENTS = "/Client/GetClients"; /** * {@inheritDoc} */
public Optional<List<ClientIdNamePair>> getClientNameIdPairs(String authToken) {
rapid7/jenkinsci-appspider-plugin
src/main/java/com/rapid7/jenkinspider/PostBuildScan.java
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // }
import com.rapid7.appspider.*; import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.models.AuthenticationModel; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Notifier; import hudson.tasks.Publisher; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import hudson.util.Secret; import org.apache.commons.validator.routines.UrlValidator; import org.apache.http.impl.client.CloseableHttpClient; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Function; import java.util.logging.Level; import java.util.stream.Collectors;
public Boolean getReport() { return generateReport; } public String getScanConfigEngineGroupName() { return scanConfigEngineGroupName; } /** * {@inheritDoc} * * @return boolean representing success or failure of the action to perform * @throws InterruptedException if stop is requested by the user */ @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException { LoggerFacade log = new PrintStreamLoggerFacade(listener.getLogger()); // Don't perform a scan if (!enableScan) { log.println("Scan is not enabled. Continuing the build without scanning."); return false; } String appSpiderEntUrl = getDescriptor().getAppSpiderEntUrl(); log.println("Value of AppSpider Enterprise Server Url: " + appSpiderEntUrl);
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // } // Path: src/main/java/com/rapid7/jenkinspider/PostBuildScan.java import com.rapid7.appspider.*; import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.models.AuthenticationModel; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Notifier; import hudson.tasks.Publisher; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import hudson.util.Secret; import org.apache.commons.validator.routines.UrlValidator; import org.apache.http.impl.client.CloseableHttpClient; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Function; import java.util.logging.Level; import java.util.stream.Collectors; public Boolean getReport() { return generateReport; } public String getScanConfigEngineGroupName() { return scanConfigEngineGroupName; } /** * {@inheritDoc} * * @return boolean representing success or failure of the action to perform * @throws InterruptedException if stop is requested by the user */ @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException { LoggerFacade log = new PrintStreamLoggerFacade(listener.getLogger()); // Don't perform a scan if (!enableScan) { log.println("Scan is not enabled. Continuing the build without scanning."); return false; } String appSpiderEntUrl = getDescriptor().getAppSpiderEntUrl(); log.println("Value of AppSpider Enterprise Server Url: " + appSpiderEntUrl);
AuthenticationModel authModel = getDescriptor().buildAuthenticationModel();
rapid7/jenkinsci-appspider-plugin
src/main/java/com/rapid7/jenkinspider/PostBuildScan.java
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // }
import com.rapid7.appspider.*; import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.models.AuthenticationModel; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Notifier; import hudson.tasks.Publisher; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import hudson.util.Secret; import org.apache.commons.validator.routines.UrlValidator; import org.apache.http.impl.client.CloseableHttpClient; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Function; import java.util.logging.Level; import java.util.stream.Collectors;
}; } private EnterpriseRestClient buildEnterpriseClient(CloseableHttpClient httpClient, String endpoint) { LoggerFacade logger = buildLoggerFacade(); ContentHelper contentHelper = new ContentHelper(logger); return new EnterpriseRestClient( new HttpClientService(httpClient, contentHelper, logger), endpoint, new ApiSerializer(logger), contentHelper, logger); } @Override public boolean configure(StaplerRequest req, net.sf.json.JSONObject formData) throws FormException { req.bindJSON(this, formData); save(); return super.configure(req, net.sf.json.JSONObject.fromObject(formData)); } /** * Method for populating the dropdown menu with * all the available scan configs * @return ListBoxModel containing the scan config names */ public ListBoxModel doFillClientNameItems() throws InterruptedException { Map<String, String> idToNames = getClientIdNamePairsWithRetry(NUMBER_OF_GET_CLIENT_ATTEMPTS, DELAY_BETWEEN_GET_CLIENT_ATTEMPTS) .stream()
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // } // Path: src/main/java/com/rapid7/jenkinspider/PostBuildScan.java import com.rapid7.appspider.*; import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.models.AuthenticationModel; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Notifier; import hudson.tasks.Publisher; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import hudson.util.Secret; import org.apache.commons.validator.routines.UrlValidator; import org.apache.http.impl.client.CloseableHttpClient; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Function; import java.util.logging.Level; import java.util.stream.Collectors; }; } private EnterpriseRestClient buildEnterpriseClient(CloseableHttpClient httpClient, String endpoint) { LoggerFacade logger = buildLoggerFacade(); ContentHelper contentHelper = new ContentHelper(logger); return new EnterpriseRestClient( new HttpClientService(httpClient, contentHelper, logger), endpoint, new ApiSerializer(logger), contentHelper, logger); } @Override public boolean configure(StaplerRequest req, net.sf.json.JSONObject formData) throws FormException { req.bindJSON(this, formData); save(); return super.configure(req, net.sf.json.JSONObject.fromObject(formData)); } /** * Method for populating the dropdown menu with * all the available scan configs * @return ListBoxModel containing the scan config names */ public ListBoxModel doFillClientNameItems() throws InterruptedException { Map<String, String> idToNames = getClientIdNamePairsWithRetry(NUMBER_OF_GET_CLIENT_ATTEMPTS, DELAY_BETWEEN_GET_CLIENT_ATTEMPTS) .stream()
.collect(Collectors.toMap(ClientIdNamePair::getName, ClientIdNamePair::getId));
rapid7/jenkinsci-appspider-plugin
src/main/java/com/rapid7/appspider/EnterpriseClient.java
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // }
import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.datatransferobjects.ScanResult; import com.rapid7.appspider.models.AuthenticationModel; import java.io.InputStream; import java.net.URL; import java.util.List; import java.util.Optional;
/* * Copyright © 2003 - 2020 Rapid7, Inc. All rights reserved. */ package com.rapid7.appspider; public interface EnterpriseClient { /** * returns the full URL for the enterprise rest endpoint * @return the full URL for the enterprise rest endpoint */ String getUrl(); /** * calls the /Authentication/Login endpoint with provided details * @param authModel authentication details such as username, password and optionally clientId * @return on success Optional containing the authorization token; otherwise empty */
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // } // Path: src/main/java/com/rapid7/appspider/EnterpriseClient.java import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.datatransferobjects.ScanResult; import com.rapid7.appspider.models.AuthenticationModel; import java.io.InputStream; import java.net.URL; import java.util.List; import java.util.Optional; /* * Copyright © 2003 - 2020 Rapid7, Inc. All rights reserved. */ package com.rapid7.appspider; public interface EnterpriseClient { /** * returns the full URL for the enterprise rest endpoint * @return the full URL for the enterprise rest endpoint */ String getUrl(); /** * calls the /Authentication/Login endpoint with provided details * @param authModel authentication details such as username, password and optionally clientId * @return on success Optional containing the authorization token; otherwise empty */
Optional<String> login(AuthenticationModel authModel);
rapid7/jenkinsci-appspider-plugin
src/main/java/com/rapid7/appspider/EnterpriseClient.java
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // }
import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.datatransferobjects.ScanResult; import com.rapid7.appspider.models.AuthenticationModel; import java.io.InputStream; import java.net.URL; import java.util.List; import java.util.Optional;
/* * Copyright © 2003 - 2020 Rapid7, Inc. All rights reserved. */ package com.rapid7.appspider; public interface EnterpriseClient { /** * returns the full URL for the enterprise rest endpoint * @return the full URL for the enterprise rest endpoint */ String getUrl(); /** * calls the /Authentication/Login endpoint with provided details * @param authModel authentication details such as username, password and optionally clientId * @return on success Optional containing the authorization token; otherwise empty */ Optional<String> login(AuthenticationModel authModel); /** * calls the /Authentication/Login endpoint with provided details returning true if credentials are valid * @param authModel authentication details such as username, password and optionally clientId * @return true if endpoint returns authorization token; otherwise, false */ boolean testAuthentication(AuthenticationModel authModel); /** * fetches the names of available engine groups * @param authToken authorization token required to execute request * @return On success an Optional containing an array of Strings * representing the names of available engine groups; * otherwise, Optional.empty() */ Optional<String[]> getEngineGroupNamesForClient(String authToken); /** * fetches the unique id of the engine group given by engineGroupName * @param authToken authorization token required to execute request * @param engineGroupName name of the engine to get the id of * @return Optional containing the id of the engine group if found; * otherwise, Optional.empty() */ Optional<String> getEngineGroupIdFromName(String authToken, String engineGroupName); /** * starts a new scan using configuration matching configName * @param authToken authorization token required to execute request * @param configName name of the config to run * @return ScanResult containing details on the success of the request and if successful the * unique id of the scan */
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // } // Path: src/main/java/com/rapid7/appspider/EnterpriseClient.java import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.datatransferobjects.ScanResult; import com.rapid7.appspider.models.AuthenticationModel; import java.io.InputStream; import java.net.URL; import java.util.List; import java.util.Optional; /* * Copyright © 2003 - 2020 Rapid7, Inc. All rights reserved. */ package com.rapid7.appspider; public interface EnterpriseClient { /** * returns the full URL for the enterprise rest endpoint * @return the full URL for the enterprise rest endpoint */ String getUrl(); /** * calls the /Authentication/Login endpoint with provided details * @param authModel authentication details such as username, password and optionally clientId * @return on success Optional containing the authorization token; otherwise empty */ Optional<String> login(AuthenticationModel authModel); /** * calls the /Authentication/Login endpoint with provided details returning true if credentials are valid * @param authModel authentication details such as username, password and optionally clientId * @return true if endpoint returns authorization token; otherwise, false */ boolean testAuthentication(AuthenticationModel authModel); /** * fetches the names of available engine groups * @param authToken authorization token required to execute request * @return On success an Optional containing an array of Strings * representing the names of available engine groups; * otherwise, Optional.empty() */ Optional<String[]> getEngineGroupNamesForClient(String authToken); /** * fetches the unique id of the engine group given by engineGroupName * @param authToken authorization token required to execute request * @param engineGroupName name of the engine to get the id of * @return Optional containing the id of the engine group if found; * otherwise, Optional.empty() */ Optional<String> getEngineGroupIdFromName(String authToken, String engineGroupName); /** * starts a new scan using configuration matching configName * @param authToken authorization token required to execute request * @param configName name of the config to run * @return ScanResult containing details on the success of the request and if successful the * unique id of the scan */
ScanResult runScanByConfigName(String authToken, String configName);
rapid7/jenkinsci-appspider-plugin
src/main/java/com/rapid7/appspider/ContentHelper.java
// Path: src/main/java/com/rapid7/appspider/Utility.java // public static boolean isSuccessStatusCode(HttpResponse response) { // if (Objects.isNull(response)) // return false; // // // https://www.w3.org/Protocols/HTTP/HTRESP.html // // while most if not all AppSpider Enterprise endpoints return 200 on success it's // // safer to treat any success code as success // int statusCode = response.getStatusLine().getStatusCode(); // return statusCode >= 200 && statusCode <= 299; // }
import org.apache.commons.io.IOUtils; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import javax.ws.rs.core.MediaType; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import static com.rapid7.appspider.Utility.isSuccessStatusCode;
} /** * simple wrapper around entityFrom(JSONObject) that uses jsonFrom to build the JSONObject * @param pairs passed to jsonFrom * @return entity returned from entityFrom(JSONObject) * @throws UnsupportedEncodingException thrown from entityFrom(JSONObject) */ public StringEntity entityFrom(NameValuePair... pairs) throws UnsupportedEncodingException { return entityFrom(jsonFrom(pairs)); } /** * simple wrapper around BasicNameValuePair constructor provided to shorten syntax * @param key key of the new NameValuePair * @param value value of the new NameValuePair * @return NameValuePair of key and value */ public NameValuePair pairFrom(String key, String value) { return new BasicNameValuePair(key, value); } /** * extracts the response content into a JSONObject * @param response response to extract JSONObject from * @param path the path used for diagnostic purposes, this is the path to the * request which can be logged in the event of failure * @return on success an Optional containing a JSONObject; otherwise, Optional.empty() */ public Optional<JSONObject> responseToJSONObject(HttpResponse response, String path) {
// Path: src/main/java/com/rapid7/appspider/Utility.java // public static boolean isSuccessStatusCode(HttpResponse response) { // if (Objects.isNull(response)) // return false; // // // https://www.w3.org/Protocols/HTTP/HTRESP.html // // while most if not all AppSpider Enterprise endpoints return 200 on success it's // // safer to treat any success code as success // int statusCode = response.getStatusLine().getStatusCode(); // return statusCode >= 200 && statusCode <= 299; // } // Path: src/main/java/com/rapid7/appspider/ContentHelper.java import org.apache.commons.io.IOUtils; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import javax.ws.rs.core.MediaType; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import static com.rapid7.appspider.Utility.isSuccessStatusCode; } /** * simple wrapper around entityFrom(JSONObject) that uses jsonFrom to build the JSONObject * @param pairs passed to jsonFrom * @return entity returned from entityFrom(JSONObject) * @throws UnsupportedEncodingException thrown from entityFrom(JSONObject) */ public StringEntity entityFrom(NameValuePair... pairs) throws UnsupportedEncodingException { return entityFrom(jsonFrom(pairs)); } /** * simple wrapper around BasicNameValuePair constructor provided to shorten syntax * @param key key of the new NameValuePair * @param value value of the new NameValuePair * @return NameValuePair of key and value */ public NameValuePair pairFrom(String key, String value) { return new BasicNameValuePair(key, value); } /** * extracts the response content into a JSONObject * @param response response to extract JSONObject from * @param path the path used for diagnostic purposes, this is the path to the * request which can be logged in the event of failure * @return on success an Optional containing a JSONObject; otherwise, Optional.empty() */ public Optional<JSONObject> responseToJSONObject(HttpResponse response, String path) {
if (isSuccessStatusCode(response)) {
rapid7/jenkinsci-appspider-plugin
src/main/java/com/rapid7/appspider/Report.java
// Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // }
import hudson.FilePath; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Objects; import java.util.Optional; import com.rapid7.appspider.models.AuthenticationModel;
/* * Copyright © 2003 - 2021 Rapid7, Inc. All rights reserved. */ package com.rapid7.appspider; public class Report { private static final int BUFFER_SIZE = 4096; private final EnterpriseClient client; private final ScanSettings settings; private final LoggerFacade log; public Report(EnterpriseClient client, ScanSettings settings, LoggerFacade log) { if (Objects.isNull(client)) throw new IllegalArgumentException("client cannot be null"); if (Objects.isNull(settings)) throw new IllegalArgumentException("settings cannot be null"); if (Objects.isNull(log)) throw new IllegalArgumentException("log cannot be null"); this.client = client; this.settings = settings; this.log = log; }
// Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // } // Path: src/main/java/com/rapid7/appspider/Report.java import hudson.FilePath; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Objects; import java.util.Optional; import com.rapid7.appspider.models.AuthenticationModel; /* * Copyright © 2003 - 2021 Rapid7, Inc. All rights reserved. */ package com.rapid7.appspider; public class Report { private static final int BUFFER_SIZE = 4096; private final EnterpriseClient client; private final ScanSettings settings; private final LoggerFacade log; public Report(EnterpriseClient client, ScanSettings settings, LoggerFacade log) { if (Objects.isNull(client)) throw new IllegalArgumentException("client cannot be null"); if (Objects.isNull(settings)) throw new IllegalArgumentException("settings cannot be null"); if (Objects.isNull(log)) throw new IllegalArgumentException("log cannot be null"); this.client = client; this.settings = settings; this.log = log; }
public boolean saveReport(AuthenticationModel authModel, String scanId, FilePath directory) {
rapid7/jenkinsci-appspider-plugin
src/main/java/com/rapid7/appspider/Scan.java
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // }
import com.rapid7.appspider.datatransferobjects.ScanResult; import com.rapid7.appspider.models.AuthenticationModel; import java.net.MalformedURLException; import java.net.URL; import java.util.Objects; import java.util.Optional; import java.util.concurrent.TimeUnit;
/* * Copyright © 2003 - 2021 Rapid7, Inc. All rights reserved. */ package com.rapid7.appspider; public class Scan { private static final String SUCCESSFUL_SCAN = "Completed|Stopped"; private static final String UNSUCCESSFUL_SCAN = "ReportError"; private static final String FAILED_SCAN = "Failed"; private static final String FINISHED_SCANNING = SUCCESSFUL_SCAN + "|" + UNSUCCESSFUL_SCAN + "|" + FAILED_SCAN; private static final String UNAUTHORIZED_ERROR = "Unauthorized, please verify credentials and try again."; private final EnterpriseClient client; private final ScanSettings settings; private final LoggerFacade log; private Optional<String> id; public Scan(EnterpriseClient client, ScanSettings settings, LoggerFacade log) { if (Objects.isNull(client)) throw new IllegalArgumentException("client cannot be null"); if (Objects.isNull(settings)) throw new IllegalArgumentException("settings cannot be null"); if (Objects.isNull(log)) throw new IllegalArgumentException("log cannot be null"); this.client = client; this.settings = settings; this.log = log; } /** * returns the current scan id, this will be empty until process has been called * @return the current scan id */ public Optional<String> getId() { return id; }
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // } // Path: src/main/java/com/rapid7/appspider/Scan.java import com.rapid7.appspider.datatransferobjects.ScanResult; import com.rapid7.appspider.models.AuthenticationModel; import java.net.MalformedURLException; import java.net.URL; import java.util.Objects; import java.util.Optional; import java.util.concurrent.TimeUnit; /* * Copyright © 2003 - 2021 Rapid7, Inc. All rights reserved. */ package com.rapid7.appspider; public class Scan { private static final String SUCCESSFUL_SCAN = "Completed|Stopped"; private static final String UNSUCCESSFUL_SCAN = "ReportError"; private static final String FAILED_SCAN = "Failed"; private static final String FINISHED_SCANNING = SUCCESSFUL_SCAN + "|" + UNSUCCESSFUL_SCAN + "|" + FAILED_SCAN; private static final String UNAUTHORIZED_ERROR = "Unauthorized, please verify credentials and try again."; private final EnterpriseClient client; private final ScanSettings settings; private final LoggerFacade log; private Optional<String> id; public Scan(EnterpriseClient client, ScanSettings settings, LoggerFacade log) { if (Objects.isNull(client)) throw new IllegalArgumentException("client cannot be null"); if (Objects.isNull(settings)) throw new IllegalArgumentException("settings cannot be null"); if (Objects.isNull(log)) throw new IllegalArgumentException("log cannot be null"); this.client = client; this.settings = settings; this.log = log; } /** * returns the current scan id, this will be empty until process has been called * @return the current scan id */ public Optional<String> getId() { return id; }
public boolean process(AuthenticationModel authModel) throws InterruptedException {
rapid7/jenkinsci-appspider-plugin
src/main/java/com/rapid7/appspider/Scan.java
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // }
import com.rapid7.appspider.datatransferobjects.ScanResult; import com.rapid7.appspider.models.AuthenticationModel; import java.net.MalformedURLException; import java.net.URL; import java.util.Objects; import java.util.Optional; import java.util.concurrent.TimeUnit;
public Scan(EnterpriseClient client, ScanSettings settings, LoggerFacade log) { if (Objects.isNull(client)) throw new IllegalArgumentException("client cannot be null"); if (Objects.isNull(settings)) throw new IllegalArgumentException("settings cannot be null"); if (Objects.isNull(log)) throw new IllegalArgumentException("log cannot be null"); this.client = client; this.settings = settings; this.log = log; } /** * returns the current scan id, this will be empty until process has been called * @return the current scan id */ public Optional<String> getId() { return id; } public boolean process(AuthenticationModel authModel) throws InterruptedException { Optional<String> maybeAuthToken = client.login(authModel); if (!maybeAuthToken.isPresent()) { log.println(UNAUTHORIZED_ERROR); return false; } String authToken = maybeAuthToken.get(); if (!createScanBeforeRunIfNeeded(authToken)) return false;
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // } // // Path: src/main/java/com/rapid7/appspider/models/AuthenticationModel.java // public class AuthenticationModel { // // private final String username; // private final String password; // private final Optional<String> clientId; // // /** // * instantiates a new instance of the {@code AuthenticationModel} class with no client Id // */ // public AuthenticationModel(String username, String password) { // this(username, password, Optional.empty()); // } // // /** // * instantiates a new instance of the {@code AuthenticationModel} class ensuring that // * username and password are both non-null and non-empty // */ // public AuthenticationModel(String username, String password, Optional<String> clientId) { // if (username == null || username.isEmpty() || password == null || password.isEmpty()) { // throw new IllegalArgumentException(); // } // this.username = username; // this.password = password; // this.clientId = clientId; // } // // /** // * gets the password value // * @return password as a {@code Secret} // */ // public String getPassword() { // return password; // } // // /** // * Get the username value // * @return username as a String // */ // public String getUsername() { // return username; // } // // /** // * Returns whether this object contains a clientId or not // * // * <p> // * should be called prior to {@code getClientId} to ensure a value is present, // * otherwise an exception may occur // * </p> // * @return true if client id is set; otherwise, false // */ // public boolean hasClientId() { // return clientId.isPresent(); // } // // /** // * Gets the client id if present; otherwise throws a {@code NoSuchElementException} // * @return the client Id if present // * @throws NoSuchElementException if this instance does not have a clientId // */ // public String getClientId() throws NoSuchElementException { // return clientId.orElseThrow(NoSuchElementException::new); // } // // // } // Path: src/main/java/com/rapid7/appspider/Scan.java import com.rapid7.appspider.datatransferobjects.ScanResult; import com.rapid7.appspider.models.AuthenticationModel; import java.net.MalformedURLException; import java.net.URL; import java.util.Objects; import java.util.Optional; import java.util.concurrent.TimeUnit; public Scan(EnterpriseClient client, ScanSettings settings, LoggerFacade log) { if (Objects.isNull(client)) throw new IllegalArgumentException("client cannot be null"); if (Objects.isNull(settings)) throw new IllegalArgumentException("settings cannot be null"); if (Objects.isNull(log)) throw new IllegalArgumentException("log cannot be null"); this.client = client; this.settings = settings; this.log = log; } /** * returns the current scan id, this will be empty until process has been called * @return the current scan id */ public Optional<String> getId() { return id; } public boolean process(AuthenticationModel authModel) throws InterruptedException { Optional<String> maybeAuthToken = client.login(authModel); if (!maybeAuthToken.isPresent()) { log.println(UNAUTHORIZED_ERROR); return false; } String authToken = maybeAuthToken.get(); if (!createScanBeforeRunIfNeeded(authToken)) return false;
ScanResult runResult = client.runScanByConfigName(authToken, settings.getConfigName());
rapid7/jenkinsci-appspider-plugin
src/main/java/com/rapid7/appspider/ApiSerializer.java
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // }
import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.datatransferobjects.ScanResult; import freemarker.template.Template; import freemarker.template.TemplateException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.*;
public Optional<String> getTokenOrEmpty(JSONObject jsonObject) { if (!getIsSuccess(jsonObject)) return Optional.empty(); try { String token = jsonObject.getString("Token"); return (Objects.isNull(token) || token.isEmpty()) ? Optional.empty() : Optional.of(token); } catch (JSONException e) { logger.severe(e.toString()); return Optional.empty(); } } /** * returns the value of "IsSuccess" from the provided jsonObject if non-null; otherwise, false * @param jsonObject JSON object containing the "IsSuccess" value to extract * @return value of "IsSuccess" from the provided jsonObject if non-null; otherwise, false */ public boolean getIsSuccess(JSONObject jsonObject) { if (Objects.isNull(jsonObject)) return false; try { return jsonObject.getBoolean("IsSuccess"); } catch (JSONException e) { logger.severe(e.toString()); return false; } }
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // } // Path: src/main/java/com/rapid7/appspider/ApiSerializer.java import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.datatransferobjects.ScanResult; import freemarker.template.Template; import freemarker.template.TemplateException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.*; public Optional<String> getTokenOrEmpty(JSONObject jsonObject) { if (!getIsSuccess(jsonObject)) return Optional.empty(); try { String token = jsonObject.getString("Token"); return (Objects.isNull(token) || token.isEmpty()) ? Optional.empty() : Optional.of(token); } catch (JSONException e) { logger.severe(e.toString()); return Optional.empty(); } } /** * returns the value of "IsSuccess" from the provided jsonObject if non-null; otherwise, false * @param jsonObject JSON object containing the "IsSuccess" value to extract * @return value of "IsSuccess" from the provided jsonObject if non-null; otherwise, false */ public boolean getIsSuccess(JSONObject jsonObject) { if (Objects.isNull(jsonObject)) return false; try { return jsonObject.getBoolean("IsSuccess"); } catch (JSONException e) { logger.severe(e.toString()); return false; } }
public ScanResult getScanResult(JSONObject jsonObject) {
rapid7/jenkinsci-appspider-plugin
src/main/java/com/rapid7/appspider/ApiSerializer.java
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // }
import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.datatransferobjects.ScanResult; import freemarker.template.Template; import freemarker.template.TemplateException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.*;
return Optional.of(config); } logger.println("no config with name " + configName + " was found."); return Optional.empty(); } catch (JSONException e) { logger.severe(e.toString()); return Optional.empty(); } } /** * returns true if all given keys in jsonObject are true * @param jsonObject json object containing keys * @param keys keys for the boolean fields of jsonObject * @return true if all keys are present and true */ public Optional<Boolean> getBooleansFrom(JSONObject jsonObject, String... keys) { return Objects.isNull(jsonObject) ? Optional.empty() : Optional .of(Arrays.stream(keys) .allMatch(jsonObject::getBoolean)); } /** * returns a list of ClientIdNamePair objects extracted from given JSONArray * @param clients JSONArray containing items with format { ClientId = String, ClientName = String } * @return on success list of ClientIdNamePairs extracted from clients; otherwise, Optional.empty() */
// Path: src/main/java/com/rapid7/appspider/datatransferobjects/ClientIdNamePair.java // public final class ClientIdNamePair { // // private final String id; // private final String name; // // public ClientIdNamePair(String id, String name) { // this.id = id; // this.name = name; // } // // public String getName() { // return name; // } // // public String getId() { // return id; // } // // } // // Path: src/main/java/com/rapid7/appspider/datatransferobjects/ScanResult.java // public class ScanResult { // private final boolean isSuccess; // private final String scanId; // // public ScanResult(boolean isSuccess, String scanId) { // this.isSuccess = isSuccess; // this.scanId = scanId; // } // public ScanResult(JSONObject jsonObject) { // if (jsonObject == null) // throw new IllegalArgumentException("jsonObject cannot be null"); // // try { // isSuccess = jsonObject.getBoolean("IsSuccess"); // scanId = jsonObject.getJSONObject("Scan").getString("Id"); // // } catch(JSONException e) { // throw new IllegalArgumentException("unexpected error occured parsing scan result", e); // } // // } // // public String getScanId() { // return scanId; // } // // public boolean isSuccess() { // return isSuccess; // } // } // Path: src/main/java/com/rapid7/appspider/ApiSerializer.java import com.rapid7.appspider.datatransferobjects.ClientIdNamePair; import com.rapid7.appspider.datatransferobjects.ScanResult; import freemarker.template.Template; import freemarker.template.TemplateException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.*; return Optional.of(config); } logger.println("no config with name " + configName + " was found."); return Optional.empty(); } catch (JSONException e) { logger.severe(e.toString()); return Optional.empty(); } } /** * returns true if all given keys in jsonObject are true * @param jsonObject json object containing keys * @param keys keys for the boolean fields of jsonObject * @return true if all keys are present and true */ public Optional<Boolean> getBooleansFrom(JSONObject jsonObject, String... keys) { return Objects.isNull(jsonObject) ? Optional.empty() : Optional .of(Arrays.stream(keys) .allMatch(jsonObject::getBoolean)); } /** * returns a list of ClientIdNamePair objects extracted from given JSONArray * @param clients JSONArray containing items with format { ClientId = String, ClientName = String } * @return on success list of ClientIdNamePairs extracted from clients; otherwise, Optional.empty() */
public Optional<List<ClientIdNamePair>> getClientIdNamePairs(JSONArray clients) {
upenn-libraries/xmlaminar
parallel/src/main/java/edu/upenn/library/xmlaminar/parallel/callback/StaticFileCallback.java
// Path: core/src/main/java/edu/upenn/library/xmlaminar/VolatileSAXSource.java // public class VolatileSAXSource extends SAXSource { // // private volatile XMLReader reader; // private volatile InputSource inputSource; // // public VolatileSAXSource() { // } // // public VolatileSAXSource(XMLReader reader, InputSource inputSource) { // this.reader = reader; // this.inputSource = inputSource; // } // // public VolatileSAXSource(InputSource inputSource) { // this(null, inputSource); // } // // @Override // public void setXMLReader(XMLReader reader) { // this.reader = reader; // } // // @Override // public XMLReader getXMLReader() { // return reader; // } // // @Override // public void setInputSource(InputSource inputSource) { // this.inputSource = inputSource; // } // // @Override // public InputSource getInputSource() { // return inputSource; // } // // @Override // public void setSystemId(String systemId) { // if (inputSource == null) { // inputSource = new InputSource(systemId); // } else { // inputSource.setSystemId(systemId); // } // } // // @Override // public String getSystemId() { // return inputSource == null ? null : inputSource.getSystemId(); // } // // }
import edu.upenn.library.xmlaminar.VolatileSAXSource; import java.io.File; import java.io.IOException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLFilter; import org.xml.sax.XMLReader;
/* * Copyright 2011-2015 The Trustees of the University of Pennsylvania * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.upenn.library.xmlaminar.parallel.callback; /** * * @author magibney */ public class StaticFileCallback implements XMLReaderCallback { private final File staticFile; private final Transformer t; private final XMLFilter outputFilter; private final boolean gzipOutput; public StaticFileCallback(Transformer t, File staticFile, XMLFilter outputFilter, boolean gzipOutput) { this.staticFile = staticFile; this.t = t; this.outputFilter = outputFilter; this.gzipOutput = gzipOutput; } public StaticFileCallback(Transformer t, File staticFile) { this(t, staticFile, null, false); } public StaticFileCallback(File staticFile) throws TransformerConfigurationException { this(TransformerFactory.newInstance().newTransformer(), staticFile); } @Override
// Path: core/src/main/java/edu/upenn/library/xmlaminar/VolatileSAXSource.java // public class VolatileSAXSource extends SAXSource { // // private volatile XMLReader reader; // private volatile InputSource inputSource; // // public VolatileSAXSource() { // } // // public VolatileSAXSource(XMLReader reader, InputSource inputSource) { // this.reader = reader; // this.inputSource = inputSource; // } // // public VolatileSAXSource(InputSource inputSource) { // this(null, inputSource); // } // // @Override // public void setXMLReader(XMLReader reader) { // this.reader = reader; // } // // @Override // public XMLReader getXMLReader() { // return reader; // } // // @Override // public void setInputSource(InputSource inputSource) { // this.inputSource = inputSource; // } // // @Override // public InputSource getInputSource() { // return inputSource; // } // // @Override // public void setSystemId(String systemId) { // if (inputSource == null) { // inputSource = new InputSource(systemId); // } else { // inputSource.setSystemId(systemId); // } // } // // @Override // public String getSystemId() { // return inputSource == null ? null : inputSource.getSystemId(); // } // // } // Path: parallel/src/main/java/edu/upenn/library/xmlaminar/parallel/callback/StaticFileCallback.java import edu.upenn.library.xmlaminar.VolatileSAXSource; import java.io.File; import java.io.IOException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLFilter; import org.xml.sax.XMLReader; /* * Copyright 2011-2015 The Trustees of the University of Pennsylvania * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.upenn.library.xmlaminar.parallel.callback; /** * * @author magibney */ public class StaticFileCallback implements XMLReaderCallback { private final File staticFile; private final Transformer t; private final XMLFilter outputFilter; private final boolean gzipOutput; public StaticFileCallback(Transformer t, File staticFile, XMLFilter outputFilter, boolean gzipOutput) { this.staticFile = staticFile; this.t = t; this.outputFilter = outputFilter; this.gzipOutput = gzipOutput; } public StaticFileCallback(Transformer t, File staticFile) { this(t, staticFile, null, false); } public StaticFileCallback(File staticFile) throws TransformerConfigurationException { this(TransformerFactory.newInstance().newTransformer(), staticFile); } @Override
public void callback(VolatileSAXSource source) throws SAXException, IOException {
upenn-libraries/xmlaminar
parallel/src/main/java/edu/upenn/library/xmlaminar/parallel/callback/IncrementingFileCallback.java
// Path: core/src/main/java/edu/upenn/library/xmlaminar/VolatileSAXSource.java // public class VolatileSAXSource extends SAXSource { // // private volatile XMLReader reader; // private volatile InputSource inputSource; // // public VolatileSAXSource() { // } // // public VolatileSAXSource(XMLReader reader, InputSource inputSource) { // this.reader = reader; // this.inputSource = inputSource; // } // // public VolatileSAXSource(InputSource inputSource) { // this(null, inputSource); // } // // @Override // public void setXMLReader(XMLReader reader) { // this.reader = reader; // } // // @Override // public XMLReader getXMLReader() { // return reader; // } // // @Override // public void setInputSource(InputSource inputSource) { // this.inputSource = inputSource; // } // // @Override // public InputSource getInputSource() { // return inputSource; // } // // @Override // public void setSystemId(String systemId) { // if (inputSource == null) { // inputSource = new InputSource(systemId); // } else { // inputSource.setSystemId(systemId); // } // } // // @Override // public String getSystemId() { // return inputSource == null ? null : inputSource.getSystemId(); // } // // }
import edu.upenn.library.xmlaminar.VolatileSAXSource; import java.io.File; import java.io.IOException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import org.xml.sax.SAXException; import org.xml.sax.XMLFilter;
this(start, t, DEFAULT_SUFFIX_SIZE, baseFile, postSuffix, outputFilter); } public IncrementingFileCallback(int start, Transformer t, int suffixSize, String baseFile, String postSuffix, XMLFilter outputFilter) { this(start, t, getDefaultSuffixFormat(suffixSize), new File(baseFile), postSuffix, outputFilter, DEFAULT_GZIP_OUTPUT); } public IncrementingFileCallback(int start, Transformer t, int suffixSize, XMLFilter outputFilter, boolean gzipOutput) { this(start, t, getDefaultSuffixFormat(suffixSize), null, null, outputFilter, gzipOutput); } public IncrementingFileCallback(int start, Transformer t, int suffixLength, File baseFile, String postSuffix, XMLFilter outputFilter, boolean gzipOutput) { this(start, t, getDefaultSuffixFormat(suffixLength), baseFile, postSuffix, outputFilter, gzipOutput); } public IncrementingFileCallback(int start, Transformer t, String suffixFormat, File baseFile, String postSuffix, XMLFilter outputFilter, boolean gzipOutput) { this.i = start; this.t = t; this.baseFile = baseFile; if (baseFile != null) { this.parentFile = baseFile.getParentFile(); this.namePrefix = baseFile.getName(); } this.postSuffix = postSuffix; this.suffixFormat = suffixFormat; this.outputFilter = outputFilter; this.gzipOutput = gzipOutput; } @Override
// Path: core/src/main/java/edu/upenn/library/xmlaminar/VolatileSAXSource.java // public class VolatileSAXSource extends SAXSource { // // private volatile XMLReader reader; // private volatile InputSource inputSource; // // public VolatileSAXSource() { // } // // public VolatileSAXSource(XMLReader reader, InputSource inputSource) { // this.reader = reader; // this.inputSource = inputSource; // } // // public VolatileSAXSource(InputSource inputSource) { // this(null, inputSource); // } // // @Override // public void setXMLReader(XMLReader reader) { // this.reader = reader; // } // // @Override // public XMLReader getXMLReader() { // return reader; // } // // @Override // public void setInputSource(InputSource inputSource) { // this.inputSource = inputSource; // } // // @Override // public InputSource getInputSource() { // return inputSource; // } // // @Override // public void setSystemId(String systemId) { // if (inputSource == null) { // inputSource = new InputSource(systemId); // } else { // inputSource.setSystemId(systemId); // } // } // // @Override // public String getSystemId() { // return inputSource == null ? null : inputSource.getSystemId(); // } // // } // Path: parallel/src/main/java/edu/upenn/library/xmlaminar/parallel/callback/IncrementingFileCallback.java import edu.upenn.library.xmlaminar.VolatileSAXSource; import java.io.File; import java.io.IOException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import org.xml.sax.SAXException; import org.xml.sax.XMLFilter; this(start, t, DEFAULT_SUFFIX_SIZE, baseFile, postSuffix, outputFilter); } public IncrementingFileCallback(int start, Transformer t, int suffixSize, String baseFile, String postSuffix, XMLFilter outputFilter) { this(start, t, getDefaultSuffixFormat(suffixSize), new File(baseFile), postSuffix, outputFilter, DEFAULT_GZIP_OUTPUT); } public IncrementingFileCallback(int start, Transformer t, int suffixSize, XMLFilter outputFilter, boolean gzipOutput) { this(start, t, getDefaultSuffixFormat(suffixSize), null, null, outputFilter, gzipOutput); } public IncrementingFileCallback(int start, Transformer t, int suffixLength, File baseFile, String postSuffix, XMLFilter outputFilter, boolean gzipOutput) { this(start, t, getDefaultSuffixFormat(suffixLength), baseFile, postSuffix, outputFilter, gzipOutput); } public IncrementingFileCallback(int start, Transformer t, String suffixFormat, File baseFile, String postSuffix, XMLFilter outputFilter, boolean gzipOutput) { this.i = start; this.t = t; this.baseFile = baseFile; if (baseFile != null) { this.parentFile = baseFile.getParentFile(); this.namePrefix = baseFile.getName(); } this.postSuffix = postSuffix; this.suffixFormat = suffixFormat; this.outputFilter = outputFilter; this.gzipOutput = gzipOutput; } @Override
public void callback(VolatileSAXSource source) throws SAXException, IOException {
upenn-libraries/xmlaminar
parallel/src/main/java/edu/upenn/library/xmlaminar/parallel/callback/StdoutCallback.java
// Path: core/src/main/java/edu/upenn/library/xmlaminar/VolatileSAXSource.java // public class VolatileSAXSource extends SAXSource { // // private volatile XMLReader reader; // private volatile InputSource inputSource; // // public VolatileSAXSource() { // } // // public VolatileSAXSource(XMLReader reader, InputSource inputSource) { // this.reader = reader; // this.inputSource = inputSource; // } // // public VolatileSAXSource(InputSource inputSource) { // this(null, inputSource); // } // // @Override // public void setXMLReader(XMLReader reader) { // this.reader = reader; // } // // @Override // public XMLReader getXMLReader() { // return reader; // } // // @Override // public void setInputSource(InputSource inputSource) { // this.inputSource = inputSource; // } // // @Override // public InputSource getInputSource() { // return inputSource; // } // // @Override // public void setSystemId(String systemId) { // if (inputSource == null) { // inputSource = new InputSource(systemId); // } else { // inputSource.setSystemId(systemId); // } // } // // @Override // public String getSystemId() { // return inputSource == null ? null : inputSource.getSystemId(); // } // // }
import org.xml.sax.SAXException; import org.xml.sax.XMLFilter; import org.xml.sax.XMLReader; import edu.upenn.library.xmlaminar.VolatileSAXSource; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.io.StringReader; import java.util.zip.GZIPOutputStream; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import org.xml.sax.InputSource;
/* * Copyright 2011-2015 The Trustees of the University of Pennsylvania * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.upenn.library.xmlaminar.parallel.callback; /** * * @author magibney */ public class StdoutCallback implements XMLReaderCallback { private static final boolean DEFAULT_GZIP_OUTPUT = false; private final Transformer t; private final XMLFilter outputFilter; private final boolean gzipOutput; private OutputStream out; public StdoutCallback(Transformer t, XMLFilter outputFilter, boolean gzipOutput) { this.t = t; this.outputFilter = outputFilter; this.gzipOutput = gzipOutput; } public StdoutCallback(Transformer t) { this(t, null, false); } public StdoutCallback(XMLFilter outputFilter) throws TransformerConfigurationException { this(TransformerFactory.newInstance().newTransformer(), outputFilter, DEFAULT_GZIP_OUTPUT); } public StdoutCallback() throws TransformerConfigurationException { this(TransformerFactory.newInstance().newTransformer(), null, DEFAULT_GZIP_OUTPUT); } @Override
// Path: core/src/main/java/edu/upenn/library/xmlaminar/VolatileSAXSource.java // public class VolatileSAXSource extends SAXSource { // // private volatile XMLReader reader; // private volatile InputSource inputSource; // // public VolatileSAXSource() { // } // // public VolatileSAXSource(XMLReader reader, InputSource inputSource) { // this.reader = reader; // this.inputSource = inputSource; // } // // public VolatileSAXSource(InputSource inputSource) { // this(null, inputSource); // } // // @Override // public void setXMLReader(XMLReader reader) { // this.reader = reader; // } // // @Override // public XMLReader getXMLReader() { // return reader; // } // // @Override // public void setInputSource(InputSource inputSource) { // this.inputSource = inputSource; // } // // @Override // public InputSource getInputSource() { // return inputSource; // } // // @Override // public void setSystemId(String systemId) { // if (inputSource == null) { // inputSource = new InputSource(systemId); // } else { // inputSource.setSystemId(systemId); // } // } // // @Override // public String getSystemId() { // return inputSource == null ? null : inputSource.getSystemId(); // } // // } // Path: parallel/src/main/java/edu/upenn/library/xmlaminar/parallel/callback/StdoutCallback.java import org.xml.sax.SAXException; import org.xml.sax.XMLFilter; import org.xml.sax.XMLReader; import edu.upenn.library.xmlaminar.VolatileSAXSource; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.io.StringReader; import java.util.zip.GZIPOutputStream; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import org.xml.sax.InputSource; /* * Copyright 2011-2015 The Trustees of the University of Pennsylvania * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.upenn.library.xmlaminar.parallel.callback; /** * * @author magibney */ public class StdoutCallback implements XMLReaderCallback { private static final boolean DEFAULT_GZIP_OUTPUT = false; private final Transformer t; private final XMLFilter outputFilter; private final boolean gzipOutput; private OutputStream out; public StdoutCallback(Transformer t, XMLFilter outputFilter, boolean gzipOutput) { this.t = t; this.outputFilter = outputFilter; this.gzipOutput = gzipOutput; } public StdoutCallback(Transformer t) { this(t, null, false); } public StdoutCallback(XMLFilter outputFilter) throws TransformerConfigurationException { this(TransformerFactory.newInstance().newTransformer(), outputFilter, DEFAULT_GZIP_OUTPUT); } public StdoutCallback() throws TransformerConfigurationException { this(TransformerFactory.newInstance().newTransformer(), null, DEFAULT_GZIP_OUTPUT); } @Override
public void callback(VolatileSAXSource source) throws SAXException, IOException {
upenn-libraries/xmlaminar
cli/src/main/java/edu/upenn/library/xmlaminar/cli/PipelineCommandFactory.java
// Path: core/src/main/java/edu/upenn/library/xmlaminar/DevNullContentHandler.java // public class DevNullContentHandler implements ContentHandler { // // @Override // public void setDocumentLocator(Locator locator) { // } // // @Override // public void startDocument() throws SAXException { // } // // @Override // public void endDocument() throws SAXException { // } // // @Override // public void startPrefixMapping(String prefix, String uri) throws SAXException { // } // // @Override // public void endPrefixMapping(String prefix) throws SAXException { // } // // @Override // public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { // } // // @Override // public void endElement(String uri, String localName, String qName) throws SAXException { // } // // @Override // public void characters(char[] ch, int start, int length) throws SAXException { // } // // @Override // public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { // } // // @Override // public void processingInstruction(String target, String data) throws SAXException { // } // // @Override // public void skippedEntity(String name) throws SAXException { // } // // }
import edu.upenn.library.xmlaminar.DevNullContentHandler; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.util.AbstractMap; import java.util.Arrays; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLFilter; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl;
public Command newCommand(boolean first, boolean last) { if (!xmlConfigured) { throw new IllegalStateException(); } return new PipelineCommand(this.first, last); } @Override public String getKey() { return KEY; } private final LinkedList<Entry<CommandFactory, String[]>> commandFactories = new LinkedList<Entry<CommandFactory, String[]>>(); private int depth = -1; private void reset() { depth = -1; commandFactories.clear(); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { depth--; super.endElement(uri, localName, qName); } private final Map<String, CommandFactory> cfs = CommandFactory.getAvailableCommandFactories(); private int delegateDepth = Integer.MAX_VALUE;
// Path: core/src/main/java/edu/upenn/library/xmlaminar/DevNullContentHandler.java // public class DevNullContentHandler implements ContentHandler { // // @Override // public void setDocumentLocator(Locator locator) { // } // // @Override // public void startDocument() throws SAXException { // } // // @Override // public void endDocument() throws SAXException { // } // // @Override // public void startPrefixMapping(String prefix, String uri) throws SAXException { // } // // @Override // public void endPrefixMapping(String prefix) throws SAXException { // } // // @Override // public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { // } // // @Override // public void endElement(String uri, String localName, String qName) throws SAXException { // } // // @Override // public void characters(char[] ch, int start, int length) throws SAXException { // } // // @Override // public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { // } // // @Override // public void processingInstruction(String target, String data) throws SAXException { // } // // @Override // public void skippedEntity(String name) throws SAXException { // } // // } // Path: cli/src/main/java/edu/upenn/library/xmlaminar/cli/PipelineCommandFactory.java import edu.upenn.library.xmlaminar.DevNullContentHandler; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.util.AbstractMap; import java.util.Arrays; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLFilter; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl; public Command newCommand(boolean first, boolean last) { if (!xmlConfigured) { throw new IllegalStateException(); } return new PipelineCommand(this.first, last); } @Override public String getKey() { return KEY; } private final LinkedList<Entry<CommandFactory, String[]>> commandFactories = new LinkedList<Entry<CommandFactory, String[]>>(); private int depth = -1; private void reset() { depth = -1; commandFactories.clear(); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { depth--; super.endElement(uri, localName, qName); } private final Map<String, CommandFactory> cfs = CommandFactory.getAvailableCommandFactories(); private int delegateDepth = Integer.MAX_VALUE;
private static final ContentHandler DEV_NULL_CONTENT_HANDLER = new DevNullContentHandler();
upenn-libraries/xmlaminar
core/src/main/java/edu/upenn/library/xmlaminar/fsxml/FilesystemXMLReaderRepo.java
// Path: core/src/main/java/edu/upenn/library/xmlaminar/Element.java // public class Element { // // public final String uri; // public final String prefix; // public final String localName; // public final String qName; // public static final Attributes EMPTY_ATTS = new UnmodifiableAttributes(); // // public Element(String uri, String prefix, String localName) { // this.uri = uri.intern(); // this.prefix = prefix.intern(); // this.localName = localName.intern(); // if (prefix.equals("")) { // qName = this.localName; // } else { // qName = (prefix + ":" + localName).intern(); // } // } // // public Element(String localName) { // uri = ""; // prefix = ""; // qName = localName.intern(); // this.localName = localName = qName; // } // // public void start(ContentHandler ch) throws SAXException { // start(ch, EMPTY_ATTS); // } // // public void start(ContentHandler ch, Attributes atts) throws SAXException { // ch.startElement(uri, localName, qName, atts); // } // // public void end(ContentHandler ch) throws SAXException { // ch.endElement(uri, localName, qName); // } // // public static void logXML(ContentHandler ch, Element element, String message) throws SAXException { // char[] messageChars = message.toCharArray(); // element.start(ch); // ch.characters(messageChars, 0, messageChars.length); // element.end(ch); // } // // private static class UnmodifiableAttributes extends AttributesImpl { // // @Override // public void addAttribute(String uri, String localName, String qName, String type, String value) { // throw new UnsupportedOperationException(); // } // // @Override // public void setAttribute(int index, String uri, String localName, String qName, String type, String value) { // throw new UnsupportedOperationException(); // } // // @Override // public void setAttributes(Attributes atts) { // throw new UnsupportedOperationException(); // } // // @Override // public void setLocalName(int index, String localName) { // throw new UnsupportedOperationException(); // } // // @Override // public void setQName(int index, String qName) { // throw new UnsupportedOperationException(); // } // // @Override // public void setType(int index, String type) { // throw new UnsupportedOperationException(); // } // // @Override // public void setURI(int index, String uri) { // throw new UnsupportedOperationException(); // } // // @Override // public void setValue(int index, String value) { // throw new UnsupportedOperationException(); // } // // } // // }
import org.xml.sax.SAXException; import org.xml.sax.XMLFilter; import org.xml.sax.helpers.AttributesImpl; import edu.upenn.library.xmlaminar.Element; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource;
/* * Copyright 2011-2015 The Trustees of the University of Pennsylvania * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.upenn.library.xmlaminar.fsxml; /** * * @author michael */ public class FilesystemXMLReaderRepo extends FilesystemXMLReader { public static final String TRANSFORMER_FACTORY_CLASS = "net.sf.saxon.TransformerFactoryImpl"; public static void main(String[] args) throws FileNotFoundException, TransformerConfigurationException, TransformerException, IOException { FilesystemXMLReader instance = new FilesystemXMLReaderRepo(); instance.setFollowSymlinks(false); XMLFilter inclRepoContents = new IncludeRepoContentsXMLFilter(); inclRepoContents.setParent(instance); File rootFile = new File("/repo/3"); TransformerFactory tf = TransformerFactory.newInstance(TRANSFORMER_FACTORY_CLASS, null); Transformer t = tf.newTransformer(); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.transform(new SAXSource(inclRepoContents, new InputSource(rootFile.getAbsolutePath())), new StreamResult(System.out)); } private static final String DFLAT_MARKER = "0=dflat";
// Path: core/src/main/java/edu/upenn/library/xmlaminar/Element.java // public class Element { // // public final String uri; // public final String prefix; // public final String localName; // public final String qName; // public static final Attributes EMPTY_ATTS = new UnmodifiableAttributes(); // // public Element(String uri, String prefix, String localName) { // this.uri = uri.intern(); // this.prefix = prefix.intern(); // this.localName = localName.intern(); // if (prefix.equals("")) { // qName = this.localName; // } else { // qName = (prefix + ":" + localName).intern(); // } // } // // public Element(String localName) { // uri = ""; // prefix = ""; // qName = localName.intern(); // this.localName = localName = qName; // } // // public void start(ContentHandler ch) throws SAXException { // start(ch, EMPTY_ATTS); // } // // public void start(ContentHandler ch, Attributes atts) throws SAXException { // ch.startElement(uri, localName, qName, atts); // } // // public void end(ContentHandler ch) throws SAXException { // ch.endElement(uri, localName, qName); // } // // public static void logXML(ContentHandler ch, Element element, String message) throws SAXException { // char[] messageChars = message.toCharArray(); // element.start(ch); // ch.characters(messageChars, 0, messageChars.length); // element.end(ch); // } // // private static class UnmodifiableAttributes extends AttributesImpl { // // @Override // public void addAttribute(String uri, String localName, String qName, String type, String value) { // throw new UnsupportedOperationException(); // } // // @Override // public void setAttribute(int index, String uri, String localName, String qName, String type, String value) { // throw new UnsupportedOperationException(); // } // // @Override // public void setAttributes(Attributes atts) { // throw new UnsupportedOperationException(); // } // // @Override // public void setLocalName(int index, String localName) { // throw new UnsupportedOperationException(); // } // // @Override // public void setQName(int index, String qName) { // throw new UnsupportedOperationException(); // } // // @Override // public void setType(int index, String type) { // throw new UnsupportedOperationException(); // } // // @Override // public void setURI(int index, String uri) { // throw new UnsupportedOperationException(); // } // // @Override // public void setValue(int index, String value) { // throw new UnsupportedOperationException(); // } // // } // // } // Path: core/src/main/java/edu/upenn/library/xmlaminar/fsxml/FilesystemXMLReaderRepo.java import org.xml.sax.SAXException; import org.xml.sax.XMLFilter; import org.xml.sax.helpers.AttributesImpl; import edu.upenn.library.xmlaminar.Element; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; /* * Copyright 2011-2015 The Trustees of the University of Pennsylvania * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.upenn.library.xmlaminar.fsxml; /** * * @author michael */ public class FilesystemXMLReaderRepo extends FilesystemXMLReader { public static final String TRANSFORMER_FACTORY_CLASS = "net.sf.saxon.TransformerFactoryImpl"; public static void main(String[] args) throws FileNotFoundException, TransformerConfigurationException, TransformerException, IOException { FilesystemXMLReader instance = new FilesystemXMLReaderRepo(); instance.setFollowSymlinks(false); XMLFilter inclRepoContents = new IncludeRepoContentsXMLFilter(); inclRepoContents.setParent(instance); File rootFile = new File("/repo/3"); TransformerFactory tf = TransformerFactory.newInstance(TRANSFORMER_FACTORY_CLASS, null); Transformer t = tf.newTransformer(); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.transform(new SAXSource(inclRepoContents, new InputSource(rootFile.getAbsolutePath())), new StreamResult(System.out)); } private static final String DFLAT_MARKER = "0=dflat";
private static final Element root = new Element("repoRoot");
upenn-libraries/xmlaminar
parallel/src/main/java/edu/upenn/library/xmlaminar/parallel/callback/BaseRelativeIncrementingFileCalback.java
// Path: core/src/main/java/edu/upenn/library/xmlaminar/VolatileSAXSource.java // public class VolatileSAXSource extends SAXSource { // // private volatile XMLReader reader; // private volatile InputSource inputSource; // // public VolatileSAXSource() { // } // // public VolatileSAXSource(XMLReader reader, InputSource inputSource) { // this.reader = reader; // this.inputSource = inputSource; // } // // public VolatileSAXSource(InputSource inputSource) { // this(null, inputSource); // } // // @Override // public void setXMLReader(XMLReader reader) { // this.reader = reader; // } // // @Override // public XMLReader getXMLReader() { // return reader; // } // // @Override // public void setInputSource(InputSource inputSource) { // this.inputSource = inputSource; // } // // @Override // public InputSource getInputSource() { // return inputSource; // } // // @Override // public void setSystemId(String systemId) { // if (inputSource == null) { // inputSource = new InputSource(systemId); // } else { // inputSource.setSystemId(systemId); // } // } // // @Override // public String getSystemId() { // return inputSource == null ? null : inputSource.getSystemId(); // } // // }
import edu.upenn.library.xmlaminar.VolatileSAXSource; import java.io.File; import java.io.IOException; import javax.xml.transform.Transformer; import javax.xml.transform.sax.SAXSource; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLFilter;
/* * Copyright 2011-2015 The Trustees of the University of Pennsylvania * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.upenn.library.xmlaminar.parallel.callback; /** * * @author magibney */ public class BaseRelativeIncrementingFileCalback extends BaseRelativeFileCallback { private final int suffixLength; public BaseRelativeIncrementingFileCalback(File inputBase, File outputBase, Transformer t, String outputExtension, boolean replaceExtension, int suffixLength, XMLFilter outputFilter, boolean gzipOutput) { super(inputBase, outputBase, t, outputExtension, replaceExtension, gzipOutput); this.suffixLength = suffixLength; this.ifc = new IncrementingFileCallback(0, t, suffixLength, outputFilter, gzipOutput); } public BaseRelativeIncrementingFileCalback(File inputBase, File outputBase, Transformer t, String outputExtension, int suffixLength, XMLFilter outputFilter, boolean gzipOutput) { super(inputBase, outputBase, t, outputExtension, gzipOutput); this.suffixLength = suffixLength; this.ifc = new IncrementingFileCallback(0, t, suffixLength, outputFilter, gzipOutput); } public BaseRelativeIncrementingFileCalback(File inputBase, File outputBase, Transformer t, int suffixLength, XMLFilter outputFilter, boolean gzipOutput) { super(inputBase, outputBase, t, gzipOutput); this.suffixLength = suffixLength; this.ifc = new IncrementingFileCallback(0, t, suffixLength, outputFilter, gzipOutput); } private final IncrementingFileCallback ifc; private String lastPath; @Override
// Path: core/src/main/java/edu/upenn/library/xmlaminar/VolatileSAXSource.java // public class VolatileSAXSource extends SAXSource { // // private volatile XMLReader reader; // private volatile InputSource inputSource; // // public VolatileSAXSource() { // } // // public VolatileSAXSource(XMLReader reader, InputSource inputSource) { // this.reader = reader; // this.inputSource = inputSource; // } // // public VolatileSAXSource(InputSource inputSource) { // this(null, inputSource); // } // // @Override // public void setXMLReader(XMLReader reader) { // this.reader = reader; // } // // @Override // public XMLReader getXMLReader() { // return reader; // } // // @Override // public void setInputSource(InputSource inputSource) { // this.inputSource = inputSource; // } // // @Override // public InputSource getInputSource() { // return inputSource; // } // // @Override // public void setSystemId(String systemId) { // if (inputSource == null) { // inputSource = new InputSource(systemId); // } else { // inputSource.setSystemId(systemId); // } // } // // @Override // public String getSystemId() { // return inputSource == null ? null : inputSource.getSystemId(); // } // // } // Path: parallel/src/main/java/edu/upenn/library/xmlaminar/parallel/callback/BaseRelativeIncrementingFileCalback.java import edu.upenn.library.xmlaminar.VolatileSAXSource; import java.io.File; import java.io.IOException; import javax.xml.transform.Transformer; import javax.xml.transform.sax.SAXSource; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLFilter; /* * Copyright 2011-2015 The Trustees of the University of Pennsylvania * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.upenn.library.xmlaminar.parallel.callback; /** * * @author magibney */ public class BaseRelativeIncrementingFileCalback extends BaseRelativeFileCallback { private final int suffixLength; public BaseRelativeIncrementingFileCalback(File inputBase, File outputBase, Transformer t, String outputExtension, boolean replaceExtension, int suffixLength, XMLFilter outputFilter, boolean gzipOutput) { super(inputBase, outputBase, t, outputExtension, replaceExtension, gzipOutput); this.suffixLength = suffixLength; this.ifc = new IncrementingFileCallback(0, t, suffixLength, outputFilter, gzipOutput); } public BaseRelativeIncrementingFileCalback(File inputBase, File outputBase, Transformer t, String outputExtension, int suffixLength, XMLFilter outputFilter, boolean gzipOutput) { super(inputBase, outputBase, t, outputExtension, gzipOutput); this.suffixLength = suffixLength; this.ifc = new IncrementingFileCallback(0, t, suffixLength, outputFilter, gzipOutput); } public BaseRelativeIncrementingFileCalback(File inputBase, File outputBase, Transformer t, int suffixLength, XMLFilter outputFilter, boolean gzipOutput) { super(inputBase, outputBase, t, gzipOutput); this.suffixLength = suffixLength; this.ifc = new IncrementingFileCallback(0, t, suffixLength, outputFilter, gzipOutput); } private final IncrementingFileCallback ifc; private String lastPath; @Override
public void callback(VolatileSAXSource source) throws SAXException, IOException {
upenn-libraries/xmlaminar
cli/src/main/java/edu/upenn/library/xmlaminar/cli/Driver.java
// Path: core/src/main/java/edu/upenn/library/xmlaminar/SAXProperties.java // public class SAXProperties { // public static final String EXECUTOR_SERVICE_PROPERTY_NAME = "http://concurrent.util.java/ExecutorService"; // public static final String DATA_SOURCE_FACTORY_PROPERTY_NAME = "http://dbxml.xmlaminar.library.upenn.edu/DataSourceFactory"; // } // // Path: core/src/main/java/edu/upenn/library/xmlaminar/dbxml/DataSourceFactory.java // public interface DataSourceFactory { // DataSource newDataSource(String name, String psSQL); // }
import edu.upenn.library.xmlaminar.SAXProperties; import edu.upenn.library.xmlaminar.dbxml.DataSourceFactory; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Level; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.sax.SAXSource; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.PatternLayout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLFilter; import org.xml.sax.XMLReader;
} else { if (child == null) { command.printHelpOn(System.err); return null; } if (last && localLast && !command.handlesOutput()) { localLast = false; iter = Collections.singletonMap((CommandFactory) ocf, new String[0]).entrySet().iterator(); } maxType = updateType(maxType, command.getCommandType()); getRootParent(child).setParent(previous); previous = child; } } return new XMLFilterSource(previous, in, inputBase, maxType, command.handlesOutput(), command.inputHandler()); } else { System.err.println("For help with a specific command: " + LS + "\t--command --help"+LS +"available commands: "+LS +"\t"+CommandFactory.getAvailableCommandFactories().keySet()); return null; } } private static void initLog4j() { PatternLayout layout = new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN); ConsoleAppender appender = new ConsoleAppender(layout, ConsoleAppender.SYSTEM_ERR); BasicConfigurator.configure(appender); }
// Path: core/src/main/java/edu/upenn/library/xmlaminar/SAXProperties.java // public class SAXProperties { // public static final String EXECUTOR_SERVICE_PROPERTY_NAME = "http://concurrent.util.java/ExecutorService"; // public static final String DATA_SOURCE_FACTORY_PROPERTY_NAME = "http://dbxml.xmlaminar.library.upenn.edu/DataSourceFactory"; // } // // Path: core/src/main/java/edu/upenn/library/xmlaminar/dbxml/DataSourceFactory.java // public interface DataSourceFactory { // DataSource newDataSource(String name, String psSQL); // } // Path: cli/src/main/java/edu/upenn/library/xmlaminar/cli/Driver.java import edu.upenn.library.xmlaminar.SAXProperties; import edu.upenn.library.xmlaminar.dbxml.DataSourceFactory; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Level; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.sax.SAXSource; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.PatternLayout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLFilter; import org.xml.sax.XMLReader; } else { if (child == null) { command.printHelpOn(System.err); return null; } if (last && localLast && !command.handlesOutput()) { localLast = false; iter = Collections.singletonMap((CommandFactory) ocf, new String[0]).entrySet().iterator(); } maxType = updateType(maxType, command.getCommandType()); getRootParent(child).setParent(previous); previous = child; } } return new XMLFilterSource(previous, in, inputBase, maxType, command.handlesOutput(), command.inputHandler()); } else { System.err.println("For help with a specific command: " + LS + "\t--command --help"+LS +"available commands: "+LS +"\t"+CommandFactory.getAvailableCommandFactories().keySet()); return null; } } private static void initLog4j() { PatternLayout layout = new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN); ConsoleAppender appender = new ConsoleAppender(layout, ConsoleAppender.SYSTEM_ERR); BasicConfigurator.configure(appender); }
public XMLReader newXMLReader(List<String> args, ExecutorService executor, DataSourceFactory dsf) throws IOException {
upenn-libraries/xmlaminar
cli/src/main/java/edu/upenn/library/xmlaminar/cli/Driver.java
// Path: core/src/main/java/edu/upenn/library/xmlaminar/SAXProperties.java // public class SAXProperties { // public static final String EXECUTOR_SERVICE_PROPERTY_NAME = "http://concurrent.util.java/ExecutorService"; // public static final String DATA_SOURCE_FACTORY_PROPERTY_NAME = "http://dbxml.xmlaminar.library.upenn.edu/DataSourceFactory"; // } // // Path: core/src/main/java/edu/upenn/library/xmlaminar/dbxml/DataSourceFactory.java // public interface DataSourceFactory { // DataSource newDataSource(String name, String psSQL); // }
import edu.upenn.library.xmlaminar.SAXProperties; import edu.upenn.library.xmlaminar.dbxml.DataSourceFactory; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Level; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.sax.SAXSource; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.PatternLayout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLFilter; import org.xml.sax.XMLReader;
getRootParent(child).setParent(previous); previous = child; } } return new XMLFilterSource(previous, in, inputBase, maxType, command.handlesOutput(), command.inputHandler()); } else { System.err.println("For help with a specific command: " + LS + "\t--command --help"+LS +"available commands: "+LS +"\t"+CommandFactory.getAvailableCommandFactories().keySet()); return null; } } private static void initLog4j() { PatternLayout layout = new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN); ConsoleAppender appender = new ConsoleAppender(layout, ConsoleAppender.SYSTEM_ERR); BasicConfigurator.configure(appender); } public XMLReader newXMLReader(List<String> args, ExecutorService executor, DataSourceFactory dsf) throws IOException { Map<String, CommandFactory> cfs = CommandFactory.getAvailableCommandFactories(); Iterable<Map.Entry<CommandFactory, String[]>> commands = buildCommandList(args.toArray(new String[args.size()]), cfs); Iterator<Map.Entry<CommandFactory, String[]>> iter = commands.iterator(); SAXSource source = chainCommands(true, null, iter, true); if (source == null) { return null; } else { XMLReader xmlReader = source.getXMLReader(); try {
// Path: core/src/main/java/edu/upenn/library/xmlaminar/SAXProperties.java // public class SAXProperties { // public static final String EXECUTOR_SERVICE_PROPERTY_NAME = "http://concurrent.util.java/ExecutorService"; // public static final String DATA_SOURCE_FACTORY_PROPERTY_NAME = "http://dbxml.xmlaminar.library.upenn.edu/DataSourceFactory"; // } // // Path: core/src/main/java/edu/upenn/library/xmlaminar/dbxml/DataSourceFactory.java // public interface DataSourceFactory { // DataSource newDataSource(String name, String psSQL); // } // Path: cli/src/main/java/edu/upenn/library/xmlaminar/cli/Driver.java import edu.upenn.library.xmlaminar.SAXProperties; import edu.upenn.library.xmlaminar.dbxml.DataSourceFactory; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Level; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.sax.SAXSource; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.PatternLayout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLFilter; import org.xml.sax.XMLReader; getRootParent(child).setParent(previous); previous = child; } } return new XMLFilterSource(previous, in, inputBase, maxType, command.handlesOutput(), command.inputHandler()); } else { System.err.println("For help with a specific command: " + LS + "\t--command --help"+LS +"available commands: "+LS +"\t"+CommandFactory.getAvailableCommandFactories().keySet()); return null; } } private static void initLog4j() { PatternLayout layout = new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN); ConsoleAppender appender = new ConsoleAppender(layout, ConsoleAppender.SYSTEM_ERR); BasicConfigurator.configure(appender); } public XMLReader newXMLReader(List<String> args, ExecutorService executor, DataSourceFactory dsf) throws IOException { Map<String, CommandFactory> cfs = CommandFactory.getAvailableCommandFactories(); Iterable<Map.Entry<CommandFactory, String[]>> commands = buildCommandList(args.toArray(new String[args.size()]), cfs); Iterator<Map.Entry<CommandFactory, String[]>> iter = commands.iterator(); SAXSource source = chainCommands(true, null, iter, true); if (source == null) { return null; } else { XMLReader xmlReader = source.getXMLReader(); try {
xmlReader.setProperty(SAXProperties.EXECUTOR_SERVICE_PROPERTY_NAME, executor);
upenn-libraries/xmlaminar
core/src/main/java/edu/upenn/library/xmlaminar/dbxml/RSXMLReader.java
// Path: core/src/main/java/edu/upenn/library/xmlaminar/SAXFeatures.java // public class SAXFeatures { // public static final String NAMESPACES = "http://xml.org/sax/features/namespaces"; // public static final String NAMESPACE_PREFIXES = "http://xml.org/sax/features/namespace-prefixes"; // public static final String STRING_INTERNING = "http://xml.org/sax/features/string-interning"; // public static final String VALIDATION = "http://xml.org/sax/features/validation"; // public static final String EXTERNAL_GENERAL_ENTITIES = "http://xml.org/sax/features/external-general-entities"; // public static final String EXTERNAL_PARAMETER_ENTITIES = "http://xml.org/sax/features/external-parameter-entities"; // } // // Path: core/src/main/java/edu/upenn/library/xmlaminar/XMLInputValidator.java // public static void writeSanitizedXMLCharacters(char[] cbuf, int off, int len, ContentHandler ch) throws SAXException { // sanitizeXMLCharacters(cbuf, off, len); // ch.characters(cbuf, off, len); // }
import edu.upenn.library.xmlaminar.SAXFeatures; import static edu.upenn.library.xmlaminar.XMLInputValidator.writeSanitizedXMLCharacters; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.HashMap; import java.util.Map; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.stream.StreamResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl;
/* * Copyright 2011-2015 The Trustees of the University of Pennsylvania * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.upenn.library.xmlaminar.dbxml; /** * * @author michael */ public class RSXMLReader extends SQLXMLReader { private final char[] characters = new char[2048]; private final AttributesImpl attRunner = new AttributesImpl(); private static final Logger logger = LoggerFactory.getLogger(RSXMLReader.class); private static final Map<String, Boolean> unmodifiableFeatures = new HashMap<String, Boolean>(); static {
// Path: core/src/main/java/edu/upenn/library/xmlaminar/SAXFeatures.java // public class SAXFeatures { // public static final String NAMESPACES = "http://xml.org/sax/features/namespaces"; // public static final String NAMESPACE_PREFIXES = "http://xml.org/sax/features/namespace-prefixes"; // public static final String STRING_INTERNING = "http://xml.org/sax/features/string-interning"; // public static final String VALIDATION = "http://xml.org/sax/features/validation"; // public static final String EXTERNAL_GENERAL_ENTITIES = "http://xml.org/sax/features/external-general-entities"; // public static final String EXTERNAL_PARAMETER_ENTITIES = "http://xml.org/sax/features/external-parameter-entities"; // } // // Path: core/src/main/java/edu/upenn/library/xmlaminar/XMLInputValidator.java // public static void writeSanitizedXMLCharacters(char[] cbuf, int off, int len, ContentHandler ch) throws SAXException { // sanitizeXMLCharacters(cbuf, off, len); // ch.characters(cbuf, off, len); // } // Path: core/src/main/java/edu/upenn/library/xmlaminar/dbxml/RSXMLReader.java import edu.upenn.library.xmlaminar.SAXFeatures; import static edu.upenn.library.xmlaminar.XMLInputValidator.writeSanitizedXMLCharacters; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.HashMap; import java.util.Map; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.stream.StreamResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /* * Copyright 2011-2015 The Trustees of the University of Pennsylvania * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.upenn.library.xmlaminar.dbxml; /** * * @author michael */ public class RSXMLReader extends SQLXMLReader { private final char[] characters = new char[2048]; private final AttributesImpl attRunner = new AttributesImpl(); private static final Logger logger = LoggerFactory.getLogger(RSXMLReader.class); private static final Map<String, Boolean> unmodifiableFeatures = new HashMap<String, Boolean>(); static {
unmodifiableFeatures.put(SAXFeatures.NAMESPACES, true);
upenn-libraries/xmlaminar
core/src/main/java/edu/upenn/library/xmlaminar/dbxml/RSXMLReader.java
// Path: core/src/main/java/edu/upenn/library/xmlaminar/SAXFeatures.java // public class SAXFeatures { // public static final String NAMESPACES = "http://xml.org/sax/features/namespaces"; // public static final String NAMESPACE_PREFIXES = "http://xml.org/sax/features/namespace-prefixes"; // public static final String STRING_INTERNING = "http://xml.org/sax/features/string-interning"; // public static final String VALIDATION = "http://xml.org/sax/features/validation"; // public static final String EXTERNAL_GENERAL_ENTITIES = "http://xml.org/sax/features/external-general-entities"; // public static final String EXTERNAL_PARAMETER_ENTITIES = "http://xml.org/sax/features/external-parameter-entities"; // } // // Path: core/src/main/java/edu/upenn/library/xmlaminar/XMLInputValidator.java // public static void writeSanitizedXMLCharacters(char[] cbuf, int off, int len, ContentHandler ch) throws SAXException { // sanitizeXMLCharacters(cbuf, off, len); // ch.characters(cbuf, off, len); // }
import edu.upenn.library.xmlaminar.SAXFeatures; import static edu.upenn.library.xmlaminar.XMLInputValidator.writeSanitizedXMLCharacters; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.HashMap; import java.util.Map; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.stream.StreamResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl;
/* * Copyright 2011-2015 The Trustees of the University of Pennsylvania * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.upenn.library.xmlaminar.dbxml; /** * * @author michael */ public class RSXMLReader extends SQLXMLReader { private final char[] characters = new char[2048]; private final AttributesImpl attRunner = new AttributesImpl(); private static final Logger logger = LoggerFactory.getLogger(RSXMLReader.class); private static final Map<String, Boolean> unmodifiableFeatures = new HashMap<String, Boolean>(); static { unmodifiableFeatures.put(SAXFeatures.NAMESPACES, true); unmodifiableFeatures.put(SAXFeatures.NAMESPACE_PREFIXES, false); unmodifiableFeatures.put(SAXFeatures.STRING_INTERNING, true); unmodifiableFeatures.put(SAXFeatures.VALIDATION, false); } public RSXMLReader() { super(InputImplementation.CHAR_ARRAY, unmodifiableFeatures); } public RSXMLReader(int batchSize, int lookaheadFactor) { super(InputImplementation.CHAR_ARRAY, unmodifiableFeatures, batchSize, lookaheadFactor); } @Override protected void outputFieldAsSAXEvents(long selfId, String fieldLabel, char[] content, int endIndex) throws SAXException, IOException { if (content != null) { ch.startElement("", fieldLabel, fieldLabel, attRunner);
// Path: core/src/main/java/edu/upenn/library/xmlaminar/SAXFeatures.java // public class SAXFeatures { // public static final String NAMESPACES = "http://xml.org/sax/features/namespaces"; // public static final String NAMESPACE_PREFIXES = "http://xml.org/sax/features/namespace-prefixes"; // public static final String STRING_INTERNING = "http://xml.org/sax/features/string-interning"; // public static final String VALIDATION = "http://xml.org/sax/features/validation"; // public static final String EXTERNAL_GENERAL_ENTITIES = "http://xml.org/sax/features/external-general-entities"; // public static final String EXTERNAL_PARAMETER_ENTITIES = "http://xml.org/sax/features/external-parameter-entities"; // } // // Path: core/src/main/java/edu/upenn/library/xmlaminar/XMLInputValidator.java // public static void writeSanitizedXMLCharacters(char[] cbuf, int off, int len, ContentHandler ch) throws SAXException { // sanitizeXMLCharacters(cbuf, off, len); // ch.characters(cbuf, off, len); // } // Path: core/src/main/java/edu/upenn/library/xmlaminar/dbxml/RSXMLReader.java import edu.upenn.library.xmlaminar.SAXFeatures; import static edu.upenn.library.xmlaminar.XMLInputValidator.writeSanitizedXMLCharacters; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.HashMap; import java.util.Map; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.stream.StreamResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /* * Copyright 2011-2015 The Trustees of the University of Pennsylvania * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.upenn.library.xmlaminar.dbxml; /** * * @author michael */ public class RSXMLReader extends SQLXMLReader { private final char[] characters = new char[2048]; private final AttributesImpl attRunner = new AttributesImpl(); private static final Logger logger = LoggerFactory.getLogger(RSXMLReader.class); private static final Map<String, Boolean> unmodifiableFeatures = new HashMap<String, Boolean>(); static { unmodifiableFeatures.put(SAXFeatures.NAMESPACES, true); unmodifiableFeatures.put(SAXFeatures.NAMESPACE_PREFIXES, false); unmodifiableFeatures.put(SAXFeatures.STRING_INTERNING, true); unmodifiableFeatures.put(SAXFeatures.VALIDATION, false); } public RSXMLReader() { super(InputImplementation.CHAR_ARRAY, unmodifiableFeatures); } public RSXMLReader(int batchSize, int lookaheadFactor) { super(InputImplementation.CHAR_ARRAY, unmodifiableFeatures, batchSize, lookaheadFactor); } @Override protected void outputFieldAsSAXEvents(long selfId, String fieldLabel, char[] content, int endIndex) throws SAXException, IOException { if (content != null) { ch.startElement("", fieldLabel, fieldLabel, attRunner);
writeSanitizedXMLCharacters(content, 0, endIndex, ch);
upenn-libraries/xmlaminar
parallel/src/main/java/edu/upenn/library/xmlaminar/parallel/callback/BaseRelativeFileCallback.java
// Path: core/src/main/java/edu/upenn/library/xmlaminar/VolatileSAXSource.java // public class VolatileSAXSource extends SAXSource { // // private volatile XMLReader reader; // private volatile InputSource inputSource; // // public VolatileSAXSource() { // } // // public VolatileSAXSource(XMLReader reader, InputSource inputSource) { // this.reader = reader; // this.inputSource = inputSource; // } // // public VolatileSAXSource(InputSource inputSource) { // this(null, inputSource); // } // // @Override // public void setXMLReader(XMLReader reader) { // this.reader = reader; // } // // @Override // public XMLReader getXMLReader() { // return reader; // } // // @Override // public void setInputSource(InputSource inputSource) { // this.inputSource = inputSource; // } // // @Override // public InputSource getInputSource() { // return inputSource; // } // // @Override // public void setSystemId(String systemId) { // if (inputSource == null) { // inputSource = new InputSource(systemId); // } else { // inputSource.setSystemId(systemId); // } // } // // @Override // public String getSystemId() { // return inputSource == null ? null : inputSource.getSystemId(); // } // // }
import edu.upenn.library.xmlaminar.VolatileSAXSource; import java.io.File; import java.io.IOException; import java.nio.file.Path; import javax.xml.transform.Transformer; import javax.xml.transform.sax.SAXSource; import org.xml.sax.SAXException;
private final Transformer t; protected final String outputExtension; protected final boolean replaceExtension; private final boolean gzipOutput; private Path validateBase(File file) { if (!file.isDirectory()) { throw new IllegalArgumentException("base file must be a directory: "+file.getAbsolutePath()); } return file.getAbsoluteFile().toPath().normalize(); } public BaseRelativeFileCallback(File inputBase, File outputBase, Transformer t, String outputExtension, boolean replaceExtension, boolean gzipOutput) { this.inputBase = validateBase(inputBase); this.outputBase = validateBase(outputBase); this.t = t; this.outputExtension = (outputExtension == null ? null : ".".concat(outputExtension)); this.replaceExtension = replaceExtension; this.gzipOutput = gzipOutput; } public BaseRelativeFileCallback(File inputBase, File outputBase, Transformer t, String outputExtension, boolean gzipOutput) { this(inputBase, outputBase, t, outputExtension, DEFAULT_REPLACE_EXTENSION, gzipOutput); } public BaseRelativeFileCallback(File inputBase, File outputBase, Transformer t, boolean gzipOutput) { this(inputBase, outputBase, t, DEFAULT_OUTPUT_EXTENSION, gzipOutput); } @Override
// Path: core/src/main/java/edu/upenn/library/xmlaminar/VolatileSAXSource.java // public class VolatileSAXSource extends SAXSource { // // private volatile XMLReader reader; // private volatile InputSource inputSource; // // public VolatileSAXSource() { // } // // public VolatileSAXSource(XMLReader reader, InputSource inputSource) { // this.reader = reader; // this.inputSource = inputSource; // } // // public VolatileSAXSource(InputSource inputSource) { // this(null, inputSource); // } // // @Override // public void setXMLReader(XMLReader reader) { // this.reader = reader; // } // // @Override // public XMLReader getXMLReader() { // return reader; // } // // @Override // public void setInputSource(InputSource inputSource) { // this.inputSource = inputSource; // } // // @Override // public InputSource getInputSource() { // return inputSource; // } // // @Override // public void setSystemId(String systemId) { // if (inputSource == null) { // inputSource = new InputSource(systemId); // } else { // inputSource.setSystemId(systemId); // } // } // // @Override // public String getSystemId() { // return inputSource == null ? null : inputSource.getSystemId(); // } // // } // Path: parallel/src/main/java/edu/upenn/library/xmlaminar/parallel/callback/BaseRelativeFileCallback.java import edu.upenn.library.xmlaminar.VolatileSAXSource; import java.io.File; import java.io.IOException; import java.nio.file.Path; import javax.xml.transform.Transformer; import javax.xml.transform.sax.SAXSource; import org.xml.sax.SAXException; private final Transformer t; protected final String outputExtension; protected final boolean replaceExtension; private final boolean gzipOutput; private Path validateBase(File file) { if (!file.isDirectory()) { throw new IllegalArgumentException("base file must be a directory: "+file.getAbsolutePath()); } return file.getAbsoluteFile().toPath().normalize(); } public BaseRelativeFileCallback(File inputBase, File outputBase, Transformer t, String outputExtension, boolean replaceExtension, boolean gzipOutput) { this.inputBase = validateBase(inputBase); this.outputBase = validateBase(outputBase); this.t = t; this.outputExtension = (outputExtension == null ? null : ".".concat(outputExtension)); this.replaceExtension = replaceExtension; this.gzipOutput = gzipOutput; } public BaseRelativeFileCallback(File inputBase, File outputBase, Transformer t, String outputExtension, boolean gzipOutput) { this(inputBase, outputBase, t, outputExtension, DEFAULT_REPLACE_EXTENSION, gzipOutput); } public BaseRelativeFileCallback(File inputBase, File outputBase, Transformer t, boolean gzipOutput) { this(inputBase, outputBase, t, DEFAULT_OUTPUT_EXTENSION, gzipOutput); } @Override
public void callback(VolatileSAXSource source) throws SAXException, IOException {
upenn-libraries/xmlaminar
core/src/main/java/edu/upenn/library/xmlaminar/fsxml/IncludeRepoContentsXMLFilter.java
// Path: core/src/main/java/edu/upenn/library/xmlaminar/DocEventIgnorer.java // public class DocEventIgnorer extends XMLFilterImpl { // // @Override // public void endDocument() throws SAXException { // } // // @Override // public void startDocument() throws SAXException { // } // // } // // Path: core/src/main/java/edu/upenn/library/xmlaminar/XMLInputValidator.java // public class XMLInputValidator extends FilterReader { // // private static final char REPLACEMENT = Charset.forName("UTF-8").newDecoder().replacement().charAt(0); // // public XMLInputValidator(Reader wrapped) { // super(wrapped); // } // // @Override // public int read(char[] cbuf, int off, int len) throws IOException { // int toReturn = super.read(cbuf, off, len); // sanitizeXMLCharacters(cbuf, off, toReturn); // return toReturn; // } // // public static boolean isValidXMLCharacter(int c) { // return is16BitXMLCharacter(c) || isHighXMLCharacter(c); // } // // public static boolean is16BitXMLCharacter(int c) { // return (c >= 0x20 && c <= 0xD7FF) || (c >= 0xE000 && c <= 0xFFFD) // || c == 0xD || c == 0xA || c == 0x9; // } // // public static boolean isHighXMLCharacter(int c) { // return c >= 0x10000 && c <= 0x10FFFF; // } // // public static char[] sanitizeXMLCharacters(char[] cbuf, int off, int len) { // int max = off + len; // char c; // char lowSurrogate; // int nextIndex; // for (int i = off; i < max; i++) { // c = cbuf[i]; // if (Character.isHighSurrogate(c) && (nextIndex = i + 1) < max // && Character.isLowSurrogate((lowSurrogate = cbuf[nextIndex]))) { // int codePoint = Character.toCodePoint(c, lowSurrogate); // if (!isHighXMLCharacter(codePoint)) { // cbuf[i] = REPLACEMENT; // cbuf[nextIndex] = REPLACEMENT; // } // i = nextIndex; // } else if (!is16BitXMLCharacter(c)) { // cbuf[i] = REPLACEMENT; // } // } // return cbuf; // } // // public static void writeSanitizedXMLCharacters(char[] cbuf, int off, int len, ContentHandler ch) throws SAXException { // sanitizeXMLCharacters(cbuf, off, len); // ch.characters(cbuf, off, len); // } // // @Override // public int read() throws IOException { // int c = super.read(); // return (is16BitXMLCharacter(c) ? c : REPLACEMENT); // } // }
import edu.upenn.library.xmlaminar.DocEventIgnorer; import edu.upenn.library.xmlaminar.XMLInputValidator; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLFilter; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl;
/* * Copyright 2011-2015 The Trustees of the University of Pennsylvania * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.upenn.library.xmlaminar.fsxml; /** * * @author Michael Gibney */ public class IncludeRepoContentsXMLFilter extends XMLFilterImpl { private final SAXParserFactory spf = SAXParserFactory.newInstance(); private SAXParser parser;
// Path: core/src/main/java/edu/upenn/library/xmlaminar/DocEventIgnorer.java // public class DocEventIgnorer extends XMLFilterImpl { // // @Override // public void endDocument() throws SAXException { // } // // @Override // public void startDocument() throws SAXException { // } // // } // // Path: core/src/main/java/edu/upenn/library/xmlaminar/XMLInputValidator.java // public class XMLInputValidator extends FilterReader { // // private static final char REPLACEMENT = Charset.forName("UTF-8").newDecoder().replacement().charAt(0); // // public XMLInputValidator(Reader wrapped) { // super(wrapped); // } // // @Override // public int read(char[] cbuf, int off, int len) throws IOException { // int toReturn = super.read(cbuf, off, len); // sanitizeXMLCharacters(cbuf, off, toReturn); // return toReturn; // } // // public static boolean isValidXMLCharacter(int c) { // return is16BitXMLCharacter(c) || isHighXMLCharacter(c); // } // // public static boolean is16BitXMLCharacter(int c) { // return (c >= 0x20 && c <= 0xD7FF) || (c >= 0xE000 && c <= 0xFFFD) // || c == 0xD || c == 0xA || c == 0x9; // } // // public static boolean isHighXMLCharacter(int c) { // return c >= 0x10000 && c <= 0x10FFFF; // } // // public static char[] sanitizeXMLCharacters(char[] cbuf, int off, int len) { // int max = off + len; // char c; // char lowSurrogate; // int nextIndex; // for (int i = off; i < max; i++) { // c = cbuf[i]; // if (Character.isHighSurrogate(c) && (nextIndex = i + 1) < max // && Character.isLowSurrogate((lowSurrogate = cbuf[nextIndex]))) { // int codePoint = Character.toCodePoint(c, lowSurrogate); // if (!isHighXMLCharacter(codePoint)) { // cbuf[i] = REPLACEMENT; // cbuf[nextIndex] = REPLACEMENT; // } // i = nextIndex; // } else if (!is16BitXMLCharacter(c)) { // cbuf[i] = REPLACEMENT; // } // } // return cbuf; // } // // public static void writeSanitizedXMLCharacters(char[] cbuf, int off, int len, ContentHandler ch) throws SAXException { // sanitizeXMLCharacters(cbuf, off, len); // ch.characters(cbuf, off, len); // } // // @Override // public int read() throws IOException { // int c = super.read(); // return (is16BitXMLCharacter(c) ? c : REPLACEMENT); // } // } // Path: core/src/main/java/edu/upenn/library/xmlaminar/fsxml/IncludeRepoContentsXMLFilter.java import edu.upenn.library.xmlaminar.DocEventIgnorer; import edu.upenn.library.xmlaminar.XMLInputValidator; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLFilter; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl; /* * Copyright 2011-2015 The Trustees of the University of Pennsylvania * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.upenn.library.xmlaminar.fsxml; /** * * @author Michael Gibney */ public class IncludeRepoContentsXMLFilter extends XMLFilterImpl { private final SAXParserFactory spf = SAXParserFactory.newInstance(); private SAXParser parser;
private final XMLFilter subReader = new DocEventIgnorer();
upenn-libraries/xmlaminar
core/src/main/java/edu/upenn/library/xmlaminar/fsxml/IncludeRepoContentsXMLFilter.java
// Path: core/src/main/java/edu/upenn/library/xmlaminar/DocEventIgnorer.java // public class DocEventIgnorer extends XMLFilterImpl { // // @Override // public void endDocument() throws SAXException { // } // // @Override // public void startDocument() throws SAXException { // } // // } // // Path: core/src/main/java/edu/upenn/library/xmlaminar/XMLInputValidator.java // public class XMLInputValidator extends FilterReader { // // private static final char REPLACEMENT = Charset.forName("UTF-8").newDecoder().replacement().charAt(0); // // public XMLInputValidator(Reader wrapped) { // super(wrapped); // } // // @Override // public int read(char[] cbuf, int off, int len) throws IOException { // int toReturn = super.read(cbuf, off, len); // sanitizeXMLCharacters(cbuf, off, toReturn); // return toReturn; // } // // public static boolean isValidXMLCharacter(int c) { // return is16BitXMLCharacter(c) || isHighXMLCharacter(c); // } // // public static boolean is16BitXMLCharacter(int c) { // return (c >= 0x20 && c <= 0xD7FF) || (c >= 0xE000 && c <= 0xFFFD) // || c == 0xD || c == 0xA || c == 0x9; // } // // public static boolean isHighXMLCharacter(int c) { // return c >= 0x10000 && c <= 0x10FFFF; // } // // public static char[] sanitizeXMLCharacters(char[] cbuf, int off, int len) { // int max = off + len; // char c; // char lowSurrogate; // int nextIndex; // for (int i = off; i < max; i++) { // c = cbuf[i]; // if (Character.isHighSurrogate(c) && (nextIndex = i + 1) < max // && Character.isLowSurrogate((lowSurrogate = cbuf[nextIndex]))) { // int codePoint = Character.toCodePoint(c, lowSurrogate); // if (!isHighXMLCharacter(codePoint)) { // cbuf[i] = REPLACEMENT; // cbuf[nextIndex] = REPLACEMENT; // } // i = nextIndex; // } else if (!is16BitXMLCharacter(c)) { // cbuf[i] = REPLACEMENT; // } // } // return cbuf; // } // // public static void writeSanitizedXMLCharacters(char[] cbuf, int off, int len, ContentHandler ch) throws SAXException { // sanitizeXMLCharacters(cbuf, off, len); // ch.characters(cbuf, off, len); // } // // @Override // public int read() throws IOException { // int c = super.read(); // return (is16BitXMLCharacter(c) ? c : REPLACEMENT); // } // }
import edu.upenn.library.xmlaminar.DocEventIgnorer; import edu.upenn.library.xmlaminar.XMLInputValidator; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLFilter; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl;
initSubReader(); super.parse(systemId); } @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { super.startElement(uri, localName, qName, atts); FilesystemXMLReader.FsxmlElement fileElement = FilesystemXMLReader.FsxmlElement.file; if (fileElement.uri.equals(uri) && fileElement.localName.equals(localName)) { FilesystemXMLReader.FsxmlAttribute absolutePathAttribute = FilesystemXMLReader.FsxmlAttribute.absolutePath; String absolutePath = atts.getValue(absolutePathAttribute.uri, absolutePathAttribute.localName); try { if (absolutePath.endsWith(".xml")) { incorporateXMLContent(absolutePath); } else if (absolutePath.endsWith(".txt") || absolutePath.endsWith(".log")) { incorporateTextContent(absolutePath); } } catch (IOException ex) { throw new RuntimeException(ex); } } } private void incorporateXMLContent(String absolutePath) throws SAXException, IOException { parser.reset(); subReader.setContentHandler(this); Reader r = new FileReader(absolutePath); try {
// Path: core/src/main/java/edu/upenn/library/xmlaminar/DocEventIgnorer.java // public class DocEventIgnorer extends XMLFilterImpl { // // @Override // public void endDocument() throws SAXException { // } // // @Override // public void startDocument() throws SAXException { // } // // } // // Path: core/src/main/java/edu/upenn/library/xmlaminar/XMLInputValidator.java // public class XMLInputValidator extends FilterReader { // // private static final char REPLACEMENT = Charset.forName("UTF-8").newDecoder().replacement().charAt(0); // // public XMLInputValidator(Reader wrapped) { // super(wrapped); // } // // @Override // public int read(char[] cbuf, int off, int len) throws IOException { // int toReturn = super.read(cbuf, off, len); // sanitizeXMLCharacters(cbuf, off, toReturn); // return toReturn; // } // // public static boolean isValidXMLCharacter(int c) { // return is16BitXMLCharacter(c) || isHighXMLCharacter(c); // } // // public static boolean is16BitXMLCharacter(int c) { // return (c >= 0x20 && c <= 0xD7FF) || (c >= 0xE000 && c <= 0xFFFD) // || c == 0xD || c == 0xA || c == 0x9; // } // // public static boolean isHighXMLCharacter(int c) { // return c >= 0x10000 && c <= 0x10FFFF; // } // // public static char[] sanitizeXMLCharacters(char[] cbuf, int off, int len) { // int max = off + len; // char c; // char lowSurrogate; // int nextIndex; // for (int i = off; i < max; i++) { // c = cbuf[i]; // if (Character.isHighSurrogate(c) && (nextIndex = i + 1) < max // && Character.isLowSurrogate((lowSurrogate = cbuf[nextIndex]))) { // int codePoint = Character.toCodePoint(c, lowSurrogate); // if (!isHighXMLCharacter(codePoint)) { // cbuf[i] = REPLACEMENT; // cbuf[nextIndex] = REPLACEMENT; // } // i = nextIndex; // } else if (!is16BitXMLCharacter(c)) { // cbuf[i] = REPLACEMENT; // } // } // return cbuf; // } // // public static void writeSanitizedXMLCharacters(char[] cbuf, int off, int len, ContentHandler ch) throws SAXException { // sanitizeXMLCharacters(cbuf, off, len); // ch.characters(cbuf, off, len); // } // // @Override // public int read() throws IOException { // int c = super.read(); // return (is16BitXMLCharacter(c) ? c : REPLACEMENT); // } // } // Path: core/src/main/java/edu/upenn/library/xmlaminar/fsxml/IncludeRepoContentsXMLFilter.java import edu.upenn.library.xmlaminar.DocEventIgnorer; import edu.upenn.library.xmlaminar.XMLInputValidator; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLFilter; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl; initSubReader(); super.parse(systemId); } @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { super.startElement(uri, localName, qName, atts); FilesystemXMLReader.FsxmlElement fileElement = FilesystemXMLReader.FsxmlElement.file; if (fileElement.uri.equals(uri) && fileElement.localName.equals(localName)) { FilesystemXMLReader.FsxmlAttribute absolutePathAttribute = FilesystemXMLReader.FsxmlAttribute.absolutePath; String absolutePath = atts.getValue(absolutePathAttribute.uri, absolutePathAttribute.localName); try { if (absolutePath.endsWith(".xml")) { incorporateXMLContent(absolutePath); } else if (absolutePath.endsWith(".txt") || absolutePath.endsWith(".log")) { incorporateTextContent(absolutePath); } } catch (IOException ex) { throw new RuntimeException(ex); } } } private void incorporateXMLContent(String absolutePath) throws SAXException, IOException { parser.reset(); subReader.setContentHandler(this); Reader r = new FileReader(absolutePath); try {
InputSource subIn = new InputSource(new XMLInputValidator(r));
upenn-libraries/xmlaminar
core/src/main/java/edu/upenn/library/xmlaminar/fsxml/FilesystemXMLReader.java
// Path: core/src/main/java/edu/upenn/library/xmlaminar/Element.java // public class Element { // // public final String uri; // public final String prefix; // public final String localName; // public final String qName; // public static final Attributes EMPTY_ATTS = new UnmodifiableAttributes(); // // public Element(String uri, String prefix, String localName) { // this.uri = uri.intern(); // this.prefix = prefix.intern(); // this.localName = localName.intern(); // if (prefix.equals("")) { // qName = this.localName; // } else { // qName = (prefix + ":" + localName).intern(); // } // } // // public Element(String localName) { // uri = ""; // prefix = ""; // qName = localName.intern(); // this.localName = localName = qName; // } // // public void start(ContentHandler ch) throws SAXException { // start(ch, EMPTY_ATTS); // } // // public void start(ContentHandler ch, Attributes atts) throws SAXException { // ch.startElement(uri, localName, qName, atts); // } // // public void end(ContentHandler ch) throws SAXException { // ch.endElement(uri, localName, qName); // } // // public static void logXML(ContentHandler ch, Element element, String message) throws SAXException { // char[] messageChars = message.toCharArray(); // element.start(ch); // ch.characters(messageChars, 0, messageChars.length); // element.end(ch); // } // // private static class UnmodifiableAttributes extends AttributesImpl { // // @Override // public void addAttribute(String uri, String localName, String qName, String type, String value) { // throw new UnsupportedOperationException(); // } // // @Override // public void setAttribute(int index, String uri, String localName, String qName, String type, String value) { // throw new UnsupportedOperationException(); // } // // @Override // public void setAttributes(Attributes atts) { // throw new UnsupportedOperationException(); // } // // @Override // public void setLocalName(int index, String localName) { // throw new UnsupportedOperationException(); // } // // @Override // public void setQName(int index, String qName) { // throw new UnsupportedOperationException(); // } // // @Override // public void setType(int index, String type) { // throw new UnsupportedOperationException(); // } // // @Override // public void setURI(int index, String uri) { // throw new UnsupportedOperationException(); // } // // @Override // public void setValue(int index, String value) { // throw new UnsupportedOperationException(); // } // // } // // }
import edu.upenn.library.xmlaminar.Element; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Stack; import javax.xml.transform.OutputKeys; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.DTDHandler; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.AttributesImpl;
/* * Copyright 2011-2015 The Trustees of the University of Pennsylvania * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.upenn.library.xmlaminar.fsxml; public abstract class FilesystemXMLReader implements XMLReader { public static final boolean DEFAULT_TOLERATE_UNREADABLE_DIRECTORIES = true; private boolean tolerateUnreadableDirectories = DEFAULT_TOLERATE_UNREADABLE_DIRECTORIES; private static final String NS_PREFIXES_FEATURE_KEY = "http://xml.org/sax/features/namespace-prefixes"; public static final String URI = "http://library.upenn.edu/fsxml"; public static final String PREFIX = "fsxml"; private static final Logger logger = LoggerFactory.getLogger(FilesystemXMLReader.class); private static final Map<String,Boolean> unmodifiableFeatures; private static final Map<String,Boolean> modifiableFeatures = new HashMap<String, Boolean>(); private static final Map<String, Object> ignorableProperties;
// Path: core/src/main/java/edu/upenn/library/xmlaminar/Element.java // public class Element { // // public final String uri; // public final String prefix; // public final String localName; // public final String qName; // public static final Attributes EMPTY_ATTS = new UnmodifiableAttributes(); // // public Element(String uri, String prefix, String localName) { // this.uri = uri.intern(); // this.prefix = prefix.intern(); // this.localName = localName.intern(); // if (prefix.equals("")) { // qName = this.localName; // } else { // qName = (prefix + ":" + localName).intern(); // } // } // // public Element(String localName) { // uri = ""; // prefix = ""; // qName = localName.intern(); // this.localName = localName = qName; // } // // public void start(ContentHandler ch) throws SAXException { // start(ch, EMPTY_ATTS); // } // // public void start(ContentHandler ch, Attributes atts) throws SAXException { // ch.startElement(uri, localName, qName, atts); // } // // public void end(ContentHandler ch) throws SAXException { // ch.endElement(uri, localName, qName); // } // // public static void logXML(ContentHandler ch, Element element, String message) throws SAXException { // char[] messageChars = message.toCharArray(); // element.start(ch); // ch.characters(messageChars, 0, messageChars.length); // element.end(ch); // } // // private static class UnmodifiableAttributes extends AttributesImpl { // // @Override // public void addAttribute(String uri, String localName, String qName, String type, String value) { // throw new UnsupportedOperationException(); // } // // @Override // public void setAttribute(int index, String uri, String localName, String qName, String type, String value) { // throw new UnsupportedOperationException(); // } // // @Override // public void setAttributes(Attributes atts) { // throw new UnsupportedOperationException(); // } // // @Override // public void setLocalName(int index, String localName) { // throw new UnsupportedOperationException(); // } // // @Override // public void setQName(int index, String qName) { // throw new UnsupportedOperationException(); // } // // @Override // public void setType(int index, String type) { // throw new UnsupportedOperationException(); // } // // @Override // public void setURI(int index, String uri) { // throw new UnsupportedOperationException(); // } // // @Override // public void setValue(int index, String value) { // throw new UnsupportedOperationException(); // } // // } // // } // Path: core/src/main/java/edu/upenn/library/xmlaminar/fsxml/FilesystemXMLReader.java import edu.upenn.library.xmlaminar.Element; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Stack; import javax.xml.transform.OutputKeys; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.DTDHandler; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.AttributesImpl; /* * Copyright 2011-2015 The Trustees of the University of Pennsylvania * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.upenn.library.xmlaminar.fsxml; public abstract class FilesystemXMLReader implements XMLReader { public static final boolean DEFAULT_TOLERATE_UNREADABLE_DIRECTORIES = true; private boolean tolerateUnreadableDirectories = DEFAULT_TOLERATE_UNREADABLE_DIRECTORIES; private static final String NS_PREFIXES_FEATURE_KEY = "http://xml.org/sax/features/namespace-prefixes"; public static final String URI = "http://library.upenn.edu/fsxml"; public static final String PREFIX = "fsxml"; private static final Logger logger = LoggerFactory.getLogger(FilesystemXMLReader.class); private static final Map<String,Boolean> unmodifiableFeatures; private static final Map<String,Boolean> modifiableFeatures = new HashMap<String, Boolean>(); private static final Map<String, Object> ignorableProperties;
private final Element root;
upenn-libraries/xmlaminar
cli/src/main/java/edu/upenn/library/xmlaminar/cli/OutputTransformerConfigurer.java
// Path: parallel/src/main/java/edu/upenn/library/xmlaminar/parallel/TXMLFilter.java // public static final String OUTPUT_TRANSFORMER_PROPERTY_NAME = "http://transform.xml.javax/Transformer#outputTransformer";
import static edu.upenn.library.xmlaminar.parallel.TXMLFilter.OUTPUT_TRANSFORMER_PROPERTY_NAME; import java.util.Map; import javax.xml.transform.Transformer; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl;
/* * Copyright 2011-2015 The Trustees of the University of Pennsylvania * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.upenn.library.xmlaminar.cli; /** * * @author magibney */ public class OutputTransformerConfigurer extends XMLFilterImpl { private final Map<String, String> outputProperties; public OutputTransformerConfigurer() { this(null, null); } public OutputTransformerConfigurer(XMLReader parent) { this(parent, null); } public OutputTransformerConfigurer(Map<String, String> outputProperties) { this(null, outputProperties); } public OutputTransformerConfigurer(XMLReader parent, Map<String, String> outputProperties) { super(parent); this.outputProperties = outputProperties; } @Override public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException { try { super.setProperty(name, value); } catch (SAXNotRecognizedException ex) {
// Path: parallel/src/main/java/edu/upenn/library/xmlaminar/parallel/TXMLFilter.java // public static final String OUTPUT_TRANSFORMER_PROPERTY_NAME = "http://transform.xml.javax/Transformer#outputTransformer"; // Path: cli/src/main/java/edu/upenn/library/xmlaminar/cli/OutputTransformerConfigurer.java import static edu.upenn.library.xmlaminar.parallel.TXMLFilter.OUTPUT_TRANSFORMER_PROPERTY_NAME; import java.util.Map; import javax.xml.transform.Transformer; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl; /* * Copyright 2011-2015 The Trustees of the University of Pennsylvania * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.upenn.library.xmlaminar.cli; /** * * @author magibney */ public class OutputTransformerConfigurer extends XMLFilterImpl { private final Map<String, String> outputProperties; public OutputTransformerConfigurer() { this(null, null); } public OutputTransformerConfigurer(XMLReader parent) { this(parent, null); } public OutputTransformerConfigurer(Map<String, String> outputProperties) { this(null, outputProperties); } public OutputTransformerConfigurer(XMLReader parent, Map<String, String> outputProperties) { super(parent); this.outputProperties = outputProperties; } @Override public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException { try { super.setProperty(name, value); } catch (SAXNotRecognizedException ex) {
if (!OUTPUT_TRANSFORMER_PROPERTY_NAME.equals(name)) {
dumptruckman/ChestRestock
src/main/java/com/dumptruckman/chestrestock/Players.java
// Path: src/main/java/com/dumptruckman/chestrestock/api/CRPlayer.java // public interface CRPlayer { // // /** // * @return The number of times the player has caused the chest to restock. // */ // int getLootCount(); // // /** // * @return The time at which the player last caused the chest to restock. // */ // long getLastRestockTime(); // // /** // * Sets the number of times a player has caused the chest to restock. // * // * @param count The number of times a player has caused the chest to restock. // */ // void setLootCount(int count); // // /** // * Sets the time at which the player last caused the chest to restock. // * // * @param time The time at which the player last caused the chest to restock. // */ // void setLastRestockTime(long time); // }
import com.dumptruckman.chestrestock.api.CRPlayer;
package com.dumptruckman.chestrestock; public final class Players { private Players() { throw new AssertionError(); }
// Path: src/main/java/com/dumptruckman/chestrestock/api/CRPlayer.java // public interface CRPlayer { // // /** // * @return The number of times the player has caused the chest to restock. // */ // int getLootCount(); // // /** // * @return The time at which the player last caused the chest to restock. // */ // long getLastRestockTime(); // // /** // * Sets the number of times a player has caused the chest to restock. // * // * @param count The number of times a player has caused the chest to restock. // */ // void setLootCount(int count); // // /** // * Sets the time at which the player last caused the chest to restock. // * // * @param time The time at which the player last caused the chest to restock. // */ // void setLastRestockTime(long time); // } // Path: src/main/java/com/dumptruckman/chestrestock/Players.java import com.dumptruckman.chestrestock.api.CRPlayer; package com.dumptruckman.chestrestock; public final class Players { private Players() { throw new AssertionError(); }
public static CRPlayer newCRPlayer() {
dumptruckman/ChestRestock
src/main/java/com/dumptruckman/chestrestock/util/Language.java
// Path: src/main/java/com/dumptruckman/chestrestock/api/CRChest.java // class Constants { // // /** // * The minimum for max inventory size. // */ // public static final int MIN_MAX_INVENTORY_SIZE = 54; // // private static int MAX_INVENTORY_SIZE = MIN_MAX_INVENTORY_SIZE; // // /** // * Sets the maximum size of any inventory for use in ChestRestock. // * // * @param size a value no less than {@link Constants#MIN_MAX_INVENTORY_SIZE}. // */ // public static void setMaxInventorySize(int size) { // if (size < MIN_MAX_INVENTORY_SIZE) { // throw new IllegalArgumentException("Size may not be less than " + MIN_MAX_INVENTORY_SIZE); // } // MAX_INVENTORY_SIZE = size; // } // // /** // * @return the max size for any inventory for use in ChestRestock. // */ // public static int getMaxInventorySize() { // return MAX_INVENTORY_SIZE; // } // }
import com.dumptruckman.chestrestock.api.CRChest.Constants; import com.dumptruckman.minecraft.pluginbase.locale.Message;
"This will cause a chest managed by dChest to become indestructible except by those with sufficient permission."); public static final Message PLAYER_LIMIT_DESC = new Message("props.player_limit.desc", "This will change the number of times a single player can loot the chest.", "-1 = no limit, 0 = none or permission based", "1 (or greater) = number of times a chest will restock for a player."); public static final Message UNIQUE_DESC = new Message("props.unique.desc", "Ensures that the chest is unique per player. This means, they will each see a different set of items per chest"); public static final Message ENABLED_DESC = new Message("props.enabled.desc", "Whether this chest is enabled with ChestRestock properties. A setting of false makes the chest behave as a NORMAL chest."); public static final Message NAME_DESC = new Message("props.name.desc", "A name for this chest. This is used for giving specific permissions for a chest."); public static final Message REDSTONE_DESC = new Message("props.redstone.desc", "This will cause the chest to be restocked when it receives redstone power."); public static final Message ACCEPT_POLL_DESC = new Message("props.accept_poll.desc", "When true, the global polling task for ChestRestock will check to see if this chest needs to restock and restock it if it is time."); public static final Message LOOT_TABLE_DESC = new Message("props.loot_table.desc", "The name of the loot table to use as defined in loot_tables.yml"); public static final Message GLOBAL_MESSAGE_DESC = new Message("props.global_message.desc", "A message to be broadcast to the server when this chest restocks. Blank means no message."); public static final Message ONLY_RESTOCK_EMPTY_DESC = new Message("props.only_restock_empty.desc", "When true, only empty chests will restock."); public static final Message AUTO_CREATE_DESC = new Message("props.other.auto_create.desc", "Automatically initializes chests, when opened, as if you created them with /cr create."); public static final Message AUTO_CREATE_NEW_DESC = new Message("props.other.auto_create_new.desc", "Automatically initializes chests, when placed, as if you created them with /cr create but only if auto_create is enabled. Most useful when set to false so auto_create only affects chests previously on the map and not ones places by players."); public static final Message EMPTY_LOOT_TABLE_DESC = new Message("props.other.empty_loot_table.desc", "The loot table to use for empty chests."); public static final Message MAX_INVENTORY_SIZE_INVALID = new Message("settings.max_inventory_size.invalid",
// Path: src/main/java/com/dumptruckman/chestrestock/api/CRChest.java // class Constants { // // /** // * The minimum for max inventory size. // */ // public static final int MIN_MAX_INVENTORY_SIZE = 54; // // private static int MAX_INVENTORY_SIZE = MIN_MAX_INVENTORY_SIZE; // // /** // * Sets the maximum size of any inventory for use in ChestRestock. // * // * @param size a value no less than {@link Constants#MIN_MAX_INVENTORY_SIZE}. // */ // public static void setMaxInventorySize(int size) { // if (size < MIN_MAX_INVENTORY_SIZE) { // throw new IllegalArgumentException("Size may not be less than " + MIN_MAX_INVENTORY_SIZE); // } // MAX_INVENTORY_SIZE = size; // } // // /** // * @return the max size for any inventory for use in ChestRestock. // */ // public static int getMaxInventorySize() { // return MAX_INVENTORY_SIZE; // } // } // Path: src/main/java/com/dumptruckman/chestrestock/util/Language.java import com.dumptruckman.chestrestock.api.CRChest.Constants; import com.dumptruckman.minecraft.pluginbase.locale.Message; "This will cause a chest managed by dChest to become indestructible except by those with sufficient permission."); public static final Message PLAYER_LIMIT_DESC = new Message("props.player_limit.desc", "This will change the number of times a single player can loot the chest.", "-1 = no limit, 0 = none or permission based", "1 (or greater) = number of times a chest will restock for a player."); public static final Message UNIQUE_DESC = new Message("props.unique.desc", "Ensures that the chest is unique per player. This means, they will each see a different set of items per chest"); public static final Message ENABLED_DESC = new Message("props.enabled.desc", "Whether this chest is enabled with ChestRestock properties. A setting of false makes the chest behave as a NORMAL chest."); public static final Message NAME_DESC = new Message("props.name.desc", "A name for this chest. This is used for giving specific permissions for a chest."); public static final Message REDSTONE_DESC = new Message("props.redstone.desc", "This will cause the chest to be restocked when it receives redstone power."); public static final Message ACCEPT_POLL_DESC = new Message("props.accept_poll.desc", "When true, the global polling task for ChestRestock will check to see if this chest needs to restock and restock it if it is time."); public static final Message LOOT_TABLE_DESC = new Message("props.loot_table.desc", "The name of the loot table to use as defined in loot_tables.yml"); public static final Message GLOBAL_MESSAGE_DESC = new Message("props.global_message.desc", "A message to be broadcast to the server when this chest restocks. Blank means no message."); public static final Message ONLY_RESTOCK_EMPTY_DESC = new Message("props.only_restock_empty.desc", "When true, only empty chests will restock."); public static final Message AUTO_CREATE_DESC = new Message("props.other.auto_create.desc", "Automatically initializes chests, when opened, as if you created them with /cr create."); public static final Message AUTO_CREATE_NEW_DESC = new Message("props.other.auto_create_new.desc", "Automatically initializes chests, when placed, as if you created them with /cr create but only if auto_create is enabled. Most useful when set to false so auto_create only affects chests previously on the map and not ones places by players."); public static final Message EMPTY_LOOT_TABLE_DESC = new Message("props.other.empty_loot_table.desc", "The loot table to use for empty chests."); public static final Message MAX_INVENTORY_SIZE_INVALID = new Message("settings.max_inventory_size.invalid",
"You must specify a number that is equal to or larger than " + Constants.MIN_MAX_INVENTORY_SIZE);
dumptruckman/ChestRestock
src/main/java/com/dumptruckman/chestrestock/DefaultLootConfig.java
// Path: src/main/java/com/dumptruckman/chestrestock/api/ChestRestock.java // public interface ChestRestock extends BukkitPlugin<CRConfig>, Plugin { // // /** // * @return The chest manager for this plugin. This is where most of the business starts. // */ // ChestManager getChestManager(); // // /** // * Retrieves the default chest settings for a specified world. If null is passed in, it will retrieve the // * global defaults. World defaults may not contain all values. For values not contained, null is returned // * from the get() method. In this case, global defaults are generally checked as the global defaults // * contains every value whether or not they are explicitly set. // * // * @param world The world to get defaults for or null for global defaults. // * @return The defaults for the world passed in or global defaults if null passed in. // */ // CRDefaults getDefaults(String world); // // /** // * @return the object that contains all data and methods related to random loot tables. // */ // LootConfig getLootConfig(); // // /** // * @return true if the ChestManager for the plugin has been loaded. Added to prevent recursive errors! // */ // boolean hasChestManagerLoaded(); // // /** // * Returns the block the player is targeting if it is an InventoryHolder otherwise, throws IllegalStateException. // * // * @param player Player to check target of. // * @return The block the player is targeting that is an InventoryHolder. // * @throws IllegalStateException If the targeted block is not an InventoryHolder or the player is not targeting a block. // */ // Block getTargetedInventoryHolder(Player player) throws IllegalStateException; // } // // Path: src/main/java/com/dumptruckman/chestrestock/api/LootConfig.java // public interface LootConfig { // // /** // * Retrieves the loot table with the specified name. // * // * @param name The name of the loot table to retrieve. // * @return The loot table by that name or null if none found. // */ // LootTable getLootTable(String name); // } // // Path: src/main/java/com/dumptruckman/chestrestock/api/LootTable.java // public interface LootTable { // // /** // * Adds the loot table to an inventory. // * // * @param inv The inventory to add the loot table to. // */ // void addToInventory(Inventory inv); // // /** // * Interface to describe a LootSection, which is a single section of the yaml file. // */ // interface LootSection { // // /** // * @return The number of rolls for the section. // */ // int getRolls(); // // /** // * @return A map of the children section with keys representing the chance of that section. The value // * is a Set since multiple sections may have the same chance. // */ // Map<Float, Set<LootSection>> getChildSections(); // // /** // * @return True if only one child should be picked for this LootSection. // */ // boolean isSplit(); // // /** // * @return The total of all the chances for all the children of this LootSection. // */ // float getTotalWeight(); // // /** // * @return The chance for this LootSection to be chosen. // */ // float getChance(); // } // // /** // * Interface to describe a LootSection that represents an Item (the default kind of LootSection). // */ // interface ItemSection extends LootSection { // // /** // * @return The item this LootSection represents. // */ // ItemStack getItem(); // // /** // * @return The enchant section for this LootSection or null if none exists. // */ // EnchantSection getEnchantSection(); // } // // /** // * Interface to describe a LootSection that represents an item enchantment. // */ // static interface EnchantSection extends LootSection { // // /** // * @return The enchantment represented by this LootSection. // */ // Enchantment getEnchantment(); // // /** // * @return The level of the enchantment. // */ // int getLevel(); // } // }
import com.dumptruckman.chestrestock.api.ChestRestock; import com.dumptruckman.chestrestock.api.LootConfig; import com.dumptruckman.chestrestock.api.LootTable; import com.dumptruckman.minecraft.pluginbase.util.Logging; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.Map; import java.util.WeakHashMap;
package com.dumptruckman.chestrestock; class DefaultLootConfig implements LootConfig { private FileConfiguration config; private File lootFolder; private File configFile;
// Path: src/main/java/com/dumptruckman/chestrestock/api/ChestRestock.java // public interface ChestRestock extends BukkitPlugin<CRConfig>, Plugin { // // /** // * @return The chest manager for this plugin. This is where most of the business starts. // */ // ChestManager getChestManager(); // // /** // * Retrieves the default chest settings for a specified world. If null is passed in, it will retrieve the // * global defaults. World defaults may not contain all values. For values not contained, null is returned // * from the get() method. In this case, global defaults are generally checked as the global defaults // * contains every value whether or not they are explicitly set. // * // * @param world The world to get defaults for or null for global defaults. // * @return The defaults for the world passed in or global defaults if null passed in. // */ // CRDefaults getDefaults(String world); // // /** // * @return the object that contains all data and methods related to random loot tables. // */ // LootConfig getLootConfig(); // // /** // * @return true if the ChestManager for the plugin has been loaded. Added to prevent recursive errors! // */ // boolean hasChestManagerLoaded(); // // /** // * Returns the block the player is targeting if it is an InventoryHolder otherwise, throws IllegalStateException. // * // * @param player Player to check target of. // * @return The block the player is targeting that is an InventoryHolder. // * @throws IllegalStateException If the targeted block is not an InventoryHolder or the player is not targeting a block. // */ // Block getTargetedInventoryHolder(Player player) throws IllegalStateException; // } // // Path: src/main/java/com/dumptruckman/chestrestock/api/LootConfig.java // public interface LootConfig { // // /** // * Retrieves the loot table with the specified name. // * // * @param name The name of the loot table to retrieve. // * @return The loot table by that name or null if none found. // */ // LootTable getLootTable(String name); // } // // Path: src/main/java/com/dumptruckman/chestrestock/api/LootTable.java // public interface LootTable { // // /** // * Adds the loot table to an inventory. // * // * @param inv The inventory to add the loot table to. // */ // void addToInventory(Inventory inv); // // /** // * Interface to describe a LootSection, which is a single section of the yaml file. // */ // interface LootSection { // // /** // * @return The number of rolls for the section. // */ // int getRolls(); // // /** // * @return A map of the children section with keys representing the chance of that section. The value // * is a Set since multiple sections may have the same chance. // */ // Map<Float, Set<LootSection>> getChildSections(); // // /** // * @return True if only one child should be picked for this LootSection. // */ // boolean isSplit(); // // /** // * @return The total of all the chances for all the children of this LootSection. // */ // float getTotalWeight(); // // /** // * @return The chance for this LootSection to be chosen. // */ // float getChance(); // } // // /** // * Interface to describe a LootSection that represents an Item (the default kind of LootSection). // */ // interface ItemSection extends LootSection { // // /** // * @return The item this LootSection represents. // */ // ItemStack getItem(); // // /** // * @return The enchant section for this LootSection or null if none exists. // */ // EnchantSection getEnchantSection(); // } // // /** // * Interface to describe a LootSection that represents an item enchantment. // */ // static interface EnchantSection extends LootSection { // // /** // * @return The enchantment represented by this LootSection. // */ // Enchantment getEnchantment(); // // /** // * @return The level of the enchantment. // */ // int getLevel(); // } // } // Path: src/main/java/com/dumptruckman/chestrestock/DefaultLootConfig.java import com.dumptruckman.chestrestock.api.ChestRestock; import com.dumptruckman.chestrestock.api.LootConfig; import com.dumptruckman.chestrestock.api.LootTable; import com.dumptruckman.minecraft.pluginbase.util.Logging; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.Map; import java.util.WeakHashMap; package com.dumptruckman.chestrestock; class DefaultLootConfig implements LootConfig { private FileConfiguration config; private File lootFolder; private File configFile;
private Map<String, LootTable> cachedTables = new WeakHashMap<String, LootTable>();
dumptruckman/ChestRestock
src/main/java/com/dumptruckman/chestrestock/DefaultLootConfig.java
// Path: src/main/java/com/dumptruckman/chestrestock/api/ChestRestock.java // public interface ChestRestock extends BukkitPlugin<CRConfig>, Plugin { // // /** // * @return The chest manager for this plugin. This is where most of the business starts. // */ // ChestManager getChestManager(); // // /** // * Retrieves the default chest settings for a specified world. If null is passed in, it will retrieve the // * global defaults. World defaults may not contain all values. For values not contained, null is returned // * from the get() method. In this case, global defaults are generally checked as the global defaults // * contains every value whether or not they are explicitly set. // * // * @param world The world to get defaults for or null for global defaults. // * @return The defaults for the world passed in or global defaults if null passed in. // */ // CRDefaults getDefaults(String world); // // /** // * @return the object that contains all data and methods related to random loot tables. // */ // LootConfig getLootConfig(); // // /** // * @return true if the ChestManager for the plugin has been loaded. Added to prevent recursive errors! // */ // boolean hasChestManagerLoaded(); // // /** // * Returns the block the player is targeting if it is an InventoryHolder otherwise, throws IllegalStateException. // * // * @param player Player to check target of. // * @return The block the player is targeting that is an InventoryHolder. // * @throws IllegalStateException If the targeted block is not an InventoryHolder or the player is not targeting a block. // */ // Block getTargetedInventoryHolder(Player player) throws IllegalStateException; // } // // Path: src/main/java/com/dumptruckman/chestrestock/api/LootConfig.java // public interface LootConfig { // // /** // * Retrieves the loot table with the specified name. // * // * @param name The name of the loot table to retrieve. // * @return The loot table by that name or null if none found. // */ // LootTable getLootTable(String name); // } // // Path: src/main/java/com/dumptruckman/chestrestock/api/LootTable.java // public interface LootTable { // // /** // * Adds the loot table to an inventory. // * // * @param inv The inventory to add the loot table to. // */ // void addToInventory(Inventory inv); // // /** // * Interface to describe a LootSection, which is a single section of the yaml file. // */ // interface LootSection { // // /** // * @return The number of rolls for the section. // */ // int getRolls(); // // /** // * @return A map of the children section with keys representing the chance of that section. The value // * is a Set since multiple sections may have the same chance. // */ // Map<Float, Set<LootSection>> getChildSections(); // // /** // * @return True if only one child should be picked for this LootSection. // */ // boolean isSplit(); // // /** // * @return The total of all the chances for all the children of this LootSection. // */ // float getTotalWeight(); // // /** // * @return The chance for this LootSection to be chosen. // */ // float getChance(); // } // // /** // * Interface to describe a LootSection that represents an Item (the default kind of LootSection). // */ // interface ItemSection extends LootSection { // // /** // * @return The item this LootSection represents. // */ // ItemStack getItem(); // // /** // * @return The enchant section for this LootSection or null if none exists. // */ // EnchantSection getEnchantSection(); // } // // /** // * Interface to describe a LootSection that represents an item enchantment. // */ // static interface EnchantSection extends LootSection { // // /** // * @return The enchantment represented by this LootSection. // */ // Enchantment getEnchantment(); // // /** // * @return The level of the enchantment. // */ // int getLevel(); // } // }
import com.dumptruckman.chestrestock.api.ChestRestock; import com.dumptruckman.chestrestock.api.LootConfig; import com.dumptruckman.chestrestock.api.LootTable; import com.dumptruckman.minecraft.pluginbase.util.Logging; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.Map; import java.util.WeakHashMap;
package com.dumptruckman.chestrestock; class DefaultLootConfig implements LootConfig { private FileConfiguration config; private File lootFolder; private File configFile; private Map<String, LootTable> cachedTables = new WeakHashMap<String, LootTable>();
// Path: src/main/java/com/dumptruckman/chestrestock/api/ChestRestock.java // public interface ChestRestock extends BukkitPlugin<CRConfig>, Plugin { // // /** // * @return The chest manager for this plugin. This is where most of the business starts. // */ // ChestManager getChestManager(); // // /** // * Retrieves the default chest settings for a specified world. If null is passed in, it will retrieve the // * global defaults. World defaults may not contain all values. For values not contained, null is returned // * from the get() method. In this case, global defaults are generally checked as the global defaults // * contains every value whether or not they are explicitly set. // * // * @param world The world to get defaults for or null for global defaults. // * @return The defaults for the world passed in or global defaults if null passed in. // */ // CRDefaults getDefaults(String world); // // /** // * @return the object that contains all data and methods related to random loot tables. // */ // LootConfig getLootConfig(); // // /** // * @return true if the ChestManager for the plugin has been loaded. Added to prevent recursive errors! // */ // boolean hasChestManagerLoaded(); // // /** // * Returns the block the player is targeting if it is an InventoryHolder otherwise, throws IllegalStateException. // * // * @param player Player to check target of. // * @return The block the player is targeting that is an InventoryHolder. // * @throws IllegalStateException If the targeted block is not an InventoryHolder or the player is not targeting a block. // */ // Block getTargetedInventoryHolder(Player player) throws IllegalStateException; // } // // Path: src/main/java/com/dumptruckman/chestrestock/api/LootConfig.java // public interface LootConfig { // // /** // * Retrieves the loot table with the specified name. // * // * @param name The name of the loot table to retrieve. // * @return The loot table by that name or null if none found. // */ // LootTable getLootTable(String name); // } // // Path: src/main/java/com/dumptruckman/chestrestock/api/LootTable.java // public interface LootTable { // // /** // * Adds the loot table to an inventory. // * // * @param inv The inventory to add the loot table to. // */ // void addToInventory(Inventory inv); // // /** // * Interface to describe a LootSection, which is a single section of the yaml file. // */ // interface LootSection { // // /** // * @return The number of rolls for the section. // */ // int getRolls(); // // /** // * @return A map of the children section with keys representing the chance of that section. The value // * is a Set since multiple sections may have the same chance. // */ // Map<Float, Set<LootSection>> getChildSections(); // // /** // * @return True if only one child should be picked for this LootSection. // */ // boolean isSplit(); // // /** // * @return The total of all the chances for all the children of this LootSection. // */ // float getTotalWeight(); // // /** // * @return The chance for this LootSection to be chosen. // */ // float getChance(); // } // // /** // * Interface to describe a LootSection that represents an Item (the default kind of LootSection). // */ // interface ItemSection extends LootSection { // // /** // * @return The item this LootSection represents. // */ // ItemStack getItem(); // // /** // * @return The enchant section for this LootSection or null if none exists. // */ // EnchantSection getEnchantSection(); // } // // /** // * Interface to describe a LootSection that represents an item enchantment. // */ // static interface EnchantSection extends LootSection { // // /** // * @return The enchantment represented by this LootSection. // */ // Enchantment getEnchantment(); // // /** // * @return The level of the enchantment. // */ // int getLevel(); // } // } // Path: src/main/java/com/dumptruckman/chestrestock/DefaultLootConfig.java import com.dumptruckman.chestrestock.api.ChestRestock; import com.dumptruckman.chestrestock.api.LootConfig; import com.dumptruckman.chestrestock.api.LootTable; import com.dumptruckman.minecraft.pluginbase.util.Logging; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.Map; import java.util.WeakHashMap; package com.dumptruckman.chestrestock; class DefaultLootConfig implements LootConfig { private FileConfiguration config; private File lootFolder; private File configFile; private Map<String, LootTable> cachedTables = new WeakHashMap<String, LootTable>();
DefaultLootConfig(ChestRestock plugin) {
dumptruckman/ChestRestock
src/main/java/com/dumptruckman/chestrestock/api/CRChest.java
// Path: src/main/java/com/dumptruckman/chestrestock/Players.java // public final class Players { // // private Players() { // throw new AssertionError(); // } // // public static CRPlayer newCRPlayer() { // return new DefaultCRPlayer(0, 0L); // } // // public static CRPlayer newCRPlayer(int lootCount, long lastRestock) { // return new DefaultCRPlayer(lootCount, lastRestock); // } // } // // Path: src/main/java/com/dumptruckman/chestrestock/util/BlockLocation.java // public class BlockLocation { // // private static final String DELIMITER = "_"; // // private final String world; // private final int x; // private final int y; // private final int z; // // private final String stringForm; // // private BlockLocation(Block block) { // this(block.getWorld(), block.getX(), block.getY(), block.getZ()); // } // // private BlockLocation(World world, int x, int y, int z) { // this(world.getName(), x, y, z); // } // // private BlockLocation(String world, int x, int y, int z) { // this.world = world; // this.x = x; // this.y = y; // this.z = z; // this.stringForm = this.x + DELIMITER + this.y + DELIMITER + this.z + DELIMITER + this.world; // } // // public final String getWorldName() { // return world; // } // // public final World getWorld() { // return Bukkit.getWorld(this.world); // } // // public final Block getBlock() { // World world = getWorld(); // if (world == null) { // return null; // } // return world.getBlockAt(getX(), getY(), getZ()); // } // // public final int getX() { // return x; // } // // public final int getY() { // return y; // } // // public final int getZ() { // return z; // } // // @Override // public final String toString() { // return stringForm; // } // // @Override // public boolean equals(Object o) { // if (o instanceof BlockLocation) { // BlockLocation otherLoc = (BlockLocation) o; // if (this.getWorld().equals(otherLoc.getWorld()) // && this.getX() == otherLoc.getX() // && this.getY() == otherLoc.getY() // && this.getZ() == otherLoc.getZ()) { // return true; // } // } // return false; // } // // @Override // public int hashCode() { // return this.toString().hashCode(); // } // // public static BlockLocation get(String stringFormat) { // String[] sections = stringFormat.split(DELIMITER, 4); // if (sections.length != 4) { // Logging.finer("Unable to parse location: " + stringFormat); // return null; // } // try { // return new BlockLocation(sections[3], // Integer.valueOf(sections[0]), // Integer.valueOf(sections[1]), // Integer.valueOf(sections[2])); // } catch (Exception e) { // Logging.finer("Unable to parse location: " + stringFormat); // return null; // } // } // // public static BlockLocation get(Block block) { // return new BlockLocation(block); // } // }
import com.dumptruckman.chestrestock.Players; import com.dumptruckman.chestrestock.util.BlockLocation; import com.dumptruckman.minecraft.pluginbase.config.Config; import com.dumptruckman.minecraft.pluginbase.config.ConfigEntry; import com.dumptruckman.minecraft.pluginbase.config.EntryBuilder; import com.dumptruckman.minecraft.pluginbase.config.EntrySerializer; import com.dumptruckman.minecraft.pluginbase.config.MappedConfigEntry; import com.dumptruckman.minecraft.pluginbase.util.Logging; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.HumanEntity; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import java.util.HashMap; import java.util.List; import java.util.Map;
@Override public CRPlayer deserialize(Object o) { int lootCount = 0; long lastRestockTime = 0; try { if (o instanceof ConfigurationSection) { o = ((ConfigurationSection) o).getValues(false); } Map<String, Object> map = (Map<String, Object>) o; if (map == null) { map = new HashMap<String, Object>(); } Object obj = map.get("restockCount"); if (obj == null) { obj = 0; } lootCount = Integer.valueOf(obj.toString()); obj = map.get("lastRestockTime"); if (obj == null) { obj = 0L; } lastRestockTime = Long.valueOf(obj.toString()); } catch (ClassCastException e) { Logging.warning("Error in player data!"); e.printStackTrace(); } catch (NumberFormatException e) { Logging.warning("Error in player data!"); e.printStackTrace(); }
// Path: src/main/java/com/dumptruckman/chestrestock/Players.java // public final class Players { // // private Players() { // throw new AssertionError(); // } // // public static CRPlayer newCRPlayer() { // return new DefaultCRPlayer(0, 0L); // } // // public static CRPlayer newCRPlayer(int lootCount, long lastRestock) { // return new DefaultCRPlayer(lootCount, lastRestock); // } // } // // Path: src/main/java/com/dumptruckman/chestrestock/util/BlockLocation.java // public class BlockLocation { // // private static final String DELIMITER = "_"; // // private final String world; // private final int x; // private final int y; // private final int z; // // private final String stringForm; // // private BlockLocation(Block block) { // this(block.getWorld(), block.getX(), block.getY(), block.getZ()); // } // // private BlockLocation(World world, int x, int y, int z) { // this(world.getName(), x, y, z); // } // // private BlockLocation(String world, int x, int y, int z) { // this.world = world; // this.x = x; // this.y = y; // this.z = z; // this.stringForm = this.x + DELIMITER + this.y + DELIMITER + this.z + DELIMITER + this.world; // } // // public final String getWorldName() { // return world; // } // // public final World getWorld() { // return Bukkit.getWorld(this.world); // } // // public final Block getBlock() { // World world = getWorld(); // if (world == null) { // return null; // } // return world.getBlockAt(getX(), getY(), getZ()); // } // // public final int getX() { // return x; // } // // public final int getY() { // return y; // } // // public final int getZ() { // return z; // } // // @Override // public final String toString() { // return stringForm; // } // // @Override // public boolean equals(Object o) { // if (o instanceof BlockLocation) { // BlockLocation otherLoc = (BlockLocation) o; // if (this.getWorld().equals(otherLoc.getWorld()) // && this.getX() == otherLoc.getX() // && this.getY() == otherLoc.getY() // && this.getZ() == otherLoc.getZ()) { // return true; // } // } // return false; // } // // @Override // public int hashCode() { // return this.toString().hashCode(); // } // // public static BlockLocation get(String stringFormat) { // String[] sections = stringFormat.split(DELIMITER, 4); // if (sections.length != 4) { // Logging.finer("Unable to parse location: " + stringFormat); // return null; // } // try { // return new BlockLocation(sections[3], // Integer.valueOf(sections[0]), // Integer.valueOf(sections[1]), // Integer.valueOf(sections[2])); // } catch (Exception e) { // Logging.finer("Unable to parse location: " + stringFormat); // return null; // } // } // // public static BlockLocation get(Block block) { // return new BlockLocation(block); // } // } // Path: src/main/java/com/dumptruckman/chestrestock/api/CRChest.java import com.dumptruckman.chestrestock.Players; import com.dumptruckman.chestrestock.util.BlockLocation; import com.dumptruckman.minecraft.pluginbase.config.Config; import com.dumptruckman.minecraft.pluginbase.config.ConfigEntry; import com.dumptruckman.minecraft.pluginbase.config.EntryBuilder; import com.dumptruckman.minecraft.pluginbase.config.EntrySerializer; import com.dumptruckman.minecraft.pluginbase.config.MappedConfigEntry; import com.dumptruckman.minecraft.pluginbase.util.Logging; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.HumanEntity; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import java.util.HashMap; import java.util.List; import java.util.Map; @Override public CRPlayer deserialize(Object o) { int lootCount = 0; long lastRestockTime = 0; try { if (o instanceof ConfigurationSection) { o = ((ConfigurationSection) o).getValues(false); } Map<String, Object> map = (Map<String, Object>) o; if (map == null) { map = new HashMap<String, Object>(); } Object obj = map.get("restockCount"); if (obj == null) { obj = 0; } lootCount = Integer.valueOf(obj.toString()); obj = map.get("lastRestockTime"); if (obj == null) { obj = 0L; } lastRestockTime = Long.valueOf(obj.toString()); } catch (ClassCastException e) { Logging.warning("Error in player data!"); e.printStackTrace(); } catch (NumberFormatException e) { Logging.warning("Error in player data!"); e.printStackTrace(); }
return Players.newCRPlayer(lootCount, lastRestockTime);
dumptruckman/ChestRestock
src/main/java/com/dumptruckman/chestrestock/api/CRChest.java
// Path: src/main/java/com/dumptruckman/chestrestock/Players.java // public final class Players { // // private Players() { // throw new AssertionError(); // } // // public static CRPlayer newCRPlayer() { // return new DefaultCRPlayer(0, 0L); // } // // public static CRPlayer newCRPlayer(int lootCount, long lastRestock) { // return new DefaultCRPlayer(lootCount, lastRestock); // } // } // // Path: src/main/java/com/dumptruckman/chestrestock/util/BlockLocation.java // public class BlockLocation { // // private static final String DELIMITER = "_"; // // private final String world; // private final int x; // private final int y; // private final int z; // // private final String stringForm; // // private BlockLocation(Block block) { // this(block.getWorld(), block.getX(), block.getY(), block.getZ()); // } // // private BlockLocation(World world, int x, int y, int z) { // this(world.getName(), x, y, z); // } // // private BlockLocation(String world, int x, int y, int z) { // this.world = world; // this.x = x; // this.y = y; // this.z = z; // this.stringForm = this.x + DELIMITER + this.y + DELIMITER + this.z + DELIMITER + this.world; // } // // public final String getWorldName() { // return world; // } // // public final World getWorld() { // return Bukkit.getWorld(this.world); // } // // public final Block getBlock() { // World world = getWorld(); // if (world == null) { // return null; // } // return world.getBlockAt(getX(), getY(), getZ()); // } // // public final int getX() { // return x; // } // // public final int getY() { // return y; // } // // public final int getZ() { // return z; // } // // @Override // public final String toString() { // return stringForm; // } // // @Override // public boolean equals(Object o) { // if (o instanceof BlockLocation) { // BlockLocation otherLoc = (BlockLocation) o; // if (this.getWorld().equals(otherLoc.getWorld()) // && this.getX() == otherLoc.getX() // && this.getY() == otherLoc.getY() // && this.getZ() == otherLoc.getZ()) { // return true; // } // } // return false; // } // // @Override // public int hashCode() { // return this.toString().hashCode(); // } // // public static BlockLocation get(String stringFormat) { // String[] sections = stringFormat.split(DELIMITER, 4); // if (sections.length != 4) { // Logging.finer("Unable to parse location: " + stringFormat); // return null; // } // try { // return new BlockLocation(sections[3], // Integer.valueOf(sections[0]), // Integer.valueOf(sections[1]), // Integer.valueOf(sections[2])); // } catch (Exception e) { // Logging.finer("Unable to parse location: " + stringFormat); // return null; // } // } // // public static BlockLocation get(Block block) { // return new BlockLocation(block); // } // }
import com.dumptruckman.chestrestock.Players; import com.dumptruckman.chestrestock.util.BlockLocation; import com.dumptruckman.minecraft.pluginbase.config.Config; import com.dumptruckman.minecraft.pluginbase.config.ConfigEntry; import com.dumptruckman.minecraft.pluginbase.config.EntryBuilder; import com.dumptruckman.minecraft.pluginbase.config.EntrySerializer; import com.dumptruckman.minecraft.pluginbase.config.MappedConfigEntry; import com.dumptruckman.minecraft.pluginbase.util.Logging; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.HumanEntity; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import java.util.HashMap; import java.util.List; import java.util.Map;
} lastRestockTime = Long.valueOf(obj.toString()); } catch (ClassCastException e) { Logging.warning("Error in player data!"); e.printStackTrace(); } catch (NumberFormatException e) { Logging.warning("Error in player data!"); e.printStackTrace(); } return Players.newCRPlayer(lootCount, lastRestockTime); } @Override public Object serialize(CRPlayer crPlayer) { Map<String, Object> map = new HashMap<String, Object>(); map.put("restockCount", crPlayer.getLootCount()); map.put("lastRestockTime", crPlayer.getLastRestockTime()); return map; } }).buildMap(); /** * The last time this chest was restocked (when not {@link CRChest#UNIQUE}). */ ConfigEntry<Long> LAST_RESTOCK = new EntryBuilder<Long>(Long.class, "lastRestockTime").def(0L).stringSerializer().build(); //ConfigEntry<Long> CREATION_TIME = new EntryBuilder<Long>(Long.class, "creationTime").def(0L).stringSerializer().build(); /** * @return The location of this chest. */
// Path: src/main/java/com/dumptruckman/chestrestock/Players.java // public final class Players { // // private Players() { // throw new AssertionError(); // } // // public static CRPlayer newCRPlayer() { // return new DefaultCRPlayer(0, 0L); // } // // public static CRPlayer newCRPlayer(int lootCount, long lastRestock) { // return new DefaultCRPlayer(lootCount, lastRestock); // } // } // // Path: src/main/java/com/dumptruckman/chestrestock/util/BlockLocation.java // public class BlockLocation { // // private static final String DELIMITER = "_"; // // private final String world; // private final int x; // private final int y; // private final int z; // // private final String stringForm; // // private BlockLocation(Block block) { // this(block.getWorld(), block.getX(), block.getY(), block.getZ()); // } // // private BlockLocation(World world, int x, int y, int z) { // this(world.getName(), x, y, z); // } // // private BlockLocation(String world, int x, int y, int z) { // this.world = world; // this.x = x; // this.y = y; // this.z = z; // this.stringForm = this.x + DELIMITER + this.y + DELIMITER + this.z + DELIMITER + this.world; // } // // public final String getWorldName() { // return world; // } // // public final World getWorld() { // return Bukkit.getWorld(this.world); // } // // public final Block getBlock() { // World world = getWorld(); // if (world == null) { // return null; // } // return world.getBlockAt(getX(), getY(), getZ()); // } // // public final int getX() { // return x; // } // // public final int getY() { // return y; // } // // public final int getZ() { // return z; // } // // @Override // public final String toString() { // return stringForm; // } // // @Override // public boolean equals(Object o) { // if (o instanceof BlockLocation) { // BlockLocation otherLoc = (BlockLocation) o; // if (this.getWorld().equals(otherLoc.getWorld()) // && this.getX() == otherLoc.getX() // && this.getY() == otherLoc.getY() // && this.getZ() == otherLoc.getZ()) { // return true; // } // } // return false; // } // // @Override // public int hashCode() { // return this.toString().hashCode(); // } // // public static BlockLocation get(String stringFormat) { // String[] sections = stringFormat.split(DELIMITER, 4); // if (sections.length != 4) { // Logging.finer("Unable to parse location: " + stringFormat); // return null; // } // try { // return new BlockLocation(sections[3], // Integer.valueOf(sections[0]), // Integer.valueOf(sections[1]), // Integer.valueOf(sections[2])); // } catch (Exception e) { // Logging.finer("Unable to parse location: " + stringFormat); // return null; // } // } // // public static BlockLocation get(Block block) { // return new BlockLocation(block); // } // } // Path: src/main/java/com/dumptruckman/chestrestock/api/CRChest.java import com.dumptruckman.chestrestock.Players; import com.dumptruckman.chestrestock.util.BlockLocation; import com.dumptruckman.minecraft.pluginbase.config.Config; import com.dumptruckman.minecraft.pluginbase.config.ConfigEntry; import com.dumptruckman.minecraft.pluginbase.config.EntryBuilder; import com.dumptruckman.minecraft.pluginbase.config.EntrySerializer; import com.dumptruckman.minecraft.pluginbase.config.MappedConfigEntry; import com.dumptruckman.minecraft.pluginbase.util.Logging; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.HumanEntity; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import java.util.HashMap; import java.util.List; import java.util.Map; } lastRestockTime = Long.valueOf(obj.toString()); } catch (ClassCastException e) { Logging.warning("Error in player data!"); e.printStackTrace(); } catch (NumberFormatException e) { Logging.warning("Error in player data!"); e.printStackTrace(); } return Players.newCRPlayer(lootCount, lastRestockTime); } @Override public Object serialize(CRPlayer crPlayer) { Map<String, Object> map = new HashMap<String, Object>(); map.put("restockCount", crPlayer.getLootCount()); map.put("lastRestockTime", crPlayer.getLastRestockTime()); return map; } }).buildMap(); /** * The last time this chest was restocked (when not {@link CRChest#UNIQUE}). */ ConfigEntry<Long> LAST_RESTOCK = new EntryBuilder<Long>(Long.class, "lastRestockTime").def(0L).stringSerializer().build(); //ConfigEntry<Long> CREATION_TIME = new EntryBuilder<Long>(Long.class, "creationTime").def(0L).stringSerializer().build(); /** * @return The location of this chest. */
BlockLocation getLocation();
hailin0/sensitive-word-filter
src/main/java/com/hlin/sensitive/processor/HTMLFragment.java
// Path: src/main/java/com/hlin/sensitive/KeyWord.java // public class KeyWord implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -6050328795034034286L; // // /** // * 关键词内容 // */ // private String word; // // /** // * (单字符)词的前缀,支持正则 // */ // private String pre; // // /** // * (单字符)词的后缀,支持正则 // */ // private String sufix; // // /** // * 关键词长度 // */ // private int wordLength = 0; // // /** // * @param word // */ // public KeyWord(String word) { // this.word = word; // this.wordLength = word.length(); // } // // /** // * @param word // * @param pre // * @param sufix // */ // public KeyWord(String word, String pre, String sufix) { // this(word); // this.pre = pre; // this.sufix = sufix; // } // // /** // * @return the word // */ // public String getWord() { // return word; // } // // /** // * @param word the word to set // */ // public void setWord(String word) { // this.word = word; // } // // /** // * @return the wordLength // */ // public int getWordLength() { // return wordLength; // } // // /** // * @param wordLength the wordLength to set // */ // public void setWordLength(int wordLength) { // this.wordLength = wordLength; // } // // /** // * @return the pre // */ // public String getPre() { // return pre; // } // // /** // * @param pre the pre to set // */ // public void setPre(String pre) { // this.pre = pre; // } // // /** // * @return the sufix // */ // public String getSufix() { // return sufix; // } // // /** // * @param sufix the sufix to set // */ // public void setSufix(String sufix) { // this.sufix = sufix; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((word == null) ? 0 : word.hashCode()); // result = prime * result + wordLength; // return result; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // KeyWord other = (KeyWord) obj; // if (word == null) { // if (other.word != null) // return false; // } else if (!word.equals(other.word)) // return false; // if (wordLength != other.wordLength) // return false; // return true; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "KeyWord [word=" + word + ", wordLength=" + wordLength + "]"; // } // // }
import org.apache.commons.lang3.StringUtils; import com.hlin.sensitive.KeyWord;
package com.hlin.sensitive.processor; /** * 高亮的方式。 * * @author hailin0@yeah.net * @createDate 2016年5月22日 * */ public class HTMLFragment extends AbstractFragment { /** * 开口标记 */ private String open; /** * 封闭标记 */ private String close; /** * 初始化开闭标签 * * @param open 开始标签,如< b >、< font >等。 * @param close 结束标签,如< /b >、< /font >等。 */ public HTMLFragment(String open, String close) { this.open = StringUtils.trimToEmpty(open); this.close = StringUtils.trimToEmpty(close); } @Override
// Path: src/main/java/com/hlin/sensitive/KeyWord.java // public class KeyWord implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -6050328795034034286L; // // /** // * 关键词内容 // */ // private String word; // // /** // * (单字符)词的前缀,支持正则 // */ // private String pre; // // /** // * (单字符)词的后缀,支持正则 // */ // private String sufix; // // /** // * 关键词长度 // */ // private int wordLength = 0; // // /** // * @param word // */ // public KeyWord(String word) { // this.word = word; // this.wordLength = word.length(); // } // // /** // * @param word // * @param pre // * @param sufix // */ // public KeyWord(String word, String pre, String sufix) { // this(word); // this.pre = pre; // this.sufix = sufix; // } // // /** // * @return the word // */ // public String getWord() { // return word; // } // // /** // * @param word the word to set // */ // public void setWord(String word) { // this.word = word; // } // // /** // * @return the wordLength // */ // public int getWordLength() { // return wordLength; // } // // /** // * @param wordLength the wordLength to set // */ // public void setWordLength(int wordLength) { // this.wordLength = wordLength; // } // // /** // * @return the pre // */ // public String getPre() { // return pre; // } // // /** // * @param pre the pre to set // */ // public void setPre(String pre) { // this.pre = pre; // } // // /** // * @return the sufix // */ // public String getSufix() { // return sufix; // } // // /** // * @param sufix the sufix to set // */ // public void setSufix(String sufix) { // this.sufix = sufix; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((word == null) ? 0 : word.hashCode()); // result = prime * result + wordLength; // return result; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // KeyWord other = (KeyWord) obj; // if (word == null) { // if (other.word != null) // return false; // } else if (!word.equals(other.word)) // return false; // if (wordLength != other.wordLength) // return false; // return true; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "KeyWord [word=" + word + ", wordLength=" + wordLength + "]"; // } // // } // Path: src/main/java/com/hlin/sensitive/processor/HTMLFragment.java import org.apache.commons.lang3.StringUtils; import com.hlin.sensitive.KeyWord; package com.hlin.sensitive.processor; /** * 高亮的方式。 * * @author hailin0@yeah.net * @createDate 2016年5月22日 * */ public class HTMLFragment extends AbstractFragment { /** * 开口标记 */ private String open; /** * 封闭标记 */ private String close; /** * 初始化开闭标签 * * @param open 开始标签,如< b >、< font >等。 * @param close 结束标签,如< /b >、< /font >等。 */ public HTMLFragment(String open, String close) { this.open = StringUtils.trimToEmpty(open); this.close = StringUtils.trimToEmpty(close); } @Override
public String format(KeyWord word) {
hailin0/sensitive-word-filter
src/main/java/com/hlin/sensitive/util/EndTagUtil.java
// Path: src/main/java/com/hlin/sensitive/KeyWord.java // public class KeyWord implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -6050328795034034286L; // // /** // * 关键词内容 // */ // private String word; // // /** // * (单字符)词的前缀,支持正则 // */ // private String pre; // // /** // * (单字符)词的后缀,支持正则 // */ // private String sufix; // // /** // * 关键词长度 // */ // private int wordLength = 0; // // /** // * @param word // */ // public KeyWord(String word) { // this.word = word; // this.wordLength = word.length(); // } // // /** // * @param word // * @param pre // * @param sufix // */ // public KeyWord(String word, String pre, String sufix) { // this(word); // this.pre = pre; // this.sufix = sufix; // } // // /** // * @return the word // */ // public String getWord() { // return word; // } // // /** // * @param word the word to set // */ // public void setWord(String word) { // this.word = word; // } // // /** // * @return the wordLength // */ // public int getWordLength() { // return wordLength; // } // // /** // * @param wordLength the wordLength to set // */ // public void setWordLength(int wordLength) { // this.wordLength = wordLength; // } // // /** // * @return the pre // */ // public String getPre() { // return pre; // } // // /** // * @param pre the pre to set // */ // public void setPre(String pre) { // this.pre = pre; // } // // /** // * @return the sufix // */ // public String getSufix() { // return sufix; // } // // /** // * @param sufix the sufix to set // */ // public void setSufix(String sufix) { // this.sufix = sufix; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((word == null) ? 0 : word.hashCode()); // result = prime * result + wordLength; // return result; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // KeyWord other = (KeyWord) obj; // if (word == null) { // if (other.word != null) // return false; // } else if (!word.equals(other.word)) // return false; // if (wordLength != other.wordLength) // return false; // return true; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "KeyWord [word=" + word + ", wordLength=" + wordLength + "]"; // } // // }
import java.io.Serializable; import java.util.HashMap; import java.util.Map; import com.hlin.sensitive.KeyWord;
package com.hlin.sensitive.util; /** * 关键词尾节点 * * @author hailin0@yeah.net * @createDate 2016年5月22日 * */ public class EndTagUtil implements Serializable { /** * */ private static final long serialVersionUID = 8278503553932163596L; /** * 尾节点key */ public static final String TREE_END_TAG = "end";
// Path: src/main/java/com/hlin/sensitive/KeyWord.java // public class KeyWord implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -6050328795034034286L; // // /** // * 关键词内容 // */ // private String word; // // /** // * (单字符)词的前缀,支持正则 // */ // private String pre; // // /** // * (单字符)词的后缀,支持正则 // */ // private String sufix; // // /** // * 关键词长度 // */ // private int wordLength = 0; // // /** // * @param word // */ // public KeyWord(String word) { // this.word = word; // this.wordLength = word.length(); // } // // /** // * @param word // * @param pre // * @param sufix // */ // public KeyWord(String word, String pre, String sufix) { // this(word); // this.pre = pre; // this.sufix = sufix; // } // // /** // * @return the word // */ // public String getWord() { // return word; // } // // /** // * @param word the word to set // */ // public void setWord(String word) { // this.word = word; // } // // /** // * @return the wordLength // */ // public int getWordLength() { // return wordLength; // } // // /** // * @param wordLength the wordLength to set // */ // public void setWordLength(int wordLength) { // this.wordLength = wordLength; // } // // /** // * @return the pre // */ // public String getPre() { // return pre; // } // // /** // * @param pre the pre to set // */ // public void setPre(String pre) { // this.pre = pre; // } // // /** // * @return the sufix // */ // public String getSufix() { // return sufix; // } // // /** // * @param sufix the sufix to set // */ // public void setSufix(String sufix) { // this.sufix = sufix; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((word == null) ? 0 : word.hashCode()); // result = prime * result + wordLength; // return result; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // KeyWord other = (KeyWord) obj; // if (word == null) { // if (other.word != null) // return false; // } else if (!word.equals(other.word)) // return false; // if (wordLength != other.wordLength) // return false; // return true; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "KeyWord [word=" + word + ", wordLength=" + wordLength + "]"; // } // // } // Path: src/main/java/com/hlin/sensitive/util/EndTagUtil.java import java.io.Serializable; import java.util.HashMap; import java.util.Map; import com.hlin.sensitive.KeyWord; package com.hlin.sensitive.util; /** * 关键词尾节点 * * @author hailin0@yeah.net * @createDate 2016年5月22日 * */ public class EndTagUtil implements Serializable { /** * */ private static final long serialVersionUID = 8278503553932163596L; /** * 尾节点key */ public static final String TREE_END_TAG = "end";
public static Map<String, Map> buind(KeyWord KeyWord) {
hailin0/sensitive-word-filter
src/main/java/com/hlin/sensitive/processor/IgnoreFragment.java
// Path: src/main/java/com/hlin/sensitive/KeyWord.java // public class KeyWord implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -6050328795034034286L; // // /** // * 关键词内容 // */ // private String word; // // /** // * (单字符)词的前缀,支持正则 // */ // private String pre; // // /** // * (单字符)词的后缀,支持正则 // */ // private String sufix; // // /** // * 关键词长度 // */ // private int wordLength = 0; // // /** // * @param word // */ // public KeyWord(String word) { // this.word = word; // this.wordLength = word.length(); // } // // /** // * @param word // * @param pre // * @param sufix // */ // public KeyWord(String word, String pre, String sufix) { // this(word); // this.pre = pre; // this.sufix = sufix; // } // // /** // * @return the word // */ // public String getWord() { // return word; // } // // /** // * @param word the word to set // */ // public void setWord(String word) { // this.word = word; // } // // /** // * @return the wordLength // */ // public int getWordLength() { // return wordLength; // } // // /** // * @param wordLength the wordLength to set // */ // public void setWordLength(int wordLength) { // this.wordLength = wordLength; // } // // /** // * @return the pre // */ // public String getPre() { // return pre; // } // // /** // * @param pre the pre to set // */ // public void setPre(String pre) { // this.pre = pre; // } // // /** // * @return the sufix // */ // public String getSufix() { // return sufix; // } // // /** // * @param sufix the sufix to set // */ // public void setSufix(String sufix) { // this.sufix = sufix; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((word == null) ? 0 : word.hashCode()); // result = prime * result + wordLength; // return result; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // KeyWord other = (KeyWord) obj; // if (word == null) { // if (other.word != null) // return false; // } else if (!word.equals(other.word)) // return false; // if (wordLength != other.wordLength) // return false; // return true; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "KeyWord [word=" + word + ", wordLength=" + wordLength + "]"; // } // // }
import com.hlin.sensitive.KeyWord;
package com.hlin.sensitive.processor; /** * * 替换内容的片段处理方式 * * @author hailin0@yeah.net * @createDate 2016年5月22日 * */ public class IgnoreFragment extends AbstractFragment { private String ignore = ""; public IgnoreFragment() { } public IgnoreFragment(String ignore) { this.ignore = ignore; } @Override
// Path: src/main/java/com/hlin/sensitive/KeyWord.java // public class KeyWord implements Serializable { // // /** // * // */ // private static final long serialVersionUID = -6050328795034034286L; // // /** // * 关键词内容 // */ // private String word; // // /** // * (单字符)词的前缀,支持正则 // */ // private String pre; // // /** // * (单字符)词的后缀,支持正则 // */ // private String sufix; // // /** // * 关键词长度 // */ // private int wordLength = 0; // // /** // * @param word // */ // public KeyWord(String word) { // this.word = word; // this.wordLength = word.length(); // } // // /** // * @param word // * @param pre // * @param sufix // */ // public KeyWord(String word, String pre, String sufix) { // this(word); // this.pre = pre; // this.sufix = sufix; // } // // /** // * @return the word // */ // public String getWord() { // return word; // } // // /** // * @param word the word to set // */ // public void setWord(String word) { // this.word = word; // } // // /** // * @return the wordLength // */ // public int getWordLength() { // return wordLength; // } // // /** // * @param wordLength the wordLength to set // */ // public void setWordLength(int wordLength) { // this.wordLength = wordLength; // } // // /** // * @return the pre // */ // public String getPre() { // return pre; // } // // /** // * @param pre the pre to set // */ // public void setPre(String pre) { // this.pre = pre; // } // // /** // * @return the sufix // */ // public String getSufix() { // return sufix; // } // // /** // * @param sufix the sufix to set // */ // public void setSufix(String sufix) { // this.sufix = sufix; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((word == null) ? 0 : word.hashCode()); // result = prime * result + wordLength; // return result; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // KeyWord other = (KeyWord) obj; // if (word == null) { // if (other.word != null) // return false; // } else if (!word.equals(other.word)) // return false; // if (wordLength != other.wordLength) // return false; // return true; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "KeyWord [word=" + word + ", wordLength=" + wordLength + "]"; // } // // } // Path: src/main/java/com/hlin/sensitive/processor/IgnoreFragment.java import com.hlin.sensitive.KeyWord; package com.hlin.sensitive.processor; /** * * 替换内容的片段处理方式 * * @author hailin0@yeah.net * @createDate 2016年5月22日 * */ public class IgnoreFragment extends AbstractFragment { private String ignore = ""; public IgnoreFragment() { } public IgnoreFragment(String ignore) { this.ignore = ignore; } @Override
public String format(KeyWord word) {
willhaben/willtest
misc/src/main/java/at/willhaben/willtest/misc/pages/AbstractWaitingBuilder.java
// Path: misc/src/main/java/at/willhaben/willtest/misc/utils/ConditionType.java // public enum ConditionType { // CLICKABLE, // VISIBLE // }
import at.willhaben.willtest.misc.utils.ConditionType; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import java.util.Objects;
package at.willhaben.willtest.misc.pages; public abstract class AbstractWaitingBuilder<T> { private final PageObject pageObject; private By by; private WebElement webElement; AbstractWaitingBuilder(PageObject pageObject, WebElement webElement) { this.pageObject = pageObject; this.webElement = webElement; } AbstractWaitingBuilder(PageObject pageObject, By by) { this.pageObject = pageObject; this.by = by; } public PageObject getPageObject() { return pageObject; } public abstract T clickable(long timeout); public abstract T visible(long timeout); public T clickable() { return clickable(PageObject.DEFAULT_WAIT_TIMEOUT); } public T visible() { return visible(PageObject.DEFAULT_WAIT_TIMEOUT); }
// Path: misc/src/main/java/at/willhaben/willtest/misc/utils/ConditionType.java // public enum ConditionType { // CLICKABLE, // VISIBLE // } // Path: misc/src/main/java/at/willhaben/willtest/misc/pages/AbstractWaitingBuilder.java import at.willhaben.willtest.misc.utils.ConditionType; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import java.util.Objects; package at.willhaben.willtest.misc.pages; public abstract class AbstractWaitingBuilder<T> { private final PageObject pageObject; private By by; private WebElement webElement; AbstractWaitingBuilder(PageObject pageObject, WebElement webElement) { this.pageObject = pageObject; this.webElement = webElement; } AbstractWaitingBuilder(PageObject pageObject, By by) { this.pageObject = pageObject; this.by = by; } public PageObject getPageObject() { return pageObject; } public abstract T clickable(long timeout); public abstract T visible(long timeout); public T clickable() { return clickable(PageObject.DEFAULT_WAIT_TIMEOUT); } public T visible() { return visible(PageObject.DEFAULT_WAIT_TIMEOUT); }
protected ExpectedCondition<WebElement> generateCondition(ConditionType condition) {
willhaben/willtest
core/src/test/java/at/willhaben/willtest/test/SeleniumProxyTest.java
// Path: core/src/main/java/at/willhaben/willtest/proxy/SeleniumProxy.java // public class SeleniumProxy extends Proxy { // // private static final Logger LOGGER = LoggerFactory.getLogger(SeleniumProxy.class); // public static final String PROXY_URL_PROPERTY_KEY = "browsermobProxyUrl"; // // public SeleniumProxy(BrowserMobProxy proxy) { // super(); // this.setProxyType(ProxyType.MANUAL); // InetAddress connectableAddress = ClientUtil.getConnectableAddress(); // InetSocketAddress inetSocketAddress = new InetSocketAddress(connectableAddress, proxy.getPort()); // String proxyUrl = System.getProperty(PROXY_URL_PROPERTY_KEY); // String proxyStr; // if (proxyUrl != null) { // proxyStr = String.format("%s:%d", proxyUrl, inetSocketAddress.getPort()); // LOGGER.debug("Use the following proxy address for the browser to connect '" + proxyStr + "'. " + // "(selected from system property [" + PROXY_URL_PROPERTY_KEY + "])"); // } else if (!RemoteSelectionUtils.isRemote() && isOnMacOS()) { // proxyStr = String.format("%s:%d", "localhost", inetSocketAddress.getPort()); // } else { // proxyStr = String.format("%s:%d", ClientUtil.getConnectableAddress().getHostAddress(), inetSocketAddress.getPort()); // LOGGER.debug("Use the following proxy address for the browser to connect '" + proxyStr + "'. " + // "(automatically selected )"); // } // this.setHttpProxy(proxyStr); // this.setSslProxy(proxyStr); // } // // private boolean isOnMacOS() { // return System.getProperty("os.name").startsWith("Mac"); // } // }
import at.willhaben.willtest.proxy.SeleniumProxy; import net.lightbody.bmp.BrowserMobProxy; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package at.willhaben.willtest.test; class SeleniumProxyTest { public static final String PROXY_URL = "http://ThisIsTheSetUrl"; public static final int PROXY_PORT = 1234; static {
// Path: core/src/main/java/at/willhaben/willtest/proxy/SeleniumProxy.java // public class SeleniumProxy extends Proxy { // // private static final Logger LOGGER = LoggerFactory.getLogger(SeleniumProxy.class); // public static final String PROXY_URL_PROPERTY_KEY = "browsermobProxyUrl"; // // public SeleniumProxy(BrowserMobProxy proxy) { // super(); // this.setProxyType(ProxyType.MANUAL); // InetAddress connectableAddress = ClientUtil.getConnectableAddress(); // InetSocketAddress inetSocketAddress = new InetSocketAddress(connectableAddress, proxy.getPort()); // String proxyUrl = System.getProperty(PROXY_URL_PROPERTY_KEY); // String proxyStr; // if (proxyUrl != null) { // proxyStr = String.format("%s:%d", proxyUrl, inetSocketAddress.getPort()); // LOGGER.debug("Use the following proxy address for the browser to connect '" + proxyStr + "'. " + // "(selected from system property [" + PROXY_URL_PROPERTY_KEY + "])"); // } else if (!RemoteSelectionUtils.isRemote() && isOnMacOS()) { // proxyStr = String.format("%s:%d", "localhost", inetSocketAddress.getPort()); // } else { // proxyStr = String.format("%s:%d", ClientUtil.getConnectableAddress().getHostAddress(), inetSocketAddress.getPort()); // LOGGER.debug("Use the following proxy address for the browser to connect '" + proxyStr + "'. " + // "(automatically selected )"); // } // this.setHttpProxy(proxyStr); // this.setSslProxy(proxyStr); // } // // private boolean isOnMacOS() { // return System.getProperty("os.name").startsWith("Mac"); // } // } // Path: core/src/test/java/at/willhaben/willtest/test/SeleniumProxyTest.java import at.willhaben.willtest.proxy.SeleniumProxy; import net.lightbody.bmp.BrowserMobProxy; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package at.willhaben.willtest.test; class SeleniumProxyTest { public static final String PROXY_URL = "http://ThisIsTheSetUrl"; public static final int PROXY_PORT = 1234; static {
System.setProperty(SeleniumProxy.PROXY_URL_PROPERTY_KEY, PROXY_URL);
willhaben/willtest
misc/src/main/java/at/willhaben/willtest/misc/pages/RequireType.java
// Path: misc/src/main/java/at/willhaben/willtest/misc/utils/ConditionType.java // public enum ConditionType { // CLICKABLE, // VISIBLE // }
import at.willhaben.willtest.misc.utils.ConditionType; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import java.util.List; import java.util.Objects; import java.util.stream.Stream; import static java.util.Arrays.asList;
package at.willhaben.willtest.misc.pages; public final class RequireType { private List<WebElement> webElementList; private List<By> byList; public RequireType(WebElement... elements) { this.webElementList = asList(elements); } public RequireType(By... bys) { this.byList = asList(bys); }
// Path: misc/src/main/java/at/willhaben/willtest/misc/utils/ConditionType.java // public enum ConditionType { // CLICKABLE, // VISIBLE // } // Path: misc/src/main/java/at/willhaben/willtest/misc/pages/RequireType.java import at.willhaben.willtest.misc.utils.ConditionType; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import java.util.List; import java.util.Objects; import java.util.stream.Stream; import static java.util.Arrays.asList; package at.willhaben.willtest.misc.pages; public final class RequireType { private List<WebElement> webElementList; private List<By> byList; public RequireType(WebElement... elements) { this.webElementList = asList(elements); } public RequireType(By... bys) { this.byList = asList(bys); }
public ExpectedCondition buildCondition(ConditionType condition) {
willhaben/willtest
core/src/main/java/at/willhaben/willtest/util/PlatformUtils.java
// Path: core/src/main/java/at/willhaben/willtest/util/Environment.java // public final class Environment { // private Environment() { // } // // /** // * Checks if the specified key is available in the system properties {@link System#getProperty(String)}, // * environment variables {@link System#getenv(String)} or takes the default value. In this sequence. // * // * @param key Key or name of the property // * @param defaultValue Value taken if nothing is available // * @return The value of the system property, variable or the default value // */ // public static String getValue(String key, String defaultValue) { // String result = System.getProperty(key); // // if (result == null) { // result = System.getenv(key); // } // // if (result == null) { // result = defaultValue; // } // // return result; // } // }
import at.willhaben.willtest.util.Environment; import java.net.MalformedURLException; import java.net.URL;
package at.willhaben.willtest.util; public class PlatformUtils { private static final String DEFAULT_PLATFORM_ANDROID = "Android"; private static final String DEFAULT_PLATFORM_ANDROID_HUB = "Android-Hub"; private static final String DEFAULT_PLATFORM_IOS = "IOS"; private static final String DEFAULT_PLATFORM_DESKTOP = "Linux"; private static final String DEFAULT_PLATFORM_WINDOWS = "Windows"; private static final String SELENIUM_HUB_SYSTEM_PROPERTY_KEY = "seleniumHub"; private static final String DEFAULT_PLATFORM_LINUX = "Linux"; public static String getPlatform() {
// Path: core/src/main/java/at/willhaben/willtest/util/Environment.java // public final class Environment { // private Environment() { // } // // /** // * Checks if the specified key is available in the system properties {@link System#getProperty(String)}, // * environment variables {@link System#getenv(String)} or takes the default value. In this sequence. // * // * @param key Key or name of the property // * @param defaultValue Value taken if nothing is available // * @return The value of the system property, variable or the default value // */ // public static String getValue(String key, String defaultValue) { // String result = System.getProperty(key); // // if (result == null) { // result = System.getenv(key); // } // // if (result == null) { // result = defaultValue; // } // // return result; // } // } // Path: core/src/main/java/at/willhaben/willtest/util/PlatformUtils.java import at.willhaben.willtest.util.Environment; import java.net.MalformedURLException; import java.net.URL; package at.willhaben.willtest.util; public class PlatformUtils { private static final String DEFAULT_PLATFORM_ANDROID = "Android"; private static final String DEFAULT_PLATFORM_ANDROID_HUB = "Android-Hub"; private static final String DEFAULT_PLATFORM_IOS = "IOS"; private static final String DEFAULT_PLATFORM_DESKTOP = "Linux"; private static final String DEFAULT_PLATFORM_WINDOWS = "Windows"; private static final String SELENIUM_HUB_SYSTEM_PROPERTY_KEY = "seleniumHub"; private static final String DEFAULT_PLATFORM_LINUX = "Linux"; public static String getPlatform() {
return Environment.getValue("platform", DEFAULT_PLATFORM_DESKTOP);
willhaben/willtest
core/src/test/java/at/willhaben/willtest/test/ReportFileNameTest.java
// Path: core/src/main/java/at/willhaben/willtest/util/TestReportFile.java // public class TestReportFile { // private static final String REPORT_FOLDER_SYSTEM_PROPERTY = "willtest.reportFolder"; // private static final String COMMON_PREFIX_FOR_ALL_REPORT_FILES = "TR_"; // private static final String DEFAULT_REPORT_FOLDER = "surefire-reports"; // // private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy.MM.dd-HH.mm.ss.SSS"); // // private ExtensionContext testExtensionContext; // private String prefix = ""; // private String postfix = ""; // // public static Builder forTest(ExtensionContext context) { // return new Builder(context); // } // // /** // * Gives back the {@link File} object, which can be used as target for report. // * // * @return the file which can be used as report file // */ // public File getFile() { // String reportFolderPath = getReportFolderDir(); // File reportFolder = new File(reportFolderPath); // if (!reportFolder.exists() && !reportFolder.mkdirs()) { // throw new RuntimeException("Could not create folder " + reportFolder + "!"); // } // return new File(reportFolder, generateFileName()); // } // // public static String getReportFolderDir() { // return Environment.getValue(REPORT_FOLDER_SYSTEM_PROPERTY, DEFAULT_REPORT_FOLDER); // } // // private String getClassName() { // return testExtensionContext.getRequiredTestClass().getSimpleName(); // } // // private String getMethodName() { // return testExtensionContext.getRequiredTestMethod().getName(); // } // // public String getGeneratedName() { // return generateFileName(); // } // // private String generateFileName() { // String className = getClassName(); // String methodName = getMethodName(); // String timeStamp = DATE_FORMAT.format(ZonedDateTime.now()); // return escapeFileName(COMMON_PREFIX_FOR_ALL_REPORT_FILES + prefix + className + // "_" + methodName + "-" + timeStamp + postfix); // } // // private String escapeFileName(String originalName) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < originalName.length(); i++) { // char c = originalName.charAt(i); // if ((c >= '0' && c <= '9') || // (c >= 'A' && c <= 'Z') || // (c >= 'a' && c <= 'z') || // (c == '.') || // (c == '_') || // (c == '-')) { // sb.append(c); // } // } // return sb.toString(); // } // // public static class Builder { // private final TestReportFile testReportFile = new TestReportFile(); // // Builder(ExtensionContext context) { // testReportFile.testExtensionContext = context; // } // // /** // * @param prefix name prefix to be used. F.i. "PaymentModule" // * @return this builder // */ // public Builder withPrefix(String prefix) { // testReportFile.prefix = prefix; // return this; // } // // /** // * @param postfix name postfix to be used. F.i. ".png" // * @return this builder // */ // public Builder withPostix(String postfix) { // testReportFile.postfix = postfix; // return this; // } // // public TestReportFile build() { // return testReportFile; // } // } // } // // Path: core/src/test/java/at/willhaben/willtest/test/mock/ExtensionMock.java // public static ExtensionContext mockWithTestClassAndMethod(Class testclass, String methodName) { // ExtensionContext context = mock(ExtensionContext.class); // doReturn(testclass).when(context).getRequiredTestClass(); // Method testMethod = mock(Method.class); // doReturn(methodName).when(testMethod).getName(); // doReturn(testMethod).when(context).getRequiredTestMethod(); // return context; // }
import at.willhaben.willtest.util.TestReportFile; import org.junit.jupiter.api.Test; import static at.willhaben.willtest.test.mock.ExtensionMock.mockWithTestClassAndMethod; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*;
package at.willhaben.willtest.test; class ReportFileNameTest { private static final String PREFIX = "prefix123_"; private static final String POSTFIX = "_postfix"; private static final String METHOD_NAME = "Testmethod"; private static final String INVALID_CHARS = ":<>*/?"; @Test void testFileNameGeneration() {
// Path: core/src/main/java/at/willhaben/willtest/util/TestReportFile.java // public class TestReportFile { // private static final String REPORT_FOLDER_SYSTEM_PROPERTY = "willtest.reportFolder"; // private static final String COMMON_PREFIX_FOR_ALL_REPORT_FILES = "TR_"; // private static final String DEFAULT_REPORT_FOLDER = "surefire-reports"; // // private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy.MM.dd-HH.mm.ss.SSS"); // // private ExtensionContext testExtensionContext; // private String prefix = ""; // private String postfix = ""; // // public static Builder forTest(ExtensionContext context) { // return new Builder(context); // } // // /** // * Gives back the {@link File} object, which can be used as target for report. // * // * @return the file which can be used as report file // */ // public File getFile() { // String reportFolderPath = getReportFolderDir(); // File reportFolder = new File(reportFolderPath); // if (!reportFolder.exists() && !reportFolder.mkdirs()) { // throw new RuntimeException("Could not create folder " + reportFolder + "!"); // } // return new File(reportFolder, generateFileName()); // } // // public static String getReportFolderDir() { // return Environment.getValue(REPORT_FOLDER_SYSTEM_PROPERTY, DEFAULT_REPORT_FOLDER); // } // // private String getClassName() { // return testExtensionContext.getRequiredTestClass().getSimpleName(); // } // // private String getMethodName() { // return testExtensionContext.getRequiredTestMethod().getName(); // } // // public String getGeneratedName() { // return generateFileName(); // } // // private String generateFileName() { // String className = getClassName(); // String methodName = getMethodName(); // String timeStamp = DATE_FORMAT.format(ZonedDateTime.now()); // return escapeFileName(COMMON_PREFIX_FOR_ALL_REPORT_FILES + prefix + className + // "_" + methodName + "-" + timeStamp + postfix); // } // // private String escapeFileName(String originalName) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < originalName.length(); i++) { // char c = originalName.charAt(i); // if ((c >= '0' && c <= '9') || // (c >= 'A' && c <= 'Z') || // (c >= 'a' && c <= 'z') || // (c == '.') || // (c == '_') || // (c == '-')) { // sb.append(c); // } // } // return sb.toString(); // } // // public static class Builder { // private final TestReportFile testReportFile = new TestReportFile(); // // Builder(ExtensionContext context) { // testReportFile.testExtensionContext = context; // } // // /** // * @param prefix name prefix to be used. F.i. "PaymentModule" // * @return this builder // */ // public Builder withPrefix(String prefix) { // testReportFile.prefix = prefix; // return this; // } // // /** // * @param postfix name postfix to be used. F.i. ".png" // * @return this builder // */ // public Builder withPostix(String postfix) { // testReportFile.postfix = postfix; // return this; // } // // public TestReportFile build() { // return testReportFile; // } // } // } // // Path: core/src/test/java/at/willhaben/willtest/test/mock/ExtensionMock.java // public static ExtensionContext mockWithTestClassAndMethod(Class testclass, String methodName) { // ExtensionContext context = mock(ExtensionContext.class); // doReturn(testclass).when(context).getRequiredTestClass(); // Method testMethod = mock(Method.class); // doReturn(methodName).when(testMethod).getName(); // doReturn(testMethod).when(context).getRequiredTestMethod(); // return context; // } // Path: core/src/test/java/at/willhaben/willtest/test/ReportFileNameTest.java import at.willhaben.willtest.util.TestReportFile; import org.junit.jupiter.api.Test; import static at.willhaben.willtest.test.mock.ExtensionMock.mockWithTestClassAndMethod; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; package at.willhaben.willtest.test; class ReportFileNameTest { private static final String PREFIX = "prefix123_"; private static final String POSTFIX = "_postfix"; private static final String METHOD_NAME = "Testmethod"; private static final String INVALID_CHARS = ":<>*/?"; @Test void testFileNameGeneration() {
TestReportFile reportFile = TestReportFile.forTest(mockWithTestClassAndMethod(ReportFileNameTest.class, METHOD_NAME))
willhaben/willtest
core/src/test/java/at/willhaben/willtest/test/ReportFileNameTest.java
// Path: core/src/main/java/at/willhaben/willtest/util/TestReportFile.java // public class TestReportFile { // private static final String REPORT_FOLDER_SYSTEM_PROPERTY = "willtest.reportFolder"; // private static final String COMMON_PREFIX_FOR_ALL_REPORT_FILES = "TR_"; // private static final String DEFAULT_REPORT_FOLDER = "surefire-reports"; // // private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy.MM.dd-HH.mm.ss.SSS"); // // private ExtensionContext testExtensionContext; // private String prefix = ""; // private String postfix = ""; // // public static Builder forTest(ExtensionContext context) { // return new Builder(context); // } // // /** // * Gives back the {@link File} object, which can be used as target for report. // * // * @return the file which can be used as report file // */ // public File getFile() { // String reportFolderPath = getReportFolderDir(); // File reportFolder = new File(reportFolderPath); // if (!reportFolder.exists() && !reportFolder.mkdirs()) { // throw new RuntimeException("Could not create folder " + reportFolder + "!"); // } // return new File(reportFolder, generateFileName()); // } // // public static String getReportFolderDir() { // return Environment.getValue(REPORT_FOLDER_SYSTEM_PROPERTY, DEFAULT_REPORT_FOLDER); // } // // private String getClassName() { // return testExtensionContext.getRequiredTestClass().getSimpleName(); // } // // private String getMethodName() { // return testExtensionContext.getRequiredTestMethod().getName(); // } // // public String getGeneratedName() { // return generateFileName(); // } // // private String generateFileName() { // String className = getClassName(); // String methodName = getMethodName(); // String timeStamp = DATE_FORMAT.format(ZonedDateTime.now()); // return escapeFileName(COMMON_PREFIX_FOR_ALL_REPORT_FILES + prefix + className + // "_" + methodName + "-" + timeStamp + postfix); // } // // private String escapeFileName(String originalName) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < originalName.length(); i++) { // char c = originalName.charAt(i); // if ((c >= '0' && c <= '9') || // (c >= 'A' && c <= 'Z') || // (c >= 'a' && c <= 'z') || // (c == '.') || // (c == '_') || // (c == '-')) { // sb.append(c); // } // } // return sb.toString(); // } // // public static class Builder { // private final TestReportFile testReportFile = new TestReportFile(); // // Builder(ExtensionContext context) { // testReportFile.testExtensionContext = context; // } // // /** // * @param prefix name prefix to be used. F.i. "PaymentModule" // * @return this builder // */ // public Builder withPrefix(String prefix) { // testReportFile.prefix = prefix; // return this; // } // // /** // * @param postfix name postfix to be used. F.i. ".png" // * @return this builder // */ // public Builder withPostix(String postfix) { // testReportFile.postfix = postfix; // return this; // } // // public TestReportFile build() { // return testReportFile; // } // } // } // // Path: core/src/test/java/at/willhaben/willtest/test/mock/ExtensionMock.java // public static ExtensionContext mockWithTestClassAndMethod(Class testclass, String methodName) { // ExtensionContext context = mock(ExtensionContext.class); // doReturn(testclass).when(context).getRequiredTestClass(); // Method testMethod = mock(Method.class); // doReturn(methodName).when(testMethod).getName(); // doReturn(testMethod).when(context).getRequiredTestMethod(); // return context; // }
import at.willhaben.willtest.util.TestReportFile; import org.junit.jupiter.api.Test; import static at.willhaben.willtest.test.mock.ExtensionMock.mockWithTestClassAndMethod; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*;
package at.willhaben.willtest.test; class ReportFileNameTest { private static final String PREFIX = "prefix123_"; private static final String POSTFIX = "_postfix"; private static final String METHOD_NAME = "Testmethod"; private static final String INVALID_CHARS = ":<>*/?"; @Test void testFileNameGeneration() {
// Path: core/src/main/java/at/willhaben/willtest/util/TestReportFile.java // public class TestReportFile { // private static final String REPORT_FOLDER_SYSTEM_PROPERTY = "willtest.reportFolder"; // private static final String COMMON_PREFIX_FOR_ALL_REPORT_FILES = "TR_"; // private static final String DEFAULT_REPORT_FOLDER = "surefire-reports"; // // private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy.MM.dd-HH.mm.ss.SSS"); // // private ExtensionContext testExtensionContext; // private String prefix = ""; // private String postfix = ""; // // public static Builder forTest(ExtensionContext context) { // return new Builder(context); // } // // /** // * Gives back the {@link File} object, which can be used as target for report. // * // * @return the file which can be used as report file // */ // public File getFile() { // String reportFolderPath = getReportFolderDir(); // File reportFolder = new File(reportFolderPath); // if (!reportFolder.exists() && !reportFolder.mkdirs()) { // throw new RuntimeException("Could not create folder " + reportFolder + "!"); // } // return new File(reportFolder, generateFileName()); // } // // public static String getReportFolderDir() { // return Environment.getValue(REPORT_FOLDER_SYSTEM_PROPERTY, DEFAULT_REPORT_FOLDER); // } // // private String getClassName() { // return testExtensionContext.getRequiredTestClass().getSimpleName(); // } // // private String getMethodName() { // return testExtensionContext.getRequiredTestMethod().getName(); // } // // public String getGeneratedName() { // return generateFileName(); // } // // private String generateFileName() { // String className = getClassName(); // String methodName = getMethodName(); // String timeStamp = DATE_FORMAT.format(ZonedDateTime.now()); // return escapeFileName(COMMON_PREFIX_FOR_ALL_REPORT_FILES + prefix + className + // "_" + methodName + "-" + timeStamp + postfix); // } // // private String escapeFileName(String originalName) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < originalName.length(); i++) { // char c = originalName.charAt(i); // if ((c >= '0' && c <= '9') || // (c >= 'A' && c <= 'Z') || // (c >= 'a' && c <= 'z') || // (c == '.') || // (c == '_') || // (c == '-')) { // sb.append(c); // } // } // return sb.toString(); // } // // public static class Builder { // private final TestReportFile testReportFile = new TestReportFile(); // // Builder(ExtensionContext context) { // testReportFile.testExtensionContext = context; // } // // /** // * @param prefix name prefix to be used. F.i. "PaymentModule" // * @return this builder // */ // public Builder withPrefix(String prefix) { // testReportFile.prefix = prefix; // return this; // } // // /** // * @param postfix name postfix to be used. F.i. ".png" // * @return this builder // */ // public Builder withPostix(String postfix) { // testReportFile.postfix = postfix; // return this; // } // // public TestReportFile build() { // return testReportFile; // } // } // } // // Path: core/src/test/java/at/willhaben/willtest/test/mock/ExtensionMock.java // public static ExtensionContext mockWithTestClassAndMethod(Class testclass, String methodName) { // ExtensionContext context = mock(ExtensionContext.class); // doReturn(testclass).when(context).getRequiredTestClass(); // Method testMethod = mock(Method.class); // doReturn(methodName).when(testMethod).getName(); // doReturn(testMethod).when(context).getRequiredTestMethod(); // return context; // } // Path: core/src/test/java/at/willhaben/willtest/test/ReportFileNameTest.java import at.willhaben.willtest.util.TestReportFile; import org.junit.jupiter.api.Test; import static at.willhaben.willtest.test.mock.ExtensionMock.mockWithTestClassAndMethod; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; package at.willhaben.willtest.test; class ReportFileNameTest { private static final String PREFIX = "prefix123_"; private static final String POSTFIX = "_postfix"; private static final String METHOD_NAME = "Testmethod"; private static final String INVALID_CHARS = ":<>*/?"; @Test void testFileNameGeneration() {
TestReportFile reportFile = TestReportFile.forTest(mockWithTestClassAndMethod(ReportFileNameTest.class, METHOD_NAME))
willhaben/willtest
misc/src/test/java/at/willhaben/misc/test/pages/StaticPage.java
// Path: misc/src/test/java/at/willhaben/misc/test/util/StaticResourceHtmlUtil.java // public static String resourceHtmlFilePath(String fileName) { // return "file://" + StaticResourceHtmlUtil.class.getClassLoader().getResource(fileName + ".html").getFile(); // }
import at.willhaben.misc.test.util.FindTestId; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ISelect; import java.util.List; import static at.willhaben.misc.test.util.StaticResourceHtmlUtil.resourceHtmlFilePath;
package at.willhaben.misc.test.pages; public class StaticPage extends AbstractTestingPage { @FindTestId(value = "check-this-id") private WebElement divElementText; @FindTestId(value = "check-this-id", tagName = "span") private WebElement spanElementText; @FindTestId("select-id") private ISelect select; @FindTestId("select-id-list") private List<ISelect> selectList; protected StaticPage(WebDriver driver) { super(driver); } public static StaticPage open(WebDriver driver) {
// Path: misc/src/test/java/at/willhaben/misc/test/util/StaticResourceHtmlUtil.java // public static String resourceHtmlFilePath(String fileName) { // return "file://" + StaticResourceHtmlUtil.class.getClassLoader().getResource(fileName + ".html").getFile(); // } // Path: misc/src/test/java/at/willhaben/misc/test/pages/StaticPage.java import at.willhaben.misc.test.util.FindTestId; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ISelect; import java.util.List; import static at.willhaben.misc.test.util.StaticResourceHtmlUtil.resourceHtmlFilePath; package at.willhaben.misc.test.pages; public class StaticPage extends AbstractTestingPage { @FindTestId(value = "check-this-id") private WebElement divElementText; @FindTestId(value = "check-this-id", tagName = "span") private WebElement spanElementText; @FindTestId("select-id") private ISelect select; @FindTestId("select-id-list") private List<ISelect> selectList; protected StaticPage(WebDriver driver) { super(driver); } public static StaticPage open(WebDriver driver) {
driver.navigate().to(resourceHtmlFilePath("static"));
willhaben/willtest
examples/src/test/java/at/willhaben/willtest/examples/config/CustomShootingStrategy.java
// Path: core/src/main/java/at/willhaben/willtest/junit5/ScreenshotInterceptor.java // public interface ScreenshotInterceptor extends BrowserUtilExtension{ // // ShootingStrategy provideShootingStrategy(); // } // // Path: core/src/main/java/at/willhaben/willtest/util/FixedTopBarShootingStrategy.java // public class FixedTopBarShootingStrategy extends ShootingStrategy { // // private static final Logger LOGGER = LoggerFactory.getLogger(FixedTopBarShootingStrategy.class); // // private int headerToCut = 0; // private int scrollTimeout; // private By topElementToRemove = null; // // /** // * Creates shootingstragety which takes screenshot of the whole page and the // * ability to remove a fixed header navbar // * @param topElementToRemove unique identifier of the top navbar // */ // public FixedTopBarShootingStrategy(By topElementToRemove) { // this.topElementToRemove = topElementToRemove; // } // // /** // * Creates shootingstragety which takes screenshot of the whole page and the // * ability to remove a fixed header navbar // * @param headerToCut size of the header to remove in px // */ // public FixedTopBarShootingStrategy(int headerToCut) { // this.headerToCut = headerToCut; // } // // @Override // public BufferedImage getScreenshot(WebDriver wd) { // if(Objects.nonNull(topElementToRemove)) { // calculateHeaderSizeToCut(wd); // } // JavascriptExecutor js = (JavascriptExecutor) wd; // // int allH = getFullHeight(wd); // int allW = getFullWidth(wd); // int winH = getWindowHeight(wd); // // winH = winH - headerToCut; // int scrollTimes = allH / winH; // int tail = allH - winH * scrollTimes; // // BufferedImage finalImage = new BufferedImage(allW, allH, BufferedImage.TYPE_4BYTE_ABGR); // Graphics2D graphics = finalImage.createGraphics(); // // js.executeScript("scroll(0, arguments[0])", 0); // BufferedImage firstPart = simple().getScreenshot(wd); // graphics.drawImage(firstPart, 0, 0, null); // // for (int n = 1; n < scrollTimes; n++) { // js.executeScript("scroll(0, arguments[0])", winH * n); // BufferedImage part = getHeaderCutImage(wd); // graphics.drawImage(part, 0, n * winH + headerToCut, null); // } // // if (tail > 0) { // js.executeScript("scroll(0, document.body.scrollHeight)"); // BufferedImage last = getHeaderCutImage(wd); // BufferedImage tailImage = last.getSubimage(0, last.getHeight() - tail, last.getWidth(), tail); // graphics.drawImage(tailImage, 0, scrollTimes * winH, null); // } // graphics.dispose(); // // return finalImage; // } // // private void calculateHeaderSizeToCut(WebDriver webDriver) { // try { // WebElement headerElement = webDriver.findElement(topElementToRemove); // int height = headerElement.getSize().getHeight(); // if (height > headerToCut) { // headerToCut = height; // } // } catch (NoSuchElementException | TimeoutException e) { // LOGGER.warn("Can't find element [" + topElementToRemove + "] to calculate the height of the top " + // "navigation. Remove height is set to zero."); // } // } // // private int getFullHeight(WebDriver driver) { // return ((Number) InnerScript.execute(InnerScript.PAGE_HEIGHT_JS, driver)).intValue(); // } // // private int getFullWidth(WebDriver driver) { // return ((Number) InnerScript.execute(InnerScript.VIEWPORT_WIDTH_JS, driver)).intValue(); // } // // private int getWindowHeight(WebDriver driver) { // return ((Number) InnerScript.execute(InnerScript.VIEWPORT_HEIGHT_JS, driver)).intValue(); // } // // private BufferedImage getHeaderCutImage(WebDriver webDriver) { // BufferedImage baseImage = simple().getScreenshot(webDriver); // int h = baseImage.getHeight(); // int w = baseImage.getWidth(); // return baseImage.getSubimage(0, headerToCut, w, h - headerToCut); // } // }
import at.willhaben.willtest.junit5.ScreenshotInterceptor; import at.willhaben.willtest.util.FixedTopBarShootingStrategy; import ru.yandex.qatools.ashot.screentaker.ShootingStrategy;
package at.willhaben.willtest.examples.config; public class CustomShootingStrategy implements ScreenshotInterceptor { @Override public ShootingStrategy provideShootingStrategy() {
// Path: core/src/main/java/at/willhaben/willtest/junit5/ScreenshotInterceptor.java // public interface ScreenshotInterceptor extends BrowserUtilExtension{ // // ShootingStrategy provideShootingStrategy(); // } // // Path: core/src/main/java/at/willhaben/willtest/util/FixedTopBarShootingStrategy.java // public class FixedTopBarShootingStrategy extends ShootingStrategy { // // private static final Logger LOGGER = LoggerFactory.getLogger(FixedTopBarShootingStrategy.class); // // private int headerToCut = 0; // private int scrollTimeout; // private By topElementToRemove = null; // // /** // * Creates shootingstragety which takes screenshot of the whole page and the // * ability to remove a fixed header navbar // * @param topElementToRemove unique identifier of the top navbar // */ // public FixedTopBarShootingStrategy(By topElementToRemove) { // this.topElementToRemove = topElementToRemove; // } // // /** // * Creates shootingstragety which takes screenshot of the whole page and the // * ability to remove a fixed header navbar // * @param headerToCut size of the header to remove in px // */ // public FixedTopBarShootingStrategy(int headerToCut) { // this.headerToCut = headerToCut; // } // // @Override // public BufferedImage getScreenshot(WebDriver wd) { // if(Objects.nonNull(topElementToRemove)) { // calculateHeaderSizeToCut(wd); // } // JavascriptExecutor js = (JavascriptExecutor) wd; // // int allH = getFullHeight(wd); // int allW = getFullWidth(wd); // int winH = getWindowHeight(wd); // // winH = winH - headerToCut; // int scrollTimes = allH / winH; // int tail = allH - winH * scrollTimes; // // BufferedImage finalImage = new BufferedImage(allW, allH, BufferedImage.TYPE_4BYTE_ABGR); // Graphics2D graphics = finalImage.createGraphics(); // // js.executeScript("scroll(0, arguments[0])", 0); // BufferedImage firstPart = simple().getScreenshot(wd); // graphics.drawImage(firstPart, 0, 0, null); // // for (int n = 1; n < scrollTimes; n++) { // js.executeScript("scroll(0, arguments[0])", winH * n); // BufferedImage part = getHeaderCutImage(wd); // graphics.drawImage(part, 0, n * winH + headerToCut, null); // } // // if (tail > 0) { // js.executeScript("scroll(0, document.body.scrollHeight)"); // BufferedImage last = getHeaderCutImage(wd); // BufferedImage tailImage = last.getSubimage(0, last.getHeight() - tail, last.getWidth(), tail); // graphics.drawImage(tailImage, 0, scrollTimes * winH, null); // } // graphics.dispose(); // // return finalImage; // } // // private void calculateHeaderSizeToCut(WebDriver webDriver) { // try { // WebElement headerElement = webDriver.findElement(topElementToRemove); // int height = headerElement.getSize().getHeight(); // if (height > headerToCut) { // headerToCut = height; // } // } catch (NoSuchElementException | TimeoutException e) { // LOGGER.warn("Can't find element [" + topElementToRemove + "] to calculate the height of the top " + // "navigation. Remove height is set to zero."); // } // } // // private int getFullHeight(WebDriver driver) { // return ((Number) InnerScript.execute(InnerScript.PAGE_HEIGHT_JS, driver)).intValue(); // } // // private int getFullWidth(WebDriver driver) { // return ((Number) InnerScript.execute(InnerScript.VIEWPORT_WIDTH_JS, driver)).intValue(); // } // // private int getWindowHeight(WebDriver driver) { // return ((Number) InnerScript.execute(InnerScript.VIEWPORT_HEIGHT_JS, driver)).intValue(); // } // // private BufferedImage getHeaderCutImage(WebDriver webDriver) { // BufferedImage baseImage = simple().getScreenshot(webDriver); // int h = baseImage.getHeight(); // int w = baseImage.getWidth(); // return baseImage.getSubimage(0, headerToCut, w, h - headerToCut); // } // } // Path: examples/src/test/java/at/willhaben/willtest/examples/config/CustomShootingStrategy.java import at.willhaben.willtest.junit5.ScreenshotInterceptor; import at.willhaben.willtest.util.FixedTopBarShootingStrategy; import ru.yandex.qatools.ashot.screentaker.ShootingStrategy; package at.willhaben.willtest.examples.config; public class CustomShootingStrategy implements ScreenshotInterceptor { @Override public ShootingStrategy provideShootingStrategy() {
return new FixedTopBarShootingStrategy(0);
willhaben/willtest
core/src/main/java/at/willhaben/willtest/junit5/OptionCombiner.java
// Path: core/src/main/java/at/willhaben/willtest/exceptions/BrowserNotSupportedException.java // public class BrowserNotSupportedException extends RuntimeException { // // public BrowserNotSupportedException(String message) { // super(message); // } // } // // Path: core/src/main/java/at/willhaben/willtest/util/AndroidOptions.java // public class AndroidOptions extends DesiredCapabilities { // } // // Path: core/src/main/java/at/willhaben/willtest/util/IOsOptions.java // public class IOsOptions extends DesiredCapabilities { // }
import at.willhaben.willtest.exceptions.BrowserNotSupportedException; import at.willhaben.willtest.util.AndroidOptions; import at.willhaben.willtest.util.IOsOptions; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.edge.EdgeOptions; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.ie.InternetExplorerOptions; import java.lang.reflect.InvocationTargetException; import java.util.List;
package at.willhaben.willtest.junit5; public class OptionCombiner { private List<OptionModifier> optionModifiers; public OptionCombiner(List<OptionModifier> optionModifiers) { this.optionModifiers = optionModifiers; } @SuppressWarnings({"unchecked"}) public <T extends MutableCapabilities> T getBrowserOptions(Class<T> optionType) { T options; try { options = optionType.getConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
// Path: core/src/main/java/at/willhaben/willtest/exceptions/BrowserNotSupportedException.java // public class BrowserNotSupportedException extends RuntimeException { // // public BrowserNotSupportedException(String message) { // super(message); // } // } // // Path: core/src/main/java/at/willhaben/willtest/util/AndroidOptions.java // public class AndroidOptions extends DesiredCapabilities { // } // // Path: core/src/main/java/at/willhaben/willtest/util/IOsOptions.java // public class IOsOptions extends DesiredCapabilities { // } // Path: core/src/main/java/at/willhaben/willtest/junit5/OptionCombiner.java import at.willhaben.willtest.exceptions.BrowserNotSupportedException; import at.willhaben.willtest.util.AndroidOptions; import at.willhaben.willtest.util.IOsOptions; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.edge.EdgeOptions; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.ie.InternetExplorerOptions; import java.lang.reflect.InvocationTargetException; import java.util.List; package at.willhaben.willtest.junit5; public class OptionCombiner { private List<OptionModifier> optionModifiers; public OptionCombiner(List<OptionModifier> optionModifiers) { this.optionModifiers = optionModifiers; } @SuppressWarnings({"unchecked"}) public <T extends MutableCapabilities> T getBrowserOptions(Class<T> optionType) { T options; try { options = optionType.getConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new BrowserNotSupportedException("The options class [" + optionType.getName() + "] can't be " +
willhaben/willtest
core/src/main/java/at/willhaben/willtest/junit5/OptionCombiner.java
// Path: core/src/main/java/at/willhaben/willtest/exceptions/BrowserNotSupportedException.java // public class BrowserNotSupportedException extends RuntimeException { // // public BrowserNotSupportedException(String message) { // super(message); // } // } // // Path: core/src/main/java/at/willhaben/willtest/util/AndroidOptions.java // public class AndroidOptions extends DesiredCapabilities { // } // // Path: core/src/main/java/at/willhaben/willtest/util/IOsOptions.java // public class IOsOptions extends DesiredCapabilities { // }
import at.willhaben.willtest.exceptions.BrowserNotSupportedException; import at.willhaben.willtest.util.AndroidOptions; import at.willhaben.willtest.util.IOsOptions; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.edge.EdgeOptions; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.ie.InternetExplorerOptions; import java.lang.reflect.InvocationTargetException; import java.util.List;
package at.willhaben.willtest.junit5; public class OptionCombiner { private List<OptionModifier> optionModifiers; public OptionCombiner(List<OptionModifier> optionModifiers) { this.optionModifiers = optionModifiers; } @SuppressWarnings({"unchecked"}) public <T extends MutableCapabilities> T getBrowserOptions(Class<T> optionType) { T options; try { options = optionType.getConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new BrowserNotSupportedException("The options class [" + optionType.getName() + "] can't be " + "created. May this is not a valid option class for the supported browsers."); } for (OptionModifier modifier : optionModifiers) { if (optionType.isAssignableFrom(FirefoxOptions.class)) { options = modifier.modifyAllBrowsers(options); options = (T) modifier.modifyFirefoxOptions(((FirefoxOptions) options)); } else if (optionType.isAssignableFrom(ChromeOptions.class)) { options = modifier.modifyAllBrowsers(options); options = (T) modifier.modifyChromeOptions(((ChromeOptions) options)); } else if (optionType.isAssignableFrom(EdgeOptions.class)) { options = modifier.modifyAllBrowsers(options); options = (T) modifier.modifyEdgeOptions(((EdgeOptions) options)); } else if (optionType.isAssignableFrom(InternetExplorerOptions.class)) { options = modifier.modifyAllBrowsers(options); options = (T) modifier.modifyInternetExplorerOptions(((InternetExplorerOptions) options));
// Path: core/src/main/java/at/willhaben/willtest/exceptions/BrowserNotSupportedException.java // public class BrowserNotSupportedException extends RuntimeException { // // public BrowserNotSupportedException(String message) { // super(message); // } // } // // Path: core/src/main/java/at/willhaben/willtest/util/AndroidOptions.java // public class AndroidOptions extends DesiredCapabilities { // } // // Path: core/src/main/java/at/willhaben/willtest/util/IOsOptions.java // public class IOsOptions extends DesiredCapabilities { // } // Path: core/src/main/java/at/willhaben/willtest/junit5/OptionCombiner.java import at.willhaben.willtest.exceptions.BrowserNotSupportedException; import at.willhaben.willtest.util.AndroidOptions; import at.willhaben.willtest.util.IOsOptions; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.edge.EdgeOptions; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.ie.InternetExplorerOptions; import java.lang.reflect.InvocationTargetException; import java.util.List; package at.willhaben.willtest.junit5; public class OptionCombiner { private List<OptionModifier> optionModifiers; public OptionCombiner(List<OptionModifier> optionModifiers) { this.optionModifiers = optionModifiers; } @SuppressWarnings({"unchecked"}) public <T extends MutableCapabilities> T getBrowserOptions(Class<T> optionType) { T options; try { options = optionType.getConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new BrowserNotSupportedException("The options class [" + optionType.getName() + "] can't be " + "created. May this is not a valid option class for the supported browsers."); } for (OptionModifier modifier : optionModifiers) { if (optionType.isAssignableFrom(FirefoxOptions.class)) { options = modifier.modifyAllBrowsers(options); options = (T) modifier.modifyFirefoxOptions(((FirefoxOptions) options)); } else if (optionType.isAssignableFrom(ChromeOptions.class)) { options = modifier.modifyAllBrowsers(options); options = (T) modifier.modifyChromeOptions(((ChromeOptions) options)); } else if (optionType.isAssignableFrom(EdgeOptions.class)) { options = modifier.modifyAllBrowsers(options); options = (T) modifier.modifyEdgeOptions(((EdgeOptions) options)); } else if (optionType.isAssignableFrom(InternetExplorerOptions.class)) { options = modifier.modifyAllBrowsers(options); options = (T) modifier.modifyInternetExplorerOptions(((InternetExplorerOptions) options));
} else if (optionType.isAssignableFrom(AndroidOptions.class)) {
willhaben/willtest
core/src/main/java/at/willhaben/willtest/junit5/OptionCombiner.java
// Path: core/src/main/java/at/willhaben/willtest/exceptions/BrowserNotSupportedException.java // public class BrowserNotSupportedException extends RuntimeException { // // public BrowserNotSupportedException(String message) { // super(message); // } // } // // Path: core/src/main/java/at/willhaben/willtest/util/AndroidOptions.java // public class AndroidOptions extends DesiredCapabilities { // } // // Path: core/src/main/java/at/willhaben/willtest/util/IOsOptions.java // public class IOsOptions extends DesiredCapabilities { // }
import at.willhaben.willtest.exceptions.BrowserNotSupportedException; import at.willhaben.willtest.util.AndroidOptions; import at.willhaben.willtest.util.IOsOptions; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.edge.EdgeOptions; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.ie.InternetExplorerOptions; import java.lang.reflect.InvocationTargetException; import java.util.List;
public OptionCombiner(List<OptionModifier> optionModifiers) { this.optionModifiers = optionModifiers; } @SuppressWarnings({"unchecked"}) public <T extends MutableCapabilities> T getBrowserOptions(Class<T> optionType) { T options; try { options = optionType.getConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new BrowserNotSupportedException("The options class [" + optionType.getName() + "] can't be " + "created. May this is not a valid option class for the supported browsers."); } for (OptionModifier modifier : optionModifiers) { if (optionType.isAssignableFrom(FirefoxOptions.class)) { options = modifier.modifyAllBrowsers(options); options = (T) modifier.modifyFirefoxOptions(((FirefoxOptions) options)); } else if (optionType.isAssignableFrom(ChromeOptions.class)) { options = modifier.modifyAllBrowsers(options); options = (T) modifier.modifyChromeOptions(((ChromeOptions) options)); } else if (optionType.isAssignableFrom(EdgeOptions.class)) { options = modifier.modifyAllBrowsers(options); options = (T) modifier.modifyEdgeOptions(((EdgeOptions) options)); } else if (optionType.isAssignableFrom(InternetExplorerOptions.class)) { options = modifier.modifyAllBrowsers(options); options = (T) modifier.modifyInternetExplorerOptions(((InternetExplorerOptions) options)); } else if (optionType.isAssignableFrom(AndroidOptions.class)) { options = modifier.modifyAllBrowsers(options); options = (T) modifier.modifyAndroidOptions(((AndroidOptions) options));
// Path: core/src/main/java/at/willhaben/willtest/exceptions/BrowserNotSupportedException.java // public class BrowserNotSupportedException extends RuntimeException { // // public BrowserNotSupportedException(String message) { // super(message); // } // } // // Path: core/src/main/java/at/willhaben/willtest/util/AndroidOptions.java // public class AndroidOptions extends DesiredCapabilities { // } // // Path: core/src/main/java/at/willhaben/willtest/util/IOsOptions.java // public class IOsOptions extends DesiredCapabilities { // } // Path: core/src/main/java/at/willhaben/willtest/junit5/OptionCombiner.java import at.willhaben.willtest.exceptions.BrowserNotSupportedException; import at.willhaben.willtest.util.AndroidOptions; import at.willhaben.willtest.util.IOsOptions; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.edge.EdgeOptions; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.ie.InternetExplorerOptions; import java.lang.reflect.InvocationTargetException; import java.util.List; public OptionCombiner(List<OptionModifier> optionModifiers) { this.optionModifiers = optionModifiers; } @SuppressWarnings({"unchecked"}) public <T extends MutableCapabilities> T getBrowserOptions(Class<T> optionType) { T options; try { options = optionType.getConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new BrowserNotSupportedException("The options class [" + optionType.getName() + "] can't be " + "created. May this is not a valid option class for the supported browsers."); } for (OptionModifier modifier : optionModifiers) { if (optionType.isAssignableFrom(FirefoxOptions.class)) { options = modifier.modifyAllBrowsers(options); options = (T) modifier.modifyFirefoxOptions(((FirefoxOptions) options)); } else if (optionType.isAssignableFrom(ChromeOptions.class)) { options = modifier.modifyAllBrowsers(options); options = (T) modifier.modifyChromeOptions(((ChromeOptions) options)); } else if (optionType.isAssignableFrom(EdgeOptions.class)) { options = modifier.modifyAllBrowsers(options); options = (T) modifier.modifyEdgeOptions(((EdgeOptions) options)); } else if (optionType.isAssignableFrom(InternetExplorerOptions.class)) { options = modifier.modifyAllBrowsers(options); options = (T) modifier.modifyInternetExplorerOptions(((InternetExplorerOptions) options)); } else if (optionType.isAssignableFrom(AndroidOptions.class)) { options = modifier.modifyAllBrowsers(options); options = (T) modifier.modifyAndroidOptions(((AndroidOptions) options));
} else if (optionType.isAssignableFrom(IOsOptions.class)) {
willhaben/willtest
misc/src/main/java/at/willhaben/willtest/misc/pages/RequireBuilder.java
// Path: misc/src/main/java/at/willhaben/willtest/misc/utils/ConditionType.java // public enum ConditionType { // CLICKABLE, // VISIBLE // } // // Path: misc/src/main/java/at/willhaben/willtest/misc/utils/WhFluentWait.java // public class WhFluentWait<T> extends FluentWait<T> { // // public WhFluentWait(T input) { // super(input); // } // // public WhFluentWait(T input, Clock clock, Sleeper sleeper) { // super(input, clock, sleeper); // } // // /** // * Waits until the given condition is met. Throws an {@link AssertionError} instead of a {@link TimeoutException} // * when the condition fails because the error is known. // * @param errorMessage concrete error message describing the failure // * @param isTrue the parameter to pass to the {@link ExpectedCondition} // * @param <V> The function's expected return type. // * @return The function's return value if the function returned something different // * from null or false before the timeout expired. // * @throws AssertionError if the timeout expires // */ // public <V> V until(String errorMessage, Function<? super T, V> isTrue) { // try { // return super.until(isTrue); // } catch (TimeoutException e) { // if (Objects.nonNull(errorMessage) && !"".equals(errorMessage)) { // throw new AssertionError(errorMessage, e); // } else { // //Regex replacing parts that hinder allure from grouping erros in the report when using "require" without custom error messages // throw new TimeoutException(e.getMessage().replaceAll("Build info:(?:.+\\s+)*Driver info:.+",""), e.getCause()); // } // } // } // // @Override // public <V> V until(Function<? super T, V> isTrue) { // return super.until(isTrue); // } // }
import at.willhaben.willtest.misc.utils.ConditionType; import at.willhaben.willtest.misc.utils.WhFluentWait;
package at.willhaben.willtest.misc.pages; public class RequireBuilder { private final PageObject pageObject; private final RequireType requireType; private String errorMessage; RequireBuilder(PageObject pageObject, RequireType requireType) { this.pageObject = pageObject; this.requireType = requireType; } public RequireBuilder withErrorMessage(String message) { this.errorMessage = message; return this; } public void clickable() { clickable(PageObject.DEFAULT_WAIT_TIMEOUT); } public void clickable(long timeout) { clickable(pageObject.getWait(timeout)); } @SuppressWarnings("unchecked")
// Path: misc/src/main/java/at/willhaben/willtest/misc/utils/ConditionType.java // public enum ConditionType { // CLICKABLE, // VISIBLE // } // // Path: misc/src/main/java/at/willhaben/willtest/misc/utils/WhFluentWait.java // public class WhFluentWait<T> extends FluentWait<T> { // // public WhFluentWait(T input) { // super(input); // } // // public WhFluentWait(T input, Clock clock, Sleeper sleeper) { // super(input, clock, sleeper); // } // // /** // * Waits until the given condition is met. Throws an {@link AssertionError} instead of a {@link TimeoutException} // * when the condition fails because the error is known. // * @param errorMessage concrete error message describing the failure // * @param isTrue the parameter to pass to the {@link ExpectedCondition} // * @param <V> The function's expected return type. // * @return The function's return value if the function returned something different // * from null or false before the timeout expired. // * @throws AssertionError if the timeout expires // */ // public <V> V until(String errorMessage, Function<? super T, V> isTrue) { // try { // return super.until(isTrue); // } catch (TimeoutException e) { // if (Objects.nonNull(errorMessage) && !"".equals(errorMessage)) { // throw new AssertionError(errorMessage, e); // } else { // //Regex replacing parts that hinder allure from grouping erros in the report when using "require" without custom error messages // throw new TimeoutException(e.getMessage().replaceAll("Build info:(?:.+\\s+)*Driver info:.+",""), e.getCause()); // } // } // } // // @Override // public <V> V until(Function<? super T, V> isTrue) { // return super.until(isTrue); // } // } // Path: misc/src/main/java/at/willhaben/willtest/misc/pages/RequireBuilder.java import at.willhaben.willtest.misc.utils.ConditionType; import at.willhaben.willtest.misc.utils.WhFluentWait; package at.willhaben.willtest.misc.pages; public class RequireBuilder { private final PageObject pageObject; private final RequireType requireType; private String errorMessage; RequireBuilder(PageObject pageObject, RequireType requireType) { this.pageObject = pageObject; this.requireType = requireType; } public RequireBuilder withErrorMessage(String message) { this.errorMessage = message; return this; } public void clickable() { clickable(PageObject.DEFAULT_WAIT_TIMEOUT); } public void clickable(long timeout) { clickable(pageObject.getWait(timeout)); } @SuppressWarnings("unchecked")
public void clickable(WhFluentWait waiter) {
willhaben/willtest
misc/src/main/java/at/willhaben/willtest/misc/pages/RequireBuilder.java
// Path: misc/src/main/java/at/willhaben/willtest/misc/utils/ConditionType.java // public enum ConditionType { // CLICKABLE, // VISIBLE // } // // Path: misc/src/main/java/at/willhaben/willtest/misc/utils/WhFluentWait.java // public class WhFluentWait<T> extends FluentWait<T> { // // public WhFluentWait(T input) { // super(input); // } // // public WhFluentWait(T input, Clock clock, Sleeper sleeper) { // super(input, clock, sleeper); // } // // /** // * Waits until the given condition is met. Throws an {@link AssertionError} instead of a {@link TimeoutException} // * when the condition fails because the error is known. // * @param errorMessage concrete error message describing the failure // * @param isTrue the parameter to pass to the {@link ExpectedCondition} // * @param <V> The function's expected return type. // * @return The function's return value if the function returned something different // * from null or false before the timeout expired. // * @throws AssertionError if the timeout expires // */ // public <V> V until(String errorMessage, Function<? super T, V> isTrue) { // try { // return super.until(isTrue); // } catch (TimeoutException e) { // if (Objects.nonNull(errorMessage) && !"".equals(errorMessage)) { // throw new AssertionError(errorMessage, e); // } else { // //Regex replacing parts that hinder allure from grouping erros in the report when using "require" without custom error messages // throw new TimeoutException(e.getMessage().replaceAll("Build info:(?:.+\\s+)*Driver info:.+",""), e.getCause()); // } // } // } // // @Override // public <V> V until(Function<? super T, V> isTrue) { // return super.until(isTrue); // } // }
import at.willhaben.willtest.misc.utils.ConditionType; import at.willhaben.willtest.misc.utils.WhFluentWait;
package at.willhaben.willtest.misc.pages; public class RequireBuilder { private final PageObject pageObject; private final RequireType requireType; private String errorMessage; RequireBuilder(PageObject pageObject, RequireType requireType) { this.pageObject = pageObject; this.requireType = requireType; } public RequireBuilder withErrorMessage(String message) { this.errorMessage = message; return this; } public void clickable() { clickable(PageObject.DEFAULT_WAIT_TIMEOUT); } public void clickable(long timeout) { clickable(pageObject.getWait(timeout)); } @SuppressWarnings("unchecked") public void clickable(WhFluentWait waiter) {
// Path: misc/src/main/java/at/willhaben/willtest/misc/utils/ConditionType.java // public enum ConditionType { // CLICKABLE, // VISIBLE // } // // Path: misc/src/main/java/at/willhaben/willtest/misc/utils/WhFluentWait.java // public class WhFluentWait<T> extends FluentWait<T> { // // public WhFluentWait(T input) { // super(input); // } // // public WhFluentWait(T input, Clock clock, Sleeper sleeper) { // super(input, clock, sleeper); // } // // /** // * Waits until the given condition is met. Throws an {@link AssertionError} instead of a {@link TimeoutException} // * when the condition fails because the error is known. // * @param errorMessage concrete error message describing the failure // * @param isTrue the parameter to pass to the {@link ExpectedCondition} // * @param <V> The function's expected return type. // * @return The function's return value if the function returned something different // * from null or false before the timeout expired. // * @throws AssertionError if the timeout expires // */ // public <V> V until(String errorMessage, Function<? super T, V> isTrue) { // try { // return super.until(isTrue); // } catch (TimeoutException e) { // if (Objects.nonNull(errorMessage) && !"".equals(errorMessage)) { // throw new AssertionError(errorMessage, e); // } else { // //Regex replacing parts that hinder allure from grouping erros in the report when using "require" without custom error messages // throw new TimeoutException(e.getMessage().replaceAll("Build info:(?:.+\\s+)*Driver info:.+",""), e.getCause()); // } // } // } // // @Override // public <V> V until(Function<? super T, V> isTrue) { // return super.until(isTrue); // } // } // Path: misc/src/main/java/at/willhaben/willtest/misc/pages/RequireBuilder.java import at.willhaben.willtest.misc.utils.ConditionType; import at.willhaben.willtest.misc.utils.WhFluentWait; package at.willhaben.willtest.misc.pages; public class RequireBuilder { private final PageObject pageObject; private final RequireType requireType; private String errorMessage; RequireBuilder(PageObject pageObject, RequireType requireType) { this.pageObject = pageObject; this.requireType = requireType; } public RequireBuilder withErrorMessage(String message) { this.errorMessage = message; return this; } public void clickable() { clickable(PageObject.DEFAULT_WAIT_TIMEOUT); } public void clickable(long timeout) { clickable(pageObject.getWait(timeout)); } @SuppressWarnings("unchecked") public void clickable(WhFluentWait waiter) {
waiter.until(errorMessage, requireType.buildCondition(ConditionType.CLICKABLE));
willhaben/willtest
misc/src/test/java/at/willhaben/misc/test/XPathBuilderTest.java
// Path: misc/src/main/java/at/willhaben/willtest/misc/utils/ByWh.java // public static XPathBuilder xpath() { // return new XPathBuilder(); // }
import org.junit.Test; import static at.willhaben.willtest.misc.utils.ByWh.xpath; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
package at.willhaben.misc.test; public class XPathBuilderTest { @Test public void testLocatorCombination() {
// Path: misc/src/main/java/at/willhaben/willtest/misc/utils/ByWh.java // public static XPathBuilder xpath() { // return new XPathBuilder(); // } // Path: misc/src/test/java/at/willhaben/misc/test/XPathBuilderTest.java import org.junit.Test; import static at.willhaben.willtest.misc.utils.ByWh.xpath; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; package at.willhaben.misc.test; public class XPathBuilderTest { @Test public void testLocatorCombination() {
String xpath = xpath().byClass("myClass").andId("myId").withText("myText").buildExpression();
willhaben/willtest
core/src/main/java/at/willhaben/willtest/junit5/extensions/PageSourceProvider.java
// Path: core/src/main/java/at/willhaben/willtest/junit5/TestFailureListener.java // public interface TestFailureListener extends BrowserUtilExtension { // // void onFailure(ExtensionContext context, WebDriver driver, Throwable throwable) throws Throwable; // } // // Path: core/src/main/java/at/willhaben/willtest/util/TestReportFile.java // public class TestReportFile { // private static final String REPORT_FOLDER_SYSTEM_PROPERTY = "willtest.reportFolder"; // private static final String COMMON_PREFIX_FOR_ALL_REPORT_FILES = "TR_"; // private static final String DEFAULT_REPORT_FOLDER = "surefire-reports"; // // private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy.MM.dd-HH.mm.ss.SSS"); // // private ExtensionContext testExtensionContext; // private String prefix = ""; // private String postfix = ""; // // public static Builder forTest(ExtensionContext context) { // return new Builder(context); // } // // /** // * Gives back the {@link File} object, which can be used as target for report. // * // * @return the file which can be used as report file // */ // public File getFile() { // String reportFolderPath = getReportFolderDir(); // File reportFolder = new File(reportFolderPath); // if (!reportFolder.exists() && !reportFolder.mkdirs()) { // throw new RuntimeException("Could not create folder " + reportFolder + "!"); // } // return new File(reportFolder, generateFileName()); // } // // public static String getReportFolderDir() { // return Environment.getValue(REPORT_FOLDER_SYSTEM_PROPERTY, DEFAULT_REPORT_FOLDER); // } // // private String getClassName() { // return testExtensionContext.getRequiredTestClass().getSimpleName(); // } // // private String getMethodName() { // return testExtensionContext.getRequiredTestMethod().getName(); // } // // public String getGeneratedName() { // return generateFileName(); // } // // private String generateFileName() { // String className = getClassName(); // String methodName = getMethodName(); // String timeStamp = DATE_FORMAT.format(ZonedDateTime.now()); // return escapeFileName(COMMON_PREFIX_FOR_ALL_REPORT_FILES + prefix + className + // "_" + methodName + "-" + timeStamp + postfix); // } // // private String escapeFileName(String originalName) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < originalName.length(); i++) { // char c = originalName.charAt(i); // if ((c >= '0' && c <= '9') || // (c >= 'A' && c <= 'Z') || // (c >= 'a' && c <= 'z') || // (c == '.') || // (c == '_') || // (c == '-')) { // sb.append(c); // } // } // return sb.toString(); // } // // public static class Builder { // private final TestReportFile testReportFile = new TestReportFile(); // // Builder(ExtensionContext context) { // testReportFile.testExtensionContext = context; // } // // /** // * @param prefix name prefix to be used. F.i. "PaymentModule" // * @return this builder // */ // public Builder withPrefix(String prefix) { // testReportFile.prefix = prefix; // return this; // } // // /** // * @param postfix name postfix to be used. F.i. ".png" // * @return this builder // */ // public Builder withPostix(String postfix) { // testReportFile.postfix = postfix; // return this; // } // // public TestReportFile build() { // return testReportFile; // } // } // }
import at.willhaben.willtest.junit5.TestFailureListener; import at.willhaben.willtest.util.TestReportFile; import org.junit.jupiter.api.extension.ExtensionContext; import org.openqa.selenium.WebDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files;
package at.willhaben.willtest.junit5.extensions; public class PageSourceProvider implements TestFailureListener { private static final Logger LOGGER = LoggerFactory.getLogger(PageSourceProvider.class); @Override public void onFailure(ExtensionContext context, WebDriver driver, Throwable throwable) throws Throwable { String pageSource = driver.getPageSource();
// Path: core/src/main/java/at/willhaben/willtest/junit5/TestFailureListener.java // public interface TestFailureListener extends BrowserUtilExtension { // // void onFailure(ExtensionContext context, WebDriver driver, Throwable throwable) throws Throwable; // } // // Path: core/src/main/java/at/willhaben/willtest/util/TestReportFile.java // public class TestReportFile { // private static final String REPORT_FOLDER_SYSTEM_PROPERTY = "willtest.reportFolder"; // private static final String COMMON_PREFIX_FOR_ALL_REPORT_FILES = "TR_"; // private static final String DEFAULT_REPORT_FOLDER = "surefire-reports"; // // private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy.MM.dd-HH.mm.ss.SSS"); // // private ExtensionContext testExtensionContext; // private String prefix = ""; // private String postfix = ""; // // public static Builder forTest(ExtensionContext context) { // return new Builder(context); // } // // /** // * Gives back the {@link File} object, which can be used as target for report. // * // * @return the file which can be used as report file // */ // public File getFile() { // String reportFolderPath = getReportFolderDir(); // File reportFolder = new File(reportFolderPath); // if (!reportFolder.exists() && !reportFolder.mkdirs()) { // throw new RuntimeException("Could not create folder " + reportFolder + "!"); // } // return new File(reportFolder, generateFileName()); // } // // public static String getReportFolderDir() { // return Environment.getValue(REPORT_FOLDER_SYSTEM_PROPERTY, DEFAULT_REPORT_FOLDER); // } // // private String getClassName() { // return testExtensionContext.getRequiredTestClass().getSimpleName(); // } // // private String getMethodName() { // return testExtensionContext.getRequiredTestMethod().getName(); // } // // public String getGeneratedName() { // return generateFileName(); // } // // private String generateFileName() { // String className = getClassName(); // String methodName = getMethodName(); // String timeStamp = DATE_FORMAT.format(ZonedDateTime.now()); // return escapeFileName(COMMON_PREFIX_FOR_ALL_REPORT_FILES + prefix + className + // "_" + methodName + "-" + timeStamp + postfix); // } // // private String escapeFileName(String originalName) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < originalName.length(); i++) { // char c = originalName.charAt(i); // if ((c >= '0' && c <= '9') || // (c >= 'A' && c <= 'Z') || // (c >= 'a' && c <= 'z') || // (c == '.') || // (c == '_') || // (c == '-')) { // sb.append(c); // } // } // return sb.toString(); // } // // public static class Builder { // private final TestReportFile testReportFile = new TestReportFile(); // // Builder(ExtensionContext context) { // testReportFile.testExtensionContext = context; // } // // /** // * @param prefix name prefix to be used. F.i. "PaymentModule" // * @return this builder // */ // public Builder withPrefix(String prefix) { // testReportFile.prefix = prefix; // return this; // } // // /** // * @param postfix name postfix to be used. F.i. ".png" // * @return this builder // */ // public Builder withPostix(String postfix) { // testReportFile.postfix = postfix; // return this; // } // // public TestReportFile build() { // return testReportFile; // } // } // } // Path: core/src/main/java/at/willhaben/willtest/junit5/extensions/PageSourceProvider.java import at.willhaben.willtest.junit5.TestFailureListener; import at.willhaben.willtest.util.TestReportFile; import org.junit.jupiter.api.extension.ExtensionContext; import org.openqa.selenium.WebDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; package at.willhaben.willtest.junit5.extensions; public class PageSourceProvider implements TestFailureListener { private static final Logger LOGGER = LoggerFactory.getLogger(PageSourceProvider.class); @Override public void onFailure(ExtensionContext context, WebDriver driver, Throwable throwable) throws Throwable { String pageSource = driver.getPageSource();
TestReportFile testReportFile = TestReportFile.forTest(context).withPostix(".html").build();
willhaben/willtest
core/src/test/java/at/willhaben/willtest/test/assertions/ProxyWrapperMockBuilder.java
// Path: core/src/main/java/at/willhaben/willtest/proxy/ProxyWrapper.java // public interface ProxyWrapper { // // BrowserMobProxy getProxy(); // // List<HarRequest> getRequests(); // // List<String> getRequestsUrls(); // // List<HarEntry> getRequestsByUrl(String urlPattern); // // HarEntry getRequestByUrl(String urlPattern); // // List<HarPostDataParam> getRequestFormParamsByUrl(String urlPattern); // // void clearRequests(); // } // // Path: core/src/main/java/at/willhaben/willtest/proxy/impl/ProxyWrapperImpl.java // public class ProxyWrapperImpl implements ProxyWrapper { // // private BrowserMobProxy proxy; // // public ProxyWrapperImpl(BrowserMobProxy proxy) { // this.proxy = proxy; // } // // @Override // public BrowserMobProxy getProxy() { // return proxy; // } // // @Override // public List<HarRequest> getRequests() { // return getEntries() // .stream() // .map(HarEntry::getRequest) // .collect(Collectors.toList()); // } // // @Override // public List<String> getRequestsUrls() { // return getRequests().stream() // .map(HarRequest::getUrl) // .collect(Collectors.toList()); // } // // @Override // public List<HarEntry> getRequestsByUrl(String urlPattern) { // return getEntries().stream() // .filter(entry -> entry.getRequest().getUrl().matches(urlPattern)) // .collect(Collectors.toList()); // } // // @Override // public HarEntry getRequestByUrl(String urlPattern) { // List<HarEntry> matchedEntries = getRequestsByUrl(urlPattern); // if (matchedEntries.size() == 1) { // return matchedEntries.get(0); // } else if (matchedEntries.size() == 0) { // throw new RuntimeException("No request match the given pattern '" + urlPattern + "'."); // } else { // List<String> matchedUrlList = matchedEntries.stream() // .map(entry -> entry.getRequest().getUrl()) // .collect(Collectors.toList()); // throw new RuntimeException("Multiple request match the given pattern '" + urlPattern + "'. " + matchedUrlList.toString()); // } // } // // @Override // public List<HarPostDataParam> getRequestFormParamsByUrl(String urlPattern) { // return getRequestByUrl(urlPattern) // .getRequest() // .getPostData() // .getParams(); // } // // @Override // public void clearRequests() { // proxy.newHar(); // } // // private List<HarEntry> getEntries() { // return proxy.getHar() // .getLog() // .getEntries(); // } // }
import at.willhaben.willtest.proxy.ProxyWrapper; import at.willhaben.willtest.proxy.impl.ProxyWrapperImpl; import net.lightbody.bmp.BrowserMobProxy; import net.lightbody.bmp.core.har.*; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package at.willhaben.willtest.test.assertions; public class ProxyWrapperMockBuilder { private ArrayList<HarEntry> harEntries = new ArrayList<>(); public static ProxyWrapperMockBuilder builder() { return new ProxyWrapperMockBuilder(); } public ProxyWrapperMockBuilder addHarEntry(String url, String body, Map<String, String> formData) { HarEntry entry = mock(HarEntry.class); HarRequest request = mock(HarRequest.class); when(request.getUrl()).thenReturn(url); if (formData != null) { List<HarPostDataParam> postDataParams = formData.keySet().stream() .map(key -> { HarPostDataParam postDataParam = mock(HarPostDataParam.class); when(postDataParam.getName()).thenReturn(key); when(postDataParam.getValue()).thenReturn(formData.get(key)); return postDataParam; }) .collect(Collectors.toList()); HarPostData postData = mock(HarPostData.class); when(postData.getParams()).thenReturn(postDataParams); when(request.getPostData()).thenReturn(postData); } when(entry.getRequest()).thenReturn(request); harEntries.add(entry); return this; }
// Path: core/src/main/java/at/willhaben/willtest/proxy/ProxyWrapper.java // public interface ProxyWrapper { // // BrowserMobProxy getProxy(); // // List<HarRequest> getRequests(); // // List<String> getRequestsUrls(); // // List<HarEntry> getRequestsByUrl(String urlPattern); // // HarEntry getRequestByUrl(String urlPattern); // // List<HarPostDataParam> getRequestFormParamsByUrl(String urlPattern); // // void clearRequests(); // } // // Path: core/src/main/java/at/willhaben/willtest/proxy/impl/ProxyWrapperImpl.java // public class ProxyWrapperImpl implements ProxyWrapper { // // private BrowserMobProxy proxy; // // public ProxyWrapperImpl(BrowserMobProxy proxy) { // this.proxy = proxy; // } // // @Override // public BrowserMobProxy getProxy() { // return proxy; // } // // @Override // public List<HarRequest> getRequests() { // return getEntries() // .stream() // .map(HarEntry::getRequest) // .collect(Collectors.toList()); // } // // @Override // public List<String> getRequestsUrls() { // return getRequests().stream() // .map(HarRequest::getUrl) // .collect(Collectors.toList()); // } // // @Override // public List<HarEntry> getRequestsByUrl(String urlPattern) { // return getEntries().stream() // .filter(entry -> entry.getRequest().getUrl().matches(urlPattern)) // .collect(Collectors.toList()); // } // // @Override // public HarEntry getRequestByUrl(String urlPattern) { // List<HarEntry> matchedEntries = getRequestsByUrl(urlPattern); // if (matchedEntries.size() == 1) { // return matchedEntries.get(0); // } else if (matchedEntries.size() == 0) { // throw new RuntimeException("No request match the given pattern '" + urlPattern + "'."); // } else { // List<String> matchedUrlList = matchedEntries.stream() // .map(entry -> entry.getRequest().getUrl()) // .collect(Collectors.toList()); // throw new RuntimeException("Multiple request match the given pattern '" + urlPattern + "'. " + matchedUrlList.toString()); // } // } // // @Override // public List<HarPostDataParam> getRequestFormParamsByUrl(String urlPattern) { // return getRequestByUrl(urlPattern) // .getRequest() // .getPostData() // .getParams(); // } // // @Override // public void clearRequests() { // proxy.newHar(); // } // // private List<HarEntry> getEntries() { // return proxy.getHar() // .getLog() // .getEntries(); // } // } // Path: core/src/test/java/at/willhaben/willtest/test/assertions/ProxyWrapperMockBuilder.java import at.willhaben.willtest.proxy.ProxyWrapper; import at.willhaben.willtest.proxy.impl.ProxyWrapperImpl; import net.lightbody.bmp.BrowserMobProxy; import net.lightbody.bmp.core.har.*; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package at.willhaben.willtest.test.assertions; public class ProxyWrapperMockBuilder { private ArrayList<HarEntry> harEntries = new ArrayList<>(); public static ProxyWrapperMockBuilder builder() { return new ProxyWrapperMockBuilder(); } public ProxyWrapperMockBuilder addHarEntry(String url, String body, Map<String, String> formData) { HarEntry entry = mock(HarEntry.class); HarRequest request = mock(HarRequest.class); when(request.getUrl()).thenReturn(url); if (formData != null) { List<HarPostDataParam> postDataParams = formData.keySet().stream() .map(key -> { HarPostDataParam postDataParam = mock(HarPostDataParam.class); when(postDataParam.getName()).thenReturn(key); when(postDataParam.getValue()).thenReturn(formData.get(key)); return postDataParam; }) .collect(Collectors.toList()); HarPostData postData = mock(HarPostData.class); when(postData.getParams()).thenReturn(postDataParams); when(request.getPostData()).thenReturn(postData); } when(entry.getRequest()).thenReturn(request); harEntries.add(entry); return this; }
public ProxyWrapper build() {
willhaben/willtest
core/src/test/java/at/willhaben/willtest/test/assertions/ProxyWrapperMockBuilder.java
// Path: core/src/main/java/at/willhaben/willtest/proxy/ProxyWrapper.java // public interface ProxyWrapper { // // BrowserMobProxy getProxy(); // // List<HarRequest> getRequests(); // // List<String> getRequestsUrls(); // // List<HarEntry> getRequestsByUrl(String urlPattern); // // HarEntry getRequestByUrl(String urlPattern); // // List<HarPostDataParam> getRequestFormParamsByUrl(String urlPattern); // // void clearRequests(); // } // // Path: core/src/main/java/at/willhaben/willtest/proxy/impl/ProxyWrapperImpl.java // public class ProxyWrapperImpl implements ProxyWrapper { // // private BrowserMobProxy proxy; // // public ProxyWrapperImpl(BrowserMobProxy proxy) { // this.proxy = proxy; // } // // @Override // public BrowserMobProxy getProxy() { // return proxy; // } // // @Override // public List<HarRequest> getRequests() { // return getEntries() // .stream() // .map(HarEntry::getRequest) // .collect(Collectors.toList()); // } // // @Override // public List<String> getRequestsUrls() { // return getRequests().stream() // .map(HarRequest::getUrl) // .collect(Collectors.toList()); // } // // @Override // public List<HarEntry> getRequestsByUrl(String urlPattern) { // return getEntries().stream() // .filter(entry -> entry.getRequest().getUrl().matches(urlPattern)) // .collect(Collectors.toList()); // } // // @Override // public HarEntry getRequestByUrl(String urlPattern) { // List<HarEntry> matchedEntries = getRequestsByUrl(urlPattern); // if (matchedEntries.size() == 1) { // return matchedEntries.get(0); // } else if (matchedEntries.size() == 0) { // throw new RuntimeException("No request match the given pattern '" + urlPattern + "'."); // } else { // List<String> matchedUrlList = matchedEntries.stream() // .map(entry -> entry.getRequest().getUrl()) // .collect(Collectors.toList()); // throw new RuntimeException("Multiple request match the given pattern '" + urlPattern + "'. " + matchedUrlList.toString()); // } // } // // @Override // public List<HarPostDataParam> getRequestFormParamsByUrl(String urlPattern) { // return getRequestByUrl(urlPattern) // .getRequest() // .getPostData() // .getParams(); // } // // @Override // public void clearRequests() { // proxy.newHar(); // } // // private List<HarEntry> getEntries() { // return proxy.getHar() // .getLog() // .getEntries(); // } // }
import at.willhaben.willtest.proxy.ProxyWrapper; import at.willhaben.willtest.proxy.impl.ProxyWrapperImpl; import net.lightbody.bmp.BrowserMobProxy; import net.lightbody.bmp.core.har.*; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
public ProxyWrapperMockBuilder addHarEntry(String url, String body, Map<String, String> formData) { HarEntry entry = mock(HarEntry.class); HarRequest request = mock(HarRequest.class); when(request.getUrl()).thenReturn(url); if (formData != null) { List<HarPostDataParam> postDataParams = formData.keySet().stream() .map(key -> { HarPostDataParam postDataParam = mock(HarPostDataParam.class); when(postDataParam.getName()).thenReturn(key); when(postDataParam.getValue()).thenReturn(formData.get(key)); return postDataParam; }) .collect(Collectors.toList()); HarPostData postData = mock(HarPostData.class); when(postData.getParams()).thenReturn(postDataParams); when(request.getPostData()).thenReturn(postData); } when(entry.getRequest()).thenReturn(request); harEntries.add(entry); return this; } public ProxyWrapper build() { BrowserMobProxy mockedProxy = mock(BrowserMobProxy.class); Har mockedHar = mock(Har.class); HarLog mockedHarLog = mock(HarLog.class); when(mockedHarLog.getEntries()).thenReturn(harEntries); when(mockedHar.getLog()).thenReturn(mockedHarLog); when(mockedProxy.getHar()).thenReturn(mockedHar);
// Path: core/src/main/java/at/willhaben/willtest/proxy/ProxyWrapper.java // public interface ProxyWrapper { // // BrowserMobProxy getProxy(); // // List<HarRequest> getRequests(); // // List<String> getRequestsUrls(); // // List<HarEntry> getRequestsByUrl(String urlPattern); // // HarEntry getRequestByUrl(String urlPattern); // // List<HarPostDataParam> getRequestFormParamsByUrl(String urlPattern); // // void clearRequests(); // } // // Path: core/src/main/java/at/willhaben/willtest/proxy/impl/ProxyWrapperImpl.java // public class ProxyWrapperImpl implements ProxyWrapper { // // private BrowserMobProxy proxy; // // public ProxyWrapperImpl(BrowserMobProxy proxy) { // this.proxy = proxy; // } // // @Override // public BrowserMobProxy getProxy() { // return proxy; // } // // @Override // public List<HarRequest> getRequests() { // return getEntries() // .stream() // .map(HarEntry::getRequest) // .collect(Collectors.toList()); // } // // @Override // public List<String> getRequestsUrls() { // return getRequests().stream() // .map(HarRequest::getUrl) // .collect(Collectors.toList()); // } // // @Override // public List<HarEntry> getRequestsByUrl(String urlPattern) { // return getEntries().stream() // .filter(entry -> entry.getRequest().getUrl().matches(urlPattern)) // .collect(Collectors.toList()); // } // // @Override // public HarEntry getRequestByUrl(String urlPattern) { // List<HarEntry> matchedEntries = getRequestsByUrl(urlPattern); // if (matchedEntries.size() == 1) { // return matchedEntries.get(0); // } else if (matchedEntries.size() == 0) { // throw new RuntimeException("No request match the given pattern '" + urlPattern + "'."); // } else { // List<String> matchedUrlList = matchedEntries.stream() // .map(entry -> entry.getRequest().getUrl()) // .collect(Collectors.toList()); // throw new RuntimeException("Multiple request match the given pattern '" + urlPattern + "'. " + matchedUrlList.toString()); // } // } // // @Override // public List<HarPostDataParam> getRequestFormParamsByUrl(String urlPattern) { // return getRequestByUrl(urlPattern) // .getRequest() // .getPostData() // .getParams(); // } // // @Override // public void clearRequests() { // proxy.newHar(); // } // // private List<HarEntry> getEntries() { // return proxy.getHar() // .getLog() // .getEntries(); // } // } // Path: core/src/test/java/at/willhaben/willtest/test/assertions/ProxyWrapperMockBuilder.java import at.willhaben.willtest.proxy.ProxyWrapper; import at.willhaben.willtest.proxy.impl.ProxyWrapperImpl; import net.lightbody.bmp.BrowserMobProxy; import net.lightbody.bmp.core.har.*; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public ProxyWrapperMockBuilder addHarEntry(String url, String body, Map<String, String> formData) { HarEntry entry = mock(HarEntry.class); HarRequest request = mock(HarRequest.class); when(request.getUrl()).thenReturn(url); if (formData != null) { List<HarPostDataParam> postDataParams = formData.keySet().stream() .map(key -> { HarPostDataParam postDataParam = mock(HarPostDataParam.class); when(postDataParam.getName()).thenReturn(key); when(postDataParam.getValue()).thenReturn(formData.get(key)); return postDataParam; }) .collect(Collectors.toList()); HarPostData postData = mock(HarPostData.class); when(postData.getParams()).thenReturn(postDataParams); when(request.getPostData()).thenReturn(postData); } when(entry.getRequest()).thenReturn(request); harEntries.add(entry); return this; } public ProxyWrapper build() { BrowserMobProxy mockedProxy = mock(BrowserMobProxy.class); Har mockedHar = mock(Har.class); HarLog mockedHarLog = mock(HarLog.class); when(mockedHarLog.getEntries()).thenReturn(harEntries); when(mockedHar.getLog()).thenReturn(mockedHarLog); when(mockedProxy.getHar()).thenReturn(mockedHar);
return new ProxyWrapperImpl(mockedProxy);
willhaben/willtest
core/src/test/java/at/willhaben/willtest/test/PageSourceProviderTest.java
// Path: core/src/main/java/at/willhaben/willtest/junit5/extensions/PageSourceProvider.java // public class PageSourceProvider implements TestFailureListener { // // private static final Logger LOGGER = LoggerFactory.getLogger(PageSourceProvider.class); // // @Override // public void onFailure(ExtensionContext context, WebDriver driver, Throwable throwable) throws Throwable { // String pageSource = driver.getPageSource(); // TestReportFile testReportFile = TestReportFile.forTest(context).withPostix(".html").build(); // File pageSourceFile = testReportFile.getFile(); // Files.write(pageSourceFile.toPath(), pageSource.getBytes(StandardCharsets.UTF_8)); // LOGGER.info("Saved page source of failed test " + // context.getRequiredTestClass().getSimpleName() + "." + // context.getRequiredTestMethod().getName() + " to " + pageSourceFile.getAbsolutePath()); // } // } // // Path: core/src/test/java/at/willhaben/willtest/test/mock/ExtensionMock.java // public class ExtensionMock { // // public static ExtensionContext mockWithTestClassAndMethod(Class testclass, String methodName) { // ExtensionContext context = mock(ExtensionContext.class); // doReturn(testclass).when(context).getRequiredTestClass(); // Method testMethod = mock(Method.class); // doReturn(methodName).when(testMethod).getName(); // doReturn(testMethod).when(context).getRequiredTestMethod(); // return context; // } // } // // Path: core/src/main/java/at/willhaben/willtest/util/TestReportFile.java // public static String getReportFolderDir() { // return Environment.getValue(REPORT_FOLDER_SYSTEM_PROPERTY, DEFAULT_REPORT_FOLDER); // }
import at.willhaben.willtest.junit5.extensions.PageSourceProvider; import at.willhaben.willtest.test.mock.ExtensionMock; import org.hamcrest.Matchers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtensionContext; import org.mockito.Mockito; import org.openqa.selenium.WebDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static at.willhaben.willtest.util.TestReportFile.getReportFolderDir; import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertTrue;
package at.willhaben.willtest.test; class PageSourceProviderTest { private static final Logger LOGGER = LoggerFactory.getLogger(PageSourceProviderTest.class); private static final String PAGESOURCE = "This is the Pagesource!"; private ExtensionContext context; private WebDriver driver; private String testMethodName; @BeforeEach void setUp() { testMethodName = "testPageSourceMethod" + System.nanoTime();
// Path: core/src/main/java/at/willhaben/willtest/junit5/extensions/PageSourceProvider.java // public class PageSourceProvider implements TestFailureListener { // // private static final Logger LOGGER = LoggerFactory.getLogger(PageSourceProvider.class); // // @Override // public void onFailure(ExtensionContext context, WebDriver driver, Throwable throwable) throws Throwable { // String pageSource = driver.getPageSource(); // TestReportFile testReportFile = TestReportFile.forTest(context).withPostix(".html").build(); // File pageSourceFile = testReportFile.getFile(); // Files.write(pageSourceFile.toPath(), pageSource.getBytes(StandardCharsets.UTF_8)); // LOGGER.info("Saved page source of failed test " + // context.getRequiredTestClass().getSimpleName() + "." + // context.getRequiredTestMethod().getName() + " to " + pageSourceFile.getAbsolutePath()); // } // } // // Path: core/src/test/java/at/willhaben/willtest/test/mock/ExtensionMock.java // public class ExtensionMock { // // public static ExtensionContext mockWithTestClassAndMethod(Class testclass, String methodName) { // ExtensionContext context = mock(ExtensionContext.class); // doReturn(testclass).when(context).getRequiredTestClass(); // Method testMethod = mock(Method.class); // doReturn(methodName).when(testMethod).getName(); // doReturn(testMethod).when(context).getRequiredTestMethod(); // return context; // } // } // // Path: core/src/main/java/at/willhaben/willtest/util/TestReportFile.java // public static String getReportFolderDir() { // return Environment.getValue(REPORT_FOLDER_SYSTEM_PROPERTY, DEFAULT_REPORT_FOLDER); // } // Path: core/src/test/java/at/willhaben/willtest/test/PageSourceProviderTest.java import at.willhaben.willtest.junit5.extensions.PageSourceProvider; import at.willhaben.willtest.test.mock.ExtensionMock; import org.hamcrest.Matchers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtensionContext; import org.mockito.Mockito; import org.openqa.selenium.WebDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static at.willhaben.willtest.util.TestReportFile.getReportFolderDir; import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertTrue; package at.willhaben.willtest.test; class PageSourceProviderTest { private static final Logger LOGGER = LoggerFactory.getLogger(PageSourceProviderTest.class); private static final String PAGESOURCE = "This is the Pagesource!"; private ExtensionContext context; private WebDriver driver; private String testMethodName; @BeforeEach void setUp() { testMethodName = "testPageSourceMethod" + System.nanoTime();
context = ExtensionMock.mockWithTestClassAndMethod(PageSourceProviderTest.class, testMethodName);
willhaben/willtest
core/src/test/java/at/willhaben/willtest/test/PageSourceProviderTest.java
// Path: core/src/main/java/at/willhaben/willtest/junit5/extensions/PageSourceProvider.java // public class PageSourceProvider implements TestFailureListener { // // private static final Logger LOGGER = LoggerFactory.getLogger(PageSourceProvider.class); // // @Override // public void onFailure(ExtensionContext context, WebDriver driver, Throwable throwable) throws Throwable { // String pageSource = driver.getPageSource(); // TestReportFile testReportFile = TestReportFile.forTest(context).withPostix(".html").build(); // File pageSourceFile = testReportFile.getFile(); // Files.write(pageSourceFile.toPath(), pageSource.getBytes(StandardCharsets.UTF_8)); // LOGGER.info("Saved page source of failed test " + // context.getRequiredTestClass().getSimpleName() + "." + // context.getRequiredTestMethod().getName() + " to " + pageSourceFile.getAbsolutePath()); // } // } // // Path: core/src/test/java/at/willhaben/willtest/test/mock/ExtensionMock.java // public class ExtensionMock { // // public static ExtensionContext mockWithTestClassAndMethod(Class testclass, String methodName) { // ExtensionContext context = mock(ExtensionContext.class); // doReturn(testclass).when(context).getRequiredTestClass(); // Method testMethod = mock(Method.class); // doReturn(methodName).when(testMethod).getName(); // doReturn(testMethod).when(context).getRequiredTestMethod(); // return context; // } // } // // Path: core/src/main/java/at/willhaben/willtest/util/TestReportFile.java // public static String getReportFolderDir() { // return Environment.getValue(REPORT_FOLDER_SYSTEM_PROPERTY, DEFAULT_REPORT_FOLDER); // }
import at.willhaben.willtest.junit5.extensions.PageSourceProvider; import at.willhaben.willtest.test.mock.ExtensionMock; import org.hamcrest.Matchers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtensionContext; import org.mockito.Mockito; import org.openqa.selenium.WebDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static at.willhaben.willtest.util.TestReportFile.getReportFolderDir; import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertTrue;
package at.willhaben.willtest.test; class PageSourceProviderTest { private static final Logger LOGGER = LoggerFactory.getLogger(PageSourceProviderTest.class); private static final String PAGESOURCE = "This is the Pagesource!"; private ExtensionContext context; private WebDriver driver; private String testMethodName; @BeforeEach void setUp() { testMethodName = "testPageSourceMethod" + System.nanoTime(); context = ExtensionMock.mockWithTestClassAndMethod(PageSourceProviderTest.class, testMethodName); driver = Mockito.mock(WebDriver.class); Mockito.when(driver.getPageSource()).thenReturn(PAGESOURCE); } @Test void testPagesourceFileCreation() throws Throwable {
// Path: core/src/main/java/at/willhaben/willtest/junit5/extensions/PageSourceProvider.java // public class PageSourceProvider implements TestFailureListener { // // private static final Logger LOGGER = LoggerFactory.getLogger(PageSourceProvider.class); // // @Override // public void onFailure(ExtensionContext context, WebDriver driver, Throwable throwable) throws Throwable { // String pageSource = driver.getPageSource(); // TestReportFile testReportFile = TestReportFile.forTest(context).withPostix(".html").build(); // File pageSourceFile = testReportFile.getFile(); // Files.write(pageSourceFile.toPath(), pageSource.getBytes(StandardCharsets.UTF_8)); // LOGGER.info("Saved page source of failed test " + // context.getRequiredTestClass().getSimpleName() + "." + // context.getRequiredTestMethod().getName() + " to " + pageSourceFile.getAbsolutePath()); // } // } // // Path: core/src/test/java/at/willhaben/willtest/test/mock/ExtensionMock.java // public class ExtensionMock { // // public static ExtensionContext mockWithTestClassAndMethod(Class testclass, String methodName) { // ExtensionContext context = mock(ExtensionContext.class); // doReturn(testclass).when(context).getRequiredTestClass(); // Method testMethod = mock(Method.class); // doReturn(methodName).when(testMethod).getName(); // doReturn(testMethod).when(context).getRequiredTestMethod(); // return context; // } // } // // Path: core/src/main/java/at/willhaben/willtest/util/TestReportFile.java // public static String getReportFolderDir() { // return Environment.getValue(REPORT_FOLDER_SYSTEM_PROPERTY, DEFAULT_REPORT_FOLDER); // } // Path: core/src/test/java/at/willhaben/willtest/test/PageSourceProviderTest.java import at.willhaben.willtest.junit5.extensions.PageSourceProvider; import at.willhaben.willtest.test.mock.ExtensionMock; import org.hamcrest.Matchers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtensionContext; import org.mockito.Mockito; import org.openqa.selenium.WebDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static at.willhaben.willtest.util.TestReportFile.getReportFolderDir; import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertTrue; package at.willhaben.willtest.test; class PageSourceProviderTest { private static final Logger LOGGER = LoggerFactory.getLogger(PageSourceProviderTest.class); private static final String PAGESOURCE = "This is the Pagesource!"; private ExtensionContext context; private WebDriver driver; private String testMethodName; @BeforeEach void setUp() { testMethodName = "testPageSourceMethod" + System.nanoTime(); context = ExtensionMock.mockWithTestClassAndMethod(PageSourceProviderTest.class, testMethodName); driver = Mockito.mock(WebDriver.class); Mockito.when(driver.getPageSource()).thenReturn(PAGESOURCE); } @Test void testPagesourceFileCreation() throws Throwable {
new PageSourceProvider().onFailure(context, driver, new AssertionError("Test failure"));
willhaben/willtest
core/src/test/java/at/willhaben/willtest/test/PageSourceProviderTest.java
// Path: core/src/main/java/at/willhaben/willtest/junit5/extensions/PageSourceProvider.java // public class PageSourceProvider implements TestFailureListener { // // private static final Logger LOGGER = LoggerFactory.getLogger(PageSourceProvider.class); // // @Override // public void onFailure(ExtensionContext context, WebDriver driver, Throwable throwable) throws Throwable { // String pageSource = driver.getPageSource(); // TestReportFile testReportFile = TestReportFile.forTest(context).withPostix(".html").build(); // File pageSourceFile = testReportFile.getFile(); // Files.write(pageSourceFile.toPath(), pageSource.getBytes(StandardCharsets.UTF_8)); // LOGGER.info("Saved page source of failed test " + // context.getRequiredTestClass().getSimpleName() + "." + // context.getRequiredTestMethod().getName() + " to " + pageSourceFile.getAbsolutePath()); // } // } // // Path: core/src/test/java/at/willhaben/willtest/test/mock/ExtensionMock.java // public class ExtensionMock { // // public static ExtensionContext mockWithTestClassAndMethod(Class testclass, String methodName) { // ExtensionContext context = mock(ExtensionContext.class); // doReturn(testclass).when(context).getRequiredTestClass(); // Method testMethod = mock(Method.class); // doReturn(methodName).when(testMethod).getName(); // doReturn(testMethod).when(context).getRequiredTestMethod(); // return context; // } // } // // Path: core/src/main/java/at/willhaben/willtest/util/TestReportFile.java // public static String getReportFolderDir() { // return Environment.getValue(REPORT_FOLDER_SYSTEM_PROPERTY, DEFAULT_REPORT_FOLDER); // }
import at.willhaben.willtest.junit5.extensions.PageSourceProvider; import at.willhaben.willtest.test.mock.ExtensionMock; import org.hamcrest.Matchers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtensionContext; import org.mockito.Mockito; import org.openqa.selenium.WebDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static at.willhaben.willtest.util.TestReportFile.getReportFolderDir; import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertTrue;
package at.willhaben.willtest.test; class PageSourceProviderTest { private static final Logger LOGGER = LoggerFactory.getLogger(PageSourceProviderTest.class); private static final String PAGESOURCE = "This is the Pagesource!"; private ExtensionContext context; private WebDriver driver; private String testMethodName; @BeforeEach void setUp() { testMethodName = "testPageSourceMethod" + System.nanoTime(); context = ExtensionMock.mockWithTestClassAndMethod(PageSourceProviderTest.class, testMethodName); driver = Mockito.mock(WebDriver.class); Mockito.when(driver.getPageSource()).thenReturn(PAGESOURCE); } @Test void testPagesourceFileCreation() throws Throwable { new PageSourceProvider().onFailure(context, driver, new AssertionError("Test failure"));
// Path: core/src/main/java/at/willhaben/willtest/junit5/extensions/PageSourceProvider.java // public class PageSourceProvider implements TestFailureListener { // // private static final Logger LOGGER = LoggerFactory.getLogger(PageSourceProvider.class); // // @Override // public void onFailure(ExtensionContext context, WebDriver driver, Throwable throwable) throws Throwable { // String pageSource = driver.getPageSource(); // TestReportFile testReportFile = TestReportFile.forTest(context).withPostix(".html").build(); // File pageSourceFile = testReportFile.getFile(); // Files.write(pageSourceFile.toPath(), pageSource.getBytes(StandardCharsets.UTF_8)); // LOGGER.info("Saved page source of failed test " + // context.getRequiredTestClass().getSimpleName() + "." + // context.getRequiredTestMethod().getName() + " to " + pageSourceFile.getAbsolutePath()); // } // } // // Path: core/src/test/java/at/willhaben/willtest/test/mock/ExtensionMock.java // public class ExtensionMock { // // public static ExtensionContext mockWithTestClassAndMethod(Class testclass, String methodName) { // ExtensionContext context = mock(ExtensionContext.class); // doReturn(testclass).when(context).getRequiredTestClass(); // Method testMethod = mock(Method.class); // doReturn(methodName).when(testMethod).getName(); // doReturn(testMethod).when(context).getRequiredTestMethod(); // return context; // } // } // // Path: core/src/main/java/at/willhaben/willtest/util/TestReportFile.java // public static String getReportFolderDir() { // return Environment.getValue(REPORT_FOLDER_SYSTEM_PROPERTY, DEFAULT_REPORT_FOLDER); // } // Path: core/src/test/java/at/willhaben/willtest/test/PageSourceProviderTest.java import at.willhaben.willtest.junit5.extensions.PageSourceProvider; import at.willhaben.willtest.test.mock.ExtensionMock; import org.hamcrest.Matchers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtensionContext; import org.mockito.Mockito; import org.openqa.selenium.WebDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static at.willhaben.willtest.util.TestReportFile.getReportFolderDir; import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertTrue; package at.willhaben.willtest.test; class PageSourceProviderTest { private static final Logger LOGGER = LoggerFactory.getLogger(PageSourceProviderTest.class); private static final String PAGESOURCE = "This is the Pagesource!"; private ExtensionContext context; private WebDriver driver; private String testMethodName; @BeforeEach void setUp() { testMethodName = "testPageSourceMethod" + System.nanoTime(); context = ExtensionMock.mockWithTestClassAndMethod(PageSourceProviderTest.class, testMethodName); driver = Mockito.mock(WebDriver.class); Mockito.when(driver.getPageSource()).thenReturn(PAGESOURCE); } @Test void testPagesourceFileCreation() throws Throwable { new PageSourceProvider().onFailure(context, driver, new AssertionError("Test failure"));
File reportDirectory = new File(getReportFolderDir());
willhaben/willtest
browserstack/src/main/java/at/willhaben/willtest/browserstack/BrowserstackEnvironment.java
// Path: browserstack/src/main/java/at/willhaben/willtest/browserstack/exception/BrowserstackEnvironmentException.java // public class BrowserstackEnvironmentException extends RuntimeException { // // public BrowserstackEnvironmentException(String message) { // super(message); // } // } // // Path: browserstack/src/main/java/at/willhaben/willtest/browserstack/BrowserstackSystemProperties.java // public class BrowserstackSystemProperties { // // public static final String BROWSERSTACK_HUB_LOCAL = "browserstack.local"; // public static final String BROWSERSTACK_PLATFORM = "platform"; // public static final String BROWSERSTACK_PLATFORM_VERSION = "platform.version"; // public static final String BROWSERSTACK_BROWSER = "browser"; // public static final String BROWSERSTACK_BROWSER_VERSION = "browser.version"; // public static final String BROWSERSTACK_DISPLAY_RESOLUTION = "display.resolution"; // // public static final String BROWSERSTACK_BUILD = "browserstack.build"; // public static final String BROWSERSTACK_PROJECT = "browserstack.project"; // // public static String getBrowserstackLocal() { // return getProperty(BROWSERSTACK_HUB_LOCAL, "false"); // } // // public static String getBrowserstackPlatform() { // return getProperty(BROWSERSTACK_PLATFORM, "linux"); // } // // public static String getBrowserstackPlatformVersion() { // return getProperty(BROWSERSTACK_PLATFORM_VERSION, "asdf"); // } // // public static String getBrowserstackBrowser() { // return getProperty(BROWSERSTACK_BROWSER, "firefox"); // } // // public static String getBrowserstackBrowserVersion() { // return getProperty(BROWSERSTACK_BROWSER_VERSION, "asdf"); // } // // public static String getBrowserstackDisplayResolution() { // return getProperty(BROWSERSTACK_DISPLAY_RESOLUTION, "1920x1080"); // } // // public static Optional<String> getBuildName() { // return Optional.ofNullable(getProperty(BROWSERSTACK_BUILD)); // } // // public static Optional<String> getProjectName() { // return Optional.ofNullable(getProperty(BROWSERSTACK_PROJECT)); // } // }
import at.willhaben.willtest.browserstack.exception.BrowserstackEnvironmentException; import org.openqa.selenium.Capabilities; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.remote.DesiredCapabilities; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static at.willhaben.willtest.browserstack.BrowserstackSystemProperties.*;
public static final String CAPABILITY_PROJECT = "project"; private final DateTimeFormatter BUILD_DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy.MM.dd"); private String os; private String osVersion; private String browser; private String browserVersion; private String displayResolution; private String local; private BrowserstackEnvironment(String os, String osVersion, String browser, String browserVersion, String displayResolution, String local) { this.os = os; this.osVersion = osVersion; this.browser = browser; this.browserVersion = browserVersion; this.displayResolution = displayResolution; this.local = local; } public static List<BrowserstackEnvironment> parseFromSystemProperties() { List<String> platforms = parseFromCommaSeparatedString(getBrowserstackPlatform()); List<String> platformsVersions = parseFromCommaSeparatedString(getBrowserstackPlatformVersion()); List<String> browsers = parseFromCommaSeparatedString(getBrowserstackBrowser()); List<String> browsersVersions = parseFromCommaSeparatedString(getBrowserstackBrowserVersion()); List<String> displayResolutions = parseFromCommaSeparatedString(getBrowserstackDisplayResolution()); String local = getBrowserstackLocal(); if((platforms.size() != platformsVersions.size()) || (platforms.size() != browsers.size()) || (platforms.size() != browsersVersions.size())) {
// Path: browserstack/src/main/java/at/willhaben/willtest/browserstack/exception/BrowserstackEnvironmentException.java // public class BrowserstackEnvironmentException extends RuntimeException { // // public BrowserstackEnvironmentException(String message) { // super(message); // } // } // // Path: browserstack/src/main/java/at/willhaben/willtest/browserstack/BrowserstackSystemProperties.java // public class BrowserstackSystemProperties { // // public static final String BROWSERSTACK_HUB_LOCAL = "browserstack.local"; // public static final String BROWSERSTACK_PLATFORM = "platform"; // public static final String BROWSERSTACK_PLATFORM_VERSION = "platform.version"; // public static final String BROWSERSTACK_BROWSER = "browser"; // public static final String BROWSERSTACK_BROWSER_VERSION = "browser.version"; // public static final String BROWSERSTACK_DISPLAY_RESOLUTION = "display.resolution"; // // public static final String BROWSERSTACK_BUILD = "browserstack.build"; // public static final String BROWSERSTACK_PROJECT = "browserstack.project"; // // public static String getBrowserstackLocal() { // return getProperty(BROWSERSTACK_HUB_LOCAL, "false"); // } // // public static String getBrowserstackPlatform() { // return getProperty(BROWSERSTACK_PLATFORM, "linux"); // } // // public static String getBrowserstackPlatformVersion() { // return getProperty(BROWSERSTACK_PLATFORM_VERSION, "asdf"); // } // // public static String getBrowserstackBrowser() { // return getProperty(BROWSERSTACK_BROWSER, "firefox"); // } // // public static String getBrowserstackBrowserVersion() { // return getProperty(BROWSERSTACK_BROWSER_VERSION, "asdf"); // } // // public static String getBrowserstackDisplayResolution() { // return getProperty(BROWSERSTACK_DISPLAY_RESOLUTION, "1920x1080"); // } // // public static Optional<String> getBuildName() { // return Optional.ofNullable(getProperty(BROWSERSTACK_BUILD)); // } // // public static Optional<String> getProjectName() { // return Optional.ofNullable(getProperty(BROWSERSTACK_PROJECT)); // } // } // Path: browserstack/src/main/java/at/willhaben/willtest/browserstack/BrowserstackEnvironment.java import at.willhaben.willtest.browserstack.exception.BrowserstackEnvironmentException; import org.openqa.selenium.Capabilities; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.remote.DesiredCapabilities; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static at.willhaben.willtest.browserstack.BrowserstackSystemProperties.*; public static final String CAPABILITY_PROJECT = "project"; private final DateTimeFormatter BUILD_DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy.MM.dd"); private String os; private String osVersion; private String browser; private String browserVersion; private String displayResolution; private String local; private BrowserstackEnvironment(String os, String osVersion, String browser, String browserVersion, String displayResolution, String local) { this.os = os; this.osVersion = osVersion; this.browser = browser; this.browserVersion = browserVersion; this.displayResolution = displayResolution; this.local = local; } public static List<BrowserstackEnvironment> parseFromSystemProperties() { List<String> platforms = parseFromCommaSeparatedString(getBrowserstackPlatform()); List<String> platformsVersions = parseFromCommaSeparatedString(getBrowserstackPlatformVersion()); List<String> browsers = parseFromCommaSeparatedString(getBrowserstackBrowser()); List<String> browsersVersions = parseFromCommaSeparatedString(getBrowserstackBrowserVersion()); List<String> displayResolutions = parseFromCommaSeparatedString(getBrowserstackDisplayResolution()); String local = getBrowserstackLocal(); if((platforms.size() != platformsVersions.size()) || (platforms.size() != browsers.size()) || (platforms.size() != browsersVersions.size())) {
throw new BrowserstackEnvironmentException("If you use comma separated environments for Browserstack, every config" +
willhaben/willtest
misc/src/main/java/at/willhaben/willtest/misc/pages/WaitForBuilder.java
// Path: misc/src/main/java/at/willhaben/willtest/misc/utils/ConditionType.java // public enum ConditionType { // CLICKABLE, // VISIBLE // }
import at.willhaben.willtest.misc.utils.ConditionType; import org.openqa.selenium.By; import org.openqa.selenium.WebElement;
package at.willhaben.willtest.misc.pages; public class WaitForBuilder extends AbstractWaitingBuilder<WebElement> { WaitForBuilder(PageObject pageObject, WebElement webElement) { super(pageObject, webElement); } WaitForBuilder(PageObject pageObject, By by) { super(pageObject, by); } @Override public WebElement clickable(long timeout) {
// Path: misc/src/main/java/at/willhaben/willtest/misc/utils/ConditionType.java // public enum ConditionType { // CLICKABLE, // VISIBLE // } // Path: misc/src/main/java/at/willhaben/willtest/misc/pages/WaitForBuilder.java import at.willhaben.willtest.misc.utils.ConditionType; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; package at.willhaben.willtest.misc.pages; public class WaitForBuilder extends AbstractWaitingBuilder<WebElement> { WaitForBuilder(PageObject pageObject, WebElement webElement) { super(pageObject, webElement); } WaitForBuilder(PageObject pageObject, By by) { super(pageObject, by); } @Override public WebElement clickable(long timeout) {
return getPageObject().getWait().until(generateCondition(ConditionType.CLICKABLE));
willhaben/willtest
core/src/main/java/at/willhaben/willtest/junit5/OptionModifier.java
// Path: core/src/main/java/at/willhaben/willtest/util/AndroidOptions.java // public class AndroidOptions extends DesiredCapabilities { // } // // Path: core/src/main/java/at/willhaben/willtest/util/IOsOptions.java // public class IOsOptions extends DesiredCapabilities { // }
import at.willhaben.willtest.util.AndroidOptions; import at.willhaben.willtest.util.IOsOptions; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.edge.EdgeOptions; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.ie.InternetExplorerOptions;
package at.willhaben.willtest.junit5; public interface OptionModifier extends BrowserUtilExtension { default FirefoxOptions modifyFirefoxOptions(FirefoxOptions options) { return options; } default ChromeOptions modifyChromeOptions(ChromeOptions options) { return options; } default EdgeOptions modifyEdgeOptions(EdgeOptions options) { return options; } default InternetExplorerOptions modifyInternetExplorerOptions(InternetExplorerOptions options) { return options; }
// Path: core/src/main/java/at/willhaben/willtest/util/AndroidOptions.java // public class AndroidOptions extends DesiredCapabilities { // } // // Path: core/src/main/java/at/willhaben/willtest/util/IOsOptions.java // public class IOsOptions extends DesiredCapabilities { // } // Path: core/src/main/java/at/willhaben/willtest/junit5/OptionModifier.java import at.willhaben.willtest.util.AndroidOptions; import at.willhaben.willtest.util.IOsOptions; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.edge.EdgeOptions; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.ie.InternetExplorerOptions; package at.willhaben.willtest.junit5; public interface OptionModifier extends BrowserUtilExtension { default FirefoxOptions modifyFirefoxOptions(FirefoxOptions options) { return options; } default ChromeOptions modifyChromeOptions(ChromeOptions options) { return options; } default EdgeOptions modifyEdgeOptions(EdgeOptions options) { return options; } default InternetExplorerOptions modifyInternetExplorerOptions(InternetExplorerOptions options) { return options; }
default AndroidOptions modifyAndroidOptions(AndroidOptions options) {
willhaben/willtest
core/src/main/java/at/willhaben/willtest/junit5/OptionModifier.java
// Path: core/src/main/java/at/willhaben/willtest/util/AndroidOptions.java // public class AndroidOptions extends DesiredCapabilities { // } // // Path: core/src/main/java/at/willhaben/willtest/util/IOsOptions.java // public class IOsOptions extends DesiredCapabilities { // }
import at.willhaben.willtest.util.AndroidOptions; import at.willhaben.willtest.util.IOsOptions; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.edge.EdgeOptions; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.ie.InternetExplorerOptions;
package at.willhaben.willtest.junit5; public interface OptionModifier extends BrowserUtilExtension { default FirefoxOptions modifyFirefoxOptions(FirefoxOptions options) { return options; } default ChromeOptions modifyChromeOptions(ChromeOptions options) { return options; } default EdgeOptions modifyEdgeOptions(EdgeOptions options) { return options; } default InternetExplorerOptions modifyInternetExplorerOptions(InternetExplorerOptions options) { return options; } default AndroidOptions modifyAndroidOptions(AndroidOptions options) { return options; }
// Path: core/src/main/java/at/willhaben/willtest/util/AndroidOptions.java // public class AndroidOptions extends DesiredCapabilities { // } // // Path: core/src/main/java/at/willhaben/willtest/util/IOsOptions.java // public class IOsOptions extends DesiredCapabilities { // } // Path: core/src/main/java/at/willhaben/willtest/junit5/OptionModifier.java import at.willhaben.willtest.util.AndroidOptions; import at.willhaben.willtest.util.IOsOptions; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.edge.EdgeOptions; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.ie.InternetExplorerOptions; package at.willhaben.willtest.junit5; public interface OptionModifier extends BrowserUtilExtension { default FirefoxOptions modifyFirefoxOptions(FirefoxOptions options) { return options; } default ChromeOptions modifyChromeOptions(ChromeOptions options) { return options; } default EdgeOptions modifyEdgeOptions(EdgeOptions options) { return options; } default InternetExplorerOptions modifyInternetExplorerOptions(InternetExplorerOptions options) { return options; } default AndroidOptions modifyAndroidOptions(AndroidOptions options) { return options; }
default IOsOptions modifyIOsOptions(IOsOptions options) {
willhaben/willtest
misc/src/main/java/at/willhaben/willtest/misc/pages/PageObject.java
// Path: misc/src/main/java/at/willhaben/willtest/misc/utils/WhFluentWait.java // public class WhFluentWait<T> extends FluentWait<T> { // // public WhFluentWait(T input) { // super(input); // } // // public WhFluentWait(T input, Clock clock, Sleeper sleeper) { // super(input, clock, sleeper); // } // // /** // * Waits until the given condition is met. Throws an {@link AssertionError} instead of a {@link TimeoutException} // * when the condition fails because the error is known. // * @param errorMessage concrete error message describing the failure // * @param isTrue the parameter to pass to the {@link ExpectedCondition} // * @param <V> The function's expected return type. // * @return The function's return value if the function returned something different // * from null or false before the timeout expired. // * @throws AssertionError if the timeout expires // */ // public <V> V until(String errorMessage, Function<? super T, V> isTrue) { // try { // return super.until(isTrue); // } catch (TimeoutException e) { // if (Objects.nonNull(errorMessage) && !"".equals(errorMessage)) { // throw new AssertionError(errorMessage, e); // } else { // //Regex replacing parts that hinder allure from grouping erros in the report when using "require" without custom error messages // throw new TimeoutException(e.getMessage().replaceAll("Build info:(?:.+\\s+)*Driver info:.+",""), e.getCause()); // } // } // } // // @Override // public <V> V until(Function<? super T, V> isTrue) { // return super.until(isTrue); // } // } // // Path: misc/src/main/java/at/willhaben/willtest/misc/utils/XPathOrCssUtil.java // public class XPathOrCssUtil { // // /** // * Generates a {@link By}. Checks for the first character in the string. A leading '/' generates a // * {@link By#xpath(String)} otherwise a {@link By#cssSelector(String)}. // * @param xPathOrCss locator string // * @return locator for selenium // */ // public static By mapToBy(String xPathOrCss) { // if (xPathOrCss.startsWith("/")) { // return By.xpath(xPathOrCss); // } else { // return By.cssSelector(xPathOrCss); // } // } // }
import at.willhaben.willtest.misc.utils.WhFluentWait; import at.willhaben.willtest.misc.utils.XPathOrCssUtil; import org.openqa.selenium.WebElement; import org.openqa.selenium.SearchContext; import org.openqa.selenium.WebDriver; import org.openqa.selenium.By; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.FluentWait; import java.time.Duration; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Function; import java.util.function.Predicate;
* @param elements list of {@link WebElement} */ public void clickRandomWebElement(List<WebElement> elements) { getRandomElement(elements).click(); } /** * Clicks on a random {@link WebElement} in given list. * @param lowerBound minimal index for the calculation of the random element * @param elements list of {@link WebElement} */ public void clickRandomWebElement(int lowerBound, List<WebElement> elements) { getRandomElement(lowerBound, elements).click(); } /** * Waiting on a specific {@link WebElement}. * @param element to wait for * @return Builder for waiting for a specific element. */ public WaitForBuilder waitFor(WebElement element) { return new WaitForBuilder(this, element); } /** * Waiting on a specific {@link WebElement} identified by an XPath expression or a CSS selector. * @param xPathOrCss to wait for * @return Builder for waiting for a specific element. */ public WaitForBuilder waitFor(String xPathOrCss) {
// Path: misc/src/main/java/at/willhaben/willtest/misc/utils/WhFluentWait.java // public class WhFluentWait<T> extends FluentWait<T> { // // public WhFluentWait(T input) { // super(input); // } // // public WhFluentWait(T input, Clock clock, Sleeper sleeper) { // super(input, clock, sleeper); // } // // /** // * Waits until the given condition is met. Throws an {@link AssertionError} instead of a {@link TimeoutException} // * when the condition fails because the error is known. // * @param errorMessage concrete error message describing the failure // * @param isTrue the parameter to pass to the {@link ExpectedCondition} // * @param <V> The function's expected return type. // * @return The function's return value if the function returned something different // * from null or false before the timeout expired. // * @throws AssertionError if the timeout expires // */ // public <V> V until(String errorMessage, Function<? super T, V> isTrue) { // try { // return super.until(isTrue); // } catch (TimeoutException e) { // if (Objects.nonNull(errorMessage) && !"".equals(errorMessage)) { // throw new AssertionError(errorMessage, e); // } else { // //Regex replacing parts that hinder allure from grouping erros in the report when using "require" without custom error messages // throw new TimeoutException(e.getMessage().replaceAll("Build info:(?:.+\\s+)*Driver info:.+",""), e.getCause()); // } // } // } // // @Override // public <V> V until(Function<? super T, V> isTrue) { // return super.until(isTrue); // } // } // // Path: misc/src/main/java/at/willhaben/willtest/misc/utils/XPathOrCssUtil.java // public class XPathOrCssUtil { // // /** // * Generates a {@link By}. Checks for the first character in the string. A leading '/' generates a // * {@link By#xpath(String)} otherwise a {@link By#cssSelector(String)}. // * @param xPathOrCss locator string // * @return locator for selenium // */ // public static By mapToBy(String xPathOrCss) { // if (xPathOrCss.startsWith("/")) { // return By.xpath(xPathOrCss); // } else { // return By.cssSelector(xPathOrCss); // } // } // } // Path: misc/src/main/java/at/willhaben/willtest/misc/pages/PageObject.java import at.willhaben.willtest.misc.utils.WhFluentWait; import at.willhaben.willtest.misc.utils.XPathOrCssUtil; import org.openqa.selenium.WebElement; import org.openqa.selenium.SearchContext; import org.openqa.selenium.WebDriver; import org.openqa.selenium.By; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.FluentWait; import java.time.Duration; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Function; import java.util.function.Predicate; * @param elements list of {@link WebElement} */ public void clickRandomWebElement(List<WebElement> elements) { getRandomElement(elements).click(); } /** * Clicks on a random {@link WebElement} in given list. * @param lowerBound minimal index for the calculation of the random element * @param elements list of {@link WebElement} */ public void clickRandomWebElement(int lowerBound, List<WebElement> elements) { getRandomElement(lowerBound, elements).click(); } /** * Waiting on a specific {@link WebElement}. * @param element to wait for * @return Builder for waiting for a specific element. */ public WaitForBuilder waitFor(WebElement element) { return new WaitForBuilder(this, element); } /** * Waiting on a specific {@link WebElement} identified by an XPath expression or a CSS selector. * @param xPathOrCss to wait for * @return Builder for waiting for a specific element. */ public WaitForBuilder waitFor(String xPathOrCss) {
return new WaitForBuilder(this, XPathOrCssUtil.mapToBy(xPathOrCss));
willhaben/willtest
misc/src/main/java/at/willhaben/willtest/misc/pages/PageObject.java
// Path: misc/src/main/java/at/willhaben/willtest/misc/utils/WhFluentWait.java // public class WhFluentWait<T> extends FluentWait<T> { // // public WhFluentWait(T input) { // super(input); // } // // public WhFluentWait(T input, Clock clock, Sleeper sleeper) { // super(input, clock, sleeper); // } // // /** // * Waits until the given condition is met. Throws an {@link AssertionError} instead of a {@link TimeoutException} // * when the condition fails because the error is known. // * @param errorMessage concrete error message describing the failure // * @param isTrue the parameter to pass to the {@link ExpectedCondition} // * @param <V> The function's expected return type. // * @return The function's return value if the function returned something different // * from null or false before the timeout expired. // * @throws AssertionError if the timeout expires // */ // public <V> V until(String errorMessage, Function<? super T, V> isTrue) { // try { // return super.until(isTrue); // } catch (TimeoutException e) { // if (Objects.nonNull(errorMessage) && !"".equals(errorMessage)) { // throw new AssertionError(errorMessage, e); // } else { // //Regex replacing parts that hinder allure from grouping erros in the report when using "require" without custom error messages // throw new TimeoutException(e.getMessage().replaceAll("Build info:(?:.+\\s+)*Driver info:.+",""), e.getCause()); // } // } // } // // @Override // public <V> V until(Function<? super T, V> isTrue) { // return super.until(isTrue); // } // } // // Path: misc/src/main/java/at/willhaben/willtest/misc/utils/XPathOrCssUtil.java // public class XPathOrCssUtil { // // /** // * Generates a {@link By}. Checks for the first character in the string. A leading '/' generates a // * {@link By#xpath(String)} otherwise a {@link By#cssSelector(String)}. // * @param xPathOrCss locator string // * @return locator for selenium // */ // public static By mapToBy(String xPathOrCss) { // if (xPathOrCss.startsWith("/")) { // return By.xpath(xPathOrCss); // } else { // return By.cssSelector(xPathOrCss); // } // } // }
import at.willhaben.willtest.misc.utils.WhFluentWait; import at.willhaben.willtest.misc.utils.XPathOrCssUtil; import org.openqa.selenium.WebElement; import org.openqa.selenium.SearchContext; import org.openqa.selenium.WebDriver; import org.openqa.selenium.By; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.FluentWait; import java.time.Duration; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Function; import java.util.function.Predicate;
* Used to check if an element is available or visible. * @param webElement element to check * @return Builder for checking appearance of element. */ public IsAvailableBuilder is(WebElement webElement) { return new IsAvailableBuilder(this, webElement); } /** * Used to check if an element is available or visible. * @param xPathOrCss XPath or CSS locator of element * @return Builder for checking appearance of element. */ public IsAvailableBuilder is(String xPathOrCss) { return new IsAvailableBuilder(this, XPathOrCssUtil.mapToBy(xPathOrCss)); } /** * Used to check if an element is available or visible. * @param by locator of the element to check * @return Builder for checking appearance of element. */ public IsAvailableBuilder is(By by) { return new IsAvailableBuilder(this, by); } /** * Same as {@link #getWait(long)} with a default wait of {@value DEFAULT_WAIT_TIMEOUT} seconds. * @return */
// Path: misc/src/main/java/at/willhaben/willtest/misc/utils/WhFluentWait.java // public class WhFluentWait<T> extends FluentWait<T> { // // public WhFluentWait(T input) { // super(input); // } // // public WhFluentWait(T input, Clock clock, Sleeper sleeper) { // super(input, clock, sleeper); // } // // /** // * Waits until the given condition is met. Throws an {@link AssertionError} instead of a {@link TimeoutException} // * when the condition fails because the error is known. // * @param errorMessage concrete error message describing the failure // * @param isTrue the parameter to pass to the {@link ExpectedCondition} // * @param <V> The function's expected return type. // * @return The function's return value if the function returned something different // * from null or false before the timeout expired. // * @throws AssertionError if the timeout expires // */ // public <V> V until(String errorMessage, Function<? super T, V> isTrue) { // try { // return super.until(isTrue); // } catch (TimeoutException e) { // if (Objects.nonNull(errorMessage) && !"".equals(errorMessage)) { // throw new AssertionError(errorMessage, e); // } else { // //Regex replacing parts that hinder allure from grouping erros in the report when using "require" without custom error messages // throw new TimeoutException(e.getMessage().replaceAll("Build info:(?:.+\\s+)*Driver info:.+",""), e.getCause()); // } // } // } // // @Override // public <V> V until(Function<? super T, V> isTrue) { // return super.until(isTrue); // } // } // // Path: misc/src/main/java/at/willhaben/willtest/misc/utils/XPathOrCssUtil.java // public class XPathOrCssUtil { // // /** // * Generates a {@link By}. Checks for the first character in the string. A leading '/' generates a // * {@link By#xpath(String)} otherwise a {@link By#cssSelector(String)}. // * @param xPathOrCss locator string // * @return locator for selenium // */ // public static By mapToBy(String xPathOrCss) { // if (xPathOrCss.startsWith("/")) { // return By.xpath(xPathOrCss); // } else { // return By.cssSelector(xPathOrCss); // } // } // } // Path: misc/src/main/java/at/willhaben/willtest/misc/pages/PageObject.java import at.willhaben.willtest.misc.utils.WhFluentWait; import at.willhaben.willtest.misc.utils.XPathOrCssUtil; import org.openqa.selenium.WebElement; import org.openqa.selenium.SearchContext; import org.openqa.selenium.WebDriver; import org.openqa.selenium.By; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.FluentWait; import java.time.Duration; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Function; import java.util.function.Predicate; * Used to check if an element is available or visible. * @param webElement element to check * @return Builder for checking appearance of element. */ public IsAvailableBuilder is(WebElement webElement) { return new IsAvailableBuilder(this, webElement); } /** * Used to check if an element is available or visible. * @param xPathOrCss XPath or CSS locator of element * @return Builder for checking appearance of element. */ public IsAvailableBuilder is(String xPathOrCss) { return new IsAvailableBuilder(this, XPathOrCssUtil.mapToBy(xPathOrCss)); } /** * Used to check if an element is available or visible. * @param by locator of the element to check * @return Builder for checking appearance of element. */ public IsAvailableBuilder is(By by) { return new IsAvailableBuilder(this, by); } /** * Same as {@link #getWait(long)} with a default wait of {@value DEFAULT_WAIT_TIMEOUT} seconds. * @return */
protected WhFluentWait<WebDriver> getWait() {
willhaben/willtest
core/src/main/java/at/willhaben/willtest/proxy/SeleniumProxy.java
// Path: core/src/main/java/at/willhaben/willtest/util/RemoteSelectionUtils.java // public class RemoteSelectionUtils { // // private static final String DEFAULT_REMOTE = ""; // private static final boolean REMOTE = true; // public static final String IS_REMOTE = "remote"; // public static final String REMOTE_PLATFORM = "remote.platform"; // // public static Boolean getRemoteIsSet() { // return Boolean.valueOf(Environment.getValue(IS_REMOTE, DEFAULT_REMOTE)); // } // // public static boolean isRemote() { // return getRemoteIsSet().equals(REMOTE); // } // // public static RemotePlatform getRemotePlatform() { // return RemotePlatform.valueOf(Environment.getValue(REMOTE_PLATFORM, RemotePlatform.GRID.toString())); // } // // public enum RemotePlatform { // GRID, // BROWSERSTACK // } // }
import at.willhaben.willtest.util.RemoteSelectionUtils; import net.lightbody.bmp.BrowserMobProxy; import net.lightbody.bmp.client.ClientUtil; import org.openqa.selenium.Proxy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.InetSocketAddress;
package at.willhaben.willtest.proxy; public class SeleniumProxy extends Proxy { private static final Logger LOGGER = LoggerFactory.getLogger(SeleniumProxy.class); public static final String PROXY_URL_PROPERTY_KEY = "browsermobProxyUrl"; public SeleniumProxy(BrowserMobProxy proxy) { super(); this.setProxyType(ProxyType.MANUAL); InetAddress connectableAddress = ClientUtil.getConnectableAddress(); InetSocketAddress inetSocketAddress = new InetSocketAddress(connectableAddress, proxy.getPort()); String proxyUrl = System.getProperty(PROXY_URL_PROPERTY_KEY); String proxyStr; if (proxyUrl != null) { proxyStr = String.format("%s:%d", proxyUrl, inetSocketAddress.getPort()); LOGGER.debug("Use the following proxy address for the browser to connect '" + proxyStr + "'. " + "(selected from system property [" + PROXY_URL_PROPERTY_KEY + "])");
// Path: core/src/main/java/at/willhaben/willtest/util/RemoteSelectionUtils.java // public class RemoteSelectionUtils { // // private static final String DEFAULT_REMOTE = ""; // private static final boolean REMOTE = true; // public static final String IS_REMOTE = "remote"; // public static final String REMOTE_PLATFORM = "remote.platform"; // // public static Boolean getRemoteIsSet() { // return Boolean.valueOf(Environment.getValue(IS_REMOTE, DEFAULT_REMOTE)); // } // // public static boolean isRemote() { // return getRemoteIsSet().equals(REMOTE); // } // // public static RemotePlatform getRemotePlatform() { // return RemotePlatform.valueOf(Environment.getValue(REMOTE_PLATFORM, RemotePlatform.GRID.toString())); // } // // public enum RemotePlatform { // GRID, // BROWSERSTACK // } // } // Path: core/src/main/java/at/willhaben/willtest/proxy/SeleniumProxy.java import at.willhaben.willtest.util.RemoteSelectionUtils; import net.lightbody.bmp.BrowserMobProxy; import net.lightbody.bmp.client.ClientUtil; import org.openqa.selenium.Proxy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.InetSocketAddress; package at.willhaben.willtest.proxy; public class SeleniumProxy extends Proxy { private static final Logger LOGGER = LoggerFactory.getLogger(SeleniumProxy.class); public static final String PROXY_URL_PROPERTY_KEY = "browsermobProxyUrl"; public SeleniumProxy(BrowserMobProxy proxy) { super(); this.setProxyType(ProxyType.MANUAL); InetAddress connectableAddress = ClientUtil.getConnectableAddress(); InetSocketAddress inetSocketAddress = new InetSocketAddress(connectableAddress, proxy.getPort()); String proxyUrl = System.getProperty(PROXY_URL_PROPERTY_KEY); String proxyStr; if (proxyUrl != null) { proxyStr = String.format("%s:%d", proxyUrl, inetSocketAddress.getPort()); LOGGER.debug("Use the following proxy address for the browser to connect '" + proxyStr + "'. " + "(selected from system property [" + PROXY_URL_PROPERTY_KEY + "])");
} else if (!RemoteSelectionUtils.isRemote() && isOnMacOS()) {
willhaben/willtest
misc/src/main/java/at/willhaben/willtest/misc/pages/IsAvailableBuilder.java
// Path: misc/src/main/java/at/willhaben/willtest/misc/utils/ConditionType.java // public enum ConditionType { // CLICKABLE, // VISIBLE // }
import at.willhaben.willtest.misc.utils.ConditionType; import org.openqa.selenium.By; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import java.util.Optional; import java.util.function.Function;
package at.willhaben.willtest.misc.pages; public class IsAvailableBuilder extends AbstractWaitingBuilder<Optional<WebElement>> { IsAvailableBuilder(PageObject pageObject, WebElement webElement) { super(pageObject, webElement); } IsAvailableBuilder(PageObject pageObject, By by) { super(pageObject, by); } @Override public Optional<WebElement> clickable(long timeout) {
// Path: misc/src/main/java/at/willhaben/willtest/misc/utils/ConditionType.java // public enum ConditionType { // CLICKABLE, // VISIBLE // } // Path: misc/src/main/java/at/willhaben/willtest/misc/pages/IsAvailableBuilder.java import at.willhaben.willtest.misc.utils.ConditionType; import org.openqa.selenium.By; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import java.util.Optional; import java.util.function.Function; package at.willhaben.willtest.misc.pages; public class IsAvailableBuilder extends AbstractWaitingBuilder<Optional<WebElement>> { IsAvailableBuilder(PageObject pageObject, WebElement webElement) { super(pageObject, webElement); } IsAvailableBuilder(PageObject pageObject, By by) { super(pageObject, by); } @Override public Optional<WebElement> clickable(long timeout) {
return waitFor(generateCondition(ConditionType.CLICKABLE), timeout);
willhaben/willtest
core/src/test/java/at/willhaben/willtest/test/assertions/RequestAssertionsTest.java
// Path: core/src/main/java/at/willhaben/willtest/proxy/ProxyWrapper.java // public interface ProxyWrapper { // // BrowserMobProxy getProxy(); // // List<HarRequest> getRequests(); // // List<String> getRequestsUrls(); // // List<HarEntry> getRequestsByUrl(String urlPattern); // // HarEntry getRequestByUrl(String urlPattern); // // List<HarPostDataParam> getRequestFormParamsByUrl(String urlPattern); // // void clearRequests(); // } // // Path: core/src/main/java/at/willhaben/willtest/proxy/assertions/ProxyMatchers.java // public static Matcher<Collection<String>> requestAvailable(String regexMatcher) { // return new RequestAvailableAssertion(regexMatcher); // } // // Path: core/src/test/java/at/willhaben/willtest/test/assertions/ProxyWrapperMockBuilder.java // public static ProxyWrapperMockBuilder builder() { // return new ProxyWrapperMockBuilder(); // }
import at.willhaben.willtest.proxy.ProxyWrapper; import com.jayway.jsonpath.JsonPath; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Collections; import static at.willhaben.willtest.proxy.assertions.ProxyMatchers.requestAvailable; import static at.willhaben.willtest.test.assertions.ProxyWrapperMockBuilder.builder; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
package at.willhaben.willtest.test.assertions; class RequestAssertionsTest { private ProxyWrapper mockedProxyWrapper; @BeforeEach void setUp() {
// Path: core/src/main/java/at/willhaben/willtest/proxy/ProxyWrapper.java // public interface ProxyWrapper { // // BrowserMobProxy getProxy(); // // List<HarRequest> getRequests(); // // List<String> getRequestsUrls(); // // List<HarEntry> getRequestsByUrl(String urlPattern); // // HarEntry getRequestByUrl(String urlPattern); // // List<HarPostDataParam> getRequestFormParamsByUrl(String urlPattern); // // void clearRequests(); // } // // Path: core/src/main/java/at/willhaben/willtest/proxy/assertions/ProxyMatchers.java // public static Matcher<Collection<String>> requestAvailable(String regexMatcher) { // return new RequestAvailableAssertion(regexMatcher); // } // // Path: core/src/test/java/at/willhaben/willtest/test/assertions/ProxyWrapperMockBuilder.java // public static ProxyWrapperMockBuilder builder() { // return new ProxyWrapperMockBuilder(); // } // Path: core/src/test/java/at/willhaben/willtest/test/assertions/RequestAssertionsTest.java import at.willhaben.willtest.proxy.ProxyWrapper; import com.jayway.jsonpath.JsonPath; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Collections; import static at.willhaben.willtest.proxy.assertions.ProxyMatchers.requestAvailable; import static at.willhaben.willtest.test.assertions.ProxyWrapperMockBuilder.builder; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; package at.willhaben.willtest.test.assertions; class RequestAssertionsTest { private ProxyWrapper mockedProxyWrapper; @BeforeEach void setUp() {
mockedProxyWrapper = builder()
willhaben/willtest
core/src/test/java/at/willhaben/willtest/test/assertions/RequestAssertionsTest.java
// Path: core/src/main/java/at/willhaben/willtest/proxy/ProxyWrapper.java // public interface ProxyWrapper { // // BrowserMobProxy getProxy(); // // List<HarRequest> getRequests(); // // List<String> getRequestsUrls(); // // List<HarEntry> getRequestsByUrl(String urlPattern); // // HarEntry getRequestByUrl(String urlPattern); // // List<HarPostDataParam> getRequestFormParamsByUrl(String urlPattern); // // void clearRequests(); // } // // Path: core/src/main/java/at/willhaben/willtest/proxy/assertions/ProxyMatchers.java // public static Matcher<Collection<String>> requestAvailable(String regexMatcher) { // return new RequestAvailableAssertion(regexMatcher); // } // // Path: core/src/test/java/at/willhaben/willtest/test/assertions/ProxyWrapperMockBuilder.java // public static ProxyWrapperMockBuilder builder() { // return new ProxyWrapperMockBuilder(); // }
import at.willhaben.willtest.proxy.ProxyWrapper; import com.jayway.jsonpath.JsonPath; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Collections; import static at.willhaben.willtest.proxy.assertions.ProxyMatchers.requestAvailable; import static at.willhaben.willtest.test.assertions.ProxyWrapperMockBuilder.builder; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
package at.willhaben.willtest.test.assertions; class RequestAssertionsTest { private ProxyWrapper mockedProxyWrapper; @BeforeEach void setUp() { mockedProxyWrapper = builder() .addHarEntry("http://www.google.com", "mydata", Collections.singletonMap("[{\"jsonkey\":\"thisisthevalue\"}]", "")) .build(); } @Test void testRequestAvailable() {
// Path: core/src/main/java/at/willhaben/willtest/proxy/ProxyWrapper.java // public interface ProxyWrapper { // // BrowserMobProxy getProxy(); // // List<HarRequest> getRequests(); // // List<String> getRequestsUrls(); // // List<HarEntry> getRequestsByUrl(String urlPattern); // // HarEntry getRequestByUrl(String urlPattern); // // List<HarPostDataParam> getRequestFormParamsByUrl(String urlPattern); // // void clearRequests(); // } // // Path: core/src/main/java/at/willhaben/willtest/proxy/assertions/ProxyMatchers.java // public static Matcher<Collection<String>> requestAvailable(String regexMatcher) { // return new RequestAvailableAssertion(regexMatcher); // } // // Path: core/src/test/java/at/willhaben/willtest/test/assertions/ProxyWrapperMockBuilder.java // public static ProxyWrapperMockBuilder builder() { // return new ProxyWrapperMockBuilder(); // } // Path: core/src/test/java/at/willhaben/willtest/test/assertions/RequestAssertionsTest.java import at.willhaben.willtest.proxy.ProxyWrapper; import com.jayway.jsonpath.JsonPath; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Collections; import static at.willhaben.willtest.proxy.assertions.ProxyMatchers.requestAvailable; import static at.willhaben.willtest.test.assertions.ProxyWrapperMockBuilder.builder; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; package at.willhaben.willtest.test.assertions; class RequestAssertionsTest { private ProxyWrapper mockedProxyWrapper; @BeforeEach void setUp() { mockedProxyWrapper = builder() .addHarEntry("http://www.google.com", "mydata", Collections.singletonMap("[{\"jsonkey\":\"thisisthevalue\"}]", "")) .build(); } @Test void testRequestAvailable() {
assertThat(mockedProxyWrapper.getRequestsUrls(), requestAvailable(".*www\\.google\\.com"));
willhaben/willtest
core/src/main/java/at/willhaben/willtest/util/AnnotationHelper.java
// Path: core/src/main/java/at/willhaben/willtest/junit5/BrowserUtilExtension.java // public interface BrowserUtilExtension { // } // // Path: core/src/main/java/at/willhaben/willtest/junit5/OptionModifier.java // public interface OptionModifier extends BrowserUtilExtension { // // default FirefoxOptions modifyFirefoxOptions(FirefoxOptions options) { // return options; // } // // default ChromeOptions modifyChromeOptions(ChromeOptions options) { // return options; // } // // default EdgeOptions modifyEdgeOptions(EdgeOptions options) { // return options; // } // // default InternetExplorerOptions modifyInternetExplorerOptions(InternetExplorerOptions options) { // return options; // } // // default AndroidOptions modifyAndroidOptions(AndroidOptions options) { // return options; // } // // default IOsOptions modifyIOsOptions(IOsOptions options) { // return options; // } // // default <T extends MutableCapabilities> T modifyAllBrowsers(T options) { return options; } // }
import at.willhaben.willtest.junit5.BrowserUtil; import at.willhaben.willtest.junit5.BrowserUtilExtension; import at.willhaben.willtest.junit5.OptionModifier; import org.junit.jupiter.api.extension.ExtensionContext; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors;
package at.willhaben.willtest.util; public class AnnotationHelper { @SuppressWarnings("unchecked") public static <T> T getFirstSuperClassAnnotation(Class testClass, Class<T> type) { testClass = testClass.getSuperclass(); if (testClass.isAssignableFrom(Object.class)) { return null; } T browserUtil = (T) testClass.getAnnotation(type); if (browserUtil != null) { return browserUtil; } else { return getFirstSuperClassAnnotation(testClass, type); } }
// Path: core/src/main/java/at/willhaben/willtest/junit5/BrowserUtilExtension.java // public interface BrowserUtilExtension { // } // // Path: core/src/main/java/at/willhaben/willtest/junit5/OptionModifier.java // public interface OptionModifier extends BrowserUtilExtension { // // default FirefoxOptions modifyFirefoxOptions(FirefoxOptions options) { // return options; // } // // default ChromeOptions modifyChromeOptions(ChromeOptions options) { // return options; // } // // default EdgeOptions modifyEdgeOptions(EdgeOptions options) { // return options; // } // // default InternetExplorerOptions modifyInternetExplorerOptions(InternetExplorerOptions options) { // return options; // } // // default AndroidOptions modifyAndroidOptions(AndroidOptions options) { // return options; // } // // default IOsOptions modifyIOsOptions(IOsOptions options) { // return options; // } // // default <T extends MutableCapabilities> T modifyAllBrowsers(T options) { return options; } // } // Path: core/src/main/java/at/willhaben/willtest/util/AnnotationHelper.java import at.willhaben.willtest.junit5.BrowserUtil; import at.willhaben.willtest.junit5.BrowserUtilExtension; import at.willhaben.willtest.junit5.OptionModifier; import org.junit.jupiter.api.extension.ExtensionContext; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; package at.willhaben.willtest.util; public class AnnotationHelper { @SuppressWarnings("unchecked") public static <T> T getFirstSuperClassAnnotation(Class testClass, Class<T> type) { testClass = testClass.getSuperclass(); if (testClass.isAssignableFrom(Object.class)) { return null; } T browserUtil = (T) testClass.getAnnotation(type); if (browserUtil != null) { return browserUtil; } else { return getFirstSuperClassAnnotation(testClass, type); } }
public static <T extends BrowserUtilExtension> List<T> getBrowserUtilList(BrowserUtil browserUtilAnnotation, Class<T> type) {
willhaben/willtest
core/src/main/java/at/willhaben/willtest/util/AnnotationHelper.java
// Path: core/src/main/java/at/willhaben/willtest/junit5/BrowserUtilExtension.java // public interface BrowserUtilExtension { // } // // Path: core/src/main/java/at/willhaben/willtest/junit5/OptionModifier.java // public interface OptionModifier extends BrowserUtilExtension { // // default FirefoxOptions modifyFirefoxOptions(FirefoxOptions options) { // return options; // } // // default ChromeOptions modifyChromeOptions(ChromeOptions options) { // return options; // } // // default EdgeOptions modifyEdgeOptions(EdgeOptions options) { // return options; // } // // default InternetExplorerOptions modifyInternetExplorerOptions(InternetExplorerOptions options) { // return options; // } // // default AndroidOptions modifyAndroidOptions(AndroidOptions options) { // return options; // } // // default IOsOptions modifyIOsOptions(IOsOptions options) { // return options; // } // // default <T extends MutableCapabilities> T modifyAllBrowsers(T options) { return options; } // }
import at.willhaben.willtest.junit5.BrowserUtil; import at.willhaben.willtest.junit5.BrowserUtilExtension; import at.willhaben.willtest.junit5.OptionModifier; import org.junit.jupiter.api.extension.ExtensionContext; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors;
return null; } T browserUtil = (T) testClass.getAnnotation(type); if (browserUtil != null) { return browserUtil; } else { return getFirstSuperClassAnnotation(testClass, type); } } public static <T extends BrowserUtilExtension> List<T> getBrowserUtilList(BrowserUtil browserUtilAnnotation, Class<T> type) { return getBrowserUtilList(browserUtilAnnotation, type, true); } @SuppressWarnings("unchecked") public static <T extends BrowserUtilExtension> List<T> getBrowserUtilList(BrowserUtil browserUtilAnnotation, Class<T> type, boolean allowMultipleExtension) { if (browserUtilAnnotation != null) { List<T> extensions = Arrays.stream(browserUtilAnnotation.value()) .filter(type::isAssignableFrom) .map(extension -> { try { return (T) extension.getConstructor().newInstance(); } catch (Exception e) { throw new RuntimeException("Can't instantiate " + extension.getName() + ".", e); } }) .collect(Collectors.toList()); if (!allowMultipleExtension) { if (extensions.size() > 1) { //TODO:Change that we can have two OptionModifier classes
// Path: core/src/main/java/at/willhaben/willtest/junit5/BrowserUtilExtension.java // public interface BrowserUtilExtension { // } // // Path: core/src/main/java/at/willhaben/willtest/junit5/OptionModifier.java // public interface OptionModifier extends BrowserUtilExtension { // // default FirefoxOptions modifyFirefoxOptions(FirefoxOptions options) { // return options; // } // // default ChromeOptions modifyChromeOptions(ChromeOptions options) { // return options; // } // // default EdgeOptions modifyEdgeOptions(EdgeOptions options) { // return options; // } // // default InternetExplorerOptions modifyInternetExplorerOptions(InternetExplorerOptions options) { // return options; // } // // default AndroidOptions modifyAndroidOptions(AndroidOptions options) { // return options; // } // // default IOsOptions modifyIOsOptions(IOsOptions options) { // return options; // } // // default <T extends MutableCapabilities> T modifyAllBrowsers(T options) { return options; } // } // Path: core/src/main/java/at/willhaben/willtest/util/AnnotationHelper.java import at.willhaben.willtest.junit5.BrowserUtil; import at.willhaben.willtest.junit5.BrowserUtilExtension; import at.willhaben.willtest.junit5.OptionModifier; import org.junit.jupiter.api.extension.ExtensionContext; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; return null; } T browserUtil = (T) testClass.getAnnotation(type); if (browserUtil != null) { return browserUtil; } else { return getFirstSuperClassAnnotation(testClass, type); } } public static <T extends BrowserUtilExtension> List<T> getBrowserUtilList(BrowserUtil browserUtilAnnotation, Class<T> type) { return getBrowserUtilList(browserUtilAnnotation, type, true); } @SuppressWarnings("unchecked") public static <T extends BrowserUtilExtension> List<T> getBrowserUtilList(BrowserUtil browserUtilAnnotation, Class<T> type, boolean allowMultipleExtension) { if (browserUtilAnnotation != null) { List<T> extensions = Arrays.stream(browserUtilAnnotation.value()) .filter(type::isAssignableFrom) .map(extension -> { try { return (T) extension.getConstructor().newInstance(); } catch (Exception e) { throw new RuntimeException("Can't instantiate " + extension.getName() + ".", e); } }) .collect(Collectors.toList()); if (!allowMultipleExtension) { if (extensions.size() > 1) { //TODO:Change that we can have two OptionModifier classes
throw new IllegalStateException("Only one extension of type " + OptionModifier.class.getName() + ".");
francesco-ficarola/gexf4j
src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/impl/data/AttributeImpl.java
// Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/data/Attribute.java // public interface Attribute { // // /** // * Returns the ID of the Attribute // * @return the ID as String // */ // String getId(); // // /** // * Returns the title of the Attribute // * @return the title as String // */ // String getTitle(); // // /** // * Sets the title of the Attribute // * @param title the Attribute's title as String // * @return the current Attribute // */ // Attribute setTitle(String title); // // /** // * Returns the type of the Attribute // * @return an AttributeType enum for that Attribute // */ // AttributeType getAttributeType(); // // /** // * Checks if the Attribute has a default value // * @return true if the Attribute has a default value // */ // boolean hasDefaultValue(); // // /** // * Clears the default value of the Attribute // * @return the current Attribute // */ // Attribute clearDefaultValue(); // // /** // * Returns the default value of the Attribute // * @return the default value as String // */ // String getDefaultValue(); // // /** // * Sets the default value of the Attribute // * @param defaultValue the default value as String // * @return the current Attribute // */ // Attribute setDefaultValue(String defaultValue); // // /** // * Returns the list of the Attribute's options // * @return the list of the options // */ // List<String> getOptions(); // // /** // * Creates a value for that Attribute // * @param value the value of the Attribute as String // * @return an instance of the AttributeValue class // */ // AttributeValue createValue(String value); // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/data/AttributeType.java // public enum AttributeType { // // INTEGER, // LONG, // DOUBLE, // FLOAT, // BOOLEAN, // STRING, // LISTSTRING, // ANYURI, // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/data/AttributeValue.java // public interface AttributeValue extends Dynamic<AttributeValue> { // // /** // * Returns the Attribute // * @return an instance of the Attribute class // */ // Attribute getAttribute(); // // /** // * Returns the value of the Attribute // * @return the value as String // */ // String getValue(); // // /** // * Sets the value for that Attribute // * @param value the value of the Attribute // * @return the current AttributeValue // */ // AttributeValue setValue(String value); // }
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import it.uniroma1.dis.wsngroup.gexf4j.core.data.Attribute; import it.uniroma1.dis.wsngroup.gexf4j.core.data.AttributeType; import it.uniroma1.dis.wsngroup.gexf4j.core.data.AttributeValue; import java.util.ArrayList; import java.util.List;
package it.uniroma1.dis.wsngroup.gexf4j.core.impl.data; /** * AttributeImpl class is an implementation of the Attribute interface. * */ public class AttributeImpl implements Attribute { private String id = ""; private String defaultValue = null;
// Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/data/Attribute.java // public interface Attribute { // // /** // * Returns the ID of the Attribute // * @return the ID as String // */ // String getId(); // // /** // * Returns the title of the Attribute // * @return the title as String // */ // String getTitle(); // // /** // * Sets the title of the Attribute // * @param title the Attribute's title as String // * @return the current Attribute // */ // Attribute setTitle(String title); // // /** // * Returns the type of the Attribute // * @return an AttributeType enum for that Attribute // */ // AttributeType getAttributeType(); // // /** // * Checks if the Attribute has a default value // * @return true if the Attribute has a default value // */ // boolean hasDefaultValue(); // // /** // * Clears the default value of the Attribute // * @return the current Attribute // */ // Attribute clearDefaultValue(); // // /** // * Returns the default value of the Attribute // * @return the default value as String // */ // String getDefaultValue(); // // /** // * Sets the default value of the Attribute // * @param defaultValue the default value as String // * @return the current Attribute // */ // Attribute setDefaultValue(String defaultValue); // // /** // * Returns the list of the Attribute's options // * @return the list of the options // */ // List<String> getOptions(); // // /** // * Creates a value for that Attribute // * @param value the value of the Attribute as String // * @return an instance of the AttributeValue class // */ // AttributeValue createValue(String value); // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/data/AttributeType.java // public enum AttributeType { // // INTEGER, // LONG, // DOUBLE, // FLOAT, // BOOLEAN, // STRING, // LISTSTRING, // ANYURI, // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/data/AttributeValue.java // public interface AttributeValue extends Dynamic<AttributeValue> { // // /** // * Returns the Attribute // * @return an instance of the Attribute class // */ // Attribute getAttribute(); // // /** // * Returns the value of the Attribute // * @return the value as String // */ // String getValue(); // // /** // * Sets the value for that Attribute // * @param value the value of the Attribute // * @return the current AttributeValue // */ // AttributeValue setValue(String value); // } // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/impl/data/AttributeImpl.java import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import it.uniroma1.dis.wsngroup.gexf4j.core.data.Attribute; import it.uniroma1.dis.wsngroup.gexf4j.core.data.AttributeType; import it.uniroma1.dis.wsngroup.gexf4j.core.data.AttributeValue; import java.util.ArrayList; import java.util.List; package it.uniroma1.dis.wsngroup.gexf4j.core.impl.data; /** * AttributeImpl class is an implementation of the Attribute interface. * */ public class AttributeImpl implements Attribute { private String id = ""; private String defaultValue = null;
private AttributeType type = AttributeType.STRING;
francesco-ficarola/gexf4j
src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/impl/data/AttributeImpl.java
// Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/data/Attribute.java // public interface Attribute { // // /** // * Returns the ID of the Attribute // * @return the ID as String // */ // String getId(); // // /** // * Returns the title of the Attribute // * @return the title as String // */ // String getTitle(); // // /** // * Sets the title of the Attribute // * @param title the Attribute's title as String // * @return the current Attribute // */ // Attribute setTitle(String title); // // /** // * Returns the type of the Attribute // * @return an AttributeType enum for that Attribute // */ // AttributeType getAttributeType(); // // /** // * Checks if the Attribute has a default value // * @return true if the Attribute has a default value // */ // boolean hasDefaultValue(); // // /** // * Clears the default value of the Attribute // * @return the current Attribute // */ // Attribute clearDefaultValue(); // // /** // * Returns the default value of the Attribute // * @return the default value as String // */ // String getDefaultValue(); // // /** // * Sets the default value of the Attribute // * @param defaultValue the default value as String // * @return the current Attribute // */ // Attribute setDefaultValue(String defaultValue); // // /** // * Returns the list of the Attribute's options // * @return the list of the options // */ // List<String> getOptions(); // // /** // * Creates a value for that Attribute // * @param value the value of the Attribute as String // * @return an instance of the AttributeValue class // */ // AttributeValue createValue(String value); // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/data/AttributeType.java // public enum AttributeType { // // INTEGER, // LONG, // DOUBLE, // FLOAT, // BOOLEAN, // STRING, // LISTSTRING, // ANYURI, // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/data/AttributeValue.java // public interface AttributeValue extends Dynamic<AttributeValue> { // // /** // * Returns the Attribute // * @return an instance of the Attribute class // */ // Attribute getAttribute(); // // /** // * Returns the value of the Attribute // * @return the value as String // */ // String getValue(); // // /** // * Sets the value for that Attribute // * @param value the value of the Attribute // * @return the current AttributeValue // */ // AttributeValue setValue(String value); // }
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import it.uniroma1.dis.wsngroup.gexf4j.core.data.Attribute; import it.uniroma1.dis.wsngroup.gexf4j.core.data.AttributeType; import it.uniroma1.dis.wsngroup.gexf4j.core.data.AttributeValue; import java.util.ArrayList; import java.util.List;
public List<String> getOptions() { return options; } @Override public String getTitle() { return title; } @Override public boolean hasDefaultValue() { return (defaultValue != null); } @Override public Attribute setDefaultValue(String defaultValue) { checkArgument(defaultValue != null, "Default Value cannot be null."); this.defaultValue = defaultValue; return this; } @Override public Attribute setTitle(String title) { checkArgument(title != null, "Title cannot be null."); checkArgument(!title.trim().isEmpty(), "Title cannot be null or blank."); this.title = title; return this; } @Override
// Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/data/Attribute.java // public interface Attribute { // // /** // * Returns the ID of the Attribute // * @return the ID as String // */ // String getId(); // // /** // * Returns the title of the Attribute // * @return the title as String // */ // String getTitle(); // // /** // * Sets the title of the Attribute // * @param title the Attribute's title as String // * @return the current Attribute // */ // Attribute setTitle(String title); // // /** // * Returns the type of the Attribute // * @return an AttributeType enum for that Attribute // */ // AttributeType getAttributeType(); // // /** // * Checks if the Attribute has a default value // * @return true if the Attribute has a default value // */ // boolean hasDefaultValue(); // // /** // * Clears the default value of the Attribute // * @return the current Attribute // */ // Attribute clearDefaultValue(); // // /** // * Returns the default value of the Attribute // * @return the default value as String // */ // String getDefaultValue(); // // /** // * Sets the default value of the Attribute // * @param defaultValue the default value as String // * @return the current Attribute // */ // Attribute setDefaultValue(String defaultValue); // // /** // * Returns the list of the Attribute's options // * @return the list of the options // */ // List<String> getOptions(); // // /** // * Creates a value for that Attribute // * @param value the value of the Attribute as String // * @return an instance of the AttributeValue class // */ // AttributeValue createValue(String value); // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/data/AttributeType.java // public enum AttributeType { // // INTEGER, // LONG, // DOUBLE, // FLOAT, // BOOLEAN, // STRING, // LISTSTRING, // ANYURI, // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/data/AttributeValue.java // public interface AttributeValue extends Dynamic<AttributeValue> { // // /** // * Returns the Attribute // * @return an instance of the Attribute class // */ // Attribute getAttribute(); // // /** // * Returns the value of the Attribute // * @return the value as String // */ // String getValue(); // // /** // * Sets the value for that Attribute // * @param value the value of the Attribute // * @return the current AttributeValue // */ // AttributeValue setValue(String value); // } // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/impl/data/AttributeImpl.java import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import it.uniroma1.dis.wsngroup.gexf4j.core.data.Attribute; import it.uniroma1.dis.wsngroup.gexf4j.core.data.AttributeType; import it.uniroma1.dis.wsngroup.gexf4j.core.data.AttributeValue; import java.util.ArrayList; import java.util.List; public List<String> getOptions() { return options; } @Override public String getTitle() { return title; } @Override public boolean hasDefaultValue() { return (defaultValue != null); } @Override public Attribute setDefaultValue(String defaultValue) { checkArgument(defaultValue != null, "Default Value cannot be null."); this.defaultValue = defaultValue; return this; } @Override public Attribute setTitle(String title) { checkArgument(title != null, "Title cannot be null."); checkArgument(!title.trim().isEmpty(), "Title cannot be null or blank."); this.title = title; return this; } @Override
public AttributeValue createValue(String value) {
francesco-ficarola/gexf4j
src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/impl/writer/GraphEntityWriter.java
// Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/Graph.java // public interface Graph extends Dynamic<Graph>, HasNodes { // // /** // * Returns the default type of the Edges // * @return an EdgeType enum for the Graph // */ // EdgeType getDefaultEdgeType(); // // /** // * Sets the default type of the Edges // * @param edgeType an instance of the EdgeType enum // * @return the current Graph // */ // Graph setDefaultEdgeType(EdgeType edgeType); // // /** // * Returns the type of the ID // * @return an IDType enum for the Graph // */ // IDType getIDType(); // // /** // * Sets the type of the ID // * @param idType an instance of IDType enum // * @return the current Graph // */ // Graph setIDType(IDType idType); // // /** // * Returns the mode of the Graph // * @return a Mode enum for the Graph // */ // Mode getMode(); // // /** // * Sets the mode of the Graph // * @param graphMode an instance of the Mode enum // * @return the current Graph // */ // Graph setMode(Mode graphMode); // // /** // * Returns the type of time // * @return the type of time as String // */ // String getTimeType(); // // /** // * Sets the type of time // * @param timeType a type of time as String // * @return the current Graph // */ // Graph setTimeType(String timeType); // // /** // * Returns the list of the Graph's attributes // * @return the list of the attributes for the Graph // */ // List<AttributeList> getAttributeLists(); // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/Mode.java // public enum Mode { // // STATIC, // DYNAMIC, // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/data/AttributeList.java // public interface AttributeList extends List<Attribute>, Dynamic<AttributeList> { // // /** // * Returns the AttributeClass for the list of Attributes // * @return an AttributeClass enum for that list // */ // AttributeClass getAttributeClass(); // // /** // * Returns the Mode of the list of Attributes // * @return a Mode enum // */ // Mode getMode(); // // /** // * Sets the Mode for that list of Attributes // * @param mode an instance of Mode enum // * @return the current AttributeList // */ // AttributeList setMode(Mode mode); // // /** // * Creates and adds an Attribute to the AttributeList // * @param type the type of the Attribute as AttributeType enum // * @param title the title of the Attribute as String // * @return the built Attribute // */ // Attribute createAttribute(AttributeType type, String title); // // /** // * Creates and adds an Attribute to the AttributeList // * @param id the ID of the Attribute as String // * @param type the type of the Attribute as AttributeType enum // * @param title the title of the Attribute as String // * @return the built Attribute // */ // Attribute createAttribute(String id, AttributeType type, String title); // // /** // * Creates and adds an Attribute to the AttributeList // * @param type the type of the Attribute as AttributeType enum // * @param title the title of the Attribute as String // * @return the current AttributeList // */ // AttributeList addAttribute(AttributeType type, String title); // // /** // * Creates and adds an Attribute to the AttributeList // * @param id the ID of the Attribute as String // * @param type the type of the Attribute as AttributeType enum // * @param title the title of the Attribute as String // * @return the current AttributeList // */ // AttributeList addAttribute(String id, AttributeType type, String title); // }
import it.uniroma1.dis.wsngroup.gexf4j.core.Graph; import it.uniroma1.dis.wsngroup.gexf4j.core.Mode; import it.uniroma1.dis.wsngroup.gexf4j.core.data.AttributeList; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter;
package it.uniroma1.dis.wsngroup.gexf4j.core.impl.writer; public class GraphEntityWriter extends DynamicEntityWriter<Graph> { private static final String ENTITY = "graph"; private static final String ATTRIB_EDGETYPE = "defaultedgetype"; private static final String ATTRIB_MODE = "mode"; private static final String ATTRIB_IDTYPE = "idtype"; private static final String ATTRIB_TIMETYPE = "timeformat"; public GraphEntityWriter(XMLStreamWriter writer, Graph entity) { super(writer, entity); write(); } @Override protected String getElementName() { return ENTITY; } @Override protected void writeAttributes() throws XMLStreamException { AbstractEntityWriter.writerTimeType = entity.getTimeType(); writer.writeAttribute( ATTRIB_EDGETYPE, entity.getDefaultEdgeType().toString().toLowerCase()); writer.writeAttribute( ATTRIB_IDTYPE, entity.getIDType().toString().toLowerCase()); writer.writeAttribute( ATTRIB_MODE, entity.getMode().toString().toLowerCase());
// Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/Graph.java // public interface Graph extends Dynamic<Graph>, HasNodes { // // /** // * Returns the default type of the Edges // * @return an EdgeType enum for the Graph // */ // EdgeType getDefaultEdgeType(); // // /** // * Sets the default type of the Edges // * @param edgeType an instance of the EdgeType enum // * @return the current Graph // */ // Graph setDefaultEdgeType(EdgeType edgeType); // // /** // * Returns the type of the ID // * @return an IDType enum for the Graph // */ // IDType getIDType(); // // /** // * Sets the type of the ID // * @param idType an instance of IDType enum // * @return the current Graph // */ // Graph setIDType(IDType idType); // // /** // * Returns the mode of the Graph // * @return a Mode enum for the Graph // */ // Mode getMode(); // // /** // * Sets the mode of the Graph // * @param graphMode an instance of the Mode enum // * @return the current Graph // */ // Graph setMode(Mode graphMode); // // /** // * Returns the type of time // * @return the type of time as String // */ // String getTimeType(); // // /** // * Sets the type of time // * @param timeType a type of time as String // * @return the current Graph // */ // Graph setTimeType(String timeType); // // /** // * Returns the list of the Graph's attributes // * @return the list of the attributes for the Graph // */ // List<AttributeList> getAttributeLists(); // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/Mode.java // public enum Mode { // // STATIC, // DYNAMIC, // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/data/AttributeList.java // public interface AttributeList extends List<Attribute>, Dynamic<AttributeList> { // // /** // * Returns the AttributeClass for the list of Attributes // * @return an AttributeClass enum for that list // */ // AttributeClass getAttributeClass(); // // /** // * Returns the Mode of the list of Attributes // * @return a Mode enum // */ // Mode getMode(); // // /** // * Sets the Mode for that list of Attributes // * @param mode an instance of Mode enum // * @return the current AttributeList // */ // AttributeList setMode(Mode mode); // // /** // * Creates and adds an Attribute to the AttributeList // * @param type the type of the Attribute as AttributeType enum // * @param title the title of the Attribute as String // * @return the built Attribute // */ // Attribute createAttribute(AttributeType type, String title); // // /** // * Creates and adds an Attribute to the AttributeList // * @param id the ID of the Attribute as String // * @param type the type of the Attribute as AttributeType enum // * @param title the title of the Attribute as String // * @return the built Attribute // */ // Attribute createAttribute(String id, AttributeType type, String title); // // /** // * Creates and adds an Attribute to the AttributeList // * @param type the type of the Attribute as AttributeType enum // * @param title the title of the Attribute as String // * @return the current AttributeList // */ // AttributeList addAttribute(AttributeType type, String title); // // /** // * Creates and adds an Attribute to the AttributeList // * @param id the ID of the Attribute as String // * @param type the type of the Attribute as AttributeType enum // * @param title the title of the Attribute as String // * @return the current AttributeList // */ // AttributeList addAttribute(String id, AttributeType type, String title); // } // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/impl/writer/GraphEntityWriter.java import it.uniroma1.dis.wsngroup.gexf4j.core.Graph; import it.uniroma1.dis.wsngroup.gexf4j.core.Mode; import it.uniroma1.dis.wsngroup.gexf4j.core.data.AttributeList; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; package it.uniroma1.dis.wsngroup.gexf4j.core.impl.writer; public class GraphEntityWriter extends DynamicEntityWriter<Graph> { private static final String ENTITY = "graph"; private static final String ATTRIB_EDGETYPE = "defaultedgetype"; private static final String ATTRIB_MODE = "mode"; private static final String ATTRIB_IDTYPE = "idtype"; private static final String ATTRIB_TIMETYPE = "timeformat"; public GraphEntityWriter(XMLStreamWriter writer, Graph entity) { super(writer, entity); write(); } @Override protected String getElementName() { return ENTITY; } @Override protected void writeAttributes() throws XMLStreamException { AbstractEntityWriter.writerTimeType = entity.getTimeType(); writer.writeAttribute( ATTRIB_EDGETYPE, entity.getDefaultEdgeType().toString().toLowerCase()); writer.writeAttribute( ATTRIB_IDTYPE, entity.getIDType().toString().toLowerCase()); writer.writeAttribute( ATTRIB_MODE, entity.getMode().toString().toLowerCase());
if(entity.getMode().equals(Mode.DYNAMIC)) {
francesco-ficarola/gexf4j
src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/impl/writer/GraphEntityWriter.java
// Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/Graph.java // public interface Graph extends Dynamic<Graph>, HasNodes { // // /** // * Returns the default type of the Edges // * @return an EdgeType enum for the Graph // */ // EdgeType getDefaultEdgeType(); // // /** // * Sets the default type of the Edges // * @param edgeType an instance of the EdgeType enum // * @return the current Graph // */ // Graph setDefaultEdgeType(EdgeType edgeType); // // /** // * Returns the type of the ID // * @return an IDType enum for the Graph // */ // IDType getIDType(); // // /** // * Sets the type of the ID // * @param idType an instance of IDType enum // * @return the current Graph // */ // Graph setIDType(IDType idType); // // /** // * Returns the mode of the Graph // * @return a Mode enum for the Graph // */ // Mode getMode(); // // /** // * Sets the mode of the Graph // * @param graphMode an instance of the Mode enum // * @return the current Graph // */ // Graph setMode(Mode graphMode); // // /** // * Returns the type of time // * @return the type of time as String // */ // String getTimeType(); // // /** // * Sets the type of time // * @param timeType a type of time as String // * @return the current Graph // */ // Graph setTimeType(String timeType); // // /** // * Returns the list of the Graph's attributes // * @return the list of the attributes for the Graph // */ // List<AttributeList> getAttributeLists(); // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/Mode.java // public enum Mode { // // STATIC, // DYNAMIC, // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/data/AttributeList.java // public interface AttributeList extends List<Attribute>, Dynamic<AttributeList> { // // /** // * Returns the AttributeClass for the list of Attributes // * @return an AttributeClass enum for that list // */ // AttributeClass getAttributeClass(); // // /** // * Returns the Mode of the list of Attributes // * @return a Mode enum // */ // Mode getMode(); // // /** // * Sets the Mode for that list of Attributes // * @param mode an instance of Mode enum // * @return the current AttributeList // */ // AttributeList setMode(Mode mode); // // /** // * Creates and adds an Attribute to the AttributeList // * @param type the type of the Attribute as AttributeType enum // * @param title the title of the Attribute as String // * @return the built Attribute // */ // Attribute createAttribute(AttributeType type, String title); // // /** // * Creates and adds an Attribute to the AttributeList // * @param id the ID of the Attribute as String // * @param type the type of the Attribute as AttributeType enum // * @param title the title of the Attribute as String // * @return the built Attribute // */ // Attribute createAttribute(String id, AttributeType type, String title); // // /** // * Creates and adds an Attribute to the AttributeList // * @param type the type of the Attribute as AttributeType enum // * @param title the title of the Attribute as String // * @return the current AttributeList // */ // AttributeList addAttribute(AttributeType type, String title); // // /** // * Creates and adds an Attribute to the AttributeList // * @param id the ID of the Attribute as String // * @param type the type of the Attribute as AttributeType enum // * @param title the title of the Attribute as String // * @return the current AttributeList // */ // AttributeList addAttribute(String id, AttributeType type, String title); // }
import it.uniroma1.dis.wsngroup.gexf4j.core.Graph; import it.uniroma1.dis.wsngroup.gexf4j.core.Mode; import it.uniroma1.dis.wsngroup.gexf4j.core.data.AttributeList; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter;
} @Override protected void writeAttributes() throws XMLStreamException { AbstractEntityWriter.writerTimeType = entity.getTimeType(); writer.writeAttribute( ATTRIB_EDGETYPE, entity.getDefaultEdgeType().toString().toLowerCase()); writer.writeAttribute( ATTRIB_IDTYPE, entity.getIDType().toString().toLowerCase()); writer.writeAttribute( ATTRIB_MODE, entity.getMode().toString().toLowerCase()); if(entity.getMode().equals(Mode.DYNAMIC)) { writer.writeAttribute( ATTRIB_TIMETYPE, AbstractEntityWriter.writerTimeType); } /** Dynamic information */ super.writeAttributes(); } @Override protected void writeElements() throws XMLStreamException {
// Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/Graph.java // public interface Graph extends Dynamic<Graph>, HasNodes { // // /** // * Returns the default type of the Edges // * @return an EdgeType enum for the Graph // */ // EdgeType getDefaultEdgeType(); // // /** // * Sets the default type of the Edges // * @param edgeType an instance of the EdgeType enum // * @return the current Graph // */ // Graph setDefaultEdgeType(EdgeType edgeType); // // /** // * Returns the type of the ID // * @return an IDType enum for the Graph // */ // IDType getIDType(); // // /** // * Sets the type of the ID // * @param idType an instance of IDType enum // * @return the current Graph // */ // Graph setIDType(IDType idType); // // /** // * Returns the mode of the Graph // * @return a Mode enum for the Graph // */ // Mode getMode(); // // /** // * Sets the mode of the Graph // * @param graphMode an instance of the Mode enum // * @return the current Graph // */ // Graph setMode(Mode graphMode); // // /** // * Returns the type of time // * @return the type of time as String // */ // String getTimeType(); // // /** // * Sets the type of time // * @param timeType a type of time as String // * @return the current Graph // */ // Graph setTimeType(String timeType); // // /** // * Returns the list of the Graph's attributes // * @return the list of the attributes for the Graph // */ // List<AttributeList> getAttributeLists(); // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/Mode.java // public enum Mode { // // STATIC, // DYNAMIC, // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/data/AttributeList.java // public interface AttributeList extends List<Attribute>, Dynamic<AttributeList> { // // /** // * Returns the AttributeClass for the list of Attributes // * @return an AttributeClass enum for that list // */ // AttributeClass getAttributeClass(); // // /** // * Returns the Mode of the list of Attributes // * @return a Mode enum // */ // Mode getMode(); // // /** // * Sets the Mode for that list of Attributes // * @param mode an instance of Mode enum // * @return the current AttributeList // */ // AttributeList setMode(Mode mode); // // /** // * Creates and adds an Attribute to the AttributeList // * @param type the type of the Attribute as AttributeType enum // * @param title the title of the Attribute as String // * @return the built Attribute // */ // Attribute createAttribute(AttributeType type, String title); // // /** // * Creates and adds an Attribute to the AttributeList // * @param id the ID of the Attribute as String // * @param type the type of the Attribute as AttributeType enum // * @param title the title of the Attribute as String // * @return the built Attribute // */ // Attribute createAttribute(String id, AttributeType type, String title); // // /** // * Creates and adds an Attribute to the AttributeList // * @param type the type of the Attribute as AttributeType enum // * @param title the title of the Attribute as String // * @return the current AttributeList // */ // AttributeList addAttribute(AttributeType type, String title); // // /** // * Creates and adds an Attribute to the AttributeList // * @param id the ID of the Attribute as String // * @param type the type of the Attribute as AttributeType enum // * @param title the title of the Attribute as String // * @return the current AttributeList // */ // AttributeList addAttribute(String id, AttributeType type, String title); // } // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/impl/writer/GraphEntityWriter.java import it.uniroma1.dis.wsngroup.gexf4j.core.Graph; import it.uniroma1.dis.wsngroup.gexf4j.core.Mode; import it.uniroma1.dis.wsngroup.gexf4j.core.data.AttributeList; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; } @Override protected void writeAttributes() throws XMLStreamException { AbstractEntityWriter.writerTimeType = entity.getTimeType(); writer.writeAttribute( ATTRIB_EDGETYPE, entity.getDefaultEdgeType().toString().toLowerCase()); writer.writeAttribute( ATTRIB_IDTYPE, entity.getIDType().toString().toLowerCase()); writer.writeAttribute( ATTRIB_MODE, entity.getMode().toString().toLowerCase()); if(entity.getMode().equals(Mode.DYNAMIC)) { writer.writeAttribute( ATTRIB_TIMETYPE, AbstractEntityWriter.writerTimeType); } /** Dynamic information */ super.writeAttributes(); } @Override protected void writeElements() throws XMLStreamException {
for (AttributeList attList : entity.getAttributeLists()) {
francesco-ficarola/gexf4j
src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/impl/writer/DynamicEntityWriter.java
// Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/IntervalType.java // public enum IntervalType { // OPEN, // CLOSE // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/dynamic/Dynamic.java // public interface Dynamic<T extends Object> { // // /** // * Checks if the element has a start date // * @return true if the element has a start date // */ // boolean hasStartDate(); // // /** // * Clears the start date of the element // * @return the current element // */ // T clearStartDate(); // // /** // * Returns the start date of the element // * @return an instance of the start date // */ // Object getStartValue(); // // /** // * Sets the start date for that element // * @param startDate an instance of the start date // * @return the current element // */ // T setStartValue(Object startDate); // // /** // * Sets the interval type for the start date // * @param startIntervalType an instance of IntervalType enum // * @return the current element // */ // T setStartIntervalType(IntervalType startIntervalType); // // /** // * Returns the interval type of the start date // * @return an instance of IntervalType enum // */ // IntervalType getStartIntervalType(); // // /** // * Checks if the element has an end date // * @return true if the element has an end date // */ // boolean hasEndDate(); // // /** // * Clears the end date of the element // * @return the current element // */ // T clearEndDate(); // // /** // * Returns the end date of the element // * @return an instance of the end date // */ // Object getEndValue(); // // /** // * Sets the end date for that element // * @param endDate an instance of the end date // * @return the current element // */ // T setEndValue(Object endDate); // // /** // * Sets the interval type for the end date // * @param endIntervalType an instance of IntervalType enum // * @return the current element // */ // T setEndIntervalType(IntervalType endIntervalType); // // /** // * Returns the interval type of the end date // * @return an instance of IntervalType enum // */ // IntervalType getEndIntervalType(); // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/dynamic/TimeFormat.java // public class TimeFormat { // public static final String INTEGER = "integer"; // public static final String DOUBLE = "double"; // public static final String DATE = "date"; // public static final String XSDDATETIME = "dateTime"; // }
import static com.google.common.base.Preconditions.checkArgument; import it.uniroma1.dis.wsngroup.gexf4j.core.IntervalType; import it.uniroma1.dis.wsngroup.gexf4j.core.dynamic.Dynamic; import it.uniroma1.dis.wsngroup.gexf4j.core.dynamic.TimeFormat; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter;
package it.uniroma1.dis.wsngroup.gexf4j.core.impl.writer; public abstract class DynamicEntityWriter<T extends Dynamic<?>> extends AbstractEntityWriter<T> { protected static final String ATTRIB_START = "start"; protected static final String ATTRIB_START_OPEN = "startopen"; protected static final String ATTRIB_END = "end"; protected static final String ATTRIB_END_OPEN = "endopen";
// Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/IntervalType.java // public enum IntervalType { // OPEN, // CLOSE // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/dynamic/Dynamic.java // public interface Dynamic<T extends Object> { // // /** // * Checks if the element has a start date // * @return true if the element has a start date // */ // boolean hasStartDate(); // // /** // * Clears the start date of the element // * @return the current element // */ // T clearStartDate(); // // /** // * Returns the start date of the element // * @return an instance of the start date // */ // Object getStartValue(); // // /** // * Sets the start date for that element // * @param startDate an instance of the start date // * @return the current element // */ // T setStartValue(Object startDate); // // /** // * Sets the interval type for the start date // * @param startIntervalType an instance of IntervalType enum // * @return the current element // */ // T setStartIntervalType(IntervalType startIntervalType); // // /** // * Returns the interval type of the start date // * @return an instance of IntervalType enum // */ // IntervalType getStartIntervalType(); // // /** // * Checks if the element has an end date // * @return true if the element has an end date // */ // boolean hasEndDate(); // // /** // * Clears the end date of the element // * @return the current element // */ // T clearEndDate(); // // /** // * Returns the end date of the element // * @return an instance of the end date // */ // Object getEndValue(); // // /** // * Sets the end date for that element // * @param endDate an instance of the end date // * @return the current element // */ // T setEndValue(Object endDate); // // /** // * Sets the interval type for the end date // * @param endIntervalType an instance of IntervalType enum // * @return the current element // */ // T setEndIntervalType(IntervalType endIntervalType); // // /** // * Returns the interval type of the end date // * @return an instance of IntervalType enum // */ // IntervalType getEndIntervalType(); // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/dynamic/TimeFormat.java // public class TimeFormat { // public static final String INTEGER = "integer"; // public static final String DOUBLE = "double"; // public static final String DATE = "date"; // public static final String XSDDATETIME = "dateTime"; // } // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/impl/writer/DynamicEntityWriter.java import static com.google.common.base.Preconditions.checkArgument; import it.uniroma1.dis.wsngroup.gexf4j.core.IntervalType; import it.uniroma1.dis.wsngroup.gexf4j.core.dynamic.Dynamic; import it.uniroma1.dis.wsngroup.gexf4j.core.dynamic.TimeFormat; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; package it.uniroma1.dis.wsngroup.gexf4j.core.impl.writer; public abstract class DynamicEntityWriter<T extends Dynamic<?>> extends AbstractEntityWriter<T> { protected static final String ATTRIB_START = "start"; protected static final String ATTRIB_START_OPEN = "startopen"; protected static final String ATTRIB_END = "end"; protected static final String ATTRIB_END_OPEN = "endopen";
private IntervalType startIntervalType = IntervalType.CLOSE;
francesco-ficarola/gexf4j
src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/impl/writer/DynamicEntityWriter.java
// Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/IntervalType.java // public enum IntervalType { // OPEN, // CLOSE // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/dynamic/Dynamic.java // public interface Dynamic<T extends Object> { // // /** // * Checks if the element has a start date // * @return true if the element has a start date // */ // boolean hasStartDate(); // // /** // * Clears the start date of the element // * @return the current element // */ // T clearStartDate(); // // /** // * Returns the start date of the element // * @return an instance of the start date // */ // Object getStartValue(); // // /** // * Sets the start date for that element // * @param startDate an instance of the start date // * @return the current element // */ // T setStartValue(Object startDate); // // /** // * Sets the interval type for the start date // * @param startIntervalType an instance of IntervalType enum // * @return the current element // */ // T setStartIntervalType(IntervalType startIntervalType); // // /** // * Returns the interval type of the start date // * @return an instance of IntervalType enum // */ // IntervalType getStartIntervalType(); // // /** // * Checks if the element has an end date // * @return true if the element has an end date // */ // boolean hasEndDate(); // // /** // * Clears the end date of the element // * @return the current element // */ // T clearEndDate(); // // /** // * Returns the end date of the element // * @return an instance of the end date // */ // Object getEndValue(); // // /** // * Sets the end date for that element // * @param endDate an instance of the end date // * @return the current element // */ // T setEndValue(Object endDate); // // /** // * Sets the interval type for the end date // * @param endIntervalType an instance of IntervalType enum // * @return the current element // */ // T setEndIntervalType(IntervalType endIntervalType); // // /** // * Returns the interval type of the end date // * @return an instance of IntervalType enum // */ // IntervalType getEndIntervalType(); // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/dynamic/TimeFormat.java // public class TimeFormat { // public static final String INTEGER = "integer"; // public static final String DOUBLE = "double"; // public static final String DATE = "date"; // public static final String XSDDATETIME = "dateTime"; // }
import static com.google.common.base.Preconditions.checkArgument; import it.uniroma1.dis.wsngroup.gexf4j.core.IntervalType; import it.uniroma1.dis.wsngroup.gexf4j.core.dynamic.Dynamic; import it.uniroma1.dis.wsngroup.gexf4j.core.dynamic.TimeFormat; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter;
package it.uniroma1.dis.wsngroup.gexf4j.core.impl.writer; public abstract class DynamicEntityWriter<T extends Dynamic<?>> extends AbstractEntityWriter<T> { protected static final String ATTRIB_START = "start"; protected static final String ATTRIB_START_OPEN = "startopen"; protected static final String ATTRIB_END = "end"; protected static final String ATTRIB_END_OPEN = "endopen"; private IntervalType startIntervalType = IntervalType.CLOSE; private IntervalType endIntervalType = IntervalType.CLOSE; public DynamicEntityWriter(XMLStreamWriter writer, T entity) { super(writer, entity); } @Override protected void writeAttributes() throws XMLStreamException { /** Set open or close tags */ startIntervalType = entity.getStartIntervalType(); endIntervalType = entity.getEndIntervalType(); String attribStart = ATTRIB_START; String attribEnd = ATTRIB_END; if(startIntervalType.equals(IntervalType.OPEN)) { attribStart = ATTRIB_START_OPEN; } if(endIntervalType.equals(IntervalType.OPEN)) { attribEnd = ATTRIB_END_OPEN; } /** Write Attributes */ /** double timeformat */
// Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/IntervalType.java // public enum IntervalType { // OPEN, // CLOSE // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/dynamic/Dynamic.java // public interface Dynamic<T extends Object> { // // /** // * Checks if the element has a start date // * @return true if the element has a start date // */ // boolean hasStartDate(); // // /** // * Clears the start date of the element // * @return the current element // */ // T clearStartDate(); // // /** // * Returns the start date of the element // * @return an instance of the start date // */ // Object getStartValue(); // // /** // * Sets the start date for that element // * @param startDate an instance of the start date // * @return the current element // */ // T setStartValue(Object startDate); // // /** // * Sets the interval type for the start date // * @param startIntervalType an instance of IntervalType enum // * @return the current element // */ // T setStartIntervalType(IntervalType startIntervalType); // // /** // * Returns the interval type of the start date // * @return an instance of IntervalType enum // */ // IntervalType getStartIntervalType(); // // /** // * Checks if the element has an end date // * @return true if the element has an end date // */ // boolean hasEndDate(); // // /** // * Clears the end date of the element // * @return the current element // */ // T clearEndDate(); // // /** // * Returns the end date of the element // * @return an instance of the end date // */ // Object getEndValue(); // // /** // * Sets the end date for that element // * @param endDate an instance of the end date // * @return the current element // */ // T setEndValue(Object endDate); // // /** // * Sets the interval type for the end date // * @param endIntervalType an instance of IntervalType enum // * @return the current element // */ // T setEndIntervalType(IntervalType endIntervalType); // // /** // * Returns the interval type of the end date // * @return an instance of IntervalType enum // */ // IntervalType getEndIntervalType(); // } // // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/dynamic/TimeFormat.java // public class TimeFormat { // public static final String INTEGER = "integer"; // public static final String DOUBLE = "double"; // public static final String DATE = "date"; // public static final String XSDDATETIME = "dateTime"; // } // Path: src/main/java/it/uniroma1/dis/wsngroup/gexf4j/core/impl/writer/DynamicEntityWriter.java import static com.google.common.base.Preconditions.checkArgument; import it.uniroma1.dis.wsngroup.gexf4j.core.IntervalType; import it.uniroma1.dis.wsngroup.gexf4j.core.dynamic.Dynamic; import it.uniroma1.dis.wsngroup.gexf4j.core.dynamic.TimeFormat; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; package it.uniroma1.dis.wsngroup.gexf4j.core.impl.writer; public abstract class DynamicEntityWriter<T extends Dynamic<?>> extends AbstractEntityWriter<T> { protected static final String ATTRIB_START = "start"; protected static final String ATTRIB_START_OPEN = "startopen"; protected static final String ATTRIB_END = "end"; protected static final String ATTRIB_END_OPEN = "endopen"; private IntervalType startIntervalType = IntervalType.CLOSE; private IntervalType endIntervalType = IntervalType.CLOSE; public DynamicEntityWriter(XMLStreamWriter writer, T entity) { super(writer, entity); } @Override protected void writeAttributes() throws XMLStreamException { /** Set open or close tags */ startIntervalType = entity.getStartIntervalType(); endIntervalType = entity.getEndIntervalType(); String attribStart = ATTRIB_START; String attribEnd = ATTRIB_END; if(startIntervalType.equals(IntervalType.OPEN)) { attribStart = ATTRIB_START_OPEN; } if(endIntervalType.equals(IntervalType.OPEN)) { attribEnd = ATTRIB_END_OPEN; } /** Write Attributes */ /** double timeformat */
if(AbstractEntityWriter.writerTimeType.equals(TimeFormat.DOUBLE)) {