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
jsptest/jsptest
jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/assertion/FormFieldAssertion.java
// Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/html/Form.java // public class Form { // // private Element element; // private NodeList fields; // // /** // * Build a <tt>Form</tt> from an HTML element. // * // * @param element // * The HTML form element to represent. // */ // public Form(Element element) { // this.element = element; // fields = element.getElementsByTagName("INPUT"); // } // // /** // * Returns the name of the HTML form. // */ // public String getName() { // return element.getAttribute("NAME"); // } // // /** // * Indicates whether the form has an input field by the given name. // * // * @param name // * The name of the input field. // */ // public boolean hasInputField(String name) { // if (getInputField(name) != null) { // return true; // } // return false; // } // // /** // * Returns the specified input field or <tt>null</tt> if no such field exists on the form. // * // * @param name // * The name of the input field. // */ // public FormField getInputField(String name) { // for (int i = 0; i < fields.getLength(); i++) { // FormField field = new FormField((Element) fields.item(i)); // if (name.equals(field.getName())) { // return field; // } // } // return null; // } // // /** // * Indicates whether the form has a submit button by the given name. // * // * @param name // * The name of the submit button. // */ // public boolean hasSubmitButton(String name) { // NodeList elems = element.getElementsByTagName("INPUT"); // for (int i = 0; i < elems.getLength(); i++) { // Element element = (Element) elems.item(i); // if ("SUBMIT".equalsIgnoreCase(element.getAttribute("TYPE"))) { // if (name.equals(element.getAttribute("VALUE"))) { // return true; // } // if (name.equals(element.getAttribute("NAME"))) { // return true; // } // } // } // return false; // } // // /** // * Indicates whether the form has a submit button. // */ // public boolean hasSubmitButton() { // NodeList elems = element.getElementsByTagName("INPUT"); // for (int i = 0; i < elems.getLength(); i++) { // Element element = (Element) elems.item(i); // if ("SUBMIT".equalsIgnoreCase(element.getAttribute("TYPE"))) { // return true; // } // } // return false; // } // } // // Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/html/FormField.java // public class FormField { // // private Element element; // // /** // * Build an input field from the given HTML element. // * // * @param element // * The HTML input element. // */ // public FormField(Element element) { // this.element = element; // } // // /** // * Returns the name of the field. // */ // public String getName() { // return element.getAttribute("NAME"); // } // // /** // * Returns the value of the field. // */ // public String getValue() { // return element.getAttribute("VALUE"); // } // }
import java.util.ArrayList; import java.util.Iterator; import java.util.List; import junit.framework.Assert; import net.sf.jsptest.html.Form; import net.sf.jsptest.html.FormField;
package net.sf.jsptest.assertion; /** * Provides form field-oriented assertion methods. * * @author Lasse Koskela */ public class FormFieldAssertion { private final List fields; private final String fieldName; /** * @param forms * The list of forms that should be considered the context for the subsequent * assertion methods. * @param fieldName * The name of the form field that should be considered the context for the * subsequent assertion methods. */ public FormFieldAssertion(List forms, String fieldName) { this.fieldName = fieldName; this.fields = new ArrayList(); for (Iterator i = forms.iterator(); i.hasNext();) { Form form = (Form) i.next(); if (form.hasInputField(fieldName)) { fields.add(form.getInputField(fieldName)); } } } /** * Assert that the selected form field has the given value. * * @param expectedValue * The expected value. */ public void shouldHaveValue(String expectedValue) { List actuals = new ArrayList(); for (Iterator i = fields.iterator(); i.hasNext();) {
// Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/html/Form.java // public class Form { // // private Element element; // private NodeList fields; // // /** // * Build a <tt>Form</tt> from an HTML element. // * // * @param element // * The HTML form element to represent. // */ // public Form(Element element) { // this.element = element; // fields = element.getElementsByTagName("INPUT"); // } // // /** // * Returns the name of the HTML form. // */ // public String getName() { // return element.getAttribute("NAME"); // } // // /** // * Indicates whether the form has an input field by the given name. // * // * @param name // * The name of the input field. // */ // public boolean hasInputField(String name) { // if (getInputField(name) != null) { // return true; // } // return false; // } // // /** // * Returns the specified input field or <tt>null</tt> if no such field exists on the form. // * // * @param name // * The name of the input field. // */ // public FormField getInputField(String name) { // for (int i = 0; i < fields.getLength(); i++) { // FormField field = new FormField((Element) fields.item(i)); // if (name.equals(field.getName())) { // return field; // } // } // return null; // } // // /** // * Indicates whether the form has a submit button by the given name. // * // * @param name // * The name of the submit button. // */ // public boolean hasSubmitButton(String name) { // NodeList elems = element.getElementsByTagName("INPUT"); // for (int i = 0; i < elems.getLength(); i++) { // Element element = (Element) elems.item(i); // if ("SUBMIT".equalsIgnoreCase(element.getAttribute("TYPE"))) { // if (name.equals(element.getAttribute("VALUE"))) { // return true; // } // if (name.equals(element.getAttribute("NAME"))) { // return true; // } // } // } // return false; // } // // /** // * Indicates whether the form has a submit button. // */ // public boolean hasSubmitButton() { // NodeList elems = element.getElementsByTagName("INPUT"); // for (int i = 0; i < elems.getLength(); i++) { // Element element = (Element) elems.item(i); // if ("SUBMIT".equalsIgnoreCase(element.getAttribute("TYPE"))) { // return true; // } // } // return false; // } // } // // Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/html/FormField.java // public class FormField { // // private Element element; // // /** // * Build an input field from the given HTML element. // * // * @param element // * The HTML input element. // */ // public FormField(Element element) { // this.element = element; // } // // /** // * Returns the name of the field. // */ // public String getName() { // return element.getAttribute("NAME"); // } // // /** // * Returns the value of the field. // */ // public String getValue() { // return element.getAttribute("VALUE"); // } // } // Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/assertion/FormFieldAssertion.java import java.util.ArrayList; import java.util.Iterator; import java.util.List; import junit.framework.Assert; import net.sf.jsptest.html.Form; import net.sf.jsptest.html.FormField; package net.sf.jsptest.assertion; /** * Provides form field-oriented assertion methods. * * @author Lasse Koskela */ public class FormFieldAssertion { private final List fields; private final String fieldName; /** * @param forms * The list of forms that should be considered the context for the subsequent * assertion methods. * @param fieldName * The name of the form field that should be considered the context for the * subsequent assertion methods. */ public FormFieldAssertion(List forms, String fieldName) { this.fieldName = fieldName; this.fields = new ArrayList(); for (Iterator i = forms.iterator(); i.hasNext();) { Form form = (Form) i.next(); if (form.hasInputField(fieldName)) { fields.add(form.getInputField(fieldName)); } } } /** * Assert that the selected form field has the given value. * * @param expectedValue * The expected value. */ public void shouldHaveValue(String expectedValue) { List actuals = new ArrayList(); for (Iterator i = fields.iterator(); i.hasNext();) {
FormField form = (FormField) i.next();
jsptest/jsptest
jsptest-generic/jsptest-framework/src/test/java/net/sf/jsptest/AbstractFakeJspCompilerTestCase.java
// Path: jsptest-generic/jsptest-framework/src/test/java/net/sf/jsptest/compiler/dummy/FakeJspCompiler.java // public class FakeJspCompiler implements JspCompiler { // // private static StringBuffer fakedOutput = new StringBuffer(2000); // private static String lastCompiledPath; // private static String lastCompiledWebRoot; // private String webRoot; // // public void setWebRoot(String directory) { // this.webRoot = directory; // } // // protected String getWebRoot() { // return webRoot; // } // // public static void cleanOutput() { // fakedOutput.setLength(0); // } // // public static void appendOutput(String content) { // fakedOutput.append(content); // } // // public Jsp compile(String path, Map taglibs) { // lastCompiledWebRoot = getWebRoot(); // lastCompiledPath = path; // return new Jsp() { // // public JspExecution request(String httpMethod, Map requestAttributes, // Map sessionAttributes, Map requestParameters) { // return new JspExecution() { // // public String getRenderedResponse() { // return fakedOutput.toString(); // } // }; // } // }; // } // // public static String lastCompiledPath() { // return lastCompiledPath; // } // // public static String lastCompiledWebRoot() { // return lastCompiledWebRoot; // } // // public void setOutputDirectory(String directory) { // } // }
import net.sf.jsptest.compiler.dummy.FakeJspCompiler; import junit.framework.TestCase;
package net.sf.jsptest; /** * @author Lasse Koskela */ public abstract class AbstractFakeJspCompilerTestCase extends TestCase { protected void setUp() throws Exception { super.setUp(); StringBuffer output = new StringBuffer(2000); appendOutput(output);
// Path: jsptest-generic/jsptest-framework/src/test/java/net/sf/jsptest/compiler/dummy/FakeJspCompiler.java // public class FakeJspCompiler implements JspCompiler { // // private static StringBuffer fakedOutput = new StringBuffer(2000); // private static String lastCompiledPath; // private static String lastCompiledWebRoot; // private String webRoot; // // public void setWebRoot(String directory) { // this.webRoot = directory; // } // // protected String getWebRoot() { // return webRoot; // } // // public static void cleanOutput() { // fakedOutput.setLength(0); // } // // public static void appendOutput(String content) { // fakedOutput.append(content); // } // // public Jsp compile(String path, Map taglibs) { // lastCompiledWebRoot = getWebRoot(); // lastCompiledPath = path; // return new Jsp() { // // public JspExecution request(String httpMethod, Map requestAttributes, // Map sessionAttributes, Map requestParameters) { // return new JspExecution() { // // public String getRenderedResponse() { // return fakedOutput.toString(); // } // }; // } // }; // } // // public static String lastCompiledPath() { // return lastCompiledPath; // } // // public static String lastCompiledWebRoot() { // return lastCompiledWebRoot; // } // // public void setOutputDirectory(String directory) { // } // } // Path: jsptest-generic/jsptest-framework/src/test/java/net/sf/jsptest/AbstractFakeJspCompilerTestCase.java import net.sf.jsptest.compiler.dummy.FakeJspCompiler; import junit.framework.TestCase; package net.sf.jsptest; /** * @author Lasse Koskela */ public abstract class AbstractFakeJspCompilerTestCase extends TestCase { protected void setUp() throws Exception { super.setUp(); StringBuffer output = new StringBuffer(2000); appendOutput(output);
FakeJspCompiler.appendOutput(output.toString());
jsptest/jsptest
jsptest-generic/jsptest-framework/src/test/java/net/sf/jsptest/TestHtmlTestCaseLinkAssertions.java
// Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/assertion/ExpectedAssertionFailure.java // public abstract class ExpectedAssertionFailure { // // private HtmlTestCase testcase; // // /** // * Override this method to perform a test that should fail with an exception. // */ // protected abstract void run() throws Exception; // // /** // * @param testcase // * The <tt>HtmlTestCase</tt> that serves as the context for this operation. // */ // public ExpectedAssertionFailure(HtmlTestCase testcase) throws Exception { // this(testcase, "Operation should've failed but it didn't."); // } // // /** // * @param testcase // * The <tt>HtmlTestCase</tt> that serves as the context for this operation. // * @param message // * The message to display if the specified operation doesn't throw an // * AssertionFailedError. // */ // public ExpectedAssertionFailure(HtmlTestCase testcase, String message) throws Exception { // this.testcase = testcase; // verify(message); // } // // /** // * Gives access to a <tt>PageAssertion</tt> object, enabling page-oriented (HTML) assertions. // */ // protected PageAssertion page() { // return testcase.page(); // } // // /** // * Gives access to an <tt>OutputAssertion</tt> object, enabling raw output-oriented // * assertions. // */ // protected OutputAssertion output() { // return testcase.output(); // } // // /** // * Gives access to an <tt>ElementAssertion</tt> object for the HTML element identified by the // * given XPath expression. // * // * @param xpath // * @return // */ // protected ElementAssertion element(String xpath) { // return testcase.element(xpath); // } // // private void verify(String message) { // try { // run(); // throw new NoExceptionWasThrown(); // } catch (AssertionFailedError expected) { // // everything went according to the plan! // } catch (NoExceptionWasThrown e) { // throw new AssertionFailedError(message); // } catch (Throwable e) { // throw new IncorrectExceptionError("A non-assertion exception was thrown: " // + e.getClass().getName(), e); // } // } // // /** // * Thrown from an assertion method indicating that the wrong kind of exception was thrown by the // * code under test. // * // * @author Lasse Koskela // */ // public static class IncorrectExceptionError extends RuntimeException { // // public IncorrectExceptionError(String message, Throwable e) { // super(message, e); // } // } // // /** // * Thrown from an assertion method indicating that no exception was thrown by the code under // * test against the expectations. This class is only used internally and is never passed to // * client code (test written by a JspTest user). // * // * @author Lasse Koskela // */ // private static class NoExceptionWasThrown extends Exception { // } // }
import net.sf.jsptest.assertion.ExpectedAssertionFailure;
/* * Copyright 2007 Lasse Koskela. * * 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 net.sf.jsptest; /** * @author Lasse Koskela */ public class TestHtmlTestCaseLinkAssertions extends AbstractHtmlTestCaseTestCase { private static final String LINK_HREF = "http://target.com/page.html"; private static final String LINK_ID = "linkId"; private static final String LINK_NAME = "linkName"; private static final String LINK_TEXT = "linkText"; private static final String LINK_CLASS = ".linkClass"; private static final String IMAGE_ID = "imageId"; private static final String IMAGE_NAME = "imageName"; private static final String IMAGE_TITLE = "imageTitle"; private static final String IMAGE_FILENAME = "filename.jpg"; private static final String IMAGE_SRC = "./images/" + IMAGE_FILENAME; protected void appendOutput(StringBuffer h) { h.append("<html><head>"); h.append("<title>PageTitle</title>"); h.append("</head><body>"); h.append("<a href='" + LINK_HREF + "'>Link with href</a>"); h.append("<a id='" + LINK_ID + "'>Link with ID</a>"); h.append("<a name='" + LINK_NAME + "'>Link with name</a>"); h.append("<a class='" + LINK_CLASS + "'>Link with class</a>"); h.append("<a href='foo'>" + LINK_TEXT + "</a>"); h.append("<a name='foo'><img id='" + IMAGE_ID + "' name='" + IMAGE_NAME + "' src='" + IMAGE_SRC + "' title='" + IMAGE_TITLE + "'/></a>"); h.append("</body></html>"); } public void testShouldHaveLinkWithText() throws Exception { testcase.page().shouldHaveLink().withText(LINK_TEXT);
// Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/assertion/ExpectedAssertionFailure.java // public abstract class ExpectedAssertionFailure { // // private HtmlTestCase testcase; // // /** // * Override this method to perform a test that should fail with an exception. // */ // protected abstract void run() throws Exception; // // /** // * @param testcase // * The <tt>HtmlTestCase</tt> that serves as the context for this operation. // */ // public ExpectedAssertionFailure(HtmlTestCase testcase) throws Exception { // this(testcase, "Operation should've failed but it didn't."); // } // // /** // * @param testcase // * The <tt>HtmlTestCase</tt> that serves as the context for this operation. // * @param message // * The message to display if the specified operation doesn't throw an // * AssertionFailedError. // */ // public ExpectedAssertionFailure(HtmlTestCase testcase, String message) throws Exception { // this.testcase = testcase; // verify(message); // } // // /** // * Gives access to a <tt>PageAssertion</tt> object, enabling page-oriented (HTML) assertions. // */ // protected PageAssertion page() { // return testcase.page(); // } // // /** // * Gives access to an <tt>OutputAssertion</tt> object, enabling raw output-oriented // * assertions. // */ // protected OutputAssertion output() { // return testcase.output(); // } // // /** // * Gives access to an <tt>ElementAssertion</tt> object for the HTML element identified by the // * given XPath expression. // * // * @param xpath // * @return // */ // protected ElementAssertion element(String xpath) { // return testcase.element(xpath); // } // // private void verify(String message) { // try { // run(); // throw new NoExceptionWasThrown(); // } catch (AssertionFailedError expected) { // // everything went according to the plan! // } catch (NoExceptionWasThrown e) { // throw new AssertionFailedError(message); // } catch (Throwable e) { // throw new IncorrectExceptionError("A non-assertion exception was thrown: " // + e.getClass().getName(), e); // } // } // // /** // * Thrown from an assertion method indicating that the wrong kind of exception was thrown by the // * code under test. // * // * @author Lasse Koskela // */ // public static class IncorrectExceptionError extends RuntimeException { // // public IncorrectExceptionError(String message, Throwable e) { // super(message, e); // } // } // // /** // * Thrown from an assertion method indicating that no exception was thrown by the code under // * test against the expectations. This class is only used internally and is never passed to // * client code (test written by a JspTest user). // * // * @author Lasse Koskela // */ // private static class NoExceptionWasThrown extends Exception { // } // } // Path: jsptest-generic/jsptest-framework/src/test/java/net/sf/jsptest/TestHtmlTestCaseLinkAssertions.java import net.sf.jsptest.assertion.ExpectedAssertionFailure; /* * Copyright 2007 Lasse Koskela. * * 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 net.sf.jsptest; /** * @author Lasse Koskela */ public class TestHtmlTestCaseLinkAssertions extends AbstractHtmlTestCaseTestCase { private static final String LINK_HREF = "http://target.com/page.html"; private static final String LINK_ID = "linkId"; private static final String LINK_NAME = "linkName"; private static final String LINK_TEXT = "linkText"; private static final String LINK_CLASS = ".linkClass"; private static final String IMAGE_ID = "imageId"; private static final String IMAGE_NAME = "imageName"; private static final String IMAGE_TITLE = "imageTitle"; private static final String IMAGE_FILENAME = "filename.jpg"; private static final String IMAGE_SRC = "./images/" + IMAGE_FILENAME; protected void appendOutput(StringBuffer h) { h.append("<html><head>"); h.append("<title>PageTitle</title>"); h.append("</head><body>"); h.append("<a href='" + LINK_HREF + "'>Link with href</a>"); h.append("<a id='" + LINK_ID + "'>Link with ID</a>"); h.append("<a name='" + LINK_NAME + "'>Link with name</a>"); h.append("<a class='" + LINK_CLASS + "'>Link with class</a>"); h.append("<a href='foo'>" + LINK_TEXT + "</a>"); h.append("<a name='foo'><img id='" + IMAGE_ID + "' name='" + IMAGE_NAME + "' src='" + IMAGE_SRC + "' title='" + IMAGE_TITLE + "'/></a>"); h.append("</body></html>"); } public void testShouldHaveLinkWithText() throws Exception { testcase.page().shouldHaveLink().withText(LINK_TEXT);
new ExpectedAssertionFailure(testcase) {
jsptest/jsptest
jsptest-generic/jsptest-framework/src/test/java/net/sf/jsptest/TestJspTestCase.java
// Path: jsptest-generic/jsptest-framework/src/test/java/net/sf/jsptest/compiler/dummy/FakeJspCompiler.java // public class FakeJspCompiler implements JspCompiler { // // private static StringBuffer fakedOutput = new StringBuffer(2000); // private static String lastCompiledPath; // private static String lastCompiledWebRoot; // private String webRoot; // // public void setWebRoot(String directory) { // this.webRoot = directory; // } // // protected String getWebRoot() { // return webRoot; // } // // public static void cleanOutput() { // fakedOutput.setLength(0); // } // // public static void appendOutput(String content) { // fakedOutput.append(content); // } // // public Jsp compile(String path, Map taglibs) { // lastCompiledWebRoot = getWebRoot(); // lastCompiledPath = path; // return new Jsp() { // // public JspExecution request(String httpMethod, Map requestAttributes, // Map sessionAttributes, Map requestParameters) { // return new JspExecution() { // // public String getRenderedResponse() { // return fakedOutput.toString(); // } // }; // } // }; // } // // public static String lastCompiledPath() { // return lastCompiledPath; // } // // public static String lastCompiledWebRoot() { // return lastCompiledWebRoot; // } // // public void setOutputDirectory(String directory) { // } // }
import junit.framework.AssertionFailedError; import junit.framework.TestCase; import net.sf.jsptest.compiler.dummy.FakeJspCompiler;
/* * Copyright 2007 Lasse Koskela. * * 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 net.sf.jsptest; /** * @author Lasse Koskela */ public class TestJspTestCase extends TestCase { private String renderedOutput; private JspTestCase testcase; protected void setUp() throws Exception { super.setUp(); renderedOutput = "there is a needle in this haystack"; testcase = new JspTestCase() { protected String getWebRoot() { return "./websrc"; } }; } public void testCorrectWebRootIsPassedToJspCompiler() throws Exception { testcase.get("/index.jsp");
// Path: jsptest-generic/jsptest-framework/src/test/java/net/sf/jsptest/compiler/dummy/FakeJspCompiler.java // public class FakeJspCompiler implements JspCompiler { // // private static StringBuffer fakedOutput = new StringBuffer(2000); // private static String lastCompiledPath; // private static String lastCompiledWebRoot; // private String webRoot; // // public void setWebRoot(String directory) { // this.webRoot = directory; // } // // protected String getWebRoot() { // return webRoot; // } // // public static void cleanOutput() { // fakedOutput.setLength(0); // } // // public static void appendOutput(String content) { // fakedOutput.append(content); // } // // public Jsp compile(String path, Map taglibs) { // lastCompiledWebRoot = getWebRoot(); // lastCompiledPath = path; // return new Jsp() { // // public JspExecution request(String httpMethod, Map requestAttributes, // Map sessionAttributes, Map requestParameters) { // return new JspExecution() { // // public String getRenderedResponse() { // return fakedOutput.toString(); // } // }; // } // }; // } // // public static String lastCompiledPath() { // return lastCompiledPath; // } // // public static String lastCompiledWebRoot() { // return lastCompiledWebRoot; // } // // public void setOutputDirectory(String directory) { // } // } // Path: jsptest-generic/jsptest-framework/src/test/java/net/sf/jsptest/TestJspTestCase.java import junit.framework.AssertionFailedError; import junit.framework.TestCase; import net.sf.jsptest.compiler.dummy.FakeJspCompiler; /* * Copyright 2007 Lasse Koskela. * * 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 net.sf.jsptest; /** * @author Lasse Koskela */ public class TestJspTestCase extends TestCase { private String renderedOutput; private JspTestCase testcase; protected void setUp() throws Exception { super.setUp(); renderedOutput = "there is a needle in this haystack"; testcase = new JspTestCase() { protected String getWebRoot() { return "./websrc"; } }; } public void testCorrectWebRootIsPassedToJspCompiler() throws Exception { testcase.get("/index.jsp");
assertEquals("./websrc", FakeJspCompiler.lastCompiledWebRoot());
jsptest/jsptest
jsptest-generic/jsptest-common/src/main/java/net/sf/jsptest/compiler/java/CommandLineJavac.java
// Path: jsptest-generic/jsptest-common/src/main/java/net/sf/jsptest/utils/StreamConsumer.java // public class StreamConsumer implements Runnable { // // private final String outputPrefix; // private final InputStream stream; // private final PrintWriter log; // // public StreamConsumer(String streamName, InputStream stream, PrintWriter log) { // this.outputPrefix = streamName + ":"; // this.stream = stream; // this.log = log; // } // // public void run() { // String output = null; // try { // output = consume(stream); // } catch (Exception e) { // e.printStackTrace(); // } // log.println(outputPrefix); // log.println(output); // } // // private String consume(InputStream stream) throws IOException { // ByteArrayOutputStream result = new ByteArrayOutputStream(8096); // byte[] buffer = new byte[8096]; // int r = -1; // while ((r = stream.read(buffer, 0, buffer.length)) != -1) { // result.write(buffer, 0, r); // } // stream.close(); // return result.toString(); // } // }
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import net.sf.jsptest.utils.StreamConsumer;
String classpathString) { return new String[] { "javac", "-classpath", classpathString, "-d", outputDirectory, pathToJavaSource }; } private String join(String[] classpath) { StringBuffer s = new StringBuffer(5000); for (int i = 0; i < classpath.length; i++) { if (s.length() > 0) { s.append(SEPARATOR); } s.append(classpath[i]); } return s.toString(); } protected boolean execute(String[] commandLine) throws IOException, InterruptedException { Process p = Runtime.getRuntime().exec(commandLine); String processOutput = readOutput(p); boolean success = (p.waitFor() == 0); if (!success) { System.err.println(processOutput); } return success; } private String readOutput(final Process p) throws IOException { try { StringWriter output = new StringWriter(); final PrintWriter ps = new PrintWriter(output);
// Path: jsptest-generic/jsptest-common/src/main/java/net/sf/jsptest/utils/StreamConsumer.java // public class StreamConsumer implements Runnable { // // private final String outputPrefix; // private final InputStream stream; // private final PrintWriter log; // // public StreamConsumer(String streamName, InputStream stream, PrintWriter log) { // this.outputPrefix = streamName + ":"; // this.stream = stream; // this.log = log; // } // // public void run() { // String output = null; // try { // output = consume(stream); // } catch (Exception e) { // e.printStackTrace(); // } // log.println(outputPrefix); // log.println(output); // } // // private String consume(InputStream stream) throws IOException { // ByteArrayOutputStream result = new ByteArrayOutputStream(8096); // byte[] buffer = new byte[8096]; // int r = -1; // while ((r = stream.read(buffer, 0, buffer.length)) != -1) { // result.write(buffer, 0, r); // } // stream.close(); // return result.toString(); // } // } // Path: jsptest-generic/jsptest-common/src/main/java/net/sf/jsptest/compiler/java/CommandLineJavac.java import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import net.sf.jsptest.utils.StreamConsumer; String classpathString) { return new String[] { "javac", "-classpath", classpathString, "-d", outputDirectory, pathToJavaSource }; } private String join(String[] classpath) { StringBuffer s = new StringBuffer(5000); for (int i = 0; i < classpath.length; i++) { if (s.length() > 0) { s.append(SEPARATOR); } s.append(classpath[i]); } return s.toString(); } protected boolean execute(String[] commandLine) throws IOException, InterruptedException { Process p = Runtime.getRuntime().exec(commandLine); String processOutput = readOutput(p); boolean success = (p.waitFor() == 0); if (!success) { System.err.println(processOutput); } return success; } private String readOutput(final Process p) throws IOException { try { StringWriter output = new StringWriter(); final PrintWriter ps = new PrintWriter(output);
Thread stderrThread = new Thread(new StreamConsumer("STDERR", p.getErrorStream(), ps));
jsptest/jsptest
jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/assertion/FormAssertion.java
// Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/html/Form.java // public class Form { // // private Element element; // private NodeList fields; // // /** // * Build a <tt>Form</tt> from an HTML element. // * // * @param element // * The HTML form element to represent. // */ // public Form(Element element) { // this.element = element; // fields = element.getElementsByTagName("INPUT"); // } // // /** // * Returns the name of the HTML form. // */ // public String getName() { // return element.getAttribute("NAME"); // } // // /** // * Indicates whether the form has an input field by the given name. // * // * @param name // * The name of the input field. // */ // public boolean hasInputField(String name) { // if (getInputField(name) != null) { // return true; // } // return false; // } // // /** // * Returns the specified input field or <tt>null</tt> if no such field exists on the form. // * // * @param name // * The name of the input field. // */ // public FormField getInputField(String name) { // for (int i = 0; i < fields.getLength(); i++) { // FormField field = new FormField((Element) fields.item(i)); // if (name.equals(field.getName())) { // return field; // } // } // return null; // } // // /** // * Indicates whether the form has a submit button by the given name. // * // * @param name // * The name of the submit button. // */ // public boolean hasSubmitButton(String name) { // NodeList elems = element.getElementsByTagName("INPUT"); // for (int i = 0; i < elems.getLength(); i++) { // Element element = (Element) elems.item(i); // if ("SUBMIT".equalsIgnoreCase(element.getAttribute("TYPE"))) { // if (name.equals(element.getAttribute("VALUE"))) { // return true; // } // if (name.equals(element.getAttribute("NAME"))) { // return true; // } // } // } // return false; // } // // /** // * Indicates whether the form has a submit button. // */ // public boolean hasSubmitButton() { // NodeList elems = element.getElementsByTagName("INPUT"); // for (int i = 0; i < elems.getLength(); i++) { // Element element = (Element) elems.item(i); // if ("SUBMIT".equalsIgnoreCase(element.getAttribute("TYPE"))) { // return true; // } // } // return false; // } // }
import java.util.ArrayList; import java.util.Iterator; import java.util.List; import junit.framework.Assert; import net.sf.jsptest.html.Form; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList;
package net.sf.jsptest.assertion; /** * Provides form-related assertion methods. * * @author Lasse Koskela */ public class FormAssertion { private final List forms; /** * @param document * The context from where to select the form as the context for subsequent assertion * methods. * @param chooser * The <tt>ElementChooser</tt> to use for selecting the form. */ public FormAssertion(Document document, ElementChooser chooser) { this.forms = new ArrayList(); NodeList elements = document.getElementsByTagName("FORM"); for (int i = 0; i < elements.getLength(); i++) { Element element = (Element) elements.item(i); if (chooser.accept(element)) {
// Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/html/Form.java // public class Form { // // private Element element; // private NodeList fields; // // /** // * Build a <tt>Form</tt> from an HTML element. // * // * @param element // * The HTML form element to represent. // */ // public Form(Element element) { // this.element = element; // fields = element.getElementsByTagName("INPUT"); // } // // /** // * Returns the name of the HTML form. // */ // public String getName() { // return element.getAttribute("NAME"); // } // // /** // * Indicates whether the form has an input field by the given name. // * // * @param name // * The name of the input field. // */ // public boolean hasInputField(String name) { // if (getInputField(name) != null) { // return true; // } // return false; // } // // /** // * Returns the specified input field or <tt>null</tt> if no such field exists on the form. // * // * @param name // * The name of the input field. // */ // public FormField getInputField(String name) { // for (int i = 0; i < fields.getLength(); i++) { // FormField field = new FormField((Element) fields.item(i)); // if (name.equals(field.getName())) { // return field; // } // } // return null; // } // // /** // * Indicates whether the form has a submit button by the given name. // * // * @param name // * The name of the submit button. // */ // public boolean hasSubmitButton(String name) { // NodeList elems = element.getElementsByTagName("INPUT"); // for (int i = 0; i < elems.getLength(); i++) { // Element element = (Element) elems.item(i); // if ("SUBMIT".equalsIgnoreCase(element.getAttribute("TYPE"))) { // if (name.equals(element.getAttribute("VALUE"))) { // return true; // } // if (name.equals(element.getAttribute("NAME"))) { // return true; // } // } // } // return false; // } // // /** // * Indicates whether the form has a submit button. // */ // public boolean hasSubmitButton() { // NodeList elems = element.getElementsByTagName("INPUT"); // for (int i = 0; i < elems.getLength(); i++) { // Element element = (Element) elems.item(i); // if ("SUBMIT".equalsIgnoreCase(element.getAttribute("TYPE"))) { // return true; // } // } // return false; // } // } // Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/assertion/FormAssertion.java import java.util.ArrayList; import java.util.Iterator; import java.util.List; import junit.framework.Assert; import net.sf.jsptest.html.Form; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; package net.sf.jsptest.assertion; /** * Provides form-related assertion methods. * * @author Lasse Koskela */ public class FormAssertion { private final List forms; /** * @param document * The context from where to select the form as the context for subsequent assertion * methods. * @param chooser * The <tt>ElementChooser</tt> to use for selecting the form. */ public FormAssertion(Document document, ElementChooser chooser) { this.forms = new ArrayList(); NodeList elements = document.getElementsByTagName("FORM"); for (int i = 0; i < elements.getLength(); i++) { Element element = (Element) elements.item(i); if (chooser.accept(element)) {
forms.add(new Form(element));
jsptest/jsptest
jsptest-jsp20/src/main/java/org/apache/jasper/compiler/MockTagPluginManager.java
// Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/TagKey.java // public class TagKey { // // private final String prefix; // private final String name; // // public TagKey(String prefix) { // this(prefix, "*"); // } // // public TagKey(String prefix, String name) { // this.prefix = prefix; // this.name = name; // } // // public String toString() { // return prefix + ":" + name; // } // // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((name == null) ? 0 : name.hashCode()); // result = prime * result + ((prefix == null) ? 0 : prefix.hashCode()); // return result; // } // // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final TagKey other = (TagKey) obj; // if (name == null) { // if (other.name != null) { // return false; // } // } else if (!name.equals(other.name)) { // return false; // } // if (prefix == null) { // if (other.prefix != null) { // return false; // } // } else if (!prefix.equals(other.prefix)) { // return false; // } // return true; // } // }
import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.jsp.tagext.TagInfo; import net.sf.jsptest.TagKey; import org.apache.jasper.JasperException; import org.apache.jasper.compiler.Node.Nodes;
substituteMocksFor(nodes); } private void substituteMocksFor(Nodes nodes) throws JasperException { nodes.visit(new TagSubstitutor(mockTaglibs)); } /** * Walks through the node tree representing the JSP and replaces the <i>handler</i> of certain * tags with a mock implementation if one has been configured. */ private static class TagSubstitutor extends Node.Visitor { private final Map mocks; public TagSubstitutor(Map mockTaglibs) { this.mocks = mockTaglibs; } public void visit(Node.CustomTag n) throws JasperException { Class mockClass = substitute(n.getTagInfo()); if (mockClass != null) { n.setTagHandlerClass(mockClass); } super.visit(n); } private Class substitute(TagInfo tagInfo) { String prefix = tagInfo.getTagLibrary().getPrefixString(); String name = tagInfo.getTagName();
// Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/TagKey.java // public class TagKey { // // private final String prefix; // private final String name; // // public TagKey(String prefix) { // this(prefix, "*"); // } // // public TagKey(String prefix, String name) { // this.prefix = prefix; // this.name = name; // } // // public String toString() { // return prefix + ":" + name; // } // // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((name == null) ? 0 : name.hashCode()); // result = prime * result + ((prefix == null) ? 0 : prefix.hashCode()); // return result; // } // // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final TagKey other = (TagKey) obj; // if (name == null) { // if (other.name != null) { // return false; // } // } else if (!name.equals(other.name)) { // return false; // } // if (prefix == null) { // if (other.prefix != null) { // return false; // } // } else if (!prefix.equals(other.prefix)) { // return false; // } // return true; // } // } // Path: jsptest-jsp20/src/main/java/org/apache/jasper/compiler/MockTagPluginManager.java import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.jsp.tagext.TagInfo; import net.sf.jsptest.TagKey; import org.apache.jasper.JasperException; import org.apache.jasper.compiler.Node.Nodes; substituteMocksFor(nodes); } private void substituteMocksFor(Nodes nodes) throws JasperException { nodes.visit(new TagSubstitutor(mockTaglibs)); } /** * Walks through the node tree representing the JSP and replaces the <i>handler</i> of certain * tags with a mock implementation if one has been configured. */ private static class TagSubstitutor extends Node.Visitor { private final Map mocks; public TagSubstitutor(Map mockTaglibs) { this.mocks = mockTaglibs; } public void visit(Node.CustomTag n) throws JasperException { Class mockClass = substitute(n.getTagInfo()); if (mockClass != null) { n.setTagHandlerClass(mockClass); } super.visit(n); } private Class substitute(TagInfo tagInfo) { String prefix = tagInfo.getTagLibrary().getPrefixString(); String name = tagInfo.getTagName();
TagKey[] matchingOrder = new TagKey[] { new TagKey(prefix, name), new TagKey(prefix) };
jsptest/jsptest
jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/JspTestCase.java
// Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/assertion/OutputAssertion.java // public class OutputAssertion extends AbstractAssertion { // // private final String content; // // /** // * @param content // * The raw output to perform assertions on. // */ // public OutputAssertion(String content) { // this.content = content; // } // // /** // * Assert that the output should contain the given text. // * // * @param text // * The (partial) content that should be found from the output. // */ // public void shouldContain(String text) { // String msg = "Rendered output did not contain the expected text <" + text + ">:\n" // + content; // assertContains(msg, content, text); // } // // /** // * Assert that the output should not contain the given text. // * // * @param text // * The (partial) content that shouldn't be found from the output. // */ // public void shouldNotContain(String text) { // String msg = "Rendered output contained unexpected text <" + text + ">:\n" + content; // assertDoesNotContain(msg, content, text); // } // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/Jsp.java // public interface Jsp { // // JspExecution request(String httpMethod, Map requestAttributes, Map sessionAttributes, Map requestParameters); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompiler.java // public interface JspCompiler { // // Jsp compile(String path, Map taglibs); // // void setWebRoot(String directory); // // void setOutputDirectory(String directory); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompilerFactory.java // public class JspCompilerFactory { // // private static final Logger log = Logger.getLogger(JspCompilerFactory.class); // private static final String RESOURCE_PATH = "jsptest.properties"; // private static final String CONFIGURATION_KEY = "jsptest.compiler.implementation"; // // public static JspCompiler newInstance() { // RuntimeException exception = new RuntimeException( // "No JSP compiler implementation configured: " + "(configuration file " // + RESOURCE_PATH + " not found from class path."); // try { // printConfigurationFiles(); // Enumeration resources = getClassLoader().getResources(RESOURCE_PATH); // while (resources.hasMoreElements()) { // URL resource = (URL) resources.nextElement(); // if (resources.hasMoreElements() // && resource.toString().indexOf("test-classes") != -1) { // log.debug("Ignoring " + resource + " because it's from 'test-classes' " // + "and there's another matching resource available"); // continue; // } // try { // return loadCompilerFrom(resource); // } catch (RuntimeException invalidConfig) { // exception = invalidConfig; // } catch (Exception invalidConfig) { // exception = new RuntimeException(invalidConfig); // } // } // throw exception; // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // private static void printConfigurationFiles() throws Exception { // Enumeration enumeration = getClassLoader().getResources(RESOURCE_PATH); // List resources = new ArrayList(); // while (enumeration.hasMoreElements()) { // resources.add(enumeration.nextElement()); // } // log.debug("Found " + resources.size() + " resources matching '" + RESOURCE_PATH + "':"); // for (Iterator i = resources.iterator(); i.hasNext();) { // log.debug(" " + ((URL) i.next())); // } // } // // private static JspCompiler loadCompilerFrom(URL resource) throws Exception { // Properties properties = new Properties(); // properties.load(resource.openStream()); // if (!properties.containsKey(CONFIGURATION_KEY)) { // throw new RuntimeException("Property " + CONFIGURATION_KEY + " not found from " // + resource); // } // String klass = properties.getProperty(CONFIGURATION_KEY); // return (JspCompiler) Class.forName(klass).newInstance(); // } // // private static ClassLoader getClassLoader() { // return Thread.currentThread().getContextClassLoader(); // } // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspExecution.java // public interface JspExecution { // // String getRenderedResponse(); // }
import java.io.File; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import net.sf.jsptest.assertion.OutputAssertion; import net.sf.jsptest.compiler.api.Jsp; import net.sf.jsptest.compiler.api.JspCompiler; import net.sf.jsptest.compiler.api.JspCompilerFactory; import net.sf.jsptest.compiler.api.JspExecution; import org.apache.log4j.Logger;
/* * Copyright 2007 Lasse Koskela. * * 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 net.sf.jsptest; /** * An abstract base class to be extended by the user. The <tt>JspTestCase</tt> class provides a * facility for rendering a JSP and a set of assertion methods for verifying that the JSP under test * renders the expected kind of output. * * @author Lasse Koskela * @author Meinert Schwartau (scwar32) * @author Ronaldo Webb */ public abstract class JspTestCase extends TestCase { private Logger log; private Map requestParameters; private Map requestAttributes; private Map sessionAttributes; private Map substituteTaglibs;
// Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/assertion/OutputAssertion.java // public class OutputAssertion extends AbstractAssertion { // // private final String content; // // /** // * @param content // * The raw output to perform assertions on. // */ // public OutputAssertion(String content) { // this.content = content; // } // // /** // * Assert that the output should contain the given text. // * // * @param text // * The (partial) content that should be found from the output. // */ // public void shouldContain(String text) { // String msg = "Rendered output did not contain the expected text <" + text + ">:\n" // + content; // assertContains(msg, content, text); // } // // /** // * Assert that the output should not contain the given text. // * // * @param text // * The (partial) content that shouldn't be found from the output. // */ // public void shouldNotContain(String text) { // String msg = "Rendered output contained unexpected text <" + text + ">:\n" + content; // assertDoesNotContain(msg, content, text); // } // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/Jsp.java // public interface Jsp { // // JspExecution request(String httpMethod, Map requestAttributes, Map sessionAttributes, Map requestParameters); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompiler.java // public interface JspCompiler { // // Jsp compile(String path, Map taglibs); // // void setWebRoot(String directory); // // void setOutputDirectory(String directory); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompilerFactory.java // public class JspCompilerFactory { // // private static final Logger log = Logger.getLogger(JspCompilerFactory.class); // private static final String RESOURCE_PATH = "jsptest.properties"; // private static final String CONFIGURATION_KEY = "jsptest.compiler.implementation"; // // public static JspCompiler newInstance() { // RuntimeException exception = new RuntimeException( // "No JSP compiler implementation configured: " + "(configuration file " // + RESOURCE_PATH + " not found from class path."); // try { // printConfigurationFiles(); // Enumeration resources = getClassLoader().getResources(RESOURCE_PATH); // while (resources.hasMoreElements()) { // URL resource = (URL) resources.nextElement(); // if (resources.hasMoreElements() // && resource.toString().indexOf("test-classes") != -1) { // log.debug("Ignoring " + resource + " because it's from 'test-classes' " // + "and there's another matching resource available"); // continue; // } // try { // return loadCompilerFrom(resource); // } catch (RuntimeException invalidConfig) { // exception = invalidConfig; // } catch (Exception invalidConfig) { // exception = new RuntimeException(invalidConfig); // } // } // throw exception; // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // private static void printConfigurationFiles() throws Exception { // Enumeration enumeration = getClassLoader().getResources(RESOURCE_PATH); // List resources = new ArrayList(); // while (enumeration.hasMoreElements()) { // resources.add(enumeration.nextElement()); // } // log.debug("Found " + resources.size() + " resources matching '" + RESOURCE_PATH + "':"); // for (Iterator i = resources.iterator(); i.hasNext();) { // log.debug(" " + ((URL) i.next())); // } // } // // private static JspCompiler loadCompilerFrom(URL resource) throws Exception { // Properties properties = new Properties(); // properties.load(resource.openStream()); // if (!properties.containsKey(CONFIGURATION_KEY)) { // throw new RuntimeException("Property " + CONFIGURATION_KEY + " not found from " // + resource); // } // String klass = properties.getProperty(CONFIGURATION_KEY); // return (JspCompiler) Class.forName(klass).newInstance(); // } // // private static ClassLoader getClassLoader() { // return Thread.currentThread().getContextClassLoader(); // } // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspExecution.java // public interface JspExecution { // // String getRenderedResponse(); // } // Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/JspTestCase.java import java.io.File; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import net.sf.jsptest.assertion.OutputAssertion; import net.sf.jsptest.compiler.api.Jsp; import net.sf.jsptest.compiler.api.JspCompiler; import net.sf.jsptest.compiler.api.JspCompilerFactory; import net.sf.jsptest.compiler.api.JspExecution; import org.apache.log4j.Logger; /* * Copyright 2007 Lasse Koskela. * * 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 net.sf.jsptest; /** * An abstract base class to be extended by the user. The <tt>JspTestCase</tt> class provides a * facility for rendering a JSP and a set of assertion methods for verifying that the JSP under test * renders the expected kind of output. * * @author Lasse Koskela * @author Meinert Schwartau (scwar32) * @author Ronaldo Webb */ public abstract class JspTestCase extends TestCase { private Logger log; private Map requestParameters; private Map requestAttributes; private Map sessionAttributes; private Map substituteTaglibs;
private JspExecution execution;
jsptest/jsptest
jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/JspTestCase.java
// Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/assertion/OutputAssertion.java // public class OutputAssertion extends AbstractAssertion { // // private final String content; // // /** // * @param content // * The raw output to perform assertions on. // */ // public OutputAssertion(String content) { // this.content = content; // } // // /** // * Assert that the output should contain the given text. // * // * @param text // * The (partial) content that should be found from the output. // */ // public void shouldContain(String text) { // String msg = "Rendered output did not contain the expected text <" + text + ">:\n" // + content; // assertContains(msg, content, text); // } // // /** // * Assert that the output should not contain the given text. // * // * @param text // * The (partial) content that shouldn't be found from the output. // */ // public void shouldNotContain(String text) { // String msg = "Rendered output contained unexpected text <" + text + ">:\n" + content; // assertDoesNotContain(msg, content, text); // } // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/Jsp.java // public interface Jsp { // // JspExecution request(String httpMethod, Map requestAttributes, Map sessionAttributes, Map requestParameters); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompiler.java // public interface JspCompiler { // // Jsp compile(String path, Map taglibs); // // void setWebRoot(String directory); // // void setOutputDirectory(String directory); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompilerFactory.java // public class JspCompilerFactory { // // private static final Logger log = Logger.getLogger(JspCompilerFactory.class); // private static final String RESOURCE_PATH = "jsptest.properties"; // private static final String CONFIGURATION_KEY = "jsptest.compiler.implementation"; // // public static JspCompiler newInstance() { // RuntimeException exception = new RuntimeException( // "No JSP compiler implementation configured: " + "(configuration file " // + RESOURCE_PATH + " not found from class path."); // try { // printConfigurationFiles(); // Enumeration resources = getClassLoader().getResources(RESOURCE_PATH); // while (resources.hasMoreElements()) { // URL resource = (URL) resources.nextElement(); // if (resources.hasMoreElements() // && resource.toString().indexOf("test-classes") != -1) { // log.debug("Ignoring " + resource + " because it's from 'test-classes' " // + "and there's another matching resource available"); // continue; // } // try { // return loadCompilerFrom(resource); // } catch (RuntimeException invalidConfig) { // exception = invalidConfig; // } catch (Exception invalidConfig) { // exception = new RuntimeException(invalidConfig); // } // } // throw exception; // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // private static void printConfigurationFiles() throws Exception { // Enumeration enumeration = getClassLoader().getResources(RESOURCE_PATH); // List resources = new ArrayList(); // while (enumeration.hasMoreElements()) { // resources.add(enumeration.nextElement()); // } // log.debug("Found " + resources.size() + " resources matching '" + RESOURCE_PATH + "':"); // for (Iterator i = resources.iterator(); i.hasNext();) { // log.debug(" " + ((URL) i.next())); // } // } // // private static JspCompiler loadCompilerFrom(URL resource) throws Exception { // Properties properties = new Properties(); // properties.load(resource.openStream()); // if (!properties.containsKey(CONFIGURATION_KEY)) { // throw new RuntimeException("Property " + CONFIGURATION_KEY + " not found from " // + resource); // } // String klass = properties.getProperty(CONFIGURATION_KEY); // return (JspCompiler) Class.forName(klass).newInstance(); // } // // private static ClassLoader getClassLoader() { // return Thread.currentThread().getContextClassLoader(); // } // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspExecution.java // public interface JspExecution { // // String getRenderedResponse(); // }
import java.io.File; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import net.sf.jsptest.assertion.OutputAssertion; import net.sf.jsptest.compiler.api.Jsp; import net.sf.jsptest.compiler.api.JspCompiler; import net.sf.jsptest.compiler.api.JspCompilerFactory; import net.sf.jsptest.compiler.api.JspExecution; import org.apache.log4j.Logger;
* * @param path * The JSP file to render. The path should start with a "/" and is interpreted to be * relative to the web root specified by <tt>getWebRoot</tt>. */ protected void get(String path) throws Exception { request(path, "GET"); } /** * Simulate a HTTP POST request to the specified JSP file. * * @param path * The JSP file to render. The path should start with a "/" and is interpreted to be * relative to the web root specified by <tt>getWebRoot</tt>. */ protected void post(String path) throws Exception { request(path, "POST"); } /** * Simulate an HTTP request to a JSP. * * @param path * The path to the JSP to execute. * @param httpMethod * "GET" or "POST". */ protected void request(String path, String httpMethod) throws Exception { validatePath(path);
// Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/assertion/OutputAssertion.java // public class OutputAssertion extends AbstractAssertion { // // private final String content; // // /** // * @param content // * The raw output to perform assertions on. // */ // public OutputAssertion(String content) { // this.content = content; // } // // /** // * Assert that the output should contain the given text. // * // * @param text // * The (partial) content that should be found from the output. // */ // public void shouldContain(String text) { // String msg = "Rendered output did not contain the expected text <" + text + ">:\n" // + content; // assertContains(msg, content, text); // } // // /** // * Assert that the output should not contain the given text. // * // * @param text // * The (partial) content that shouldn't be found from the output. // */ // public void shouldNotContain(String text) { // String msg = "Rendered output contained unexpected text <" + text + ">:\n" + content; // assertDoesNotContain(msg, content, text); // } // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/Jsp.java // public interface Jsp { // // JspExecution request(String httpMethod, Map requestAttributes, Map sessionAttributes, Map requestParameters); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompiler.java // public interface JspCompiler { // // Jsp compile(String path, Map taglibs); // // void setWebRoot(String directory); // // void setOutputDirectory(String directory); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompilerFactory.java // public class JspCompilerFactory { // // private static final Logger log = Logger.getLogger(JspCompilerFactory.class); // private static final String RESOURCE_PATH = "jsptest.properties"; // private static final String CONFIGURATION_KEY = "jsptest.compiler.implementation"; // // public static JspCompiler newInstance() { // RuntimeException exception = new RuntimeException( // "No JSP compiler implementation configured: " + "(configuration file " // + RESOURCE_PATH + " not found from class path."); // try { // printConfigurationFiles(); // Enumeration resources = getClassLoader().getResources(RESOURCE_PATH); // while (resources.hasMoreElements()) { // URL resource = (URL) resources.nextElement(); // if (resources.hasMoreElements() // && resource.toString().indexOf("test-classes") != -1) { // log.debug("Ignoring " + resource + " because it's from 'test-classes' " // + "and there's another matching resource available"); // continue; // } // try { // return loadCompilerFrom(resource); // } catch (RuntimeException invalidConfig) { // exception = invalidConfig; // } catch (Exception invalidConfig) { // exception = new RuntimeException(invalidConfig); // } // } // throw exception; // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // private static void printConfigurationFiles() throws Exception { // Enumeration enumeration = getClassLoader().getResources(RESOURCE_PATH); // List resources = new ArrayList(); // while (enumeration.hasMoreElements()) { // resources.add(enumeration.nextElement()); // } // log.debug("Found " + resources.size() + " resources matching '" + RESOURCE_PATH + "':"); // for (Iterator i = resources.iterator(); i.hasNext();) { // log.debug(" " + ((URL) i.next())); // } // } // // private static JspCompiler loadCompilerFrom(URL resource) throws Exception { // Properties properties = new Properties(); // properties.load(resource.openStream()); // if (!properties.containsKey(CONFIGURATION_KEY)) { // throw new RuntimeException("Property " + CONFIGURATION_KEY + " not found from " // + resource); // } // String klass = properties.getProperty(CONFIGURATION_KEY); // return (JspCompiler) Class.forName(klass).newInstance(); // } // // private static ClassLoader getClassLoader() { // return Thread.currentThread().getContextClassLoader(); // } // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspExecution.java // public interface JspExecution { // // String getRenderedResponse(); // } // Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/JspTestCase.java import java.io.File; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import net.sf.jsptest.assertion.OutputAssertion; import net.sf.jsptest.compiler.api.Jsp; import net.sf.jsptest.compiler.api.JspCompiler; import net.sf.jsptest.compiler.api.JspCompilerFactory; import net.sf.jsptest.compiler.api.JspExecution; import org.apache.log4j.Logger; * * @param path * The JSP file to render. The path should start with a "/" and is interpreted to be * relative to the web root specified by <tt>getWebRoot</tt>. */ protected void get(String path) throws Exception { request(path, "GET"); } /** * Simulate a HTTP POST request to the specified JSP file. * * @param path * The JSP file to render. The path should start with a "/" and is interpreted to be * relative to the web root specified by <tt>getWebRoot</tt>. */ protected void post(String path) throws Exception { request(path, "POST"); } /** * Simulate an HTTP request to a JSP. * * @param path * The path to the JSP to execute. * @param httpMethod * "GET" or "POST". */ protected void request(String path, String httpMethod) throws Exception { validatePath(path);
JspCompiler compiler = JspCompilerFactory.newInstance();
jsptest/jsptest
jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/JspTestCase.java
// Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/assertion/OutputAssertion.java // public class OutputAssertion extends AbstractAssertion { // // private final String content; // // /** // * @param content // * The raw output to perform assertions on. // */ // public OutputAssertion(String content) { // this.content = content; // } // // /** // * Assert that the output should contain the given text. // * // * @param text // * The (partial) content that should be found from the output. // */ // public void shouldContain(String text) { // String msg = "Rendered output did not contain the expected text <" + text + ">:\n" // + content; // assertContains(msg, content, text); // } // // /** // * Assert that the output should not contain the given text. // * // * @param text // * The (partial) content that shouldn't be found from the output. // */ // public void shouldNotContain(String text) { // String msg = "Rendered output contained unexpected text <" + text + ">:\n" + content; // assertDoesNotContain(msg, content, text); // } // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/Jsp.java // public interface Jsp { // // JspExecution request(String httpMethod, Map requestAttributes, Map sessionAttributes, Map requestParameters); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompiler.java // public interface JspCompiler { // // Jsp compile(String path, Map taglibs); // // void setWebRoot(String directory); // // void setOutputDirectory(String directory); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompilerFactory.java // public class JspCompilerFactory { // // private static final Logger log = Logger.getLogger(JspCompilerFactory.class); // private static final String RESOURCE_PATH = "jsptest.properties"; // private static final String CONFIGURATION_KEY = "jsptest.compiler.implementation"; // // public static JspCompiler newInstance() { // RuntimeException exception = new RuntimeException( // "No JSP compiler implementation configured: " + "(configuration file " // + RESOURCE_PATH + " not found from class path."); // try { // printConfigurationFiles(); // Enumeration resources = getClassLoader().getResources(RESOURCE_PATH); // while (resources.hasMoreElements()) { // URL resource = (URL) resources.nextElement(); // if (resources.hasMoreElements() // && resource.toString().indexOf("test-classes") != -1) { // log.debug("Ignoring " + resource + " because it's from 'test-classes' " // + "and there's another matching resource available"); // continue; // } // try { // return loadCompilerFrom(resource); // } catch (RuntimeException invalidConfig) { // exception = invalidConfig; // } catch (Exception invalidConfig) { // exception = new RuntimeException(invalidConfig); // } // } // throw exception; // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // private static void printConfigurationFiles() throws Exception { // Enumeration enumeration = getClassLoader().getResources(RESOURCE_PATH); // List resources = new ArrayList(); // while (enumeration.hasMoreElements()) { // resources.add(enumeration.nextElement()); // } // log.debug("Found " + resources.size() + " resources matching '" + RESOURCE_PATH + "':"); // for (Iterator i = resources.iterator(); i.hasNext();) { // log.debug(" " + ((URL) i.next())); // } // } // // private static JspCompiler loadCompilerFrom(URL resource) throws Exception { // Properties properties = new Properties(); // properties.load(resource.openStream()); // if (!properties.containsKey(CONFIGURATION_KEY)) { // throw new RuntimeException("Property " + CONFIGURATION_KEY + " not found from " // + resource); // } // String klass = properties.getProperty(CONFIGURATION_KEY); // return (JspCompiler) Class.forName(klass).newInstance(); // } // // private static ClassLoader getClassLoader() { // return Thread.currentThread().getContextClassLoader(); // } // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspExecution.java // public interface JspExecution { // // String getRenderedResponse(); // }
import java.io.File; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import net.sf.jsptest.assertion.OutputAssertion; import net.sf.jsptest.compiler.api.Jsp; import net.sf.jsptest.compiler.api.JspCompiler; import net.sf.jsptest.compiler.api.JspCompilerFactory; import net.sf.jsptest.compiler.api.JspExecution; import org.apache.log4j.Logger;
* * @param path * The JSP file to render. The path should start with a "/" and is interpreted to be * relative to the web root specified by <tt>getWebRoot</tt>. */ protected void get(String path) throws Exception { request(path, "GET"); } /** * Simulate a HTTP POST request to the specified JSP file. * * @param path * The JSP file to render. The path should start with a "/" and is interpreted to be * relative to the web root specified by <tt>getWebRoot</tt>. */ protected void post(String path) throws Exception { request(path, "POST"); } /** * Simulate an HTTP request to a JSP. * * @param path * The path to the JSP to execute. * @param httpMethod * "GET" or "POST". */ protected void request(String path, String httpMethod) throws Exception { validatePath(path);
// Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/assertion/OutputAssertion.java // public class OutputAssertion extends AbstractAssertion { // // private final String content; // // /** // * @param content // * The raw output to perform assertions on. // */ // public OutputAssertion(String content) { // this.content = content; // } // // /** // * Assert that the output should contain the given text. // * // * @param text // * The (partial) content that should be found from the output. // */ // public void shouldContain(String text) { // String msg = "Rendered output did not contain the expected text <" + text + ">:\n" // + content; // assertContains(msg, content, text); // } // // /** // * Assert that the output should not contain the given text. // * // * @param text // * The (partial) content that shouldn't be found from the output. // */ // public void shouldNotContain(String text) { // String msg = "Rendered output contained unexpected text <" + text + ">:\n" + content; // assertDoesNotContain(msg, content, text); // } // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/Jsp.java // public interface Jsp { // // JspExecution request(String httpMethod, Map requestAttributes, Map sessionAttributes, Map requestParameters); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompiler.java // public interface JspCompiler { // // Jsp compile(String path, Map taglibs); // // void setWebRoot(String directory); // // void setOutputDirectory(String directory); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompilerFactory.java // public class JspCompilerFactory { // // private static final Logger log = Logger.getLogger(JspCompilerFactory.class); // private static final String RESOURCE_PATH = "jsptest.properties"; // private static final String CONFIGURATION_KEY = "jsptest.compiler.implementation"; // // public static JspCompiler newInstance() { // RuntimeException exception = new RuntimeException( // "No JSP compiler implementation configured: " + "(configuration file " // + RESOURCE_PATH + " not found from class path."); // try { // printConfigurationFiles(); // Enumeration resources = getClassLoader().getResources(RESOURCE_PATH); // while (resources.hasMoreElements()) { // URL resource = (URL) resources.nextElement(); // if (resources.hasMoreElements() // && resource.toString().indexOf("test-classes") != -1) { // log.debug("Ignoring " + resource + " because it's from 'test-classes' " // + "and there's another matching resource available"); // continue; // } // try { // return loadCompilerFrom(resource); // } catch (RuntimeException invalidConfig) { // exception = invalidConfig; // } catch (Exception invalidConfig) { // exception = new RuntimeException(invalidConfig); // } // } // throw exception; // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // private static void printConfigurationFiles() throws Exception { // Enumeration enumeration = getClassLoader().getResources(RESOURCE_PATH); // List resources = new ArrayList(); // while (enumeration.hasMoreElements()) { // resources.add(enumeration.nextElement()); // } // log.debug("Found " + resources.size() + " resources matching '" + RESOURCE_PATH + "':"); // for (Iterator i = resources.iterator(); i.hasNext();) { // log.debug(" " + ((URL) i.next())); // } // } // // private static JspCompiler loadCompilerFrom(URL resource) throws Exception { // Properties properties = new Properties(); // properties.load(resource.openStream()); // if (!properties.containsKey(CONFIGURATION_KEY)) { // throw new RuntimeException("Property " + CONFIGURATION_KEY + " not found from " // + resource); // } // String klass = properties.getProperty(CONFIGURATION_KEY); // return (JspCompiler) Class.forName(klass).newInstance(); // } // // private static ClassLoader getClassLoader() { // return Thread.currentThread().getContextClassLoader(); // } // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspExecution.java // public interface JspExecution { // // String getRenderedResponse(); // } // Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/JspTestCase.java import java.io.File; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import net.sf.jsptest.assertion.OutputAssertion; import net.sf.jsptest.compiler.api.Jsp; import net.sf.jsptest.compiler.api.JspCompiler; import net.sf.jsptest.compiler.api.JspCompilerFactory; import net.sf.jsptest.compiler.api.JspExecution; import org.apache.log4j.Logger; * * @param path * The JSP file to render. The path should start with a "/" and is interpreted to be * relative to the web root specified by <tt>getWebRoot</tt>. */ protected void get(String path) throws Exception { request(path, "GET"); } /** * Simulate a HTTP POST request to the specified JSP file. * * @param path * The JSP file to render. The path should start with a "/" and is interpreted to be * relative to the web root specified by <tt>getWebRoot</tt>. */ protected void post(String path) throws Exception { request(path, "POST"); } /** * Simulate an HTTP request to a JSP. * * @param path * The path to the JSP to execute. * @param httpMethod * "GET" or "POST". */ protected void request(String path, String httpMethod) throws Exception { validatePath(path);
JspCompiler compiler = JspCompilerFactory.newInstance();
jsptest/jsptest
jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/JspTestCase.java
// Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/assertion/OutputAssertion.java // public class OutputAssertion extends AbstractAssertion { // // private final String content; // // /** // * @param content // * The raw output to perform assertions on. // */ // public OutputAssertion(String content) { // this.content = content; // } // // /** // * Assert that the output should contain the given text. // * // * @param text // * The (partial) content that should be found from the output. // */ // public void shouldContain(String text) { // String msg = "Rendered output did not contain the expected text <" + text + ">:\n" // + content; // assertContains(msg, content, text); // } // // /** // * Assert that the output should not contain the given text. // * // * @param text // * The (partial) content that shouldn't be found from the output. // */ // public void shouldNotContain(String text) { // String msg = "Rendered output contained unexpected text <" + text + ">:\n" + content; // assertDoesNotContain(msg, content, text); // } // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/Jsp.java // public interface Jsp { // // JspExecution request(String httpMethod, Map requestAttributes, Map sessionAttributes, Map requestParameters); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompiler.java // public interface JspCompiler { // // Jsp compile(String path, Map taglibs); // // void setWebRoot(String directory); // // void setOutputDirectory(String directory); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompilerFactory.java // public class JspCompilerFactory { // // private static final Logger log = Logger.getLogger(JspCompilerFactory.class); // private static final String RESOURCE_PATH = "jsptest.properties"; // private static final String CONFIGURATION_KEY = "jsptest.compiler.implementation"; // // public static JspCompiler newInstance() { // RuntimeException exception = new RuntimeException( // "No JSP compiler implementation configured: " + "(configuration file " // + RESOURCE_PATH + " not found from class path."); // try { // printConfigurationFiles(); // Enumeration resources = getClassLoader().getResources(RESOURCE_PATH); // while (resources.hasMoreElements()) { // URL resource = (URL) resources.nextElement(); // if (resources.hasMoreElements() // && resource.toString().indexOf("test-classes") != -1) { // log.debug("Ignoring " + resource + " because it's from 'test-classes' " // + "and there's another matching resource available"); // continue; // } // try { // return loadCompilerFrom(resource); // } catch (RuntimeException invalidConfig) { // exception = invalidConfig; // } catch (Exception invalidConfig) { // exception = new RuntimeException(invalidConfig); // } // } // throw exception; // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // private static void printConfigurationFiles() throws Exception { // Enumeration enumeration = getClassLoader().getResources(RESOURCE_PATH); // List resources = new ArrayList(); // while (enumeration.hasMoreElements()) { // resources.add(enumeration.nextElement()); // } // log.debug("Found " + resources.size() + " resources matching '" + RESOURCE_PATH + "':"); // for (Iterator i = resources.iterator(); i.hasNext();) { // log.debug(" " + ((URL) i.next())); // } // } // // private static JspCompiler loadCompilerFrom(URL resource) throws Exception { // Properties properties = new Properties(); // properties.load(resource.openStream()); // if (!properties.containsKey(CONFIGURATION_KEY)) { // throw new RuntimeException("Property " + CONFIGURATION_KEY + " not found from " // + resource); // } // String klass = properties.getProperty(CONFIGURATION_KEY); // return (JspCompiler) Class.forName(klass).newInstance(); // } // // private static ClassLoader getClassLoader() { // return Thread.currentThread().getContextClassLoader(); // } // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspExecution.java // public interface JspExecution { // // String getRenderedResponse(); // }
import java.io.File; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import net.sf.jsptest.assertion.OutputAssertion; import net.sf.jsptest.compiler.api.Jsp; import net.sf.jsptest.compiler.api.JspCompiler; import net.sf.jsptest.compiler.api.JspCompilerFactory; import net.sf.jsptest.compiler.api.JspExecution; import org.apache.log4j.Logger;
protected void get(String path) throws Exception { request(path, "GET"); } /** * Simulate a HTTP POST request to the specified JSP file. * * @param path * The JSP file to render. The path should start with a "/" and is interpreted to be * relative to the web root specified by <tt>getWebRoot</tt>. */ protected void post(String path) throws Exception { request(path, "POST"); } /** * Simulate an HTTP request to a JSP. * * @param path * The path to the JSP to execute. * @param httpMethod * "GET" or "POST". */ protected void request(String path, String httpMethod) throws Exception { validatePath(path); JspCompiler compiler = JspCompilerFactory.newInstance(); log.debug("Using compiler " + compiler.getClass().getName() + " and webroot " + new File(getWebRoot()).getAbsolutePath()); compiler.setWebRoot(getWebRoot()); compiler.setOutputDirectory(getOutputDirectory());
// Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/assertion/OutputAssertion.java // public class OutputAssertion extends AbstractAssertion { // // private final String content; // // /** // * @param content // * The raw output to perform assertions on. // */ // public OutputAssertion(String content) { // this.content = content; // } // // /** // * Assert that the output should contain the given text. // * // * @param text // * The (partial) content that should be found from the output. // */ // public void shouldContain(String text) { // String msg = "Rendered output did not contain the expected text <" + text + ">:\n" // + content; // assertContains(msg, content, text); // } // // /** // * Assert that the output should not contain the given text. // * // * @param text // * The (partial) content that shouldn't be found from the output. // */ // public void shouldNotContain(String text) { // String msg = "Rendered output contained unexpected text <" + text + ">:\n" + content; // assertDoesNotContain(msg, content, text); // } // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/Jsp.java // public interface Jsp { // // JspExecution request(String httpMethod, Map requestAttributes, Map sessionAttributes, Map requestParameters); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompiler.java // public interface JspCompiler { // // Jsp compile(String path, Map taglibs); // // void setWebRoot(String directory); // // void setOutputDirectory(String directory); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompilerFactory.java // public class JspCompilerFactory { // // private static final Logger log = Logger.getLogger(JspCompilerFactory.class); // private static final String RESOURCE_PATH = "jsptest.properties"; // private static final String CONFIGURATION_KEY = "jsptest.compiler.implementation"; // // public static JspCompiler newInstance() { // RuntimeException exception = new RuntimeException( // "No JSP compiler implementation configured: " + "(configuration file " // + RESOURCE_PATH + " not found from class path."); // try { // printConfigurationFiles(); // Enumeration resources = getClassLoader().getResources(RESOURCE_PATH); // while (resources.hasMoreElements()) { // URL resource = (URL) resources.nextElement(); // if (resources.hasMoreElements() // && resource.toString().indexOf("test-classes") != -1) { // log.debug("Ignoring " + resource + " because it's from 'test-classes' " // + "and there's another matching resource available"); // continue; // } // try { // return loadCompilerFrom(resource); // } catch (RuntimeException invalidConfig) { // exception = invalidConfig; // } catch (Exception invalidConfig) { // exception = new RuntimeException(invalidConfig); // } // } // throw exception; // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // private static void printConfigurationFiles() throws Exception { // Enumeration enumeration = getClassLoader().getResources(RESOURCE_PATH); // List resources = new ArrayList(); // while (enumeration.hasMoreElements()) { // resources.add(enumeration.nextElement()); // } // log.debug("Found " + resources.size() + " resources matching '" + RESOURCE_PATH + "':"); // for (Iterator i = resources.iterator(); i.hasNext();) { // log.debug(" " + ((URL) i.next())); // } // } // // private static JspCompiler loadCompilerFrom(URL resource) throws Exception { // Properties properties = new Properties(); // properties.load(resource.openStream()); // if (!properties.containsKey(CONFIGURATION_KEY)) { // throw new RuntimeException("Property " + CONFIGURATION_KEY + " not found from " // + resource); // } // String klass = properties.getProperty(CONFIGURATION_KEY); // return (JspCompiler) Class.forName(klass).newInstance(); // } // // private static ClassLoader getClassLoader() { // return Thread.currentThread().getContextClassLoader(); // } // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspExecution.java // public interface JspExecution { // // String getRenderedResponse(); // } // Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/JspTestCase.java import java.io.File; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import net.sf.jsptest.assertion.OutputAssertion; import net.sf.jsptest.compiler.api.Jsp; import net.sf.jsptest.compiler.api.JspCompiler; import net.sf.jsptest.compiler.api.JspCompilerFactory; import net.sf.jsptest.compiler.api.JspExecution; import org.apache.log4j.Logger; protected void get(String path) throws Exception { request(path, "GET"); } /** * Simulate a HTTP POST request to the specified JSP file. * * @param path * The JSP file to render. The path should start with a "/" and is interpreted to be * relative to the web root specified by <tt>getWebRoot</tt>. */ protected void post(String path) throws Exception { request(path, "POST"); } /** * Simulate an HTTP request to a JSP. * * @param path * The path to the JSP to execute. * @param httpMethod * "GET" or "POST". */ protected void request(String path, String httpMethod) throws Exception { validatePath(path); JspCompiler compiler = JspCompilerFactory.newInstance(); log.debug("Using compiler " + compiler.getClass().getName() + " and webroot " + new File(getWebRoot()).getAbsolutePath()); compiler.setWebRoot(getWebRoot()); compiler.setOutputDirectory(getOutputDirectory());
Jsp jsp = compiler.compile(path, substituteTaglibs);
jsptest/jsptest
jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/JspTestCase.java
// Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/assertion/OutputAssertion.java // public class OutputAssertion extends AbstractAssertion { // // private final String content; // // /** // * @param content // * The raw output to perform assertions on. // */ // public OutputAssertion(String content) { // this.content = content; // } // // /** // * Assert that the output should contain the given text. // * // * @param text // * The (partial) content that should be found from the output. // */ // public void shouldContain(String text) { // String msg = "Rendered output did not contain the expected text <" + text + ">:\n" // + content; // assertContains(msg, content, text); // } // // /** // * Assert that the output should not contain the given text. // * // * @param text // * The (partial) content that shouldn't be found from the output. // */ // public void shouldNotContain(String text) { // String msg = "Rendered output contained unexpected text <" + text + ">:\n" + content; // assertDoesNotContain(msg, content, text); // } // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/Jsp.java // public interface Jsp { // // JspExecution request(String httpMethod, Map requestAttributes, Map sessionAttributes, Map requestParameters); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompiler.java // public interface JspCompiler { // // Jsp compile(String path, Map taglibs); // // void setWebRoot(String directory); // // void setOutputDirectory(String directory); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompilerFactory.java // public class JspCompilerFactory { // // private static final Logger log = Logger.getLogger(JspCompilerFactory.class); // private static final String RESOURCE_PATH = "jsptest.properties"; // private static final String CONFIGURATION_KEY = "jsptest.compiler.implementation"; // // public static JspCompiler newInstance() { // RuntimeException exception = new RuntimeException( // "No JSP compiler implementation configured: " + "(configuration file " // + RESOURCE_PATH + " not found from class path."); // try { // printConfigurationFiles(); // Enumeration resources = getClassLoader().getResources(RESOURCE_PATH); // while (resources.hasMoreElements()) { // URL resource = (URL) resources.nextElement(); // if (resources.hasMoreElements() // && resource.toString().indexOf("test-classes") != -1) { // log.debug("Ignoring " + resource + " because it's from 'test-classes' " // + "and there's another matching resource available"); // continue; // } // try { // return loadCompilerFrom(resource); // } catch (RuntimeException invalidConfig) { // exception = invalidConfig; // } catch (Exception invalidConfig) { // exception = new RuntimeException(invalidConfig); // } // } // throw exception; // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // private static void printConfigurationFiles() throws Exception { // Enumeration enumeration = getClassLoader().getResources(RESOURCE_PATH); // List resources = new ArrayList(); // while (enumeration.hasMoreElements()) { // resources.add(enumeration.nextElement()); // } // log.debug("Found " + resources.size() + " resources matching '" + RESOURCE_PATH + "':"); // for (Iterator i = resources.iterator(); i.hasNext();) { // log.debug(" " + ((URL) i.next())); // } // } // // private static JspCompiler loadCompilerFrom(URL resource) throws Exception { // Properties properties = new Properties(); // properties.load(resource.openStream()); // if (!properties.containsKey(CONFIGURATION_KEY)) { // throw new RuntimeException("Property " + CONFIGURATION_KEY + " not found from " // + resource); // } // String klass = properties.getProperty(CONFIGURATION_KEY); // return (JspCompiler) Class.forName(klass).newInstance(); // } // // private static ClassLoader getClassLoader() { // return Thread.currentThread().getContextClassLoader(); // } // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspExecution.java // public interface JspExecution { // // String getRenderedResponse(); // }
import java.io.File; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import net.sf.jsptest.assertion.OutputAssertion; import net.sf.jsptest.compiler.api.Jsp; import net.sf.jsptest.compiler.api.JspCompiler; import net.sf.jsptest.compiler.api.JspCompilerFactory; import net.sf.jsptest.compiler.api.JspExecution; import org.apache.log4j.Logger;
JspCompiler compiler = JspCompilerFactory.newInstance(); log.debug("Using compiler " + compiler.getClass().getName() + " and webroot " + new File(getWebRoot()).getAbsolutePath()); compiler.setWebRoot(getWebRoot()); compiler.setOutputDirectory(getOutputDirectory()); Jsp jsp = compiler.compile(path, substituteTaglibs); log.debug("Simulating a request to " + path); execution = jsp.request(httpMethod, requestAttributes, sessionAttributes, requestParameters); } private void validatePath(String path) { if (!path.startsWith("/")) { throw new IllegalArgumentException("The JSP path must start with a \"/\""); } } private String getOutputDirectory() { return "target/jsptest"; } /** * Returns the rendered output. */ protected String getRenderedResponse() { return execution.getRenderedResponse(); } /** * Returns a handle for making assertions about the rendered content. */
// Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/assertion/OutputAssertion.java // public class OutputAssertion extends AbstractAssertion { // // private final String content; // // /** // * @param content // * The raw output to perform assertions on. // */ // public OutputAssertion(String content) { // this.content = content; // } // // /** // * Assert that the output should contain the given text. // * // * @param text // * The (partial) content that should be found from the output. // */ // public void shouldContain(String text) { // String msg = "Rendered output did not contain the expected text <" + text + ">:\n" // + content; // assertContains(msg, content, text); // } // // /** // * Assert that the output should not contain the given text. // * // * @param text // * The (partial) content that shouldn't be found from the output. // */ // public void shouldNotContain(String text) { // String msg = "Rendered output contained unexpected text <" + text + ">:\n" + content; // assertDoesNotContain(msg, content, text); // } // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/Jsp.java // public interface Jsp { // // JspExecution request(String httpMethod, Map requestAttributes, Map sessionAttributes, Map requestParameters); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompiler.java // public interface JspCompiler { // // Jsp compile(String path, Map taglibs); // // void setWebRoot(String directory); // // void setOutputDirectory(String directory); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompilerFactory.java // public class JspCompilerFactory { // // private static final Logger log = Logger.getLogger(JspCompilerFactory.class); // private static final String RESOURCE_PATH = "jsptest.properties"; // private static final String CONFIGURATION_KEY = "jsptest.compiler.implementation"; // // public static JspCompiler newInstance() { // RuntimeException exception = new RuntimeException( // "No JSP compiler implementation configured: " + "(configuration file " // + RESOURCE_PATH + " not found from class path."); // try { // printConfigurationFiles(); // Enumeration resources = getClassLoader().getResources(RESOURCE_PATH); // while (resources.hasMoreElements()) { // URL resource = (URL) resources.nextElement(); // if (resources.hasMoreElements() // && resource.toString().indexOf("test-classes") != -1) { // log.debug("Ignoring " + resource + " because it's from 'test-classes' " // + "and there's another matching resource available"); // continue; // } // try { // return loadCompilerFrom(resource); // } catch (RuntimeException invalidConfig) { // exception = invalidConfig; // } catch (Exception invalidConfig) { // exception = new RuntimeException(invalidConfig); // } // } // throw exception; // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // private static void printConfigurationFiles() throws Exception { // Enumeration enumeration = getClassLoader().getResources(RESOURCE_PATH); // List resources = new ArrayList(); // while (enumeration.hasMoreElements()) { // resources.add(enumeration.nextElement()); // } // log.debug("Found " + resources.size() + " resources matching '" + RESOURCE_PATH + "':"); // for (Iterator i = resources.iterator(); i.hasNext();) { // log.debug(" " + ((URL) i.next())); // } // } // // private static JspCompiler loadCompilerFrom(URL resource) throws Exception { // Properties properties = new Properties(); // properties.load(resource.openStream()); // if (!properties.containsKey(CONFIGURATION_KEY)) { // throw new RuntimeException("Property " + CONFIGURATION_KEY + " not found from " // + resource); // } // String klass = properties.getProperty(CONFIGURATION_KEY); // return (JspCompiler) Class.forName(klass).newInstance(); // } // // private static ClassLoader getClassLoader() { // return Thread.currentThread().getContextClassLoader(); // } // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspExecution.java // public interface JspExecution { // // String getRenderedResponse(); // } // Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/JspTestCase.java import java.io.File; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import net.sf.jsptest.assertion.OutputAssertion; import net.sf.jsptest.compiler.api.Jsp; import net.sf.jsptest.compiler.api.JspCompiler; import net.sf.jsptest.compiler.api.JspCompilerFactory; import net.sf.jsptest.compiler.api.JspExecution; import org.apache.log4j.Logger; JspCompiler compiler = JspCompilerFactory.newInstance(); log.debug("Using compiler " + compiler.getClass().getName() + " and webroot " + new File(getWebRoot()).getAbsolutePath()); compiler.setWebRoot(getWebRoot()); compiler.setOutputDirectory(getOutputDirectory()); Jsp jsp = compiler.compile(path, substituteTaglibs); log.debug("Simulating a request to " + path); execution = jsp.request(httpMethod, requestAttributes, sessionAttributes, requestParameters); } private void validatePath(String path) { if (!path.startsWith("/")) { throw new IllegalArgumentException("The JSP path must start with a \"/\""); } } private String getOutputDirectory() { return "target/jsptest"; } /** * Returns the rendered output. */ protected String getRenderedResponse() { return execution.getRenderedResponse(); } /** * Returns a handle for making assertions about the rendered content. */
public OutputAssertion output() {
jsptest/jsptest
jsptest-jsp20/src/test/java/net/sf/jsptest/compiler/jsp20/TestJspImpl.java
// Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspExecution.java // public interface JspExecution { // // String getRenderedResponse(); // } // // Path: jsptest-jsp20/src/main/java/net/sf/jsptest/compiler/jsp20/mock/MockJspWriter.java // public class MockJspWriter extends JspWriter { // // private Log log; // private PrintWriter writer; // private StringWriter stringWriter; // // public String getContents() { // return stringWriter.toString(); // } // // public MockJspWriter() { // super(1024, true); // log = LogFactory.getLog(getClass()); // stringWriter = new StringWriter(); // writer = new PrintWriter(stringWriter, true); // } // // public void newLine() throws IOException { // writer.println(); // } // // public void print(boolean x) throws IOException { // writer.print(x); // } // // public void print(char x) throws IOException { // writer.print(x); // } // // public void print(int x) throws IOException { // writer.print(x); // } // // public void print(long x) throws IOException { // writer.print(x); // } // // public void print(float x) throws IOException { // writer.print(x); // } // // public void print(double x) throws IOException { // writer.print(x); // } // // public void print(char[] x) throws IOException { // writer.print(x); // } // // public void print(String x) throws IOException { // writer.print(x); // } // // public void print(Object x) throws IOException { // writer.print(x); // } // // public void println() throws IOException { // writer.println(); // } // // public void println(boolean x) throws IOException { // writer.println(x); // } // // public void println(char x) throws IOException { // writer.println(x); // } // // public void println(int x) throws IOException { // writer.println(x); // } // // public void println(long x) throws IOException { // writer.println(x); // } // // public void println(float x) throws IOException { // writer.println(x); // } // // public void println(double x) throws IOException { // writer.println(x); // } // // public void println(char[] x) throws IOException { // writer.println(x); // } // // public void println(String x) throws IOException { // writer.println(x); // } // // public void println(Object x) throws IOException { // writer.println(x); // } // // public void clear() throws IOException { // notImplemented("clear()"); // } // // public void clearBuffer() throws IOException { // notImplemented("clearBuffer()"); // } // // public void flush() throws IOException { // writer.flush(); // } // // public void close() throws IOException { // writer.close(); // } // // public int getRemaining() { // notImplemented("getRemaining()"); // return 0; // } // // public void write(char[] x, int start, int length) throws IOException { // writer.write(x, start, length); // } // // private void notImplemented(String methodSignature) { // log.error(getClass().getName() + "#" + methodSignature + " not implemented"); // } // }
import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.jsp.JspFactory; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import junit.framework.TestCase; import net.sf.jsptest.compiler.api.JspExecution; import net.sf.jsptest.compiler.jsp20.mock.MockJspWriter;
String name = (String) names.nextElement(); out.print(name); out.print("="); out.println(req.getAttribute(name)); } Enumeration names2 = session.getAttributeNames(); while (names2.hasMoreElements()) { String name = (String) names2.nextElement(); out.print(name); out.print("="); out.println(session.getAttribute(name)); } Enumeration names3 = req.getParameterNames(); while (names3.hasMoreElements()) { String name = (String) names3.nextElement(); out.print(name); out.print("="); out.println(req.getParameter(name)); } out.println(); out.flush(); out.close(); } } protected String responseOutput; private JspImpl jspImpl; private Map requestParameters; private Map requestAttributes; private Map sessionAttributes;
// Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspExecution.java // public interface JspExecution { // // String getRenderedResponse(); // } // // Path: jsptest-jsp20/src/main/java/net/sf/jsptest/compiler/jsp20/mock/MockJspWriter.java // public class MockJspWriter extends JspWriter { // // private Log log; // private PrintWriter writer; // private StringWriter stringWriter; // // public String getContents() { // return stringWriter.toString(); // } // // public MockJspWriter() { // super(1024, true); // log = LogFactory.getLog(getClass()); // stringWriter = new StringWriter(); // writer = new PrintWriter(stringWriter, true); // } // // public void newLine() throws IOException { // writer.println(); // } // // public void print(boolean x) throws IOException { // writer.print(x); // } // // public void print(char x) throws IOException { // writer.print(x); // } // // public void print(int x) throws IOException { // writer.print(x); // } // // public void print(long x) throws IOException { // writer.print(x); // } // // public void print(float x) throws IOException { // writer.print(x); // } // // public void print(double x) throws IOException { // writer.print(x); // } // // public void print(char[] x) throws IOException { // writer.print(x); // } // // public void print(String x) throws IOException { // writer.print(x); // } // // public void print(Object x) throws IOException { // writer.print(x); // } // // public void println() throws IOException { // writer.println(); // } // // public void println(boolean x) throws IOException { // writer.println(x); // } // // public void println(char x) throws IOException { // writer.println(x); // } // // public void println(int x) throws IOException { // writer.println(x); // } // // public void println(long x) throws IOException { // writer.println(x); // } // // public void println(float x) throws IOException { // writer.println(x); // } // // public void println(double x) throws IOException { // writer.println(x); // } // // public void println(char[] x) throws IOException { // writer.println(x); // } // // public void println(String x) throws IOException { // writer.println(x); // } // // public void println(Object x) throws IOException { // writer.println(x); // } // // public void clear() throws IOException { // notImplemented("clear()"); // } // // public void clearBuffer() throws IOException { // notImplemented("clearBuffer()"); // } // // public void flush() throws IOException { // writer.flush(); // } // // public void close() throws IOException { // writer.close(); // } // // public int getRemaining() { // notImplemented("getRemaining()"); // return 0; // } // // public void write(char[] x, int start, int length) throws IOException { // writer.write(x, start, length); // } // // private void notImplemented(String methodSignature) { // log.error(getClass().getName() + "#" + methodSignature + " not implemented"); // } // } // Path: jsptest-jsp20/src/test/java/net/sf/jsptest/compiler/jsp20/TestJspImpl.java import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.jsp.JspFactory; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import junit.framework.TestCase; import net.sf.jsptest.compiler.api.JspExecution; import net.sf.jsptest.compiler.jsp20.mock.MockJspWriter; String name = (String) names.nextElement(); out.print(name); out.print("="); out.println(req.getAttribute(name)); } Enumeration names2 = session.getAttributeNames(); while (names2.hasMoreElements()) { String name = (String) names2.nextElement(); out.print(name); out.print("="); out.println(session.getAttribute(name)); } Enumeration names3 = req.getParameterNames(); while (names3.hasMoreElements()) { String name = (String) names3.nextElement(); out.print(name); out.print("="); out.println(req.getParameter(name)); } out.println(); out.flush(); out.close(); } } protected String responseOutput; private JspImpl jspImpl; private Map requestParameters; private Map requestAttributes; private Map sessionAttributes;
private MockJspWriter mockJspWriter;
jsptest/jsptest
jsptest-jsp20/src/test/java/net/sf/jsptest/compiler/jsp20/TestJspImpl.java
// Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspExecution.java // public interface JspExecution { // // String getRenderedResponse(); // } // // Path: jsptest-jsp20/src/main/java/net/sf/jsptest/compiler/jsp20/mock/MockJspWriter.java // public class MockJspWriter extends JspWriter { // // private Log log; // private PrintWriter writer; // private StringWriter stringWriter; // // public String getContents() { // return stringWriter.toString(); // } // // public MockJspWriter() { // super(1024, true); // log = LogFactory.getLog(getClass()); // stringWriter = new StringWriter(); // writer = new PrintWriter(stringWriter, true); // } // // public void newLine() throws IOException { // writer.println(); // } // // public void print(boolean x) throws IOException { // writer.print(x); // } // // public void print(char x) throws IOException { // writer.print(x); // } // // public void print(int x) throws IOException { // writer.print(x); // } // // public void print(long x) throws IOException { // writer.print(x); // } // // public void print(float x) throws IOException { // writer.print(x); // } // // public void print(double x) throws IOException { // writer.print(x); // } // // public void print(char[] x) throws IOException { // writer.print(x); // } // // public void print(String x) throws IOException { // writer.print(x); // } // // public void print(Object x) throws IOException { // writer.print(x); // } // // public void println() throws IOException { // writer.println(); // } // // public void println(boolean x) throws IOException { // writer.println(x); // } // // public void println(char x) throws IOException { // writer.println(x); // } // // public void println(int x) throws IOException { // writer.println(x); // } // // public void println(long x) throws IOException { // writer.println(x); // } // // public void println(float x) throws IOException { // writer.println(x); // } // // public void println(double x) throws IOException { // writer.println(x); // } // // public void println(char[] x) throws IOException { // writer.println(x); // } // // public void println(String x) throws IOException { // writer.println(x); // } // // public void println(Object x) throws IOException { // writer.println(x); // } // // public void clear() throws IOException { // notImplemented("clear()"); // } // // public void clearBuffer() throws IOException { // notImplemented("clearBuffer()"); // } // // public void flush() throws IOException { // writer.flush(); // } // // public void close() throws IOException { // writer.close(); // } // // public int getRemaining() { // notImplemented("getRemaining()"); // return 0; // } // // public void write(char[] x, int start, int length) throws IOException { // writer.write(x, start, length); // } // // private void notImplemented(String methodSignature) { // log.error(getClass().getName() + "#" + methodSignature + " not implemented"); // } // }
import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.jsp.JspFactory; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import junit.framework.TestCase; import net.sf.jsptest.compiler.api.JspExecution; import net.sf.jsptest.compiler.jsp20.mock.MockJspWriter;
}; } public void testHttpMethodIsPassedToTheServletInstance() throws Exception { simulateRequest("GET"); assertOutputContains("httpMethod=GET"); simulateRequest("POST"); assertOutputContains("httpMethod=POST"); } public void testRequestParametersArePassedToTheServletInstance() throws Exception { simulateRequest(); assertOutputContains("REQPARM=PARAMVAL"); } public void testRequestAttributesArePassedToTheServletInstance() throws Exception { simulateRequest(); assertOutputContains("REQATTR=REQVALUE"); } public void testSessionAttributesArePassedToTheServletInstance() throws Exception { simulateRequest(); assertOutputContains("SESATTR=SESVALUE"); } private void simulateRequest() { simulateRequest("GET"); } private void simulateRequest(String method) {
// Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspExecution.java // public interface JspExecution { // // String getRenderedResponse(); // } // // Path: jsptest-jsp20/src/main/java/net/sf/jsptest/compiler/jsp20/mock/MockJspWriter.java // public class MockJspWriter extends JspWriter { // // private Log log; // private PrintWriter writer; // private StringWriter stringWriter; // // public String getContents() { // return stringWriter.toString(); // } // // public MockJspWriter() { // super(1024, true); // log = LogFactory.getLog(getClass()); // stringWriter = new StringWriter(); // writer = new PrintWriter(stringWriter, true); // } // // public void newLine() throws IOException { // writer.println(); // } // // public void print(boolean x) throws IOException { // writer.print(x); // } // // public void print(char x) throws IOException { // writer.print(x); // } // // public void print(int x) throws IOException { // writer.print(x); // } // // public void print(long x) throws IOException { // writer.print(x); // } // // public void print(float x) throws IOException { // writer.print(x); // } // // public void print(double x) throws IOException { // writer.print(x); // } // // public void print(char[] x) throws IOException { // writer.print(x); // } // // public void print(String x) throws IOException { // writer.print(x); // } // // public void print(Object x) throws IOException { // writer.print(x); // } // // public void println() throws IOException { // writer.println(); // } // // public void println(boolean x) throws IOException { // writer.println(x); // } // // public void println(char x) throws IOException { // writer.println(x); // } // // public void println(int x) throws IOException { // writer.println(x); // } // // public void println(long x) throws IOException { // writer.println(x); // } // // public void println(float x) throws IOException { // writer.println(x); // } // // public void println(double x) throws IOException { // writer.println(x); // } // // public void println(char[] x) throws IOException { // writer.println(x); // } // // public void println(String x) throws IOException { // writer.println(x); // } // // public void println(Object x) throws IOException { // writer.println(x); // } // // public void clear() throws IOException { // notImplemented("clear()"); // } // // public void clearBuffer() throws IOException { // notImplemented("clearBuffer()"); // } // // public void flush() throws IOException { // writer.flush(); // } // // public void close() throws IOException { // writer.close(); // } // // public int getRemaining() { // notImplemented("getRemaining()"); // return 0; // } // // public void write(char[] x, int start, int length) throws IOException { // writer.write(x, start, length); // } // // private void notImplemented(String methodSignature) { // log.error(getClass().getName() + "#" + methodSignature + " not implemented"); // } // } // Path: jsptest-jsp20/src/test/java/net/sf/jsptest/compiler/jsp20/TestJspImpl.java import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.jsp.JspFactory; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import junit.framework.TestCase; import net.sf.jsptest.compiler.api.JspExecution; import net.sf.jsptest.compiler.jsp20.mock.MockJspWriter; }; } public void testHttpMethodIsPassedToTheServletInstance() throws Exception { simulateRequest("GET"); assertOutputContains("httpMethod=GET"); simulateRequest("POST"); assertOutputContains("httpMethod=POST"); } public void testRequestParametersArePassedToTheServletInstance() throws Exception { simulateRequest(); assertOutputContains("REQPARM=PARAMVAL"); } public void testRequestAttributesArePassedToTheServletInstance() throws Exception { simulateRequest(); assertOutputContains("REQATTR=REQVALUE"); } public void testSessionAttributesArePassedToTheServletInstance() throws Exception { simulateRequest(); assertOutputContains("SESATTR=SESVALUE"); } private void simulateRequest() { simulateRequest("GET"); } private void simulateRequest(String method) {
JspExecution execution = jspImpl.request(method, requestAttributes, sessionAttributes, requestParameters);
jsptest/jsptest
jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/assertion/DOMAssertion.java
// Path: jsptest-generic/jsptest-common/src/main/java/net/sf/jsptest/utils/XML.java // public class XML { // // private static final String APACHE_INDENTATION = "{http://xml.apache.org/xslt}indent-amount"; // // public static String toString(Node xml) { // try { // TransformerFactory f = TransformerFactory.newInstance(); // Transformer t = f.newTransformer(); // t.setOutputProperty(OutputKeys.INDENT, "yes"); // t.setOutputProperty(APACHE_INDENTATION, "2"); // OutputStream out = new ByteArrayOutputStream(); // t.transform(new DOMSource(xml), new StreamResult(out)); // return out.toString(); // } catch (TransformerException e) { // throw new RuntimeException(e); // } // } // // public static String textContentOf(Element element) { // StringBuffer textContent = new StringBuffer(100); // NodeList children = element.getChildNodes(); // for (int i = 0; i < children.getLength(); i++) { // appendTextContentOf(children.item(i), textContent); // } // return textContent.toString(); // } // // private static void appendTextContentOf(Node from, StringBuffer to) { // if (from.getNodeType() == Node.ELEMENT_NODE) { // to.append(textContentOf((Element) from)); // } else if (from.getNodeType() != Node.COMMENT_NODE) { // to.append(from.getNodeValue().trim()); // } // } // }
import java.util.List; import junit.framework.Assert; import net.sf.jsptest.utils.XML; import org.jaxen.JaxenException; import org.jaxen.dom.DOMXPath; import org.w3c.dom.Element;
package net.sf.jsptest.assertion; /** * Base class providing assertion methods related to the HTML DOM tree. * * @author Lasse Koskela */ public abstract class DOMAssertion extends AbstractAssertion { protected Element context; /** * Returns the <tt>Element</tt> as the context of assertions. */ public Element getElement() { return context; } /** * Assert that the selected DOM element contains the given text. * * @param text * The (partial) content that should be found. */ public void shouldContain(String text) {
// Path: jsptest-generic/jsptest-common/src/main/java/net/sf/jsptest/utils/XML.java // public class XML { // // private static final String APACHE_INDENTATION = "{http://xml.apache.org/xslt}indent-amount"; // // public static String toString(Node xml) { // try { // TransformerFactory f = TransformerFactory.newInstance(); // Transformer t = f.newTransformer(); // t.setOutputProperty(OutputKeys.INDENT, "yes"); // t.setOutputProperty(APACHE_INDENTATION, "2"); // OutputStream out = new ByteArrayOutputStream(); // t.transform(new DOMSource(xml), new StreamResult(out)); // return out.toString(); // } catch (TransformerException e) { // throw new RuntimeException(e); // } // } // // public static String textContentOf(Element element) { // StringBuffer textContent = new StringBuffer(100); // NodeList children = element.getChildNodes(); // for (int i = 0; i < children.getLength(); i++) { // appendTextContentOf(children.item(i), textContent); // } // return textContent.toString(); // } // // private static void appendTextContentOf(Node from, StringBuffer to) { // if (from.getNodeType() == Node.ELEMENT_NODE) { // to.append(textContentOf((Element) from)); // } else if (from.getNodeType() != Node.COMMENT_NODE) { // to.append(from.getNodeValue().trim()); // } // } // } // Path: jsptest-generic/jsptest-framework/src/main/java/net/sf/jsptest/assertion/DOMAssertion.java import java.util.List; import junit.framework.Assert; import net.sf.jsptest.utils.XML; import org.jaxen.JaxenException; import org.jaxen.dom.DOMXPath; import org.w3c.dom.Element; package net.sf.jsptest.assertion; /** * Base class providing assertion methods related to the HTML DOM tree. * * @author Lasse Koskela */ public abstract class DOMAssertion extends AbstractAssertion { protected Element context; /** * Returns the <tt>Element</tt> as the context of assertions. */ public Element getElement() { return context; } /** * Assert that the selected DOM element contains the given text. * * @param text * The (partial) content that should be found. */ public void shouldContain(String text) {
assertContains(XML.textContentOf(context), text);
jsptest/jsptest
jsptest-generic/jsptest-framework/src/test/java/net/sf/jsptest/compiler/dummy/FakeJspCompiler.java
// Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/Jsp.java // public interface Jsp { // // JspExecution request(String httpMethod, Map requestAttributes, Map sessionAttributes, Map requestParameters); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompiler.java // public interface JspCompiler { // // Jsp compile(String path, Map taglibs); // // void setWebRoot(String directory); // // void setOutputDirectory(String directory); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspExecution.java // public interface JspExecution { // // String getRenderedResponse(); // }
import java.util.Map; import net.sf.jsptest.compiler.api.Jsp; import net.sf.jsptest.compiler.api.JspCompiler; import net.sf.jsptest.compiler.api.JspExecution;
package net.sf.jsptest.compiler.dummy; /** * @author Lasse Koskela * @author Meinert Schwartau (scwar32) * @author Ronaldo Webb */ public class FakeJspCompiler implements JspCompiler { private static StringBuffer fakedOutput = new StringBuffer(2000); private static String lastCompiledPath; private static String lastCompiledWebRoot; private String webRoot; public void setWebRoot(String directory) { this.webRoot = directory; } protected String getWebRoot() { return webRoot; } public static void cleanOutput() { fakedOutput.setLength(0); } public static void appendOutput(String content) { fakedOutput.append(content); }
// Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/Jsp.java // public interface Jsp { // // JspExecution request(String httpMethod, Map requestAttributes, Map sessionAttributes, Map requestParameters); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompiler.java // public interface JspCompiler { // // Jsp compile(String path, Map taglibs); // // void setWebRoot(String directory); // // void setOutputDirectory(String directory); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspExecution.java // public interface JspExecution { // // String getRenderedResponse(); // } // Path: jsptest-generic/jsptest-framework/src/test/java/net/sf/jsptest/compiler/dummy/FakeJspCompiler.java import java.util.Map; import net.sf.jsptest.compiler.api.Jsp; import net.sf.jsptest.compiler.api.JspCompiler; import net.sf.jsptest.compiler.api.JspExecution; package net.sf.jsptest.compiler.dummy; /** * @author Lasse Koskela * @author Meinert Schwartau (scwar32) * @author Ronaldo Webb */ public class FakeJspCompiler implements JspCompiler { private static StringBuffer fakedOutput = new StringBuffer(2000); private static String lastCompiledPath; private static String lastCompiledWebRoot; private String webRoot; public void setWebRoot(String directory) { this.webRoot = directory; } protected String getWebRoot() { return webRoot; } public static void cleanOutput() { fakedOutput.setLength(0); } public static void appendOutput(String content) { fakedOutput.append(content); }
public Jsp compile(String path, Map taglibs) {
jsptest/jsptest
jsptest-generic/jsptest-framework/src/test/java/net/sf/jsptest/compiler/dummy/FakeJspCompiler.java
// Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/Jsp.java // public interface Jsp { // // JspExecution request(String httpMethod, Map requestAttributes, Map sessionAttributes, Map requestParameters); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompiler.java // public interface JspCompiler { // // Jsp compile(String path, Map taglibs); // // void setWebRoot(String directory); // // void setOutputDirectory(String directory); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspExecution.java // public interface JspExecution { // // String getRenderedResponse(); // }
import java.util.Map; import net.sf.jsptest.compiler.api.Jsp; import net.sf.jsptest.compiler.api.JspCompiler; import net.sf.jsptest.compiler.api.JspExecution;
package net.sf.jsptest.compiler.dummy; /** * @author Lasse Koskela * @author Meinert Schwartau (scwar32) * @author Ronaldo Webb */ public class FakeJspCompiler implements JspCompiler { private static StringBuffer fakedOutput = new StringBuffer(2000); private static String lastCompiledPath; private static String lastCompiledWebRoot; private String webRoot; public void setWebRoot(String directory) { this.webRoot = directory; } protected String getWebRoot() { return webRoot; } public static void cleanOutput() { fakedOutput.setLength(0); } public static void appendOutput(String content) { fakedOutput.append(content); } public Jsp compile(String path, Map taglibs) { lastCompiledWebRoot = getWebRoot(); lastCompiledPath = path; return new Jsp() {
// Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/Jsp.java // public interface Jsp { // // JspExecution request(String httpMethod, Map requestAttributes, Map sessionAttributes, Map requestParameters); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspCompiler.java // public interface JspCompiler { // // Jsp compile(String path, Map taglibs); // // void setWebRoot(String directory); // // void setOutputDirectory(String directory); // } // // Path: jsptest-generic/jsptest-compiler-api/src/main/java/net/sf/jsptest/compiler/api/JspExecution.java // public interface JspExecution { // // String getRenderedResponse(); // } // Path: jsptest-generic/jsptest-framework/src/test/java/net/sf/jsptest/compiler/dummy/FakeJspCompiler.java import java.util.Map; import net.sf.jsptest.compiler.api.Jsp; import net.sf.jsptest.compiler.api.JspCompiler; import net.sf.jsptest.compiler.api.JspExecution; package net.sf.jsptest.compiler.dummy; /** * @author Lasse Koskela * @author Meinert Schwartau (scwar32) * @author Ronaldo Webb */ public class FakeJspCompiler implements JspCompiler { private static StringBuffer fakedOutput = new StringBuffer(2000); private static String lastCompiledPath; private static String lastCompiledWebRoot; private String webRoot; public void setWebRoot(String directory) { this.webRoot = directory; } protected String getWebRoot() { return webRoot; } public static void cleanOutput() { fakedOutput.setLength(0); } public static void appendOutput(String content) { fakedOutput.append(content); } public Jsp compile(String path, Map taglibs) { lastCompiledWebRoot = getWebRoot(); lastCompiledPath = path; return new Jsp() {
public JspExecution request(String httpMethod, Map requestAttributes,
jsptest/jsptest
jsptest-generic/jsptest-framework/src/test/java/net/sf/jsptest/TestHtmlTestCaseElementAssertions.java
// Path: jsptest-generic/jsptest-common/src/main/java/net/sf/jsptest/utils/XML.java // public class XML { // // private static final String APACHE_INDENTATION = "{http://xml.apache.org/xslt}indent-amount"; // // public static String toString(Node xml) { // try { // TransformerFactory f = TransformerFactory.newInstance(); // Transformer t = f.newTransformer(); // t.setOutputProperty(OutputKeys.INDENT, "yes"); // t.setOutputProperty(APACHE_INDENTATION, "2"); // OutputStream out = new ByteArrayOutputStream(); // t.transform(new DOMSource(xml), new StreamResult(out)); // return out.toString(); // } catch (TransformerException e) { // throw new RuntimeException(e); // } // } // // public static String textContentOf(Element element) { // StringBuffer textContent = new StringBuffer(100); // NodeList children = element.getChildNodes(); // for (int i = 0; i < children.getLength(); i++) { // appendTextContentOf(children.item(i), textContent); // } // return textContent.toString(); // } // // private static void appendTextContentOf(Node from, StringBuffer to) { // if (from.getNodeType() == Node.ELEMENT_NODE) { // to.append(textContentOf((Element) from)); // } else if (from.getNodeType() != Node.COMMENT_NODE) { // to.append(from.getNodeValue().trim()); // } // } // }
import junit.framework.AssertionFailedError; import net.sf.jsptest.utils.XML; import org.w3c.dom.Element;
public void testAssertingAgainstNonElementXPathFails() throws Exception { String xpath = "//P[@CLASS='p1']/text()"; try { testcase.element(xpath); throw new RuntimeException("Expected assertion to fail but it didn't."); } catch (AssertionFailedError expected) { } } public void testElementShouldContain() throws Exception { testcase.element("//P[@CLASS='p2']").shouldContain("this is p2"); try { testcase.element("//P[@CLASS='p1']").shouldContain("it doesn't contain this"); throw new RuntimeException("Expected assertion to fail but it didn't."); } catch (AssertionFailedError expected) { } } public void testElementShouldNotContain() throws Exception { testcase.element("//P[@CLASS='p2']").shouldNotContain("bad things"); try { testcase.element("//P[@CLASS='p2']").shouldNotContain("p2"); throw new RuntimeException("Expected assertion to fail but it didn't."); } catch (AssertionFailedError expected) { } } public void testHasAccessToUnderlyingDomElement() throws Exception { Element element = testcase.element("//P[@CLASS='p2']").getElement(); assertNotNull(element);
// Path: jsptest-generic/jsptest-common/src/main/java/net/sf/jsptest/utils/XML.java // public class XML { // // private static final String APACHE_INDENTATION = "{http://xml.apache.org/xslt}indent-amount"; // // public static String toString(Node xml) { // try { // TransformerFactory f = TransformerFactory.newInstance(); // Transformer t = f.newTransformer(); // t.setOutputProperty(OutputKeys.INDENT, "yes"); // t.setOutputProperty(APACHE_INDENTATION, "2"); // OutputStream out = new ByteArrayOutputStream(); // t.transform(new DOMSource(xml), new StreamResult(out)); // return out.toString(); // } catch (TransformerException e) { // throw new RuntimeException(e); // } // } // // public static String textContentOf(Element element) { // StringBuffer textContent = new StringBuffer(100); // NodeList children = element.getChildNodes(); // for (int i = 0; i < children.getLength(); i++) { // appendTextContentOf(children.item(i), textContent); // } // return textContent.toString(); // } // // private static void appendTextContentOf(Node from, StringBuffer to) { // if (from.getNodeType() == Node.ELEMENT_NODE) { // to.append(textContentOf((Element) from)); // } else if (from.getNodeType() != Node.COMMENT_NODE) { // to.append(from.getNodeValue().trim()); // } // } // } // Path: jsptest-generic/jsptest-framework/src/test/java/net/sf/jsptest/TestHtmlTestCaseElementAssertions.java import junit.framework.AssertionFailedError; import net.sf.jsptest.utils.XML; import org.w3c.dom.Element; public void testAssertingAgainstNonElementXPathFails() throws Exception { String xpath = "//P[@CLASS='p1']/text()"; try { testcase.element(xpath); throw new RuntimeException("Expected assertion to fail but it didn't."); } catch (AssertionFailedError expected) { } } public void testElementShouldContain() throws Exception { testcase.element("//P[@CLASS='p2']").shouldContain("this is p2"); try { testcase.element("//P[@CLASS='p1']").shouldContain("it doesn't contain this"); throw new RuntimeException("Expected assertion to fail but it didn't."); } catch (AssertionFailedError expected) { } } public void testElementShouldNotContain() throws Exception { testcase.element("//P[@CLASS='p2']").shouldNotContain("bad things"); try { testcase.element("//P[@CLASS='p2']").shouldNotContain("p2"); throw new RuntimeException("Expected assertion to fail but it didn't."); } catch (AssertionFailedError expected) { } } public void testHasAccessToUnderlyingDomElement() throws Exception { Element element = testcase.element("//P[@CLASS='p2']").getElement(); assertNotNull(element);
assertEquals("this is p2", XML.textContentOf(element));
jagrosh/GiveawayBot
src/main/java/com/jagrosh/giveawaybot/database/managers/GuildSettingsManager.java
// Path: src/main/java/com/jagrosh/giveawaybot/Constants.java // public class Constants // { // public static final OffsetDateTime STARTUP = OffsetDateTime.now(); // public static final int PRIZE_MAX = 250; // public static final long SERVER_ID = 585687812548853760L; // public static final String TADA = "\uD83C\uDF89"; // 🎉 // public static final String WARNING = "\uD83D\uDCA5"; // 💥 // public static final String ERROR = "\uD83D\uDCA5"; // 💥 // public static final String YAY = "<:yay:585696613507399692>";//"<:yay:440620097543864320>"; // public static final String REACTION = "yay:585696613507399692";//"yay:440620097543864320"; // public static final Color BLURPLE = Color.decode("#7289DA"); // public static final String INVITE = "https://giveawaybot.party/invite"; // public static final String DONATE = "https://giveawaybot.party/donate"; // public static final int MIN_TIME = 10; // public static final String WEBSITE = "https://giveawaybot.party"; // public static final String OWNER = "**jagrosh**#4824"; // public static final String GITHUB = "https://github.com/jagrosh/GiveawayBot"; // public static final String VERSION = "2.2"; // public static final String PERMS = "`Read Messages`, `Write Messages`, `Read Message History`, `Embed Links`, `Use External Emoji`, and `Add Reactions`"; // // public static final boolean canSendGiveaway(TextChannel channel) // { // return channel.getGuild().getSelfMember().hasPermission(channel, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, // Permission.MESSAGE_HISTORY, Permission.MESSAGE_EMBED_LINKS, Permission.MESSAGE_EXT_EMOJI, Permission.MESSAGE_ADD_REACTION); // } // } // // Path: src/main/java/com/jagrosh/giveawaybot/database/Database.java // public class Database extends DatabaseConnector // { // public final GiveawayManager giveaways; // public final GuildSettingsManager settings; // public final PremiumManager premium; // public final ExpandedGiveawayManager expanded; // // public Database (String host, String user, String pass) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException // { // super(host, user, pass); // // this.giveaways = new GiveawayManager(this); // this.settings = new GuildSettingsManager(this); // this.premium = new PremiumManager(this); // this.expanded = new ExpandedGiveawayManager(this); // // init(); // } // // public boolean databaseCheck() // { // return this.giveaways.getGiveaways() != null; // } // }
import com.jagrosh.easysql.DataManager; import com.jagrosh.easysql.SQLColumn; import com.jagrosh.easysql.columns.*; import com.jagrosh.giveawaybot.Constants; import com.jagrosh.giveawaybot.database.Database; import java.awt.Color; import java.sql.ResultSet; import java.sql.SQLException; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.TextChannel;
/* * Copyright 2017 John Grosh ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jagrosh.giveawaybot.database.managers; /** * * @author John Grosh ([email protected]) */ public class GuildSettingsManager extends DataManager { public final static SQLColumn<Long> GUILD_ID = new LongColumn("GUILD_ID", false, 0, true);
// Path: src/main/java/com/jagrosh/giveawaybot/Constants.java // public class Constants // { // public static final OffsetDateTime STARTUP = OffsetDateTime.now(); // public static final int PRIZE_MAX = 250; // public static final long SERVER_ID = 585687812548853760L; // public static final String TADA = "\uD83C\uDF89"; // 🎉 // public static final String WARNING = "\uD83D\uDCA5"; // 💥 // public static final String ERROR = "\uD83D\uDCA5"; // 💥 // public static final String YAY = "<:yay:585696613507399692>";//"<:yay:440620097543864320>"; // public static final String REACTION = "yay:585696613507399692";//"yay:440620097543864320"; // public static final Color BLURPLE = Color.decode("#7289DA"); // public static final String INVITE = "https://giveawaybot.party/invite"; // public static final String DONATE = "https://giveawaybot.party/donate"; // public static final int MIN_TIME = 10; // public static final String WEBSITE = "https://giveawaybot.party"; // public static final String OWNER = "**jagrosh**#4824"; // public static final String GITHUB = "https://github.com/jagrosh/GiveawayBot"; // public static final String VERSION = "2.2"; // public static final String PERMS = "`Read Messages`, `Write Messages`, `Read Message History`, `Embed Links`, `Use External Emoji`, and `Add Reactions`"; // // public static final boolean canSendGiveaway(TextChannel channel) // { // return channel.getGuild().getSelfMember().hasPermission(channel, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, // Permission.MESSAGE_HISTORY, Permission.MESSAGE_EMBED_LINKS, Permission.MESSAGE_EXT_EMOJI, Permission.MESSAGE_ADD_REACTION); // } // } // // Path: src/main/java/com/jagrosh/giveawaybot/database/Database.java // public class Database extends DatabaseConnector // { // public final GiveawayManager giveaways; // public final GuildSettingsManager settings; // public final PremiumManager premium; // public final ExpandedGiveawayManager expanded; // // public Database (String host, String user, String pass) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException // { // super(host, user, pass); // // this.giveaways = new GiveawayManager(this); // this.settings = new GuildSettingsManager(this); // this.premium = new PremiumManager(this); // this.expanded = new ExpandedGiveawayManager(this); // // init(); // } // // public boolean databaseCheck() // { // return this.giveaways.getGiveaways() != null; // } // } // Path: src/main/java/com/jagrosh/giveawaybot/database/managers/GuildSettingsManager.java import com.jagrosh.easysql.DataManager; import com.jagrosh.easysql.SQLColumn; import com.jagrosh.easysql.columns.*; import com.jagrosh.giveawaybot.Constants; import com.jagrosh.giveawaybot.database.Database; import java.awt.Color; import java.sql.ResultSet; import java.sql.SQLException; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.TextChannel; /* * Copyright 2017 John Grosh ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jagrosh.giveawaybot.database.managers; /** * * @author John Grosh ([email protected]) */ public class GuildSettingsManager extends DataManager { public final static SQLColumn<Long> GUILD_ID = new LongColumn("GUILD_ID", false, 0, true);
public final static SQLColumn<Integer> COLOR = new IntegerColumn("COLOR", false, Constants.BLURPLE.getRGB());
jagrosh/GiveawayBot
src/main/java/com/jagrosh/giveawaybot/database/managers/GuildSettingsManager.java
// Path: src/main/java/com/jagrosh/giveawaybot/Constants.java // public class Constants // { // public static final OffsetDateTime STARTUP = OffsetDateTime.now(); // public static final int PRIZE_MAX = 250; // public static final long SERVER_ID = 585687812548853760L; // public static final String TADA = "\uD83C\uDF89"; // 🎉 // public static final String WARNING = "\uD83D\uDCA5"; // 💥 // public static final String ERROR = "\uD83D\uDCA5"; // 💥 // public static final String YAY = "<:yay:585696613507399692>";//"<:yay:440620097543864320>"; // public static final String REACTION = "yay:585696613507399692";//"yay:440620097543864320"; // public static final Color BLURPLE = Color.decode("#7289DA"); // public static final String INVITE = "https://giveawaybot.party/invite"; // public static final String DONATE = "https://giveawaybot.party/donate"; // public static final int MIN_TIME = 10; // public static final String WEBSITE = "https://giveawaybot.party"; // public static final String OWNER = "**jagrosh**#4824"; // public static final String GITHUB = "https://github.com/jagrosh/GiveawayBot"; // public static final String VERSION = "2.2"; // public static final String PERMS = "`Read Messages`, `Write Messages`, `Read Message History`, `Embed Links`, `Use External Emoji`, and `Add Reactions`"; // // public static final boolean canSendGiveaway(TextChannel channel) // { // return channel.getGuild().getSelfMember().hasPermission(channel, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, // Permission.MESSAGE_HISTORY, Permission.MESSAGE_EMBED_LINKS, Permission.MESSAGE_EXT_EMOJI, Permission.MESSAGE_ADD_REACTION); // } // } // // Path: src/main/java/com/jagrosh/giveawaybot/database/Database.java // public class Database extends DatabaseConnector // { // public final GiveawayManager giveaways; // public final GuildSettingsManager settings; // public final PremiumManager premium; // public final ExpandedGiveawayManager expanded; // // public Database (String host, String user, String pass) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException // { // super(host, user, pass); // // this.giveaways = new GiveawayManager(this); // this.settings = new GuildSettingsManager(this); // this.premium = new PremiumManager(this); // this.expanded = new ExpandedGiveawayManager(this); // // init(); // } // // public boolean databaseCheck() // { // return this.giveaways.getGiveaways() != null; // } // }
import com.jagrosh.easysql.DataManager; import com.jagrosh.easysql.SQLColumn; import com.jagrosh.easysql.columns.*; import com.jagrosh.giveawaybot.Constants; import com.jagrosh.giveawaybot.database.Database; import java.awt.Color; import java.sql.ResultSet; import java.sql.SQLException; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.TextChannel;
/* * Copyright 2017 John Grosh ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jagrosh.giveawaybot.database.managers; /** * * @author John Grosh ([email protected]) */ public class GuildSettingsManager extends DataManager { public final static SQLColumn<Long> GUILD_ID = new LongColumn("GUILD_ID", false, 0, true); public final static SQLColumn<Integer> COLOR = new IntegerColumn("COLOR", false, Constants.BLURPLE.getRGB()); public final static SQLColumn<Long> DEFAULT_CHANNEL = new LongColumn("DEFAULT_CHANNEL", false, 0); // currently unused public final static SQLColumn<Long> MANAGER_ROLE = new LongColumn("MANAGER_ROLE", false, 0L); // currently unused public final static SQLColumn<String> EMOJI = new StringColumn("EMOJI", true, null, 60); // currently unused
// Path: src/main/java/com/jagrosh/giveawaybot/Constants.java // public class Constants // { // public static final OffsetDateTime STARTUP = OffsetDateTime.now(); // public static final int PRIZE_MAX = 250; // public static final long SERVER_ID = 585687812548853760L; // public static final String TADA = "\uD83C\uDF89"; // 🎉 // public static final String WARNING = "\uD83D\uDCA5"; // 💥 // public static final String ERROR = "\uD83D\uDCA5"; // 💥 // public static final String YAY = "<:yay:585696613507399692>";//"<:yay:440620097543864320>"; // public static final String REACTION = "yay:585696613507399692";//"yay:440620097543864320"; // public static final Color BLURPLE = Color.decode("#7289DA"); // public static final String INVITE = "https://giveawaybot.party/invite"; // public static final String DONATE = "https://giveawaybot.party/donate"; // public static final int MIN_TIME = 10; // public static final String WEBSITE = "https://giveawaybot.party"; // public static final String OWNER = "**jagrosh**#4824"; // public static final String GITHUB = "https://github.com/jagrosh/GiveawayBot"; // public static final String VERSION = "2.2"; // public static final String PERMS = "`Read Messages`, `Write Messages`, `Read Message History`, `Embed Links`, `Use External Emoji`, and `Add Reactions`"; // // public static final boolean canSendGiveaway(TextChannel channel) // { // return channel.getGuild().getSelfMember().hasPermission(channel, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, // Permission.MESSAGE_HISTORY, Permission.MESSAGE_EMBED_LINKS, Permission.MESSAGE_EXT_EMOJI, Permission.MESSAGE_ADD_REACTION); // } // } // // Path: src/main/java/com/jagrosh/giveawaybot/database/Database.java // public class Database extends DatabaseConnector // { // public final GiveawayManager giveaways; // public final GuildSettingsManager settings; // public final PremiumManager premium; // public final ExpandedGiveawayManager expanded; // // public Database (String host, String user, String pass) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException // { // super(host, user, pass); // // this.giveaways = new GiveawayManager(this); // this.settings = new GuildSettingsManager(this); // this.premium = new PremiumManager(this); // this.expanded = new ExpandedGiveawayManager(this); // // init(); // } // // public boolean databaseCheck() // { // return this.giveaways.getGiveaways() != null; // } // } // Path: src/main/java/com/jagrosh/giveawaybot/database/managers/GuildSettingsManager.java import com.jagrosh.easysql.DataManager; import com.jagrosh.easysql.SQLColumn; import com.jagrosh.easysql.columns.*; import com.jagrosh.giveawaybot.Constants; import com.jagrosh.giveawaybot.database.Database; import java.awt.Color; import java.sql.ResultSet; import java.sql.SQLException; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.TextChannel; /* * Copyright 2017 John Grosh ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jagrosh.giveawaybot.database.managers; /** * * @author John Grosh ([email protected]) */ public class GuildSettingsManager extends DataManager { public final static SQLColumn<Long> GUILD_ID = new LongColumn("GUILD_ID", false, 0, true); public final static SQLColumn<Integer> COLOR = new IntegerColumn("COLOR", false, Constants.BLURPLE.getRGB()); public final static SQLColumn<Long> DEFAULT_CHANNEL = new LongColumn("DEFAULT_CHANNEL", false, 0); // currently unused public final static SQLColumn<Long> MANAGER_ROLE = new LongColumn("MANAGER_ROLE", false, 0L); // currently unused public final static SQLColumn<String> EMOJI = new StringColumn("EMOJI", true, null, 60); // currently unused
public GuildSettingsManager(Database connector)
jagrosh/GiveawayBot
src/main/java/com/jagrosh/giveawaybot/util/FormatUtil.java
// Path: src/main/java/com/jagrosh/giveawaybot/Constants.java // public class Constants // { // public static final OffsetDateTime STARTUP = OffsetDateTime.now(); // public static final int PRIZE_MAX = 250; // public static final long SERVER_ID = 585687812548853760L; // public static final String TADA = "\uD83C\uDF89"; // 🎉 // public static final String WARNING = "\uD83D\uDCA5"; // 💥 // public static final String ERROR = "\uD83D\uDCA5"; // 💥 // public static final String YAY = "<:yay:585696613507399692>";//"<:yay:440620097543864320>"; // public static final String REACTION = "yay:585696613507399692";//"yay:440620097543864320"; // public static final Color BLURPLE = Color.decode("#7289DA"); // public static final String INVITE = "https://giveawaybot.party/invite"; // public static final String DONATE = "https://giveawaybot.party/donate"; // public static final int MIN_TIME = 10; // public static final String WEBSITE = "https://giveawaybot.party"; // public static final String OWNER = "**jagrosh**#4824"; // public static final String GITHUB = "https://github.com/jagrosh/GiveawayBot"; // public static final String VERSION = "2.2"; // public static final String PERMS = "`Read Messages`, `Write Messages`, `Read Message History`, `Embed Links`, `Use External Emoji`, and `Add Reactions`"; // // public static final boolean canSendGiveaway(TextChannel channel) // { // return channel.getGuild().getSelfMember().hasPermission(channel, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, // Permission.MESSAGE_HISTORY, Permission.MESSAGE_EMBED_LINKS, Permission.MESSAGE_EXT_EMOJI, Permission.MESSAGE_ADD_REACTION); // } // }
import com.jagrosh.giveawaybot.Constants; import java.util.Objects; import com.jagrosh.jdautilities.command.Command; import com.jagrosh.jdautilities.command.Command.Category; import com.jagrosh.jdautilities.command.CommandEvent; import java.util.Collection; import java.util.HashMap; import net.dv8tion.jda.api.JDA;
/* * Copyright 2017 John Grosh ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jagrosh.giveawaybot.util; /** * * This file contains utility methods to help with formatting output. * * @author John Grosh ([email protected]) */ public class FormatUtil { public static String filter(String input) { return input.replace("\u202E","") // RTL override .replace("@everyone","@\u0435veryone") // cyrillic e .replace("@here","@h\u0435re") // cyrillic e .trim(); } public static String formatShardStatuses(Collection<JDA> shards) { HashMap<JDA.Status, String> map = new HashMap<>(); shards.forEach(jda -> map.put(jda.getStatus(), map.getOrDefault(jda.getStatus(), "") + " " + jda.getShardInfo().getShardId())); StringBuilder sb = new StringBuilder("```diff"); map.entrySet().forEach(entry -> sb.append("\n").append(entry.getKey()==JDA.Status.CONNECTED ? "+ " : "- ") .append(entry.getKey()).append(":").append(entry.getValue())); return sb.append(" ```").toString(); } public static String pluralise(long x, String singular, String plural) { return x == 1 ? singular : plural; } public static String formatHelp(CommandEvent event) {
// Path: src/main/java/com/jagrosh/giveawaybot/Constants.java // public class Constants // { // public static final OffsetDateTime STARTUP = OffsetDateTime.now(); // public static final int PRIZE_MAX = 250; // public static final long SERVER_ID = 585687812548853760L; // public static final String TADA = "\uD83C\uDF89"; // 🎉 // public static final String WARNING = "\uD83D\uDCA5"; // 💥 // public static final String ERROR = "\uD83D\uDCA5"; // 💥 // public static final String YAY = "<:yay:585696613507399692>";//"<:yay:440620097543864320>"; // public static final String REACTION = "yay:585696613507399692";//"yay:440620097543864320"; // public static final Color BLURPLE = Color.decode("#7289DA"); // public static final String INVITE = "https://giveawaybot.party/invite"; // public static final String DONATE = "https://giveawaybot.party/donate"; // public static final int MIN_TIME = 10; // public static final String WEBSITE = "https://giveawaybot.party"; // public static final String OWNER = "**jagrosh**#4824"; // public static final String GITHUB = "https://github.com/jagrosh/GiveawayBot"; // public static final String VERSION = "2.2"; // public static final String PERMS = "`Read Messages`, `Write Messages`, `Read Message History`, `Embed Links`, `Use External Emoji`, and `Add Reactions`"; // // public static final boolean canSendGiveaway(TextChannel channel) // { // return channel.getGuild().getSelfMember().hasPermission(channel, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, // Permission.MESSAGE_HISTORY, Permission.MESSAGE_EMBED_LINKS, Permission.MESSAGE_EXT_EMOJI, Permission.MESSAGE_ADD_REACTION); // } // } // Path: src/main/java/com/jagrosh/giveawaybot/util/FormatUtil.java import com.jagrosh.giveawaybot.Constants; import java.util.Objects; import com.jagrosh.jdautilities.command.Command; import com.jagrosh.jdautilities.command.Command.Category; import com.jagrosh.jdautilities.command.CommandEvent; import java.util.Collection; import java.util.HashMap; import net.dv8tion.jda.api.JDA; /* * Copyright 2017 John Grosh ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jagrosh.giveawaybot.util; /** * * This file contains utility methods to help with formatting output. * * @author John Grosh ([email protected]) */ public class FormatUtil { public static String filter(String input) { return input.replace("\u202E","") // RTL override .replace("@everyone","@\u0435veryone") // cyrillic e .replace("@here","@h\u0435re") // cyrillic e .trim(); } public static String formatShardStatuses(Collection<JDA> shards) { HashMap<JDA.Status, String> map = new HashMap<>(); shards.forEach(jda -> map.put(jda.getStatus(), map.getOrDefault(jda.getStatus(), "") + " " + jda.getShardInfo().getShardId())); StringBuilder sb = new StringBuilder("```diff"); map.entrySet().forEach(entry -> sb.append("\n").append(entry.getKey()==JDA.Status.CONNECTED ? "+ " : "- ") .append(entry.getKey()).append(":").append(entry.getValue())); return sb.append(" ```").toString(); } public static String pluralise(long x, String singular, String plural) { return x == 1 ? singular : plural; } public static String formatHelp(CommandEvent event) {
StringBuilder builder = new StringBuilder(Constants.YAY+" __**"+event.getSelfUser().getName()+"** commands:__\n");
jagrosh/GiveawayBot
src/main/java/com/jagrosh/giveawaybot/util/GiveawayUtil.java
// Path: src/main/java/com/jagrosh/giveawaybot/Constants.java // public class Constants // { // public static final OffsetDateTime STARTUP = OffsetDateTime.now(); // public static final int PRIZE_MAX = 250; // public static final long SERVER_ID = 585687812548853760L; // public static final String TADA = "\uD83C\uDF89"; // 🎉 // public static final String WARNING = "\uD83D\uDCA5"; // 💥 // public static final String ERROR = "\uD83D\uDCA5"; // 💥 // public static final String YAY = "<:yay:585696613507399692>";//"<:yay:440620097543864320>"; // public static final String REACTION = "yay:585696613507399692";//"yay:440620097543864320"; // public static final Color BLURPLE = Color.decode("#7289DA"); // public static final String INVITE = "https://giveawaybot.party/invite"; // public static final String DONATE = "https://giveawaybot.party/donate"; // public static final int MIN_TIME = 10; // public static final String WEBSITE = "https://giveawaybot.party"; // public static final String OWNER = "**jagrosh**#4824"; // public static final String GITHUB = "https://github.com/jagrosh/GiveawayBot"; // public static final String VERSION = "2.2"; // public static final String PERMS = "`Read Messages`, `Write Messages`, `Read Message History`, `Embed Links`, `Use External Emoji`, and `Add Reactions`"; // // public static final boolean canSendGiveaway(TextChannel channel) // { // return channel.getGuild().getSelfMember().hasPermission(channel, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, // Permission.MESSAGE_HISTORY, Permission.MESSAGE_EMBED_LINKS, Permission.MESSAGE_EXT_EMOJI, Permission.MESSAGE_ADD_REACTION); // } // }
import com.jagrosh.giveawaybot.Constants; import java.security.SecureRandom; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.function.Consumer; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.MessageReaction; import net.dv8tion.jda.api.entities.User;
/* * Copyright 2019 John Grosh ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jagrosh.giveawaybot.util; /** * * @author John Grosh ([email protected]) */ public class GiveawayUtil { private static final SecureRandom random = new SecureRandom(); private static synchronized double randDouble() { return random.nextDouble(); } public static <T> List<T> selectWinners(Set<T> set, int winners) { return selectWinners(new ArrayList<>(set), winners); } public static <T> List<T> selectWinners(List<T> list, int winners) { List<T> winlist = new LinkedList<>(); List<T> pullist = new LinkedList<>(list); for(int i=0; i<winners && !pullist.isEmpty(); i++) { winlist.add(pullist.remove((int)(randDouble() * pullist.size()))); } return winlist; } public static void getSingleWinner(Message message, Consumer<User> success, Runnable failure, ExecutorService threadpool) { threadpool.submit(() -> { try {
// Path: src/main/java/com/jagrosh/giveawaybot/Constants.java // public class Constants // { // public static final OffsetDateTime STARTUP = OffsetDateTime.now(); // public static final int PRIZE_MAX = 250; // public static final long SERVER_ID = 585687812548853760L; // public static final String TADA = "\uD83C\uDF89"; // 🎉 // public static final String WARNING = "\uD83D\uDCA5"; // 💥 // public static final String ERROR = "\uD83D\uDCA5"; // 💥 // public static final String YAY = "<:yay:585696613507399692>";//"<:yay:440620097543864320>"; // public static final String REACTION = "yay:585696613507399692";//"yay:440620097543864320"; // public static final Color BLURPLE = Color.decode("#7289DA"); // public static final String INVITE = "https://giveawaybot.party/invite"; // public static final String DONATE = "https://giveawaybot.party/donate"; // public static final int MIN_TIME = 10; // public static final String WEBSITE = "https://giveawaybot.party"; // public static final String OWNER = "**jagrosh**#4824"; // public static final String GITHUB = "https://github.com/jagrosh/GiveawayBot"; // public static final String VERSION = "2.2"; // public static final String PERMS = "`Read Messages`, `Write Messages`, `Read Message History`, `Embed Links`, `Use External Emoji`, and `Add Reactions`"; // // public static final boolean canSendGiveaway(TextChannel channel) // { // return channel.getGuild().getSelfMember().hasPermission(channel, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, // Permission.MESSAGE_HISTORY, Permission.MESSAGE_EMBED_LINKS, Permission.MESSAGE_EXT_EMOJI, Permission.MESSAGE_ADD_REACTION); // } // } // Path: src/main/java/com/jagrosh/giveawaybot/util/GiveawayUtil.java import com.jagrosh.giveawaybot.Constants; import java.security.SecureRandom; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.function.Consumer; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.MessageReaction; import net.dv8tion.jda.api.entities.User; /* * Copyright 2019 John Grosh ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jagrosh.giveawaybot.util; /** * * @author John Grosh ([email protected]) */ public class GiveawayUtil { private static final SecureRandom random = new SecureRandom(); private static synchronized double randDouble() { return random.nextDouble(); } public static <T> List<T> selectWinners(Set<T> set, int winners) { return selectWinners(new ArrayList<>(set), winners); } public static <T> List<T> selectWinners(List<T> list, int winners) { List<T> winlist = new LinkedList<>(); List<T> pullist = new LinkedList<>(list); for(int i=0; i<winners && !pullist.isEmpty(); i++) { winlist.add(pullist.remove((int)(randDouble() * pullist.size()))); } return winlist; } public static void getSingleWinner(Message message, Consumer<User> success, Runnable failure, ExecutorService threadpool) { threadpool.submit(() -> { try {
MessageReaction mr = message.getReactions().stream().filter(r -> r.getReactionEmote().getName().equals(Constants.TADA)).findAny().orElse(null);
jagrosh/GiveawayBot
src/main/java/com/jagrosh/giveawaybot/Checker.java
// Path: src/main/java/com/jagrosh/giveawaybot/database/Database.java // public class Database extends DatabaseConnector // { // public final GiveawayManager giveaways; // public final GuildSettingsManager settings; // public final PremiumManager premium; // public final ExpandedGiveawayManager expanded; // // public Database (String host, String user, String pass) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException // { // super(host, user, pass); // // this.giveaways = new GiveawayManager(this); // this.settings = new GuildSettingsManager(this); // this.premium = new PremiumManager(this); // this.expanded = new ExpandedGiveawayManager(this); // // init(); // } // // public boolean databaseCheck() // { // return this.giveaways.getGiveaways() != null; // } // } // // Path: src/main/java/com/jagrosh/giveawaybot/database/managers/PremiumManager.java // public class Summary // { // private final Map<Long,PremiumLevel> removed = new HashMap<>(); // private final Map<Long,Pair<PremiumLevel,PremiumLevel>> changed = new HashMap<>(); // private final Map<Long,PremiumLevel> added = new HashMap<>(); // // public boolean isEmpty() // { // return removed.isEmpty() && changed.isEmpty() && added.isEmpty(); // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder("```diff"); // added.forEach((u,l) -> sb.append("\n+ ").append(u).append(" ").append(l)); // changed.forEach((u,p) -> sb.append("\n# ").append(u).append(" ").append(p.getLeft()).append(" -> ").append(p.getRight())); // removed.forEach((u,l) -> sb.append("\n- ").append(u).append(" ").append(l)); // return sb.append("\n```").toString(); // } // }
import club.minnced.discord.webhook.WebhookClient; import club.minnced.discord.webhook.WebhookClientBuilder; import com.jagrosh.giveawaybot.database.Database; import com.jagrosh.giveawaybot.database.managers.PremiumManager.Summary; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.util.EnumSet; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.OnlineStatus; import net.dv8tion.jda.api.requests.GatewayIntent; import net.dv8tion.jda.api.utils.ChunkingFilter; import net.dv8tion.jda.api.utils.MemberCachePolicy; import net.dv8tion.jda.api.utils.cache.CacheFlag; import org.slf4j.LoggerFactory;
/* * Copyright 2019 John Grosh ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jagrosh.giveawaybot; /** * * @author John Grosh ([email protected]) */ public class Checker { /** * Runs the application as a premium updater * @throws Exception */ public static void main() throws Exception { LoggerFactory.getLogger("Checker").info("Checker starting."); Config config = ConfigFactory.load(); long premiumServerId = config.getLong("checker-server"); // connects to the database
// Path: src/main/java/com/jagrosh/giveawaybot/database/Database.java // public class Database extends DatabaseConnector // { // public final GiveawayManager giveaways; // public final GuildSettingsManager settings; // public final PremiumManager premium; // public final ExpandedGiveawayManager expanded; // // public Database (String host, String user, String pass) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException // { // super(host, user, pass); // // this.giveaways = new GiveawayManager(this); // this.settings = new GuildSettingsManager(this); // this.premium = new PremiumManager(this); // this.expanded = new ExpandedGiveawayManager(this); // // init(); // } // // public boolean databaseCheck() // { // return this.giveaways.getGiveaways() != null; // } // } // // Path: src/main/java/com/jagrosh/giveawaybot/database/managers/PremiumManager.java // public class Summary // { // private final Map<Long,PremiumLevel> removed = new HashMap<>(); // private final Map<Long,Pair<PremiumLevel,PremiumLevel>> changed = new HashMap<>(); // private final Map<Long,PremiumLevel> added = new HashMap<>(); // // public boolean isEmpty() // { // return removed.isEmpty() && changed.isEmpty() && added.isEmpty(); // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder("```diff"); // added.forEach((u,l) -> sb.append("\n+ ").append(u).append(" ").append(l)); // changed.forEach((u,p) -> sb.append("\n# ").append(u).append(" ").append(p.getLeft()).append(" -> ").append(p.getRight())); // removed.forEach((u,l) -> sb.append("\n- ").append(u).append(" ").append(l)); // return sb.append("\n```").toString(); // } // } // Path: src/main/java/com/jagrosh/giveawaybot/Checker.java import club.minnced.discord.webhook.WebhookClient; import club.minnced.discord.webhook.WebhookClientBuilder; import com.jagrosh.giveawaybot.database.Database; import com.jagrosh.giveawaybot.database.managers.PremiumManager.Summary; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.util.EnumSet; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.OnlineStatus; import net.dv8tion.jda.api.requests.GatewayIntent; import net.dv8tion.jda.api.utils.ChunkingFilter; import net.dv8tion.jda.api.utils.MemberCachePolicy; import net.dv8tion.jda.api.utils.cache.CacheFlag; import org.slf4j.LoggerFactory; /* * Copyright 2019 John Grosh ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jagrosh.giveawaybot; /** * * @author John Grosh ([email protected]) */ public class Checker { /** * Runs the application as a premium updater * @throws Exception */ public static void main() throws Exception { LoggerFactory.getLogger("Checker").info("Checker starting."); Config config = ConfigFactory.load(); long premiumServerId = config.getLong("checker-server"); // connects to the database
Database database = new Database(config.getString("database.host"),
jagrosh/GiveawayBot
src/main/java/com/jagrosh/giveawaybot/Checker.java
// Path: src/main/java/com/jagrosh/giveawaybot/database/Database.java // public class Database extends DatabaseConnector // { // public final GiveawayManager giveaways; // public final GuildSettingsManager settings; // public final PremiumManager premium; // public final ExpandedGiveawayManager expanded; // // public Database (String host, String user, String pass) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException // { // super(host, user, pass); // // this.giveaways = new GiveawayManager(this); // this.settings = new GuildSettingsManager(this); // this.premium = new PremiumManager(this); // this.expanded = new ExpandedGiveawayManager(this); // // init(); // } // // public boolean databaseCheck() // { // return this.giveaways.getGiveaways() != null; // } // } // // Path: src/main/java/com/jagrosh/giveawaybot/database/managers/PremiumManager.java // public class Summary // { // private final Map<Long,PremiumLevel> removed = new HashMap<>(); // private final Map<Long,Pair<PremiumLevel,PremiumLevel>> changed = new HashMap<>(); // private final Map<Long,PremiumLevel> added = new HashMap<>(); // // public boolean isEmpty() // { // return removed.isEmpty() && changed.isEmpty() && added.isEmpty(); // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder("```diff"); // added.forEach((u,l) -> sb.append("\n+ ").append(u).append(" ").append(l)); // changed.forEach((u,p) -> sb.append("\n# ").append(u).append(" ").append(p.getLeft()).append(" -> ").append(p.getRight())); // removed.forEach((u,l) -> sb.append("\n- ").append(u).append(" ").append(l)); // return sb.append("\n```").toString(); // } // }
import club.minnced.discord.webhook.WebhookClient; import club.minnced.discord.webhook.WebhookClientBuilder; import com.jagrosh.giveawaybot.database.Database; import com.jagrosh.giveawaybot.database.managers.PremiumManager.Summary; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.util.EnumSet; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.OnlineStatus; import net.dv8tion.jda.api.requests.GatewayIntent; import net.dv8tion.jda.api.utils.ChunkingFilter; import net.dv8tion.jda.api.utils.MemberCachePolicy; import net.dv8tion.jda.api.utils.cache.CacheFlag; import org.slf4j.LoggerFactory;
/* * Copyright 2019 John Grosh ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jagrosh.giveawaybot; /** * * @author John Grosh ([email protected]) */ public class Checker { /** * Runs the application as a premium updater * @throws Exception */ public static void main() throws Exception { LoggerFactory.getLogger("Checker").info("Checker starting."); Config config = ConfigFactory.load(); long premiumServerId = config.getLong("checker-server"); // connects to the database Database database = new Database(config.getString("database.host"), config.getString("database.username"), config.getString("database.password")); // sends starting message WebhookClient webhook = new WebhookClientBuilder(config.getString("webhook")).build(); webhook.send(Constants.TADA + " Starting checker..."); JDA jda = JDABuilder.createDefault(config.getString("checker-token"), GatewayIntent.GUILD_MEMBERS) .setStatus(OnlineStatus.IDLE) .setMemberCachePolicy(MemberCachePolicy.ALL) .setChunkingFilter(ChunkingFilter.ALL) .disableCache(EnumSet.of(CacheFlag.ACTIVITY, CacheFlag.CLIENT_STATUS, CacheFlag.EMOTE, CacheFlag.VOICE_STATE)) .build().awaitReady(); webhook.send(Constants.TADA + " Checker ready! `" + premiumServerId + "` ~ `" + jda.getGuildById(premiumServerId).getMemberCache().size() + "`"); // main checker loop while(true) { Thread.sleep(1000 * 60); // update premium levels
// Path: src/main/java/com/jagrosh/giveawaybot/database/Database.java // public class Database extends DatabaseConnector // { // public final GiveawayManager giveaways; // public final GuildSettingsManager settings; // public final PremiumManager premium; // public final ExpandedGiveawayManager expanded; // // public Database (String host, String user, String pass) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException // { // super(host, user, pass); // // this.giveaways = new GiveawayManager(this); // this.settings = new GuildSettingsManager(this); // this.premium = new PremiumManager(this); // this.expanded = new ExpandedGiveawayManager(this); // // init(); // } // // public boolean databaseCheck() // { // return this.giveaways.getGiveaways() != null; // } // } // // Path: src/main/java/com/jagrosh/giveawaybot/database/managers/PremiumManager.java // public class Summary // { // private final Map<Long,PremiumLevel> removed = new HashMap<>(); // private final Map<Long,Pair<PremiumLevel,PremiumLevel>> changed = new HashMap<>(); // private final Map<Long,PremiumLevel> added = new HashMap<>(); // // public boolean isEmpty() // { // return removed.isEmpty() && changed.isEmpty() && added.isEmpty(); // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder("```diff"); // added.forEach((u,l) -> sb.append("\n+ ").append(u).append(" ").append(l)); // changed.forEach((u,p) -> sb.append("\n# ").append(u).append(" ").append(p.getLeft()).append(" -> ").append(p.getRight())); // removed.forEach((u,l) -> sb.append("\n- ").append(u).append(" ").append(l)); // return sb.append("\n```").toString(); // } // } // Path: src/main/java/com/jagrosh/giveawaybot/Checker.java import club.minnced.discord.webhook.WebhookClient; import club.minnced.discord.webhook.WebhookClientBuilder; import com.jagrosh.giveawaybot.database.Database; import com.jagrosh.giveawaybot.database.managers.PremiumManager.Summary; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.util.EnumSet; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.OnlineStatus; import net.dv8tion.jda.api.requests.GatewayIntent; import net.dv8tion.jda.api.utils.ChunkingFilter; import net.dv8tion.jda.api.utils.MemberCachePolicy; import net.dv8tion.jda.api.utils.cache.CacheFlag; import org.slf4j.LoggerFactory; /* * Copyright 2019 John Grosh ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jagrosh.giveawaybot; /** * * @author John Grosh ([email protected]) */ public class Checker { /** * Runs the application as a premium updater * @throws Exception */ public static void main() throws Exception { LoggerFactory.getLogger("Checker").info("Checker starting."); Config config = ConfigFactory.load(); long premiumServerId = config.getLong("checker-server"); // connects to the database Database database = new Database(config.getString("database.host"), config.getString("database.username"), config.getString("database.password")); // sends starting message WebhookClient webhook = new WebhookClientBuilder(config.getString("webhook")).build(); webhook.send(Constants.TADA + " Starting checker..."); JDA jda = JDABuilder.createDefault(config.getString("checker-token"), GatewayIntent.GUILD_MEMBERS) .setStatus(OnlineStatus.IDLE) .setMemberCachePolicy(MemberCachePolicy.ALL) .setChunkingFilter(ChunkingFilter.ALL) .disableCache(EnumSet.of(CacheFlag.ACTIVITY, CacheFlag.CLIENT_STATUS, CacheFlag.EMOTE, CacheFlag.VOICE_STATE)) .build().awaitReady(); webhook.send(Constants.TADA + " Checker ready! `" + premiumServerId + "` ~ `" + jda.getGuildById(premiumServerId).getMemberCache().size() + "`"); // main checker loop while(true) { Thread.sleep(1000 * 60); // update premium levels
Summary sum = database.premium.updatePremiumLevels(jda.getGuildById(premiumServerId));
jagrosh/GiveawayBot
src/main/java/com/jagrosh/giveawaybot/commands/InviteCommand.java
// Path: src/main/java/com/jagrosh/giveawaybot/Constants.java // public class Constants // { // public static final OffsetDateTime STARTUP = OffsetDateTime.now(); // public static final int PRIZE_MAX = 250; // public static final long SERVER_ID = 585687812548853760L; // public static final String TADA = "\uD83C\uDF89"; // 🎉 // public static final String WARNING = "\uD83D\uDCA5"; // 💥 // public static final String ERROR = "\uD83D\uDCA5"; // 💥 // public static final String YAY = "<:yay:585696613507399692>";//"<:yay:440620097543864320>"; // public static final String REACTION = "yay:585696613507399692";//"yay:440620097543864320"; // public static final Color BLURPLE = Color.decode("#7289DA"); // public static final String INVITE = "https://giveawaybot.party/invite"; // public static final String DONATE = "https://giveawaybot.party/donate"; // public static final int MIN_TIME = 10; // public static final String WEBSITE = "https://giveawaybot.party"; // public static final String OWNER = "**jagrosh**#4824"; // public static final String GITHUB = "https://github.com/jagrosh/GiveawayBot"; // public static final String VERSION = "2.2"; // public static final String PERMS = "`Read Messages`, `Write Messages`, `Read Message History`, `Embed Links`, `Use External Emoji`, and `Add Reactions`"; // // public static final boolean canSendGiveaway(TextChannel channel) // { // return channel.getGuild().getSelfMember().hasPermission(channel, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, // Permission.MESSAGE_HISTORY, Permission.MESSAGE_EMBED_LINKS, Permission.MESSAGE_EXT_EMOJI, Permission.MESSAGE_ADD_REACTION); // } // }
import com.jagrosh.giveawaybot.Constants; import com.jagrosh.jdautilities.command.Command; import com.jagrosh.jdautilities.command.CommandEvent;
/* * Copyright 2017 John Grosh ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jagrosh.giveawaybot.commands; /** * * @author John Grosh ([email protected]) */ public class InviteCommand extends Command { private final static String LINK = "\uD83D\uDD17"; // 🔗 public InviteCommand() { name = "invite"; help = "shows how to invite the bot"; guildOnly = false; } @Override protected void execute(CommandEvent event) {
// Path: src/main/java/com/jagrosh/giveawaybot/Constants.java // public class Constants // { // public static final OffsetDateTime STARTUP = OffsetDateTime.now(); // public static final int PRIZE_MAX = 250; // public static final long SERVER_ID = 585687812548853760L; // public static final String TADA = "\uD83C\uDF89"; // 🎉 // public static final String WARNING = "\uD83D\uDCA5"; // 💥 // public static final String ERROR = "\uD83D\uDCA5"; // 💥 // public static final String YAY = "<:yay:585696613507399692>";//"<:yay:440620097543864320>"; // public static final String REACTION = "yay:585696613507399692";//"yay:440620097543864320"; // public static final Color BLURPLE = Color.decode("#7289DA"); // public static final String INVITE = "https://giveawaybot.party/invite"; // public static final String DONATE = "https://giveawaybot.party/donate"; // public static final int MIN_TIME = 10; // public static final String WEBSITE = "https://giveawaybot.party"; // public static final String OWNER = "**jagrosh**#4824"; // public static final String GITHUB = "https://github.com/jagrosh/GiveawayBot"; // public static final String VERSION = "2.2"; // public static final String PERMS = "`Read Messages`, `Write Messages`, `Read Message History`, `Embed Links`, `Use External Emoji`, and `Add Reactions`"; // // public static final boolean canSendGiveaway(TextChannel channel) // { // return channel.getGuild().getSelfMember().hasPermission(channel, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, // Permission.MESSAGE_HISTORY, Permission.MESSAGE_EMBED_LINKS, Permission.MESSAGE_EXT_EMOJI, Permission.MESSAGE_ADD_REACTION); // } // } // Path: src/main/java/com/jagrosh/giveawaybot/commands/InviteCommand.java import com.jagrosh.giveawaybot.Constants; import com.jagrosh.jdautilities.command.Command; import com.jagrosh.jdautilities.command.CommandEvent; /* * Copyright 2017 John Grosh ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jagrosh.giveawaybot.commands; /** * * @author John Grosh ([email protected]) */ public class InviteCommand extends Command { private final static String LINK = "\uD83D\uDD17"; // 🔗 public InviteCommand() { name = "invite"; help = "shows how to invite the bot"; guildOnly = false; } @Override protected void execute(CommandEvent event) {
event.reply(Constants.YAY+" Hello! I'm **GiveawayBot**! I help to make giveaways quick and easy!\n"
jagrosh/GiveawayBot
src/main/java/com/jagrosh/giveawaybot/entities/PremiumLevel.java
// Path: src/main/java/com/jagrosh/giveawaybot/Constants.java // public class Constants // { // public static final OffsetDateTime STARTUP = OffsetDateTime.now(); // public static final int PRIZE_MAX = 250; // public static final long SERVER_ID = 585687812548853760L; // public static final String TADA = "\uD83C\uDF89"; // 🎉 // public static final String WARNING = "\uD83D\uDCA5"; // 💥 // public static final String ERROR = "\uD83D\uDCA5"; // 💥 // public static final String YAY = "<:yay:585696613507399692>";//"<:yay:440620097543864320>"; // public static final String REACTION = "yay:585696613507399692";//"yay:440620097543864320"; // public static final Color BLURPLE = Color.decode("#7289DA"); // public static final String INVITE = "https://giveawaybot.party/invite"; // public static final String DONATE = "https://giveawaybot.party/donate"; // public static final int MIN_TIME = 10; // public static final String WEBSITE = "https://giveawaybot.party"; // public static final String OWNER = "**jagrosh**#4824"; // public static final String GITHUB = "https://github.com/jagrosh/GiveawayBot"; // public static final String VERSION = "2.2"; // public static final String PERMS = "`Read Messages`, `Write Messages`, `Read Message History`, `Embed Links`, `Use External Emoji`, and `Add Reactions`"; // // public static final boolean canSendGiveaway(TextChannel channel) // { // return channel.getGuild().getSelfMember().hasPermission(channel, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, // Permission.MESSAGE_HISTORY, Permission.MESSAGE_EMBED_LINKS, Permission.MESSAGE_EXT_EMOJI, Permission.MESSAGE_ADD_REACTION); // } // }
import com.jagrosh.giveawaybot.Constants;
/* * Copyright 2019 John Grosh ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jagrosh.giveawaybot.entities; /** * * @author John Grosh ([email protected]) */ public enum PremiumLevel { // name time win giv channel roleid NONE (0, "None", 60*60*24*7*2, 20, 20, false, 0L), BOOST (1, "Nitro Booster", 60*60*24*7*5, 30, 25, true, 585981877396045826L), PATRON (2, "Patron", 60*60*24*7*5, 30, 25, true, 585689274565918721L), DONATOR(3, "Donator", 60*60*24*7*5, 30, 25, true, 585708901270421504L), DISCORD(4, "Discord", 60*60*24*7*5, 50, 25, true, 778420722673778748L), SUPER (5, "Super Patron", 60*60*24*7*5, 50, 25, true, 589196324193173512L); public final int level; public final String name; public final int maxTime, maxWinners, maxGiveaways; public final boolean perChannelMaxGiveaways; public final long roleId; private PremiumLevel(int level, String name, int maxTime, int maxWinners, int maxGiveaways, boolean perChannelMaxGiveaways, long roleId) { this.level = level; this.name = name; this.maxTime = maxTime; this.maxWinners = maxWinners; this.maxGiveaways = maxGiveaways; this.perChannelMaxGiveaways = perChannelMaxGiveaways; this.roleId = roleId; } public boolean isValidTime(int seconds) {
// Path: src/main/java/com/jagrosh/giveawaybot/Constants.java // public class Constants // { // public static final OffsetDateTime STARTUP = OffsetDateTime.now(); // public static final int PRIZE_MAX = 250; // public static final long SERVER_ID = 585687812548853760L; // public static final String TADA = "\uD83C\uDF89"; // 🎉 // public static final String WARNING = "\uD83D\uDCA5"; // 💥 // public static final String ERROR = "\uD83D\uDCA5"; // 💥 // public static final String YAY = "<:yay:585696613507399692>";//"<:yay:440620097543864320>"; // public static final String REACTION = "yay:585696613507399692";//"yay:440620097543864320"; // public static final Color BLURPLE = Color.decode("#7289DA"); // public static final String INVITE = "https://giveawaybot.party/invite"; // public static final String DONATE = "https://giveawaybot.party/donate"; // public static final int MIN_TIME = 10; // public static final String WEBSITE = "https://giveawaybot.party"; // public static final String OWNER = "**jagrosh**#4824"; // public static final String GITHUB = "https://github.com/jagrosh/GiveawayBot"; // public static final String VERSION = "2.2"; // public static final String PERMS = "`Read Messages`, `Write Messages`, `Read Message History`, `Embed Links`, `Use External Emoji`, and `Add Reactions`"; // // public static final boolean canSendGiveaway(TextChannel channel) // { // return channel.getGuild().getSelfMember().hasPermission(channel, Permission.MESSAGE_READ, Permission.MESSAGE_WRITE, // Permission.MESSAGE_HISTORY, Permission.MESSAGE_EMBED_LINKS, Permission.MESSAGE_EXT_EMOJI, Permission.MESSAGE_ADD_REACTION); // } // } // Path: src/main/java/com/jagrosh/giveawaybot/entities/PremiumLevel.java import com.jagrosh.giveawaybot.Constants; /* * Copyright 2019 John Grosh ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jagrosh.giveawaybot.entities; /** * * @author John Grosh ([email protected]) */ public enum PremiumLevel { // name time win giv channel roleid NONE (0, "None", 60*60*24*7*2, 20, 20, false, 0L), BOOST (1, "Nitro Booster", 60*60*24*7*5, 30, 25, true, 585981877396045826L), PATRON (2, "Patron", 60*60*24*7*5, 30, 25, true, 585689274565918721L), DONATOR(3, "Donator", 60*60*24*7*5, 30, 25, true, 585708901270421504L), DISCORD(4, "Discord", 60*60*24*7*5, 50, 25, true, 778420722673778748L), SUPER (5, "Super Patron", 60*60*24*7*5, 50, 25, true, 589196324193173512L); public final int level; public final String name; public final int maxTime, maxWinners, maxGiveaways; public final boolean perChannelMaxGiveaways; public final long roleId; private PremiumLevel(int level, String name, int maxTime, int maxWinners, int maxGiveaways, boolean perChannelMaxGiveaways, long roleId) { this.level = level; this.name = name; this.maxTime = maxTime; this.maxWinners = maxWinners; this.maxGiveaways = maxGiveaways; this.perChannelMaxGiveaways = perChannelMaxGiveaways; this.roleId = roleId; } public boolean isValidTime(int seconds) {
return seconds >= Constants.MIN_TIME && seconds <= maxTime;
jagrosh/GiveawayBot
src/main/java/com/jagrosh/giveawaybot/database/managers/ExpandedGiveawayManager.java
// Path: src/main/java/com/jagrosh/giveawaybot/database/Database.java // public class Database extends DatabaseConnector // { // public final GiveawayManager giveaways; // public final GuildSettingsManager settings; // public final PremiumManager premium; // public final ExpandedGiveawayManager expanded; // // public Database (String host, String user, String pass) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException // { // super(host, user, pass); // // this.giveaways = new GiveawayManager(this); // this.settings = new GuildSettingsManager(this); // this.premium = new PremiumManager(this); // this.expanded = new ExpandedGiveawayManager(this); // // init(); // } // // public boolean databaseCheck() // { // return this.giveaways.getGiveaways() != null; // } // }
import com.jagrosh.easysql.DataManager; import com.jagrosh.easysql.SQLColumn; import com.jagrosh.easysql.columns.LongColumn; import com.jagrosh.giveawaybot.database.Database; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry;
/* * Copyright 2020 John Grosh ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jagrosh.giveawaybot.database.managers; /** * * @author John Grosh ([email protected]) */ public class ExpandedGiveawayManager extends DataManager { public final static SQLColumn<Long> GIVEAWAY_ID = new LongColumn("GIVEAWAY_ID", false, 0L); public final static SQLColumn<Long> CHANNEL_ID = new LongColumn("CHANNEL_ID", false, 0L); public final static SQLColumn<Long> MESSAGE_ID = new LongColumn("MESSAGE_ID", false, 0L, true);
// Path: src/main/java/com/jagrosh/giveawaybot/database/Database.java // public class Database extends DatabaseConnector // { // public final GiveawayManager giveaways; // public final GuildSettingsManager settings; // public final PremiumManager premium; // public final ExpandedGiveawayManager expanded; // // public Database (String host, String user, String pass) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException // { // super(host, user, pass); // // this.giveaways = new GiveawayManager(this); // this.settings = new GuildSettingsManager(this); // this.premium = new PremiumManager(this); // this.expanded = new ExpandedGiveawayManager(this); // // init(); // } // // public boolean databaseCheck() // { // return this.giveaways.getGiveaways() != null; // } // } // Path: src/main/java/com/jagrosh/giveawaybot/database/managers/ExpandedGiveawayManager.java import com.jagrosh.easysql.DataManager; import com.jagrosh.easysql.SQLColumn; import com.jagrosh.easysql.columns.LongColumn; import com.jagrosh.giveawaybot.database.Database; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; /* * Copyright 2020 John Grosh ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jagrosh.giveawaybot.database.managers; /** * * @author John Grosh ([email protected]) */ public class ExpandedGiveawayManager extends DataManager { public final static SQLColumn<Long> GIVEAWAY_ID = new LongColumn("GIVEAWAY_ID", false, 0L); public final static SQLColumn<Long> CHANNEL_ID = new LongColumn("CHANNEL_ID", false, 0L); public final static SQLColumn<Long> MESSAGE_ID = new LongColumn("MESSAGE_ID", false, 0L, true);
public ExpandedGiveawayManager(Database connector)
jagrosh/GiveawayBot
src/main/java/com/jagrosh/giveawaybot/database/managers/PremiumManager.java
// Path: src/main/java/com/jagrosh/giveawaybot/entities/PremiumLevel.java // public enum PremiumLevel // { // // name time win giv channel roleid // NONE (0, "None", 60*60*24*7*2, 20, 20, false, 0L), // // BOOST (1, "Nitro Booster", 60*60*24*7*5, 30, 25, true, 585981877396045826L), // PATRON (2, "Patron", 60*60*24*7*5, 30, 25, true, 585689274565918721L), // DONATOR(3, "Donator", 60*60*24*7*5, 30, 25, true, 585708901270421504L), // // DISCORD(4, "Discord", 60*60*24*7*5, 50, 25, true, 778420722673778748L), // SUPER (5, "Super Patron", 60*60*24*7*5, 50, 25, true, 589196324193173512L); // // public final int level; // public final String name; // public final int maxTime, maxWinners, maxGiveaways; // public final boolean perChannelMaxGiveaways; // public final long roleId; // // private PremiumLevel(int level, String name, int maxTime, int maxWinners, // int maxGiveaways, boolean perChannelMaxGiveaways, long roleId) // { // this.level = level; // this.name = name; // this.maxTime = maxTime; // this.maxWinners = maxWinners; // this.maxGiveaways = maxGiveaways; // this.perChannelMaxGiveaways = perChannelMaxGiveaways; // this.roleId = roleId; // } // // public boolean isValidTime(int seconds) // { // return seconds >= Constants.MIN_TIME && seconds <= maxTime; // } // // public boolean isValidWinners(int winners) // { // return winners >= 1 && winners <= maxWinners; // } // // // static methods // public static PremiumLevel get(int level) // { // for(PremiumLevel p: values()) // if(p.level == level) // return p; // return NONE; // } // }
import com.jagrosh.easysql.DataManager; import com.jagrosh.easysql.DatabaseConnector; import com.jagrosh.easysql.SQLColumn; import com.jagrosh.easysql.columns.*; import com.jagrosh.giveawaybot.entities.PremiumLevel; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.internal.utils.tuple.Pair;
/* * Copyright 2019 John Grosh ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jagrosh.giveawaybot.database.managers; /** * * @author John Grosh ([email protected]) */ public class PremiumManager extends DataManager { public final static SQLColumn<Long> USER_ID = new LongColumn("USER_ID", false, 0L, true);
// Path: src/main/java/com/jagrosh/giveawaybot/entities/PremiumLevel.java // public enum PremiumLevel // { // // name time win giv channel roleid // NONE (0, "None", 60*60*24*7*2, 20, 20, false, 0L), // // BOOST (1, "Nitro Booster", 60*60*24*7*5, 30, 25, true, 585981877396045826L), // PATRON (2, "Patron", 60*60*24*7*5, 30, 25, true, 585689274565918721L), // DONATOR(3, "Donator", 60*60*24*7*5, 30, 25, true, 585708901270421504L), // // DISCORD(4, "Discord", 60*60*24*7*5, 50, 25, true, 778420722673778748L), // SUPER (5, "Super Patron", 60*60*24*7*5, 50, 25, true, 589196324193173512L); // // public final int level; // public final String name; // public final int maxTime, maxWinners, maxGiveaways; // public final boolean perChannelMaxGiveaways; // public final long roleId; // // private PremiumLevel(int level, String name, int maxTime, int maxWinners, // int maxGiveaways, boolean perChannelMaxGiveaways, long roleId) // { // this.level = level; // this.name = name; // this.maxTime = maxTime; // this.maxWinners = maxWinners; // this.maxGiveaways = maxGiveaways; // this.perChannelMaxGiveaways = perChannelMaxGiveaways; // this.roleId = roleId; // } // // public boolean isValidTime(int seconds) // { // return seconds >= Constants.MIN_TIME && seconds <= maxTime; // } // // public boolean isValidWinners(int winners) // { // return winners >= 1 && winners <= maxWinners; // } // // // static methods // public static PremiumLevel get(int level) // { // for(PremiumLevel p: values()) // if(p.level == level) // return p; // return NONE; // } // } // Path: src/main/java/com/jagrosh/giveawaybot/database/managers/PremiumManager.java import com.jagrosh.easysql.DataManager; import com.jagrosh.easysql.DatabaseConnector; import com.jagrosh.easysql.SQLColumn; import com.jagrosh.easysql.columns.*; import com.jagrosh.giveawaybot.entities.PremiumLevel; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.internal.utils.tuple.Pair; /* * Copyright 2019 John Grosh ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jagrosh.giveawaybot.database.managers; /** * * @author John Grosh ([email protected]) */ public class PremiumManager extends DataManager { public final static SQLColumn<Long> USER_ID = new LongColumn("USER_ID", false, 0L, true);
public final static SQLColumn<Integer> PREMIUM_LEVEL = new IntegerColumn("LEVEL", false, PremiumLevel.NONE.level);
ddossot/mule-in-action-2e
chapter13/restclient/src/main/java/org/mule/modules/RestClientConnector.java
// Path: chapter13/restclient/src/main/java/org/mule/modules/TranslateException.java // public class TranslateException extends RuntimeException { // // public TranslateException(){ // } // // public TranslateException(String reason){ // } // }
import java.io.IOException; import org.apache.commons.httpclient.HttpClient; import org.mule.api.annotations.Configurable; import org.mule.api.annotations.Connector; import org.mule.api.annotations.Processor; import org.mule.api.annotations.rest.HttpMethod; import org.mule.api.annotations.rest.RestCall; import org.mule.api.annotations.rest.RestExceptionOn; import org.mule.api.annotations.rest.RestHttpClient; import org.mule.api.annotations.rest.RestUriParam; import org.mule.modules.TranslateException;
/** * This file was automatically generated by the Mule Development Kit */ package org.mule.modules; /** * Cloud Connector * * @author MuleSoft, Inc. */ @Connector(name="restclient", schemaVersion="1.0-SNAPSHOT") public abstract class RestClientConnector { //<start id="lis_13_httpclient"/> @RestHttpClient HttpClient client = new HttpClient(); //<end id="lis_13_httpclient"/> //<start id="lis_13_restcall"/> @Processor @RestCall(uri = "https://www.googleapis.com/language/translate/v2" + "?key={apiKey}&source={sourceLang}&target={destLang}" + "&q={text}", method = HttpMethod.GET, contentType ="application/json") public abstract Object translate( @RestUriParam("apiKey") String apiKey, @RestUriParam("sourceLang") String sourceLang, @RestUriParam("destLang") String destLang, @RestUriParam("text") String text) throws IOException; //<end id="lis_13_restcall"/> //<start id="lis_13_configurable-resturi"/> @RestUriParam("apiKey") @Configurable private String apiKey; //<end id="lis_13_configurable-resturi"/> //<start id="lis_13_configurable-resturi-exception"/> @Processor @RestCall(uri = "https://www.googleapis.com/language/translate/v2" + "?key={apiKey}&source={sourceLang}&target={destLang}" + "&q={text}", method = HttpMethod.GET, exceptions= @RestExceptionOn(
// Path: chapter13/restclient/src/main/java/org/mule/modules/TranslateException.java // public class TranslateException extends RuntimeException { // // public TranslateException(){ // } // // public TranslateException(String reason){ // } // } // Path: chapter13/restclient/src/main/java/org/mule/modules/RestClientConnector.java import java.io.IOException; import org.apache.commons.httpclient.HttpClient; import org.mule.api.annotations.Configurable; import org.mule.api.annotations.Connector; import org.mule.api.annotations.Processor; import org.mule.api.annotations.rest.HttpMethod; import org.mule.api.annotations.rest.RestCall; import org.mule.api.annotations.rest.RestExceptionOn; import org.mule.api.annotations.rest.RestHttpClient; import org.mule.api.annotations.rest.RestUriParam; import org.mule.modules.TranslateException; /** * This file was automatically generated by the Mule Development Kit */ package org.mule.modules; /** * Cloud Connector * * @author MuleSoft, Inc. */ @Connector(name="restclient", schemaVersion="1.0-SNAPSHOT") public abstract class RestClientConnector { //<start id="lis_13_httpclient"/> @RestHttpClient HttpClient client = new HttpClient(); //<end id="lis_13_httpclient"/> //<start id="lis_13_restcall"/> @Processor @RestCall(uri = "https://www.googleapis.com/language/translate/v2" + "?key={apiKey}&source={sourceLang}&target={destLang}" + "&q={text}", method = HttpMethod.GET, contentType ="application/json") public abstract Object translate( @RestUriParam("apiKey") String apiKey, @RestUriParam("sourceLang") String sourceLang, @RestUriParam("destLang") String destLang, @RestUriParam("text") String text) throws IOException; //<end id="lis_13_restcall"/> //<start id="lis_13_configurable-resturi"/> @RestUriParam("apiKey") @Configurable private String apiKey; //<end id="lis_13_configurable-resturi"/> //<start id="lis_13_configurable-resturi-exception"/> @Processor @RestCall(uri = "https://www.googleapis.com/language/translate/v2" + "?key={apiKey}&source={sourceLang}&target={destLang}" + "&q={text}", method = HttpMethod.GET, exceptions= @RestExceptionOn(
exception = TranslateException.class,
ddossot/mule-in-action-2e
chapter06/src/test/java/com/muleinaction/pattern/service/PatternServiceRefTestCase.java
// Path: chapter06/src/main/java/com/prancingdonkey/reciclingplant/RecicledCountRequest.java // public class RecicledCountRequest { // // String type; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // }
import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import org.junit.Test; import org.mule.api.MuleMessage; import org.mule.module.client.MuleClient; import org.mule.tck.junit4.FunctionalTestCase; import com.prancingdonkey.reciclingplant.RecicledCountRequest;
package com.muleinaction.pattern.service; public class PatternServiceRefTestCase extends FunctionalTestCase { @Override protected String getConfigResources() { return "pattern/service/pattern-service-ref.xml"; } @Test public void testSimpleValidator() throws Exception { MuleClient muleClient = new MuleClient(muleContext);
// Path: chapter06/src/main/java/com/prancingdonkey/reciclingplant/RecicledCountRequest.java // public class RecicledCountRequest { // // String type; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // } // Path: chapter06/src/test/java/com/muleinaction/pattern/service/PatternServiceRefTestCase.java import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import org.junit.Test; import org.mule.api.MuleMessage; import org.mule.module.client.MuleClient; import org.mule.tck.junit4.FunctionalTestCase; import com.prancingdonkey.reciclingplant.RecicledCountRequest; package com.muleinaction.pattern.service; public class PatternServiceRefTestCase extends FunctionalTestCase { @Override protected String getConfigResources() { return "pattern/service/pattern-service-ref.xml"; } @Test public void testSimpleValidator() throws Exception { MuleClient muleClient = new MuleClient(muleContext);
RecicledCountRequest payload = new RecicledCountRequest();
ddossot/mule-in-action-2e
chapter06/src/test/java/com/muleinaction/pattern/service/PatternServiceInheritanceTestCase.java
// Path: chapter06/src/main/java/com/prancingdonkey/reciclingplant/RecicledCountRequest.java // public class RecicledCountRequest { // // String type; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // }
import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import org.junit.Test; import org.mule.api.MuleMessage; import org.mule.module.client.MuleClient; import org.mule.tck.junit4.FunctionalTestCase; import com.prancingdonkey.reciclingplant.RecicledCountRequest;
package com.muleinaction.pattern.service; public class PatternServiceInheritanceTestCase extends FunctionalTestCase { @Override protected String getConfigResources() { return "pattern/service/pattern-service-inheritance.xml"; } @Test public void testSimpleValidator() throws Exception { MuleClient muleClient = new MuleClient(muleContext);
// Path: chapter06/src/main/java/com/prancingdonkey/reciclingplant/RecicledCountRequest.java // public class RecicledCountRequest { // // String type; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // } // Path: chapter06/src/test/java/com/muleinaction/pattern/service/PatternServiceInheritanceTestCase.java import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import org.junit.Test; import org.mule.api.MuleMessage; import org.mule.module.client.MuleClient; import org.mule.tck.junit4.FunctionalTestCase; import com.prancingdonkey.reciclingplant.RecicledCountRequest; package com.muleinaction.pattern.service; public class PatternServiceInheritanceTestCase extends FunctionalTestCase { @Override protected String getConfigResources() { return "pattern/service/pattern-service-inheritance.xml"; } @Test public void testSimpleValidator() throws Exception { MuleClient muleClient = new MuleClient(muleContext);
RecicledCountRequest payload = new RecicledCountRequest();
ddossot/mule-in-action-2e
chapter05/src/test/java/RouteToDLQFunctionalTestCase.java
// Path: chapter05/src/main/java/com/prancingdonkey/domain/Order.java // public class Order implements Serializable { // private String id; // private String priority; // private String customerId; // private BigDecimal total; // private BigDecimal shippingCost; // private List<LineItem> lineItems; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getPriority() { // return priority; // } // // public void setPriority(String priority) { // this.priority = priority; // } // // public String getCustomerId() { // return customerId; // } // // public void setCustomerId(String customerId) { // this.customerId = customerId; // } // // public BigDecimal getTotal() { // return total; // } // // public void setTotal(BigDecimal total) { // this.total = total; // } // // public BigDecimal getShippingCost() { // return shippingCost; // } // // public void setShippingCost(BigDecimal shippingCost) { // this.shippingCost = shippingCost; // } // // public List<LineItem> getLineItems() { // return lineItems; // } // // public void setLineItems(List<LineItem> lineItems) { // this.lineItems = lineItems; // } // }
import com.prancingdonkey.domain.Order; import org.junit.Assert; import org.junit.Test; import org.mule.api.MuleMessage; import org.mule.tck.junit4.FunctionalTestCase;
public class RouteToDLQFunctionalTestCase extends FunctionalTestCase { @Override protected String getConfigResources() { return "src/main/app/routeToDLQ.xml"; } @Test public void testCanRouteOnUnaccepted() throws Exception {
// Path: chapter05/src/main/java/com/prancingdonkey/domain/Order.java // public class Order implements Serializable { // private String id; // private String priority; // private String customerId; // private BigDecimal total; // private BigDecimal shippingCost; // private List<LineItem> lineItems; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getPriority() { // return priority; // } // // public void setPriority(String priority) { // this.priority = priority; // } // // public String getCustomerId() { // return customerId; // } // // public void setCustomerId(String customerId) { // this.customerId = customerId; // } // // public BigDecimal getTotal() { // return total; // } // // public void setTotal(BigDecimal total) { // this.total = total; // } // // public BigDecimal getShippingCost() { // return shippingCost; // } // // public void setShippingCost(BigDecimal shippingCost) { // this.shippingCost = shippingCost; // } // // public List<LineItem> getLineItems() { // return lineItems; // } // // public void setLineItems(List<LineItem> lineItems) { // this.lineItems = lineItems; // } // } // Path: chapter05/src/test/java/RouteToDLQFunctionalTestCase.java import com.prancingdonkey.domain.Order; import org.junit.Assert; import org.junit.Test; import org.mule.api.MuleMessage; import org.mule.tck.junit4.FunctionalTestCase; public class RouteToDLQFunctionalTestCase extends FunctionalTestCase { @Override protected String getConfigResources() { return "src/main/app/routeToDLQ.xml"; } @Test public void testCanRouteOnUnaccepted() throws Exception {
muleContext.getClient().dispatch("jms://topic:orders", new Order(),null);
ddossot/mule-in-action-2e
chapter05/src/main/java/com/prancingdonkey/transformer/LineItemsToOrderTransformer.java
// Path: chapter05/src/main/java/com/prancingdonkey/domain/Order.java // public class Order implements Serializable { // private String id; // private String priority; // private String customerId; // private BigDecimal total; // private BigDecimal shippingCost; // private List<LineItem> lineItems; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getPriority() { // return priority; // } // // public void setPriority(String priority) { // this.priority = priority; // } // // public String getCustomerId() { // return customerId; // } // // public void setCustomerId(String customerId) { // this.customerId = customerId; // } // // public BigDecimal getTotal() { // return total; // } // // public void setTotal(BigDecimal total) { // this.total = total; // } // // public BigDecimal getShippingCost() { // return shippingCost; // } // // public void setShippingCost(BigDecimal shippingCost) { // this.shippingCost = shippingCost; // } // // public List<LineItem> getLineItems() { // return lineItems; // } // // public void setLineItems(List<LineItem> lineItems) { // this.lineItems = lineItems; // } // }
import com.prancingdonkey.domain.LineItem; import com.prancingdonkey.domain.Order; import org.mule.api.transformer.TransformerException; import org.mule.transformer.AbstractTransformer; import java.util.List;
package com.prancingdonkey.transformer; public class LineItemsToOrderTransformer extends AbstractTransformer { @Override protected Object doTransform(Object src, String enc) throws TransformerException { List<LineItem> lineItems = (List<LineItem>) src;
// Path: chapter05/src/main/java/com/prancingdonkey/domain/Order.java // public class Order implements Serializable { // private String id; // private String priority; // private String customerId; // private BigDecimal total; // private BigDecimal shippingCost; // private List<LineItem> lineItems; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getPriority() { // return priority; // } // // public void setPriority(String priority) { // this.priority = priority; // } // // public String getCustomerId() { // return customerId; // } // // public void setCustomerId(String customerId) { // this.customerId = customerId; // } // // public BigDecimal getTotal() { // return total; // } // // public void setTotal(BigDecimal total) { // this.total = total; // } // // public BigDecimal getShippingCost() { // return shippingCost; // } // // public void setShippingCost(BigDecimal shippingCost) { // this.shippingCost = shippingCost; // } // // public List<LineItem> getLineItems() { // return lineItems; // } // // public void setLineItems(List<LineItem> lineItems) { // this.lineItems = lineItems; // } // } // Path: chapter05/src/main/java/com/prancingdonkey/transformer/LineItemsToOrderTransformer.java import com.prancingdonkey.domain.LineItem; import com.prancingdonkey.domain.Order; import org.mule.api.transformer.TransformerException; import org.mule.transformer.AbstractTransformer; import java.util.List; package com.prancingdonkey.transformer; public class LineItemsToOrderTransformer extends AbstractTransformer { @Override protected Object doTransform(Object src, String enc) throws TransformerException { List<LineItem> lineItems = (List<LineItem>) src;
Order order = new Order();
ChoicesWang/ImageCompare
app/src/main/java/com/choices/imagecompare/configs/volley/SampleVolleyFactory.java
// Path: app/src/main/java/com/choices/imagecompare/configs/ConfigConstants.java // public class ConfigConstants { // public static final int MAX_DISK_CACHE_SIZE = 40 * ByteConstants.MB; // private static final int MAX_HEAP_SIZE = (int) Runtime.getRuntime().maxMemory(); // public static final int MAX_MEMORY_CACHE_SIZE = MAX_HEAP_SIZE / 4; // }
import android.content.Context; import com.android.volley.RequestQueue; import com.android.volley.toolbox.BasicNetwork; import com.android.volley.toolbox.DiskBasedCache; import com.android.volley.toolbox.HurlStack; import com.android.volley.toolbox.ImageLoader; import com.choices.imagecompare.configs.ConfigConstants; import java.io.File;
/* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.configs.volley; /** * Creates singletons of relevant volley classes */ public class SampleVolleyFactory { private static final String VOLLEY_CACHE_DIR = "volley"; private static ImageLoader sImageLoader; private static RequestQueue sRequestQueue; private static VolleyMemoryCache sMemoryCache; public static RequestQueue getRequestQueue(Context context) { if (sRequestQueue == null) { File cacheDir = new File(context.getCacheDir(), VOLLEY_CACHE_DIR); sRequestQueue = new RequestQueue(
// Path: app/src/main/java/com/choices/imagecompare/configs/ConfigConstants.java // public class ConfigConstants { // public static final int MAX_DISK_CACHE_SIZE = 40 * ByteConstants.MB; // private static final int MAX_HEAP_SIZE = (int) Runtime.getRuntime().maxMemory(); // public static final int MAX_MEMORY_CACHE_SIZE = MAX_HEAP_SIZE / 4; // } // Path: app/src/main/java/com/choices/imagecompare/configs/volley/SampleVolleyFactory.java import android.content.Context; import com.android.volley.RequestQueue; import com.android.volley.toolbox.BasicNetwork; import com.android.volley.toolbox.DiskBasedCache; import com.android.volley.toolbox.HurlStack; import com.android.volley.toolbox.ImageLoader; import com.choices.imagecompare.configs.ConfigConstants; import java.io.File; /* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.configs.volley; /** * Creates singletons of relevant volley classes */ public class SampleVolleyFactory { private static final String VOLLEY_CACHE_DIR = "volley"; private static ImageLoader sImageLoader; private static RequestQueue sRequestQueue; private static VolleyMemoryCache sMemoryCache; public static RequestQueue getRequestQueue(Context context) { if (sRequestQueue == null) { File cacheDir = new File(context.getCacheDir(), VOLLEY_CACHE_DIR); sRequestQueue = new RequestQueue(
new DiskBasedCache(cacheDir, ConfigConstants.MAX_DISK_CACHE_SIZE),
ChoicesWang/ImageCompare
app/src/main/java/com/choices/imagecompare/configs/picasso/SamplePicassoFactory.java
// Path: app/src/main/java/com/choices/imagecompare/configs/ConfigConstants.java // public class ConfigConstants { // public static final int MAX_DISK_CACHE_SIZE = 40 * ByteConstants.MB; // private static final int MAX_HEAP_SIZE = (int) Runtime.getRuntime().maxMemory(); // public static final int MAX_MEMORY_CACHE_SIZE = MAX_HEAP_SIZE / 4; // }
import android.content.Context; import com.choices.imagecompare.configs.ConfigConstants; import com.squareup.picasso.LruCache; import com.squareup.picasso.OkHttpDownloader; import com.squareup.picasso.Picasso;
/* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.configs.picasso; /** * Provides instance of Picasso with common configuration for the sample app */ public class SamplePicassoFactory { private static Picasso sPicasso; public static Picasso getPicasso(Context context) { if (sPicasso == null) { sPicasso = new Picasso.Builder(context)
// Path: app/src/main/java/com/choices/imagecompare/configs/ConfigConstants.java // public class ConfigConstants { // public static final int MAX_DISK_CACHE_SIZE = 40 * ByteConstants.MB; // private static final int MAX_HEAP_SIZE = (int) Runtime.getRuntime().maxMemory(); // public static final int MAX_MEMORY_CACHE_SIZE = MAX_HEAP_SIZE / 4; // } // Path: app/src/main/java/com/choices/imagecompare/configs/picasso/SamplePicassoFactory.java import android.content.Context; import com.choices.imagecompare.configs.ConfigConstants; import com.squareup.picasso.LruCache; import com.squareup.picasso.OkHttpDownloader; import com.squareup.picasso.Picasso; /* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.configs.picasso; /** * Provides instance of Picasso with common configuration for the sample app */ public class SamplePicassoFactory { private static Picasso sPicasso; public static Picasso getPicasso(Context context) { if (sPicasso == null) { sPicasso = new Picasso.Builder(context)
.downloader(new OkHttpDownloader(context, ConfigConstants.MAX_DISK_CACHE_SIZE))
ChoicesWang/ImageCompare
app/src/main/java/com/choices/imagecompare/instrumentation/InstrumentedImageView.java
// Path: app/src/main/java/com/choices/imagecompare/Drawables.java // public class Drawables { // public static Drawable sPlaceholderDrawable; // public static Drawable sErrorDrawable; // private Drawables() { // } // // public static void init(final Resources resources) { // if (sPlaceholderDrawable == null) { // sPlaceholderDrawable = resources.getDrawable(R.color.placeholder); // } // if (sErrorDrawable == null) { // sErrorDrawable = resources.getDrawable(R.color.error); // } // } // }
import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.net.Uri; import android.widget.ImageView; import com.facebook.common.internal.Preconditions; import com.choices.imagecompare.Drawables;
/* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.instrumentation; /** * {@link ImageView} that notifies its instance of {@link Instrumentation} whenever an image request * lifecycle event happens. * <p/> * <p> setImageResource and setImageURI methods are not expected to be used by any library, * UnsupportedOperationException is thrown if those are called */ public class InstrumentedImageView extends ImageView implements Instrumented { private final Instrumentation mInstrumentation; public InstrumentedImageView(final Context context) { super(context); mInstrumentation = new Instrumentation(this); } @Override public void initInstrumentation(final String tag, PerfListener perfListener) { mInstrumentation.init(tag, perfListener); // we don't have a better estimate on when to call onStart, so do it here. mInstrumentation.onStart(); } @Override public void onDraw(final Canvas canvas) { super.onDraw(canvas); mInstrumentation.onDraw(canvas); } @Override public void setImageDrawable(final Drawable drawable) { Preconditions.checkNotNull(drawable);
// Path: app/src/main/java/com/choices/imagecompare/Drawables.java // public class Drawables { // public static Drawable sPlaceholderDrawable; // public static Drawable sErrorDrawable; // private Drawables() { // } // // public static void init(final Resources resources) { // if (sPlaceholderDrawable == null) { // sPlaceholderDrawable = resources.getDrawable(R.color.placeholder); // } // if (sErrorDrawable == null) { // sErrorDrawable = resources.getDrawable(R.color.error); // } // } // } // Path: app/src/main/java/com/choices/imagecompare/instrumentation/InstrumentedImageView.java import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.net.Uri; import android.widget.ImageView; import com.facebook.common.internal.Preconditions; import com.choices.imagecompare.Drawables; /* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.instrumentation; /** * {@link ImageView} that notifies its instance of {@link Instrumentation} whenever an image request * lifecycle event happens. * <p/> * <p> setImageResource and setImageURI methods are not expected to be used by any library, * UnsupportedOperationException is thrown if those are called */ public class InstrumentedImageView extends ImageView implements Instrumented { private final Instrumentation mInstrumentation; public InstrumentedImageView(final Context context) { super(context); mInstrumentation = new Instrumentation(this); } @Override public void initInstrumentation(final String tag, PerfListener perfListener) { mInstrumentation.init(tag, perfListener); // we don't have a better estimate on when to call onStart, so do it here. mInstrumentation.onStart(); } @Override public void onDraw(final Canvas canvas) { super.onDraw(canvas); mInstrumentation.onDraw(canvas); } @Override public void setImageDrawable(final Drawable drawable) { Preconditions.checkNotNull(drawable);
if (drawable == Drawables.sPlaceholderDrawable) {
ChoicesWang/ImageCompare
app/src/main/java/com/choices/imagecompare/holders/UilHolder.java
// Path: app/src/main/java/com/choices/imagecompare/instrumentation/InstrumentedImageView.java // public class InstrumentedImageView extends ImageView implements Instrumented { // // private final Instrumentation mInstrumentation; // // public InstrumentedImageView(final Context context) { // super(context); // mInstrumentation = new Instrumentation(this); // } // // @Override // public void initInstrumentation(final String tag, PerfListener perfListener) { // mInstrumentation.init(tag, perfListener); // // we don't have a better estimate on when to call onStart, so do it here. // mInstrumentation.onStart(); // } // // @Override // public void onDraw(final Canvas canvas) { // super.onDraw(canvas); // mInstrumentation.onDraw(canvas); // } // // @Override // public void setImageDrawable(final Drawable drawable) { // Preconditions.checkNotNull(drawable); // if (drawable == Drawables.sPlaceholderDrawable) { // // ignore // } else if (drawable == Drawables.sErrorDrawable) { // mInstrumentation.onFailure(); // } else { // mInstrumentation.onSuccess(); // } // super.setImageDrawable(drawable); // } // // /** // * Throws UnsupportedOperationException // */ // @Override // public void setImageResource(int resourceId) { // throw new UnsupportedOperationException(); // } // // /** // * Throws UnsupportedOperationException // */ // @Override // public void setImageURI(Uri uri) { // throw new UnsupportedOperationException(); // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/PerfListener.java // public class PerfListener { // private long mSumOfWaitTime; // private long mStartedRequests; // private long mSuccessfulRequests; // private long mCancelledRequests; // private long mFailedRequests; // // public PerfListener() { // mSumOfWaitTime = 0; // mStartedRequests = 0; // mSuccessfulRequests = 0; // mCancelledRequests = 0; // mFailedRequests = 0; // } // // /** // * Called whenever image request finishes successfully, that is whenever final image is set. // */ // public void reportSuccess(long waitTime) { // mSumOfWaitTime += waitTime; // mSuccessfulRequests++; // } // // /** // * Called whenever image request fails, that is whenever failure drawable is set. // */ // public void reportFailure(long waitTime) { // mSumOfWaitTime += waitTime; // mFailedRequests++; // } // // /** // * Called whenever image request is cancelled, that is whenever image view is reused without // * setting final image first // */ // public void reportCancellation(long waitTime) { // mSumOfWaitTime += waitTime; // mCancelledRequests++; // } // // /** // * Called whenver new request is started. // */ // public void reportStart() { // mStartedRequests++; // } // // /** // * @return average wait time, that is sum of reported wait times divided by number of completed // * requests // */ // public long getAverageWaitTime() { // final long completedRequests = getCompletedRequests(); // return completedRequests > 0 ? mSumOfWaitTime / completedRequests : 0; // } // // /** // * @return difference between number of started requests and number of completed requests // */ // public long getOutstandingRequests() { // return mStartedRequests - getCompletedRequests(); // } // // /** // * @return number of cancelled requests // */ // public long getCancelledRequests() { // return mCancelledRequests; // } // // /** // * @return number of completed requests, either by seting final image, failure or cancellation // */ // public long getCompletedRequests() { // return mSuccessfulRequests + mCancelledRequests + mFailedRequests; // } // }
import android.content.Context; import android.view.View; import com.choices.imagecompare.instrumentation.InstrumentedImageView; import com.choices.imagecompare.instrumentation.PerfListener; import com.nostra13.universalimageloader.core.ImageLoader;
/* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.holders; /** * This is the Holder class for the RecycleView to use with Universal Image Loader */ public class UilHolder extends BaseViewHolder<InstrumentedImageView> { private final ImageLoader mImageLoader; public UilHolder( Context context, ImageLoader imageLoader, View layoutView,
// Path: app/src/main/java/com/choices/imagecompare/instrumentation/InstrumentedImageView.java // public class InstrumentedImageView extends ImageView implements Instrumented { // // private final Instrumentation mInstrumentation; // // public InstrumentedImageView(final Context context) { // super(context); // mInstrumentation = new Instrumentation(this); // } // // @Override // public void initInstrumentation(final String tag, PerfListener perfListener) { // mInstrumentation.init(tag, perfListener); // // we don't have a better estimate on when to call onStart, so do it here. // mInstrumentation.onStart(); // } // // @Override // public void onDraw(final Canvas canvas) { // super.onDraw(canvas); // mInstrumentation.onDraw(canvas); // } // // @Override // public void setImageDrawable(final Drawable drawable) { // Preconditions.checkNotNull(drawable); // if (drawable == Drawables.sPlaceholderDrawable) { // // ignore // } else if (drawable == Drawables.sErrorDrawable) { // mInstrumentation.onFailure(); // } else { // mInstrumentation.onSuccess(); // } // super.setImageDrawable(drawable); // } // // /** // * Throws UnsupportedOperationException // */ // @Override // public void setImageResource(int resourceId) { // throw new UnsupportedOperationException(); // } // // /** // * Throws UnsupportedOperationException // */ // @Override // public void setImageURI(Uri uri) { // throw new UnsupportedOperationException(); // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/PerfListener.java // public class PerfListener { // private long mSumOfWaitTime; // private long mStartedRequests; // private long mSuccessfulRequests; // private long mCancelledRequests; // private long mFailedRequests; // // public PerfListener() { // mSumOfWaitTime = 0; // mStartedRequests = 0; // mSuccessfulRequests = 0; // mCancelledRequests = 0; // mFailedRequests = 0; // } // // /** // * Called whenever image request finishes successfully, that is whenever final image is set. // */ // public void reportSuccess(long waitTime) { // mSumOfWaitTime += waitTime; // mSuccessfulRequests++; // } // // /** // * Called whenever image request fails, that is whenever failure drawable is set. // */ // public void reportFailure(long waitTime) { // mSumOfWaitTime += waitTime; // mFailedRequests++; // } // // /** // * Called whenever image request is cancelled, that is whenever image view is reused without // * setting final image first // */ // public void reportCancellation(long waitTime) { // mSumOfWaitTime += waitTime; // mCancelledRequests++; // } // // /** // * Called whenver new request is started. // */ // public void reportStart() { // mStartedRequests++; // } // // /** // * @return average wait time, that is sum of reported wait times divided by number of completed // * requests // */ // public long getAverageWaitTime() { // final long completedRequests = getCompletedRequests(); // return completedRequests > 0 ? mSumOfWaitTime / completedRequests : 0; // } // // /** // * @return difference between number of started requests and number of completed requests // */ // public long getOutstandingRequests() { // return mStartedRequests - getCompletedRequests(); // } // // /** // * @return number of cancelled requests // */ // public long getCancelledRequests() { // return mCancelledRequests; // } // // /** // * @return number of completed requests, either by seting final image, failure or cancellation // */ // public long getCompletedRequests() { // return mSuccessfulRequests + mCancelledRequests + mFailedRequests; // } // } // Path: app/src/main/java/com/choices/imagecompare/holders/UilHolder.java import android.content.Context; import android.view.View; import com.choices.imagecompare.instrumentation.InstrumentedImageView; import com.choices.imagecompare.instrumentation.PerfListener; import com.nostra13.universalimageloader.core.ImageLoader; /* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.holders; /** * This is the Holder class for the RecycleView to use with Universal Image Loader */ public class UilHolder extends BaseViewHolder<InstrumentedImageView> { private final ImageLoader mImageLoader; public UilHolder( Context context, ImageLoader imageLoader, View layoutView,
InstrumentedImageView view, PerfListener perfListener) {
ChoicesWang/ImageCompare
app/src/main/java/com/choices/imagecompare/holders/VolleyHolder.java
// Path: app/src/main/java/com/choices/imagecompare/instrumentation/InstrumentedNetworkImageView.java // public class InstrumentedNetworkImageView extends NetworkImageView implements Instrumented { // // private final Instrumentation mInstrumentation; // // public InstrumentedNetworkImageView(final Context context) { // super(context); // mInstrumentation = new Instrumentation(this); // } // // @Override // public void initInstrumentation(final String tag, final PerfListener perfListener) { // mInstrumentation.init(tag, perfListener); // // we don't have a better estimate on when to call onStart, so do it here. // mInstrumentation.onStart(); // } // // @Override // public void onDraw(final Canvas canvas) { // super.onDraw(canvas); // mInstrumentation.onDraw(canvas); // } // // @Override // public void setImageBitmap(final Bitmap bm) { // // bm == null in couple of situations like // // - detaching from window // // - cleaning up previous request // if (bm != null) { // mInstrumentation.onSuccess(); // } // super.setImageBitmap(bm); // } // // public void setImageResource(int resourceId) { // if (resourceId == R.color.placeholder) { // // ignore // } else if (resourceId == R.color.error) { // mInstrumentation.onFailure(); // } else { // throw new IllegalArgumentException("Unrecognized resourceId"); // } // super.setImageResource(resourceId); // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/PerfListener.java // public class PerfListener { // private long mSumOfWaitTime; // private long mStartedRequests; // private long mSuccessfulRequests; // private long mCancelledRequests; // private long mFailedRequests; // // public PerfListener() { // mSumOfWaitTime = 0; // mStartedRequests = 0; // mSuccessfulRequests = 0; // mCancelledRequests = 0; // mFailedRequests = 0; // } // // /** // * Called whenever image request finishes successfully, that is whenever final image is set. // */ // public void reportSuccess(long waitTime) { // mSumOfWaitTime += waitTime; // mSuccessfulRequests++; // } // // /** // * Called whenever image request fails, that is whenever failure drawable is set. // */ // public void reportFailure(long waitTime) { // mSumOfWaitTime += waitTime; // mFailedRequests++; // } // // /** // * Called whenever image request is cancelled, that is whenever image view is reused without // * setting final image first // */ // public void reportCancellation(long waitTime) { // mSumOfWaitTime += waitTime; // mCancelledRequests++; // } // // /** // * Called whenver new request is started. // */ // public void reportStart() { // mStartedRequests++; // } // // /** // * @return average wait time, that is sum of reported wait times divided by number of completed // * requests // */ // public long getAverageWaitTime() { // final long completedRequests = getCompletedRequests(); // return completedRequests > 0 ? mSumOfWaitTime / completedRequests : 0; // } // // /** // * @return difference between number of started requests and number of completed requests // */ // public long getOutstandingRequests() { // return mStartedRequests - getCompletedRequests(); // } // // /** // * @return number of cancelled requests // */ // public long getCancelledRequests() { // return mCancelledRequests; // } // // /** // * @return number of completed requests, either by seting final image, failure or cancellation // */ // public long getCompletedRequests() { // return mSuccessfulRequests + mCancelledRequests + mFailedRequests; // } // }
import android.content.Context; import android.view.View; import com.android.volley.toolbox.ImageLoader; import com.choices.imagecompare.instrumentation.InstrumentedNetworkImageView; import com.choices.imagecompare.instrumentation.PerfListener;
/* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.holders; /** * This is the Holder class for the RecycleView to use with Volley */ public class VolleyHolder extends BaseViewHolder<InstrumentedNetworkImageView> { private final ImageLoader mImageLoader; public VolleyHolder( Context context, ImageLoader imageLoader, View layoutView,
// Path: app/src/main/java/com/choices/imagecompare/instrumentation/InstrumentedNetworkImageView.java // public class InstrumentedNetworkImageView extends NetworkImageView implements Instrumented { // // private final Instrumentation mInstrumentation; // // public InstrumentedNetworkImageView(final Context context) { // super(context); // mInstrumentation = new Instrumentation(this); // } // // @Override // public void initInstrumentation(final String tag, final PerfListener perfListener) { // mInstrumentation.init(tag, perfListener); // // we don't have a better estimate on when to call onStart, so do it here. // mInstrumentation.onStart(); // } // // @Override // public void onDraw(final Canvas canvas) { // super.onDraw(canvas); // mInstrumentation.onDraw(canvas); // } // // @Override // public void setImageBitmap(final Bitmap bm) { // // bm == null in couple of situations like // // - detaching from window // // - cleaning up previous request // if (bm != null) { // mInstrumentation.onSuccess(); // } // super.setImageBitmap(bm); // } // // public void setImageResource(int resourceId) { // if (resourceId == R.color.placeholder) { // // ignore // } else if (resourceId == R.color.error) { // mInstrumentation.onFailure(); // } else { // throw new IllegalArgumentException("Unrecognized resourceId"); // } // super.setImageResource(resourceId); // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/PerfListener.java // public class PerfListener { // private long mSumOfWaitTime; // private long mStartedRequests; // private long mSuccessfulRequests; // private long mCancelledRequests; // private long mFailedRequests; // // public PerfListener() { // mSumOfWaitTime = 0; // mStartedRequests = 0; // mSuccessfulRequests = 0; // mCancelledRequests = 0; // mFailedRequests = 0; // } // // /** // * Called whenever image request finishes successfully, that is whenever final image is set. // */ // public void reportSuccess(long waitTime) { // mSumOfWaitTime += waitTime; // mSuccessfulRequests++; // } // // /** // * Called whenever image request fails, that is whenever failure drawable is set. // */ // public void reportFailure(long waitTime) { // mSumOfWaitTime += waitTime; // mFailedRequests++; // } // // /** // * Called whenever image request is cancelled, that is whenever image view is reused without // * setting final image first // */ // public void reportCancellation(long waitTime) { // mSumOfWaitTime += waitTime; // mCancelledRequests++; // } // // /** // * Called whenver new request is started. // */ // public void reportStart() { // mStartedRequests++; // } // // /** // * @return average wait time, that is sum of reported wait times divided by number of completed // * requests // */ // public long getAverageWaitTime() { // final long completedRequests = getCompletedRequests(); // return completedRequests > 0 ? mSumOfWaitTime / completedRequests : 0; // } // // /** // * @return difference between number of started requests and number of completed requests // */ // public long getOutstandingRequests() { // return mStartedRequests - getCompletedRequests(); // } // // /** // * @return number of cancelled requests // */ // public long getCancelledRequests() { // return mCancelledRequests; // } // // /** // * @return number of completed requests, either by seting final image, failure or cancellation // */ // public long getCompletedRequests() { // return mSuccessfulRequests + mCancelledRequests + mFailedRequests; // } // } // Path: app/src/main/java/com/choices/imagecompare/holders/VolleyHolder.java import android.content.Context; import android.view.View; import com.android.volley.toolbox.ImageLoader; import com.choices.imagecompare.instrumentation.InstrumentedNetworkImageView; import com.choices.imagecompare.instrumentation.PerfListener; /* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.holders; /** * This is the Holder class for the RecycleView to use with Volley */ public class VolleyHolder extends BaseViewHolder<InstrumentedNetworkImageView> { private final ImageLoader mImageLoader; public VolleyHolder( Context context, ImageLoader imageLoader, View layoutView,
InstrumentedNetworkImageView view, PerfListener perfListener) {
ChoicesWang/ImageCompare
app/src/main/java/com/choices/imagecompare/configs/uil/SampleUilFactory.java
// Path: app/src/main/java/com/choices/imagecompare/Drawables.java // public class Drawables { // public static Drawable sPlaceholderDrawable; // public static Drawable sErrorDrawable; // private Drawables() { // } // // public static void init(final Resources resources) { // if (sPlaceholderDrawable == null) { // sPlaceholderDrawable = resources.getDrawable(R.color.placeholder); // } // if (sErrorDrawable == null) { // sErrorDrawable = resources.getDrawable(R.color.error); // } // } // } // // Path: app/src/main/java/com/choices/imagecompare/configs/ConfigConstants.java // public class ConfigConstants { // public static final int MAX_DISK_CACHE_SIZE = 40 * ByteConstants.MB; // private static final int MAX_HEAP_SIZE = (int) Runtime.getRuntime().maxMemory(); // public static final int MAX_MEMORY_CACHE_SIZE = MAX_HEAP_SIZE / 4; // }
import android.content.Context; import com.choices.imagecompare.Drawables; import com.choices.imagecompare.configs.ConfigConstants; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
/* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.configs.uil; /** * Provides instance of ImageLoader with appropriately configured caches and placeholder/failure * drawables. */ public class SampleUilFactory { private static ImageLoader sImageLoader; public static ImageLoader getImageLoader(Context context) { if (sImageLoader == null) { DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder()
// Path: app/src/main/java/com/choices/imagecompare/Drawables.java // public class Drawables { // public static Drawable sPlaceholderDrawable; // public static Drawable sErrorDrawable; // private Drawables() { // } // // public static void init(final Resources resources) { // if (sPlaceholderDrawable == null) { // sPlaceholderDrawable = resources.getDrawable(R.color.placeholder); // } // if (sErrorDrawable == null) { // sErrorDrawable = resources.getDrawable(R.color.error); // } // } // } // // Path: app/src/main/java/com/choices/imagecompare/configs/ConfigConstants.java // public class ConfigConstants { // public static final int MAX_DISK_CACHE_SIZE = 40 * ByteConstants.MB; // private static final int MAX_HEAP_SIZE = (int) Runtime.getRuntime().maxMemory(); // public static final int MAX_MEMORY_CACHE_SIZE = MAX_HEAP_SIZE / 4; // } // Path: app/src/main/java/com/choices/imagecompare/configs/uil/SampleUilFactory.java import android.content.Context; import com.choices.imagecompare.Drawables; import com.choices.imagecompare.configs.ConfigConstants; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; /* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.configs.uil; /** * Provides instance of ImageLoader with appropriately configured caches and placeholder/failure * drawables. */ public class SampleUilFactory { private static ImageLoader sImageLoader; public static ImageLoader getImageLoader(Context context) { if (sImageLoader == null) { DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder()
.showImageOnLoading(Drawables.sPlaceholderDrawable)
ChoicesWang/ImageCompare
app/src/main/java/com/choices/imagecompare/configs/uil/SampleUilFactory.java
// Path: app/src/main/java/com/choices/imagecompare/Drawables.java // public class Drawables { // public static Drawable sPlaceholderDrawable; // public static Drawable sErrorDrawable; // private Drawables() { // } // // public static void init(final Resources resources) { // if (sPlaceholderDrawable == null) { // sPlaceholderDrawable = resources.getDrawable(R.color.placeholder); // } // if (sErrorDrawable == null) { // sErrorDrawable = resources.getDrawable(R.color.error); // } // } // } // // Path: app/src/main/java/com/choices/imagecompare/configs/ConfigConstants.java // public class ConfigConstants { // public static final int MAX_DISK_CACHE_SIZE = 40 * ByteConstants.MB; // private static final int MAX_HEAP_SIZE = (int) Runtime.getRuntime().maxMemory(); // public static final int MAX_MEMORY_CACHE_SIZE = MAX_HEAP_SIZE / 4; // }
import android.content.Context; import com.choices.imagecompare.Drawables; import com.choices.imagecompare.configs.ConfigConstants; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
/* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.configs.uil; /** * Provides instance of ImageLoader with appropriately configured caches and placeholder/failure * drawables. */ public class SampleUilFactory { private static ImageLoader sImageLoader; public static ImageLoader getImageLoader(Context context) { if (sImageLoader == null) { DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder() .showImageOnLoading(Drawables.sPlaceholderDrawable) .showImageOnFail(Drawables.sErrorDrawable) .cacheInMemory(true) .cacheOnDisk(true) .build(); ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context) .defaultDisplayImageOptions(displayImageOptions)
// Path: app/src/main/java/com/choices/imagecompare/Drawables.java // public class Drawables { // public static Drawable sPlaceholderDrawable; // public static Drawable sErrorDrawable; // private Drawables() { // } // // public static void init(final Resources resources) { // if (sPlaceholderDrawable == null) { // sPlaceholderDrawable = resources.getDrawable(R.color.placeholder); // } // if (sErrorDrawable == null) { // sErrorDrawable = resources.getDrawable(R.color.error); // } // } // } // // Path: app/src/main/java/com/choices/imagecompare/configs/ConfigConstants.java // public class ConfigConstants { // public static final int MAX_DISK_CACHE_SIZE = 40 * ByteConstants.MB; // private static final int MAX_HEAP_SIZE = (int) Runtime.getRuntime().maxMemory(); // public static final int MAX_MEMORY_CACHE_SIZE = MAX_HEAP_SIZE / 4; // } // Path: app/src/main/java/com/choices/imagecompare/configs/uil/SampleUilFactory.java import android.content.Context; import com.choices.imagecompare.Drawables; import com.choices.imagecompare.configs.ConfigConstants; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; /* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.configs.uil; /** * Provides instance of ImageLoader with appropriately configured caches and placeholder/failure * drawables. */ public class SampleUilFactory { private static ImageLoader sImageLoader; public static ImageLoader getImageLoader(Context context) { if (sImageLoader == null) { DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder() .showImageOnLoading(Drawables.sPlaceholderDrawable) .showImageOnFail(Drawables.sErrorDrawable) .cacheInMemory(true) .cacheOnDisk(true) .build(); ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context) .defaultDisplayImageOptions(displayImageOptions)
.diskCacheSize(ConfigConstants.MAX_DISK_CACHE_SIZE)
ChoicesWang/ImageCompare
app/src/main/java/com/choices/imagecompare/holders/VolleyDraweeHolder.java
// Path: app/src/main/java/com/choices/imagecompare/instrumentation/InstrumentedDraweeView.java // public class InstrumentedDraweeView extends SimpleDraweeView implements Instrumented { // // private Instrumentation mInstrumentation; // private ControllerListener<Object> mListener; // // public InstrumentedDraweeView(Context context, GenericDraweeHierarchy hierarchy) { // super(context, hierarchy); // init(); // } // // public InstrumentedDraweeView(Context context) { // super(context); // init(); // } // // public InstrumentedDraweeView(Context context, AttributeSet attrs) { // super(context, attrs); // init(); // } // // public InstrumentedDraweeView(Context context, AttributeSet attrs, int defStyle) { // super(context, attrs, defStyle); // init(); // } // // private void init() { // mInstrumentation = new Instrumentation(this); // mListener = new BaseControllerListener<Object>() { // @Override // public void onSubmit(String id, Object callerContext) { // mInstrumentation.onStart(); // } // // @Override // public void onFinalImageSet( // String id, // @Nullable Object imageInfo, // @Nullable Animatable animatable) { // mInstrumentation.onSuccess(); // } // // @Override // public void onFailure(String id, Throwable throwable) { // mInstrumentation.onFailure(); // } // // @Override // public void onRelease(String id) { // mInstrumentation.onCancellation(); // } // }; // } // // @Override // public void initInstrumentation(String tag, PerfListener perfListener) { // mInstrumentation.init(tag, perfListener); // } // // @Override // public void onDraw(final Canvas canvas) { // super.onDraw(canvas); // mInstrumentation.onDraw(canvas); // } // // @Override // public void setImageURI(Uri uri, @Nullable Object callerContext) { // SimpleDraweeControllerBuilder controllerBuilder = getControllerBuilder() // .setUri(uri) // .setCallerContext(callerContext) // .setOldController(getController()); // if (controllerBuilder instanceof AbstractDraweeControllerBuilder) { // ((AbstractDraweeControllerBuilder<?, ?, ?, ?>) controllerBuilder) // .setControllerListener(mListener); // } // setController(controllerBuilder.build()); // } // // public ControllerListener<Object> getListener() { // return mListener; // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/PerfListener.java // public class PerfListener { // private long mSumOfWaitTime; // private long mStartedRequests; // private long mSuccessfulRequests; // private long mCancelledRequests; // private long mFailedRequests; // // public PerfListener() { // mSumOfWaitTime = 0; // mStartedRequests = 0; // mSuccessfulRequests = 0; // mCancelledRequests = 0; // mFailedRequests = 0; // } // // /** // * Called whenever image request finishes successfully, that is whenever final image is set. // */ // public void reportSuccess(long waitTime) { // mSumOfWaitTime += waitTime; // mSuccessfulRequests++; // } // // /** // * Called whenever image request fails, that is whenever failure drawable is set. // */ // public void reportFailure(long waitTime) { // mSumOfWaitTime += waitTime; // mFailedRequests++; // } // // /** // * Called whenever image request is cancelled, that is whenever image view is reused without // * setting final image first // */ // public void reportCancellation(long waitTime) { // mSumOfWaitTime += waitTime; // mCancelledRequests++; // } // // /** // * Called whenver new request is started. // */ // public void reportStart() { // mStartedRequests++; // } // // /** // * @return average wait time, that is sum of reported wait times divided by number of completed // * requests // */ // public long getAverageWaitTime() { // final long completedRequests = getCompletedRequests(); // return completedRequests > 0 ? mSumOfWaitTime / completedRequests : 0; // } // // /** // * @return difference between number of started requests and number of completed requests // */ // public long getOutstandingRequests() { // return mStartedRequests - getCompletedRequests(); // } // // /** // * @return number of cancelled requests // */ // public long getCancelledRequests() { // return mCancelledRequests; // } // // /** // * @return number of completed requests, either by seting final image, failure or cancellation // */ // public long getCompletedRequests() { // return mSuccessfulRequests + mCancelledRequests + mFailedRequests; // } // }
import android.content.Context; import android.net.Uri; import android.view.View; import com.choices.imagecompare.instrumentation.InstrumentedDraweeView; import com.choices.imagecompare.instrumentation.PerfListener;
/* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.holders; /** * This is the Holder class for the RecycleView to use with Volley and Drawee */ public class VolleyDraweeHolder extends BaseViewHolder<InstrumentedDraweeView> { public VolleyDraweeHolder( Context context, View parentView,
// Path: app/src/main/java/com/choices/imagecompare/instrumentation/InstrumentedDraweeView.java // public class InstrumentedDraweeView extends SimpleDraweeView implements Instrumented { // // private Instrumentation mInstrumentation; // private ControllerListener<Object> mListener; // // public InstrumentedDraweeView(Context context, GenericDraweeHierarchy hierarchy) { // super(context, hierarchy); // init(); // } // // public InstrumentedDraweeView(Context context) { // super(context); // init(); // } // // public InstrumentedDraweeView(Context context, AttributeSet attrs) { // super(context, attrs); // init(); // } // // public InstrumentedDraweeView(Context context, AttributeSet attrs, int defStyle) { // super(context, attrs, defStyle); // init(); // } // // private void init() { // mInstrumentation = new Instrumentation(this); // mListener = new BaseControllerListener<Object>() { // @Override // public void onSubmit(String id, Object callerContext) { // mInstrumentation.onStart(); // } // // @Override // public void onFinalImageSet( // String id, // @Nullable Object imageInfo, // @Nullable Animatable animatable) { // mInstrumentation.onSuccess(); // } // // @Override // public void onFailure(String id, Throwable throwable) { // mInstrumentation.onFailure(); // } // // @Override // public void onRelease(String id) { // mInstrumentation.onCancellation(); // } // }; // } // // @Override // public void initInstrumentation(String tag, PerfListener perfListener) { // mInstrumentation.init(tag, perfListener); // } // // @Override // public void onDraw(final Canvas canvas) { // super.onDraw(canvas); // mInstrumentation.onDraw(canvas); // } // // @Override // public void setImageURI(Uri uri, @Nullable Object callerContext) { // SimpleDraweeControllerBuilder controllerBuilder = getControllerBuilder() // .setUri(uri) // .setCallerContext(callerContext) // .setOldController(getController()); // if (controllerBuilder instanceof AbstractDraweeControllerBuilder) { // ((AbstractDraweeControllerBuilder<?, ?, ?, ?>) controllerBuilder) // .setControllerListener(mListener); // } // setController(controllerBuilder.build()); // } // // public ControllerListener<Object> getListener() { // return mListener; // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/PerfListener.java // public class PerfListener { // private long mSumOfWaitTime; // private long mStartedRequests; // private long mSuccessfulRequests; // private long mCancelledRequests; // private long mFailedRequests; // // public PerfListener() { // mSumOfWaitTime = 0; // mStartedRequests = 0; // mSuccessfulRequests = 0; // mCancelledRequests = 0; // mFailedRequests = 0; // } // // /** // * Called whenever image request finishes successfully, that is whenever final image is set. // */ // public void reportSuccess(long waitTime) { // mSumOfWaitTime += waitTime; // mSuccessfulRequests++; // } // // /** // * Called whenever image request fails, that is whenever failure drawable is set. // */ // public void reportFailure(long waitTime) { // mSumOfWaitTime += waitTime; // mFailedRequests++; // } // // /** // * Called whenever image request is cancelled, that is whenever image view is reused without // * setting final image first // */ // public void reportCancellation(long waitTime) { // mSumOfWaitTime += waitTime; // mCancelledRequests++; // } // // /** // * Called whenver new request is started. // */ // public void reportStart() { // mStartedRequests++; // } // // /** // * @return average wait time, that is sum of reported wait times divided by number of completed // * requests // */ // public long getAverageWaitTime() { // final long completedRequests = getCompletedRequests(); // return completedRequests > 0 ? mSumOfWaitTime / completedRequests : 0; // } // // /** // * @return difference between number of started requests and number of completed requests // */ // public long getOutstandingRequests() { // return mStartedRequests - getCompletedRequests(); // } // // /** // * @return number of cancelled requests // */ // public long getCancelledRequests() { // return mCancelledRequests; // } // // /** // * @return number of completed requests, either by seting final image, failure or cancellation // */ // public long getCompletedRequests() { // return mSuccessfulRequests + mCancelledRequests + mFailedRequests; // } // } // Path: app/src/main/java/com/choices/imagecompare/holders/VolleyDraweeHolder.java import android.content.Context; import android.net.Uri; import android.view.View; import com.choices.imagecompare.instrumentation.InstrumentedDraweeView; import com.choices.imagecompare.instrumentation.PerfListener; /* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.holders; /** * This is the Holder class for the RecycleView to use with Volley and Drawee */ public class VolleyDraweeHolder extends BaseViewHolder<InstrumentedDraweeView> { public VolleyDraweeHolder( Context context, View parentView,
InstrumentedDraweeView view, PerfListener perfListener) {
ChoicesWang/ImageCompare
app/src/main/java/com/choices/imagecompare/holders/GlideHolder.java
// Path: app/src/main/java/com/choices/imagecompare/Drawables.java // public class Drawables { // public static Drawable sPlaceholderDrawable; // public static Drawable sErrorDrawable; // private Drawables() { // } // // public static void init(final Resources resources) { // if (sPlaceholderDrawable == null) { // sPlaceholderDrawable = resources.getDrawable(R.color.placeholder); // } // if (sErrorDrawable == null) { // sErrorDrawable = resources.getDrawable(R.color.error); // } // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/InstrumentedImageView.java // public class InstrumentedImageView extends ImageView implements Instrumented { // // private final Instrumentation mInstrumentation; // // public InstrumentedImageView(final Context context) { // super(context); // mInstrumentation = new Instrumentation(this); // } // // @Override // public void initInstrumentation(final String tag, PerfListener perfListener) { // mInstrumentation.init(tag, perfListener); // // we don't have a better estimate on when to call onStart, so do it here. // mInstrumentation.onStart(); // } // // @Override // public void onDraw(final Canvas canvas) { // super.onDraw(canvas); // mInstrumentation.onDraw(canvas); // } // // @Override // public void setImageDrawable(final Drawable drawable) { // Preconditions.checkNotNull(drawable); // if (drawable == Drawables.sPlaceholderDrawable) { // // ignore // } else if (drawable == Drawables.sErrorDrawable) { // mInstrumentation.onFailure(); // } else { // mInstrumentation.onSuccess(); // } // super.setImageDrawable(drawable); // } // // /** // * Throws UnsupportedOperationException // */ // @Override // public void setImageResource(int resourceId) { // throw new UnsupportedOperationException(); // } // // /** // * Throws UnsupportedOperationException // */ // @Override // public void setImageURI(Uri uri) { // throw new UnsupportedOperationException(); // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/PerfListener.java // public class PerfListener { // private long mSumOfWaitTime; // private long mStartedRequests; // private long mSuccessfulRequests; // private long mCancelledRequests; // private long mFailedRequests; // // public PerfListener() { // mSumOfWaitTime = 0; // mStartedRequests = 0; // mSuccessfulRequests = 0; // mCancelledRequests = 0; // mFailedRequests = 0; // } // // /** // * Called whenever image request finishes successfully, that is whenever final image is set. // */ // public void reportSuccess(long waitTime) { // mSumOfWaitTime += waitTime; // mSuccessfulRequests++; // } // // /** // * Called whenever image request fails, that is whenever failure drawable is set. // */ // public void reportFailure(long waitTime) { // mSumOfWaitTime += waitTime; // mFailedRequests++; // } // // /** // * Called whenever image request is cancelled, that is whenever image view is reused without // * setting final image first // */ // public void reportCancellation(long waitTime) { // mSumOfWaitTime += waitTime; // mCancelledRequests++; // } // // /** // * Called whenver new request is started. // */ // public void reportStart() { // mStartedRequests++; // } // // /** // * @return average wait time, that is sum of reported wait times divided by number of completed // * requests // */ // public long getAverageWaitTime() { // final long completedRequests = getCompletedRequests(); // return completedRequests > 0 ? mSumOfWaitTime / completedRequests : 0; // } // // /** // * @return difference between number of started requests and number of completed requests // */ // public long getOutstandingRequests() { // return mStartedRequests - getCompletedRequests(); // } // // /** // * @return number of cancelled requests // */ // public long getCancelledRequests() { // return mCancelledRequests; // } // // /** // * @return number of completed requests, either by seting final image, failure or cancellation // */ // public long getCompletedRequests() { // return mSuccessfulRequests + mCancelledRequests + mFailedRequests; // } // }
import android.content.Context; import android.view.View; import com.bumptech.glide.Glide; import com.choices.imagecompare.Drawables; import com.choices.imagecompare.instrumentation.InstrumentedImageView; import com.choices.imagecompare.instrumentation.PerfListener;
/* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.holders; /** * This is the Holder class for the RecycleView to use with Glide */ public class GlideHolder extends BaseViewHolder<InstrumentedImageView> { public GlideHolder( Context context, View layoutView,
// Path: app/src/main/java/com/choices/imagecompare/Drawables.java // public class Drawables { // public static Drawable sPlaceholderDrawable; // public static Drawable sErrorDrawable; // private Drawables() { // } // // public static void init(final Resources resources) { // if (sPlaceholderDrawable == null) { // sPlaceholderDrawable = resources.getDrawable(R.color.placeholder); // } // if (sErrorDrawable == null) { // sErrorDrawable = resources.getDrawable(R.color.error); // } // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/InstrumentedImageView.java // public class InstrumentedImageView extends ImageView implements Instrumented { // // private final Instrumentation mInstrumentation; // // public InstrumentedImageView(final Context context) { // super(context); // mInstrumentation = new Instrumentation(this); // } // // @Override // public void initInstrumentation(final String tag, PerfListener perfListener) { // mInstrumentation.init(tag, perfListener); // // we don't have a better estimate on when to call onStart, so do it here. // mInstrumentation.onStart(); // } // // @Override // public void onDraw(final Canvas canvas) { // super.onDraw(canvas); // mInstrumentation.onDraw(canvas); // } // // @Override // public void setImageDrawable(final Drawable drawable) { // Preconditions.checkNotNull(drawable); // if (drawable == Drawables.sPlaceholderDrawable) { // // ignore // } else if (drawable == Drawables.sErrorDrawable) { // mInstrumentation.onFailure(); // } else { // mInstrumentation.onSuccess(); // } // super.setImageDrawable(drawable); // } // // /** // * Throws UnsupportedOperationException // */ // @Override // public void setImageResource(int resourceId) { // throw new UnsupportedOperationException(); // } // // /** // * Throws UnsupportedOperationException // */ // @Override // public void setImageURI(Uri uri) { // throw new UnsupportedOperationException(); // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/PerfListener.java // public class PerfListener { // private long mSumOfWaitTime; // private long mStartedRequests; // private long mSuccessfulRequests; // private long mCancelledRequests; // private long mFailedRequests; // // public PerfListener() { // mSumOfWaitTime = 0; // mStartedRequests = 0; // mSuccessfulRequests = 0; // mCancelledRequests = 0; // mFailedRequests = 0; // } // // /** // * Called whenever image request finishes successfully, that is whenever final image is set. // */ // public void reportSuccess(long waitTime) { // mSumOfWaitTime += waitTime; // mSuccessfulRequests++; // } // // /** // * Called whenever image request fails, that is whenever failure drawable is set. // */ // public void reportFailure(long waitTime) { // mSumOfWaitTime += waitTime; // mFailedRequests++; // } // // /** // * Called whenever image request is cancelled, that is whenever image view is reused without // * setting final image first // */ // public void reportCancellation(long waitTime) { // mSumOfWaitTime += waitTime; // mCancelledRequests++; // } // // /** // * Called whenver new request is started. // */ // public void reportStart() { // mStartedRequests++; // } // // /** // * @return average wait time, that is sum of reported wait times divided by number of completed // * requests // */ // public long getAverageWaitTime() { // final long completedRequests = getCompletedRequests(); // return completedRequests > 0 ? mSumOfWaitTime / completedRequests : 0; // } // // /** // * @return difference between number of started requests and number of completed requests // */ // public long getOutstandingRequests() { // return mStartedRequests - getCompletedRequests(); // } // // /** // * @return number of cancelled requests // */ // public long getCancelledRequests() { // return mCancelledRequests; // } // // /** // * @return number of completed requests, either by seting final image, failure or cancellation // */ // public long getCompletedRequests() { // return mSuccessfulRequests + mCancelledRequests + mFailedRequests; // } // } // Path: app/src/main/java/com/choices/imagecompare/holders/GlideHolder.java import android.content.Context; import android.view.View; import com.bumptech.glide.Glide; import com.choices.imagecompare.Drawables; import com.choices.imagecompare.instrumentation.InstrumentedImageView; import com.choices.imagecompare.instrumentation.PerfListener; /* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.holders; /** * This is the Holder class for the RecycleView to use with Glide */ public class GlideHolder extends BaseViewHolder<InstrumentedImageView> { public GlideHolder( Context context, View layoutView,
InstrumentedImageView instrumentedImageView, PerfListener perfListener) {
ChoicesWang/ImageCompare
app/src/main/java/com/choices/imagecompare/holders/GlideHolder.java
// Path: app/src/main/java/com/choices/imagecompare/Drawables.java // public class Drawables { // public static Drawable sPlaceholderDrawable; // public static Drawable sErrorDrawable; // private Drawables() { // } // // public static void init(final Resources resources) { // if (sPlaceholderDrawable == null) { // sPlaceholderDrawable = resources.getDrawable(R.color.placeholder); // } // if (sErrorDrawable == null) { // sErrorDrawable = resources.getDrawable(R.color.error); // } // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/InstrumentedImageView.java // public class InstrumentedImageView extends ImageView implements Instrumented { // // private final Instrumentation mInstrumentation; // // public InstrumentedImageView(final Context context) { // super(context); // mInstrumentation = new Instrumentation(this); // } // // @Override // public void initInstrumentation(final String tag, PerfListener perfListener) { // mInstrumentation.init(tag, perfListener); // // we don't have a better estimate on when to call onStart, so do it here. // mInstrumentation.onStart(); // } // // @Override // public void onDraw(final Canvas canvas) { // super.onDraw(canvas); // mInstrumentation.onDraw(canvas); // } // // @Override // public void setImageDrawable(final Drawable drawable) { // Preconditions.checkNotNull(drawable); // if (drawable == Drawables.sPlaceholderDrawable) { // // ignore // } else if (drawable == Drawables.sErrorDrawable) { // mInstrumentation.onFailure(); // } else { // mInstrumentation.onSuccess(); // } // super.setImageDrawable(drawable); // } // // /** // * Throws UnsupportedOperationException // */ // @Override // public void setImageResource(int resourceId) { // throw new UnsupportedOperationException(); // } // // /** // * Throws UnsupportedOperationException // */ // @Override // public void setImageURI(Uri uri) { // throw new UnsupportedOperationException(); // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/PerfListener.java // public class PerfListener { // private long mSumOfWaitTime; // private long mStartedRequests; // private long mSuccessfulRequests; // private long mCancelledRequests; // private long mFailedRequests; // // public PerfListener() { // mSumOfWaitTime = 0; // mStartedRequests = 0; // mSuccessfulRequests = 0; // mCancelledRequests = 0; // mFailedRequests = 0; // } // // /** // * Called whenever image request finishes successfully, that is whenever final image is set. // */ // public void reportSuccess(long waitTime) { // mSumOfWaitTime += waitTime; // mSuccessfulRequests++; // } // // /** // * Called whenever image request fails, that is whenever failure drawable is set. // */ // public void reportFailure(long waitTime) { // mSumOfWaitTime += waitTime; // mFailedRequests++; // } // // /** // * Called whenever image request is cancelled, that is whenever image view is reused without // * setting final image first // */ // public void reportCancellation(long waitTime) { // mSumOfWaitTime += waitTime; // mCancelledRequests++; // } // // /** // * Called whenver new request is started. // */ // public void reportStart() { // mStartedRequests++; // } // // /** // * @return average wait time, that is sum of reported wait times divided by number of completed // * requests // */ // public long getAverageWaitTime() { // final long completedRequests = getCompletedRequests(); // return completedRequests > 0 ? mSumOfWaitTime / completedRequests : 0; // } // // /** // * @return difference between number of started requests and number of completed requests // */ // public long getOutstandingRequests() { // return mStartedRequests - getCompletedRequests(); // } // // /** // * @return number of cancelled requests // */ // public long getCancelledRequests() { // return mCancelledRequests; // } // // /** // * @return number of completed requests, either by seting final image, failure or cancellation // */ // public long getCompletedRequests() { // return mSuccessfulRequests + mCancelledRequests + mFailedRequests; // } // }
import android.content.Context; import android.view.View; import com.bumptech.glide.Glide; import com.choices.imagecompare.Drawables; import com.choices.imagecompare.instrumentation.InstrumentedImageView; import com.choices.imagecompare.instrumentation.PerfListener;
/* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.holders; /** * This is the Holder class for the RecycleView to use with Glide */ public class GlideHolder extends BaseViewHolder<InstrumentedImageView> { public GlideHolder( Context context, View layoutView, InstrumentedImageView instrumentedImageView, PerfListener perfListener) { super(context, layoutView, instrumentedImageView, perfListener); } @Override protected void onBind(String uri) { Glide.with(mImageView.getContext()) .load(uri)
// Path: app/src/main/java/com/choices/imagecompare/Drawables.java // public class Drawables { // public static Drawable sPlaceholderDrawable; // public static Drawable sErrorDrawable; // private Drawables() { // } // // public static void init(final Resources resources) { // if (sPlaceholderDrawable == null) { // sPlaceholderDrawable = resources.getDrawable(R.color.placeholder); // } // if (sErrorDrawable == null) { // sErrorDrawable = resources.getDrawable(R.color.error); // } // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/InstrumentedImageView.java // public class InstrumentedImageView extends ImageView implements Instrumented { // // private final Instrumentation mInstrumentation; // // public InstrumentedImageView(final Context context) { // super(context); // mInstrumentation = new Instrumentation(this); // } // // @Override // public void initInstrumentation(final String tag, PerfListener perfListener) { // mInstrumentation.init(tag, perfListener); // // we don't have a better estimate on when to call onStart, so do it here. // mInstrumentation.onStart(); // } // // @Override // public void onDraw(final Canvas canvas) { // super.onDraw(canvas); // mInstrumentation.onDraw(canvas); // } // // @Override // public void setImageDrawable(final Drawable drawable) { // Preconditions.checkNotNull(drawable); // if (drawable == Drawables.sPlaceholderDrawable) { // // ignore // } else if (drawable == Drawables.sErrorDrawable) { // mInstrumentation.onFailure(); // } else { // mInstrumentation.onSuccess(); // } // super.setImageDrawable(drawable); // } // // /** // * Throws UnsupportedOperationException // */ // @Override // public void setImageResource(int resourceId) { // throw new UnsupportedOperationException(); // } // // /** // * Throws UnsupportedOperationException // */ // @Override // public void setImageURI(Uri uri) { // throw new UnsupportedOperationException(); // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/PerfListener.java // public class PerfListener { // private long mSumOfWaitTime; // private long mStartedRequests; // private long mSuccessfulRequests; // private long mCancelledRequests; // private long mFailedRequests; // // public PerfListener() { // mSumOfWaitTime = 0; // mStartedRequests = 0; // mSuccessfulRequests = 0; // mCancelledRequests = 0; // mFailedRequests = 0; // } // // /** // * Called whenever image request finishes successfully, that is whenever final image is set. // */ // public void reportSuccess(long waitTime) { // mSumOfWaitTime += waitTime; // mSuccessfulRequests++; // } // // /** // * Called whenever image request fails, that is whenever failure drawable is set. // */ // public void reportFailure(long waitTime) { // mSumOfWaitTime += waitTime; // mFailedRequests++; // } // // /** // * Called whenever image request is cancelled, that is whenever image view is reused without // * setting final image first // */ // public void reportCancellation(long waitTime) { // mSumOfWaitTime += waitTime; // mCancelledRequests++; // } // // /** // * Called whenver new request is started. // */ // public void reportStart() { // mStartedRequests++; // } // // /** // * @return average wait time, that is sum of reported wait times divided by number of completed // * requests // */ // public long getAverageWaitTime() { // final long completedRequests = getCompletedRequests(); // return completedRequests > 0 ? mSumOfWaitTime / completedRequests : 0; // } // // /** // * @return difference between number of started requests and number of completed requests // */ // public long getOutstandingRequests() { // return mStartedRequests - getCompletedRequests(); // } // // /** // * @return number of cancelled requests // */ // public long getCancelledRequests() { // return mCancelledRequests; // } // // /** // * @return number of completed requests, either by seting final image, failure or cancellation // */ // public long getCompletedRequests() { // return mSuccessfulRequests + mCancelledRequests + mFailedRequests; // } // } // Path: app/src/main/java/com/choices/imagecompare/holders/GlideHolder.java import android.content.Context; import android.view.View; import com.bumptech.glide.Glide; import com.choices.imagecompare.Drawables; import com.choices.imagecompare.instrumentation.InstrumentedImageView; import com.choices.imagecompare.instrumentation.PerfListener; /* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.holders; /** * This is the Holder class for the RecycleView to use with Glide */ public class GlideHolder extends BaseViewHolder<InstrumentedImageView> { public GlideHolder( Context context, View layoutView, InstrumentedImageView instrumentedImageView, PerfListener perfListener) { super(context, layoutView, instrumentedImageView, perfListener); } @Override protected void onBind(String uri) { Glide.with(mImageView.getContext()) .load(uri)
.placeholder(Drawables.sPlaceholderDrawable)
ChoicesWang/ImageCompare
app/src/main/java/com/choices/imagecompare/configs/glide/SampleGlideModule.java
// Path: app/src/main/java/com/choices/imagecompare/configs/ConfigConstants.java // public class ConfigConstants { // public static final int MAX_DISK_CACHE_SIZE = 40 * ByteConstants.MB; // private static final int MAX_HEAP_SIZE = (int) Runtime.getRuntime().maxMemory(); // public static final int MAX_MEMORY_CACHE_SIZE = MAX_HEAP_SIZE / 4; // }
import android.content.Context; import com.bumptech.glide.Glide; import com.bumptech.glide.GlideBuilder; import com.bumptech.glide.load.engine.cache.DiskCache; import com.bumptech.glide.load.engine.cache.DiskLruCacheWrapper; import com.bumptech.glide.load.engine.cache.LruResourceCache; import com.bumptech.glide.module.GlideModule; import com.choices.imagecompare.configs.ConfigConstants;
/* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.configs.glide; /** * {@link com.bumptech.glide.module.GlideModule} implementation for the sample app. */ public class SampleGlideModule implements GlideModule { @Override public void applyOptions(final Context context, GlideBuilder builder) { builder.setDiskCache( new DiskCache.Factory() { @Override public DiskCache build() { return DiskLruCacheWrapper.get( Glide.getPhotoCacheDir(context),
// Path: app/src/main/java/com/choices/imagecompare/configs/ConfigConstants.java // public class ConfigConstants { // public static final int MAX_DISK_CACHE_SIZE = 40 * ByteConstants.MB; // private static final int MAX_HEAP_SIZE = (int) Runtime.getRuntime().maxMemory(); // public static final int MAX_MEMORY_CACHE_SIZE = MAX_HEAP_SIZE / 4; // } // Path: app/src/main/java/com/choices/imagecompare/configs/glide/SampleGlideModule.java import android.content.Context; import com.bumptech.glide.Glide; import com.bumptech.glide.GlideBuilder; import com.bumptech.glide.load.engine.cache.DiskCache; import com.bumptech.glide.load.engine.cache.DiskLruCacheWrapper; import com.bumptech.glide.load.engine.cache.LruResourceCache; import com.bumptech.glide.module.GlideModule; import com.choices.imagecompare.configs.ConfigConstants; /* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.configs.glide; /** * {@link com.bumptech.glide.module.GlideModule} implementation for the sample app. */ public class SampleGlideModule implements GlideModule { @Override public void applyOptions(final Context context, GlideBuilder builder) { builder.setDiskCache( new DiskCache.Factory() { @Override public DiskCache build() { return DiskLruCacheWrapper.get( Glide.getPhotoCacheDir(context),
ConfigConstants.MAX_DISK_CACHE_SIZE);
ChoicesWang/ImageCompare
app/src/main/java/com/choices/imagecompare/holders/BaseViewHolder.java
// Path: app/src/main/java/com/choices/imagecompare/instrumentation/Instrumented.java // public interface Instrumented { // // /** // * Forget what happened so far and start measuring once again. // * // * @param tag String used to identify the image request // * @param perfListener listener to be used to track the request state // */ // void initInstrumentation(final String tag, PerfListener perfListener); // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/PerfListener.java // public class PerfListener { // private long mSumOfWaitTime; // private long mStartedRequests; // private long mSuccessfulRequests; // private long mCancelledRequests; // private long mFailedRequests; // // public PerfListener() { // mSumOfWaitTime = 0; // mStartedRequests = 0; // mSuccessfulRequests = 0; // mCancelledRequests = 0; // mFailedRequests = 0; // } // // /** // * Called whenever image request finishes successfully, that is whenever final image is set. // */ // public void reportSuccess(long waitTime) { // mSumOfWaitTime += waitTime; // mSuccessfulRequests++; // } // // /** // * Called whenever image request fails, that is whenever failure drawable is set. // */ // public void reportFailure(long waitTime) { // mSumOfWaitTime += waitTime; // mFailedRequests++; // } // // /** // * Called whenever image request is cancelled, that is whenever image view is reused without // * setting final image first // */ // public void reportCancellation(long waitTime) { // mSumOfWaitTime += waitTime; // mCancelledRequests++; // } // // /** // * Called whenver new request is started. // */ // public void reportStart() { // mStartedRequests++; // } // // /** // * @return average wait time, that is sum of reported wait times divided by number of completed // * requests // */ // public long getAverageWaitTime() { // final long completedRequests = getCompletedRequests(); // return completedRequests > 0 ? mSumOfWaitTime / completedRequests : 0; // } // // /** // * @return difference between number of started requests and number of completed requests // */ // public long getOutstandingRequests() { // return mStartedRequests - getCompletedRequests(); // } // // /** // * @return number of cancelled requests // */ // public long getCancelledRequests() { // return mCancelledRequests; // } // // /** // * @return number of completed requests, either by seting final image, failure or cancellation // */ // public long getCompletedRequests() { // return mSuccessfulRequests + mCancelledRequests + mFailedRequests; // } // }
import android.content.Context; import android.content.res.Configuration; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import com.choices.imagecompare.instrumentation.Instrumented; import com.choices.imagecompare.instrumentation.PerfListener;
/* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.holders; /** * The base ViewHolder with instrumentation */ public abstract class BaseViewHolder<V extends View & Instrumented> extends RecyclerView.ViewHolder { protected final V mImageView;
// Path: app/src/main/java/com/choices/imagecompare/instrumentation/Instrumented.java // public interface Instrumented { // // /** // * Forget what happened so far and start measuring once again. // * // * @param tag String used to identify the image request // * @param perfListener listener to be used to track the request state // */ // void initInstrumentation(final String tag, PerfListener perfListener); // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/PerfListener.java // public class PerfListener { // private long mSumOfWaitTime; // private long mStartedRequests; // private long mSuccessfulRequests; // private long mCancelledRequests; // private long mFailedRequests; // // public PerfListener() { // mSumOfWaitTime = 0; // mStartedRequests = 0; // mSuccessfulRequests = 0; // mCancelledRequests = 0; // mFailedRequests = 0; // } // // /** // * Called whenever image request finishes successfully, that is whenever final image is set. // */ // public void reportSuccess(long waitTime) { // mSumOfWaitTime += waitTime; // mSuccessfulRequests++; // } // // /** // * Called whenever image request fails, that is whenever failure drawable is set. // */ // public void reportFailure(long waitTime) { // mSumOfWaitTime += waitTime; // mFailedRequests++; // } // // /** // * Called whenever image request is cancelled, that is whenever image view is reused without // * setting final image first // */ // public void reportCancellation(long waitTime) { // mSumOfWaitTime += waitTime; // mCancelledRequests++; // } // // /** // * Called whenver new request is started. // */ // public void reportStart() { // mStartedRequests++; // } // // /** // * @return average wait time, that is sum of reported wait times divided by number of completed // * requests // */ // public long getAverageWaitTime() { // final long completedRequests = getCompletedRequests(); // return completedRequests > 0 ? mSumOfWaitTime / completedRequests : 0; // } // // /** // * @return difference between number of started requests and number of completed requests // */ // public long getOutstandingRequests() { // return mStartedRequests - getCompletedRequests(); // } // // /** // * @return number of cancelled requests // */ // public long getCancelledRequests() { // return mCancelledRequests; // } // // /** // * @return number of completed requests, either by seting final image, failure or cancellation // */ // public long getCompletedRequests() { // return mSuccessfulRequests + mCancelledRequests + mFailedRequests; // } // } // Path: app/src/main/java/com/choices/imagecompare/holders/BaseViewHolder.java import android.content.Context; import android.content.res.Configuration; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import com.choices.imagecompare.instrumentation.Instrumented; import com.choices.imagecompare.instrumentation.PerfListener; /* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.holders; /** * The base ViewHolder with instrumentation */ public abstract class BaseViewHolder<V extends View & Instrumented> extends RecyclerView.ViewHolder { protected final V mImageView;
private final PerfListener mPerfListener;
ChoicesWang/ImageCompare
app/src/main/java/com/choices/imagecompare/holders/FrescoHolder.java
// Path: app/src/main/java/com/choices/imagecompare/instrumentation/InstrumentedDraweeView.java // public class InstrumentedDraweeView extends SimpleDraweeView implements Instrumented { // // private Instrumentation mInstrumentation; // private ControllerListener<Object> mListener; // // public InstrumentedDraweeView(Context context, GenericDraweeHierarchy hierarchy) { // super(context, hierarchy); // init(); // } // // public InstrumentedDraweeView(Context context) { // super(context); // init(); // } // // public InstrumentedDraweeView(Context context, AttributeSet attrs) { // super(context, attrs); // init(); // } // // public InstrumentedDraweeView(Context context, AttributeSet attrs, int defStyle) { // super(context, attrs, defStyle); // init(); // } // // private void init() { // mInstrumentation = new Instrumentation(this); // mListener = new BaseControllerListener<Object>() { // @Override // public void onSubmit(String id, Object callerContext) { // mInstrumentation.onStart(); // } // // @Override // public void onFinalImageSet( // String id, // @Nullable Object imageInfo, // @Nullable Animatable animatable) { // mInstrumentation.onSuccess(); // } // // @Override // public void onFailure(String id, Throwable throwable) { // mInstrumentation.onFailure(); // } // // @Override // public void onRelease(String id) { // mInstrumentation.onCancellation(); // } // }; // } // // @Override // public void initInstrumentation(String tag, PerfListener perfListener) { // mInstrumentation.init(tag, perfListener); // } // // @Override // public void onDraw(final Canvas canvas) { // super.onDraw(canvas); // mInstrumentation.onDraw(canvas); // } // // @Override // public void setImageURI(Uri uri, @Nullable Object callerContext) { // SimpleDraweeControllerBuilder controllerBuilder = getControllerBuilder() // .setUri(uri) // .setCallerContext(callerContext) // .setOldController(getController()); // if (controllerBuilder instanceof AbstractDraweeControllerBuilder) { // ((AbstractDraweeControllerBuilder<?, ?, ?, ?>) controllerBuilder) // .setControllerListener(mListener); // } // setController(controllerBuilder.build()); // } // // public ControllerListener<Object> getListener() { // return mListener; // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/PerfListener.java // public class PerfListener { // private long mSumOfWaitTime; // private long mStartedRequests; // private long mSuccessfulRequests; // private long mCancelledRequests; // private long mFailedRequests; // // public PerfListener() { // mSumOfWaitTime = 0; // mStartedRequests = 0; // mSuccessfulRequests = 0; // mCancelledRequests = 0; // mFailedRequests = 0; // } // // /** // * Called whenever image request finishes successfully, that is whenever final image is set. // */ // public void reportSuccess(long waitTime) { // mSumOfWaitTime += waitTime; // mSuccessfulRequests++; // } // // /** // * Called whenever image request fails, that is whenever failure drawable is set. // */ // public void reportFailure(long waitTime) { // mSumOfWaitTime += waitTime; // mFailedRequests++; // } // // /** // * Called whenever image request is cancelled, that is whenever image view is reused without // * setting final image first // */ // public void reportCancellation(long waitTime) { // mSumOfWaitTime += waitTime; // mCancelledRequests++; // } // // /** // * Called whenver new request is started. // */ // public void reportStart() { // mStartedRequests++; // } // // /** // * @return average wait time, that is sum of reported wait times divided by number of completed // * requests // */ // public long getAverageWaitTime() { // final long completedRequests = getCompletedRequests(); // return completedRequests > 0 ? mSumOfWaitTime / completedRequests : 0; // } // // /** // * @return difference between number of started requests and number of completed requests // */ // public long getOutstandingRequests() { // return mStartedRequests - getCompletedRequests(); // } // // /** // * @return number of cancelled requests // */ // public long getCancelledRequests() { // return mCancelledRequests; // } // // /** // * @return number of completed requests, either by seting final image, failure or cancellation // */ // public long getCompletedRequests() { // return mSuccessfulRequests + mCancelledRequests + mFailedRequests; // } // }
import android.content.Context; import android.net.Uri; import android.view.View; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.interfaces.DraweeController; import com.facebook.imagepipeline.common.ResizeOptions; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.request.ImageRequestBuilder; import com.choices.imagecompare.instrumentation.InstrumentedDraweeView; import com.choices.imagecompare.instrumentation.PerfListener;
/* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.holders; /** * This is the Holder class for the RecycleView to use with Fresco */ public class FrescoHolder extends BaseViewHolder<InstrumentedDraweeView> { public FrescoHolder( Context context, View parentView,
// Path: app/src/main/java/com/choices/imagecompare/instrumentation/InstrumentedDraweeView.java // public class InstrumentedDraweeView extends SimpleDraweeView implements Instrumented { // // private Instrumentation mInstrumentation; // private ControllerListener<Object> mListener; // // public InstrumentedDraweeView(Context context, GenericDraweeHierarchy hierarchy) { // super(context, hierarchy); // init(); // } // // public InstrumentedDraweeView(Context context) { // super(context); // init(); // } // // public InstrumentedDraweeView(Context context, AttributeSet attrs) { // super(context, attrs); // init(); // } // // public InstrumentedDraweeView(Context context, AttributeSet attrs, int defStyle) { // super(context, attrs, defStyle); // init(); // } // // private void init() { // mInstrumentation = new Instrumentation(this); // mListener = new BaseControllerListener<Object>() { // @Override // public void onSubmit(String id, Object callerContext) { // mInstrumentation.onStart(); // } // // @Override // public void onFinalImageSet( // String id, // @Nullable Object imageInfo, // @Nullable Animatable animatable) { // mInstrumentation.onSuccess(); // } // // @Override // public void onFailure(String id, Throwable throwable) { // mInstrumentation.onFailure(); // } // // @Override // public void onRelease(String id) { // mInstrumentation.onCancellation(); // } // }; // } // // @Override // public void initInstrumentation(String tag, PerfListener perfListener) { // mInstrumentation.init(tag, perfListener); // } // // @Override // public void onDraw(final Canvas canvas) { // super.onDraw(canvas); // mInstrumentation.onDraw(canvas); // } // // @Override // public void setImageURI(Uri uri, @Nullable Object callerContext) { // SimpleDraweeControllerBuilder controllerBuilder = getControllerBuilder() // .setUri(uri) // .setCallerContext(callerContext) // .setOldController(getController()); // if (controllerBuilder instanceof AbstractDraweeControllerBuilder) { // ((AbstractDraweeControllerBuilder<?, ?, ?, ?>) controllerBuilder) // .setControllerListener(mListener); // } // setController(controllerBuilder.build()); // } // // public ControllerListener<Object> getListener() { // return mListener; // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/PerfListener.java // public class PerfListener { // private long mSumOfWaitTime; // private long mStartedRequests; // private long mSuccessfulRequests; // private long mCancelledRequests; // private long mFailedRequests; // // public PerfListener() { // mSumOfWaitTime = 0; // mStartedRequests = 0; // mSuccessfulRequests = 0; // mCancelledRequests = 0; // mFailedRequests = 0; // } // // /** // * Called whenever image request finishes successfully, that is whenever final image is set. // */ // public void reportSuccess(long waitTime) { // mSumOfWaitTime += waitTime; // mSuccessfulRequests++; // } // // /** // * Called whenever image request fails, that is whenever failure drawable is set. // */ // public void reportFailure(long waitTime) { // mSumOfWaitTime += waitTime; // mFailedRequests++; // } // // /** // * Called whenever image request is cancelled, that is whenever image view is reused without // * setting final image first // */ // public void reportCancellation(long waitTime) { // mSumOfWaitTime += waitTime; // mCancelledRequests++; // } // // /** // * Called whenver new request is started. // */ // public void reportStart() { // mStartedRequests++; // } // // /** // * @return average wait time, that is sum of reported wait times divided by number of completed // * requests // */ // public long getAverageWaitTime() { // final long completedRequests = getCompletedRequests(); // return completedRequests > 0 ? mSumOfWaitTime / completedRequests : 0; // } // // /** // * @return difference between number of started requests and number of completed requests // */ // public long getOutstandingRequests() { // return mStartedRequests - getCompletedRequests(); // } // // /** // * @return number of cancelled requests // */ // public long getCancelledRequests() { // return mCancelledRequests; // } // // /** // * @return number of completed requests, either by seting final image, failure or cancellation // */ // public long getCompletedRequests() { // return mSuccessfulRequests + mCancelledRequests + mFailedRequests; // } // } // Path: app/src/main/java/com/choices/imagecompare/holders/FrescoHolder.java import android.content.Context; import android.net.Uri; import android.view.View; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.interfaces.DraweeController; import com.facebook.imagepipeline.common.ResizeOptions; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.request.ImageRequestBuilder; import com.choices.imagecompare.instrumentation.InstrumentedDraweeView; import com.choices.imagecompare.instrumentation.PerfListener; /* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.holders; /** * This is the Holder class for the RecycleView to use with Fresco */ public class FrescoHolder extends BaseViewHolder<InstrumentedDraweeView> { public FrescoHolder( Context context, View parentView,
InstrumentedDraweeView intrumentedDraweeView, PerfListener perfListener) {
ChoicesWang/ImageCompare
app/src/main/java/com/choices/imagecompare/configs/imagepipeline/ImagePipelineConfigFactory.java
// Path: app/src/main/java/com/choices/imagecompare/configs/ConfigConstants.java // public class ConfigConstants { // public static final int MAX_DISK_CACHE_SIZE = 40 * ByteConstants.MB; // private static final int MAX_HEAP_SIZE = (int) Runtime.getRuntime().maxMemory(); // public static final int MAX_MEMORY_CACHE_SIZE = MAX_HEAP_SIZE / 4; // }
import android.content.Context; import com.facebook.cache.disk.DiskCacheConfig; import com.facebook.common.internal.Supplier; import com.facebook.imagepipeline.backends.okhttp.OkHttpImagePipelineConfigFactory; import com.facebook.imagepipeline.cache.MemoryCacheParams; import com.facebook.imagepipeline.core.ImagePipelineConfig; import com.facebook.imagepipeline.listener.RequestListener; import com.facebook.imagepipeline.listener.RequestLoggingListener; import com.choices.imagecompare.configs.ConfigConstants; import com.squareup.okhttp.OkHttpClient; import java.util.HashSet; import java.util.Set;
/* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.configs.imagepipeline; /** * Creates ImagePipeline configuration for the sample app */ public class ImagePipelineConfigFactory { private static final String IMAGE_PIPELINE_CACHE_DIR = "imagepipeline_cache"; private static ImagePipelineConfig sImagePipelineConfig; private static ImagePipelineConfig sOkHttpImagePipelineConfig; /** * Creates config using android http stack as network backend. */ public static ImagePipelineConfig getImagePipelineConfig(Context context) { if (sImagePipelineConfig == null) { ImagePipelineConfig.Builder configBuilder = ImagePipelineConfig.newBuilder(context); configureCaches(configBuilder, context); configureLoggingListeners(configBuilder); sImagePipelineConfig = configBuilder.build(); } return sImagePipelineConfig; } /** * Creates config using OkHttp as network backed. */ public static ImagePipelineConfig getOkHttpImagePipelineConfig(Context context) { if (sOkHttpImagePipelineConfig == null) { OkHttpClient okHttpClient = new OkHttpClient(); ImagePipelineConfig.Builder configBuilder = OkHttpImagePipelineConfigFactory.newBuilder(context, okHttpClient); configureCaches(configBuilder, context); configureLoggingListeners(configBuilder); sOkHttpImagePipelineConfig = configBuilder.build(); } return sOkHttpImagePipelineConfig; } /** * Configures disk and memory cache not to exceed common limits */ private static void configureCaches( ImagePipelineConfig.Builder configBuilder, Context context) { final MemoryCacheParams bitmapCacheParams = new MemoryCacheParams(
// Path: app/src/main/java/com/choices/imagecompare/configs/ConfigConstants.java // public class ConfigConstants { // public static final int MAX_DISK_CACHE_SIZE = 40 * ByteConstants.MB; // private static final int MAX_HEAP_SIZE = (int) Runtime.getRuntime().maxMemory(); // public static final int MAX_MEMORY_CACHE_SIZE = MAX_HEAP_SIZE / 4; // } // Path: app/src/main/java/com/choices/imagecompare/configs/imagepipeline/ImagePipelineConfigFactory.java import android.content.Context; import com.facebook.cache.disk.DiskCacheConfig; import com.facebook.common.internal.Supplier; import com.facebook.imagepipeline.backends.okhttp.OkHttpImagePipelineConfigFactory; import com.facebook.imagepipeline.cache.MemoryCacheParams; import com.facebook.imagepipeline.core.ImagePipelineConfig; import com.facebook.imagepipeline.listener.RequestListener; import com.facebook.imagepipeline.listener.RequestLoggingListener; import com.choices.imagecompare.configs.ConfigConstants; import com.squareup.okhttp.OkHttpClient; import java.util.HashSet; import java.util.Set; /* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.configs.imagepipeline; /** * Creates ImagePipeline configuration for the sample app */ public class ImagePipelineConfigFactory { private static final String IMAGE_PIPELINE_CACHE_DIR = "imagepipeline_cache"; private static ImagePipelineConfig sImagePipelineConfig; private static ImagePipelineConfig sOkHttpImagePipelineConfig; /** * Creates config using android http stack as network backend. */ public static ImagePipelineConfig getImagePipelineConfig(Context context) { if (sImagePipelineConfig == null) { ImagePipelineConfig.Builder configBuilder = ImagePipelineConfig.newBuilder(context); configureCaches(configBuilder, context); configureLoggingListeners(configBuilder); sImagePipelineConfig = configBuilder.build(); } return sImagePipelineConfig; } /** * Creates config using OkHttp as network backed. */ public static ImagePipelineConfig getOkHttpImagePipelineConfig(Context context) { if (sOkHttpImagePipelineConfig == null) { OkHttpClient okHttpClient = new OkHttpClient(); ImagePipelineConfig.Builder configBuilder = OkHttpImagePipelineConfigFactory.newBuilder(context, okHttpClient); configureCaches(configBuilder, context); configureLoggingListeners(configBuilder); sOkHttpImagePipelineConfig = configBuilder.build(); } return sOkHttpImagePipelineConfig; } /** * Configures disk and memory cache not to exceed common limits */ private static void configureCaches( ImagePipelineConfig.Builder configBuilder, Context context) { final MemoryCacheParams bitmapCacheParams = new MemoryCacheParams(
ConfigConstants.MAX_MEMORY_CACHE_SIZE, // Max total size of elements in the cache
ChoicesWang/ImageCompare
app/src/main/java/com/choices/imagecompare/holders/PicassoHolder.java
// Path: app/src/main/java/com/choices/imagecompare/Drawables.java // public class Drawables { // public static Drawable sPlaceholderDrawable; // public static Drawable sErrorDrawable; // private Drawables() { // } // // public static void init(final Resources resources) { // if (sPlaceholderDrawable == null) { // sPlaceholderDrawable = resources.getDrawable(R.color.placeholder); // } // if (sErrorDrawable == null) { // sErrorDrawable = resources.getDrawable(R.color.error); // } // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/InstrumentedImageView.java // public class InstrumentedImageView extends ImageView implements Instrumented { // // private final Instrumentation mInstrumentation; // // public InstrumentedImageView(final Context context) { // super(context); // mInstrumentation = new Instrumentation(this); // } // // @Override // public void initInstrumentation(final String tag, PerfListener perfListener) { // mInstrumentation.init(tag, perfListener); // // we don't have a better estimate on when to call onStart, so do it here. // mInstrumentation.onStart(); // } // // @Override // public void onDraw(final Canvas canvas) { // super.onDraw(canvas); // mInstrumentation.onDraw(canvas); // } // // @Override // public void setImageDrawable(final Drawable drawable) { // Preconditions.checkNotNull(drawable); // if (drawable == Drawables.sPlaceholderDrawable) { // // ignore // } else if (drawable == Drawables.sErrorDrawable) { // mInstrumentation.onFailure(); // } else { // mInstrumentation.onSuccess(); // } // super.setImageDrawable(drawable); // } // // /** // * Throws UnsupportedOperationException // */ // @Override // public void setImageResource(int resourceId) { // throw new UnsupportedOperationException(); // } // // /** // * Throws UnsupportedOperationException // */ // @Override // public void setImageURI(Uri uri) { // throw new UnsupportedOperationException(); // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/PerfListener.java // public class PerfListener { // private long mSumOfWaitTime; // private long mStartedRequests; // private long mSuccessfulRequests; // private long mCancelledRequests; // private long mFailedRequests; // // public PerfListener() { // mSumOfWaitTime = 0; // mStartedRequests = 0; // mSuccessfulRequests = 0; // mCancelledRequests = 0; // mFailedRequests = 0; // } // // /** // * Called whenever image request finishes successfully, that is whenever final image is set. // */ // public void reportSuccess(long waitTime) { // mSumOfWaitTime += waitTime; // mSuccessfulRequests++; // } // // /** // * Called whenever image request fails, that is whenever failure drawable is set. // */ // public void reportFailure(long waitTime) { // mSumOfWaitTime += waitTime; // mFailedRequests++; // } // // /** // * Called whenever image request is cancelled, that is whenever image view is reused without // * setting final image first // */ // public void reportCancellation(long waitTime) { // mSumOfWaitTime += waitTime; // mCancelledRequests++; // } // // /** // * Called whenver new request is started. // */ // public void reportStart() { // mStartedRequests++; // } // // /** // * @return average wait time, that is sum of reported wait times divided by number of completed // * requests // */ // public long getAverageWaitTime() { // final long completedRequests = getCompletedRequests(); // return completedRequests > 0 ? mSumOfWaitTime / completedRequests : 0; // } // // /** // * @return difference between number of started requests and number of completed requests // */ // public long getOutstandingRequests() { // return mStartedRequests - getCompletedRequests(); // } // // /** // * @return number of cancelled requests // */ // public long getCancelledRequests() { // return mCancelledRequests; // } // // /** // * @return number of completed requests, either by seting final image, failure or cancellation // */ // public long getCompletedRequests() { // return mSuccessfulRequests + mCancelledRequests + mFailedRequests; // } // }
import android.content.Context; import android.view.View; import com.choices.imagecompare.Drawables; import com.choices.imagecompare.instrumentation.InstrumentedImageView; import com.choices.imagecompare.instrumentation.PerfListener; import com.squareup.picasso.Picasso;
/* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.holders; /** * This is the Holder class for the RecycleView to use with Picasso */ public class PicassoHolder extends BaseViewHolder<InstrumentedImageView> { private final Picasso mPicasso; public PicassoHolder( Context context, Picasso picasso, View parent,
// Path: app/src/main/java/com/choices/imagecompare/Drawables.java // public class Drawables { // public static Drawable sPlaceholderDrawable; // public static Drawable sErrorDrawable; // private Drawables() { // } // // public static void init(final Resources resources) { // if (sPlaceholderDrawable == null) { // sPlaceholderDrawable = resources.getDrawable(R.color.placeholder); // } // if (sErrorDrawable == null) { // sErrorDrawable = resources.getDrawable(R.color.error); // } // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/InstrumentedImageView.java // public class InstrumentedImageView extends ImageView implements Instrumented { // // private final Instrumentation mInstrumentation; // // public InstrumentedImageView(final Context context) { // super(context); // mInstrumentation = new Instrumentation(this); // } // // @Override // public void initInstrumentation(final String tag, PerfListener perfListener) { // mInstrumentation.init(tag, perfListener); // // we don't have a better estimate on when to call onStart, so do it here. // mInstrumentation.onStart(); // } // // @Override // public void onDraw(final Canvas canvas) { // super.onDraw(canvas); // mInstrumentation.onDraw(canvas); // } // // @Override // public void setImageDrawable(final Drawable drawable) { // Preconditions.checkNotNull(drawable); // if (drawable == Drawables.sPlaceholderDrawable) { // // ignore // } else if (drawable == Drawables.sErrorDrawable) { // mInstrumentation.onFailure(); // } else { // mInstrumentation.onSuccess(); // } // super.setImageDrawable(drawable); // } // // /** // * Throws UnsupportedOperationException // */ // @Override // public void setImageResource(int resourceId) { // throw new UnsupportedOperationException(); // } // // /** // * Throws UnsupportedOperationException // */ // @Override // public void setImageURI(Uri uri) { // throw new UnsupportedOperationException(); // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/PerfListener.java // public class PerfListener { // private long mSumOfWaitTime; // private long mStartedRequests; // private long mSuccessfulRequests; // private long mCancelledRequests; // private long mFailedRequests; // // public PerfListener() { // mSumOfWaitTime = 0; // mStartedRequests = 0; // mSuccessfulRequests = 0; // mCancelledRequests = 0; // mFailedRequests = 0; // } // // /** // * Called whenever image request finishes successfully, that is whenever final image is set. // */ // public void reportSuccess(long waitTime) { // mSumOfWaitTime += waitTime; // mSuccessfulRequests++; // } // // /** // * Called whenever image request fails, that is whenever failure drawable is set. // */ // public void reportFailure(long waitTime) { // mSumOfWaitTime += waitTime; // mFailedRequests++; // } // // /** // * Called whenever image request is cancelled, that is whenever image view is reused without // * setting final image first // */ // public void reportCancellation(long waitTime) { // mSumOfWaitTime += waitTime; // mCancelledRequests++; // } // // /** // * Called whenver new request is started. // */ // public void reportStart() { // mStartedRequests++; // } // // /** // * @return average wait time, that is sum of reported wait times divided by number of completed // * requests // */ // public long getAverageWaitTime() { // final long completedRequests = getCompletedRequests(); // return completedRequests > 0 ? mSumOfWaitTime / completedRequests : 0; // } // // /** // * @return difference between number of started requests and number of completed requests // */ // public long getOutstandingRequests() { // return mStartedRequests - getCompletedRequests(); // } // // /** // * @return number of cancelled requests // */ // public long getCancelledRequests() { // return mCancelledRequests; // } // // /** // * @return number of completed requests, either by seting final image, failure or cancellation // */ // public long getCompletedRequests() { // return mSuccessfulRequests + mCancelledRequests + mFailedRequests; // } // } // Path: app/src/main/java/com/choices/imagecompare/holders/PicassoHolder.java import android.content.Context; import android.view.View; import com.choices.imagecompare.Drawables; import com.choices.imagecompare.instrumentation.InstrumentedImageView; import com.choices.imagecompare.instrumentation.PerfListener; import com.squareup.picasso.Picasso; /* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.holders; /** * This is the Holder class for the RecycleView to use with Picasso */ public class PicassoHolder extends BaseViewHolder<InstrumentedImageView> { private final Picasso mPicasso; public PicassoHolder( Context context, Picasso picasso, View parent,
InstrumentedImageView view, PerfListener perfListener) {
ChoicesWang/ImageCompare
app/src/main/java/com/choices/imagecompare/holders/PicassoHolder.java
// Path: app/src/main/java/com/choices/imagecompare/Drawables.java // public class Drawables { // public static Drawable sPlaceholderDrawable; // public static Drawable sErrorDrawable; // private Drawables() { // } // // public static void init(final Resources resources) { // if (sPlaceholderDrawable == null) { // sPlaceholderDrawable = resources.getDrawable(R.color.placeholder); // } // if (sErrorDrawable == null) { // sErrorDrawable = resources.getDrawable(R.color.error); // } // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/InstrumentedImageView.java // public class InstrumentedImageView extends ImageView implements Instrumented { // // private final Instrumentation mInstrumentation; // // public InstrumentedImageView(final Context context) { // super(context); // mInstrumentation = new Instrumentation(this); // } // // @Override // public void initInstrumentation(final String tag, PerfListener perfListener) { // mInstrumentation.init(tag, perfListener); // // we don't have a better estimate on when to call onStart, so do it here. // mInstrumentation.onStart(); // } // // @Override // public void onDraw(final Canvas canvas) { // super.onDraw(canvas); // mInstrumentation.onDraw(canvas); // } // // @Override // public void setImageDrawable(final Drawable drawable) { // Preconditions.checkNotNull(drawable); // if (drawable == Drawables.sPlaceholderDrawable) { // // ignore // } else if (drawable == Drawables.sErrorDrawable) { // mInstrumentation.onFailure(); // } else { // mInstrumentation.onSuccess(); // } // super.setImageDrawable(drawable); // } // // /** // * Throws UnsupportedOperationException // */ // @Override // public void setImageResource(int resourceId) { // throw new UnsupportedOperationException(); // } // // /** // * Throws UnsupportedOperationException // */ // @Override // public void setImageURI(Uri uri) { // throw new UnsupportedOperationException(); // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/PerfListener.java // public class PerfListener { // private long mSumOfWaitTime; // private long mStartedRequests; // private long mSuccessfulRequests; // private long mCancelledRequests; // private long mFailedRequests; // // public PerfListener() { // mSumOfWaitTime = 0; // mStartedRequests = 0; // mSuccessfulRequests = 0; // mCancelledRequests = 0; // mFailedRequests = 0; // } // // /** // * Called whenever image request finishes successfully, that is whenever final image is set. // */ // public void reportSuccess(long waitTime) { // mSumOfWaitTime += waitTime; // mSuccessfulRequests++; // } // // /** // * Called whenever image request fails, that is whenever failure drawable is set. // */ // public void reportFailure(long waitTime) { // mSumOfWaitTime += waitTime; // mFailedRequests++; // } // // /** // * Called whenever image request is cancelled, that is whenever image view is reused without // * setting final image first // */ // public void reportCancellation(long waitTime) { // mSumOfWaitTime += waitTime; // mCancelledRequests++; // } // // /** // * Called whenver new request is started. // */ // public void reportStart() { // mStartedRequests++; // } // // /** // * @return average wait time, that is sum of reported wait times divided by number of completed // * requests // */ // public long getAverageWaitTime() { // final long completedRequests = getCompletedRequests(); // return completedRequests > 0 ? mSumOfWaitTime / completedRequests : 0; // } // // /** // * @return difference between number of started requests and number of completed requests // */ // public long getOutstandingRequests() { // return mStartedRequests - getCompletedRequests(); // } // // /** // * @return number of cancelled requests // */ // public long getCancelledRequests() { // return mCancelledRequests; // } // // /** // * @return number of completed requests, either by seting final image, failure or cancellation // */ // public long getCompletedRequests() { // return mSuccessfulRequests + mCancelledRequests + mFailedRequests; // } // }
import android.content.Context; import android.view.View; import com.choices.imagecompare.Drawables; import com.choices.imagecompare.instrumentation.InstrumentedImageView; import com.choices.imagecompare.instrumentation.PerfListener; import com.squareup.picasso.Picasso;
/* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.holders; /** * This is the Holder class for the RecycleView to use with Picasso */ public class PicassoHolder extends BaseViewHolder<InstrumentedImageView> { private final Picasso mPicasso; public PicassoHolder( Context context, Picasso picasso, View parent, InstrumentedImageView view, PerfListener perfListener) { super(context, parent, view, perfListener); mPicasso = picasso; } @Override protected void onBind(String uri) { mPicasso.load(uri)
// Path: app/src/main/java/com/choices/imagecompare/Drawables.java // public class Drawables { // public static Drawable sPlaceholderDrawable; // public static Drawable sErrorDrawable; // private Drawables() { // } // // public static void init(final Resources resources) { // if (sPlaceholderDrawable == null) { // sPlaceholderDrawable = resources.getDrawable(R.color.placeholder); // } // if (sErrorDrawable == null) { // sErrorDrawable = resources.getDrawable(R.color.error); // } // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/InstrumentedImageView.java // public class InstrumentedImageView extends ImageView implements Instrumented { // // private final Instrumentation mInstrumentation; // // public InstrumentedImageView(final Context context) { // super(context); // mInstrumentation = new Instrumentation(this); // } // // @Override // public void initInstrumentation(final String tag, PerfListener perfListener) { // mInstrumentation.init(tag, perfListener); // // we don't have a better estimate on when to call onStart, so do it here. // mInstrumentation.onStart(); // } // // @Override // public void onDraw(final Canvas canvas) { // super.onDraw(canvas); // mInstrumentation.onDraw(canvas); // } // // @Override // public void setImageDrawable(final Drawable drawable) { // Preconditions.checkNotNull(drawable); // if (drawable == Drawables.sPlaceholderDrawable) { // // ignore // } else if (drawable == Drawables.sErrorDrawable) { // mInstrumentation.onFailure(); // } else { // mInstrumentation.onSuccess(); // } // super.setImageDrawable(drawable); // } // // /** // * Throws UnsupportedOperationException // */ // @Override // public void setImageResource(int resourceId) { // throw new UnsupportedOperationException(); // } // // /** // * Throws UnsupportedOperationException // */ // @Override // public void setImageURI(Uri uri) { // throw new UnsupportedOperationException(); // } // } // // Path: app/src/main/java/com/choices/imagecompare/instrumentation/PerfListener.java // public class PerfListener { // private long mSumOfWaitTime; // private long mStartedRequests; // private long mSuccessfulRequests; // private long mCancelledRequests; // private long mFailedRequests; // // public PerfListener() { // mSumOfWaitTime = 0; // mStartedRequests = 0; // mSuccessfulRequests = 0; // mCancelledRequests = 0; // mFailedRequests = 0; // } // // /** // * Called whenever image request finishes successfully, that is whenever final image is set. // */ // public void reportSuccess(long waitTime) { // mSumOfWaitTime += waitTime; // mSuccessfulRequests++; // } // // /** // * Called whenever image request fails, that is whenever failure drawable is set. // */ // public void reportFailure(long waitTime) { // mSumOfWaitTime += waitTime; // mFailedRequests++; // } // // /** // * Called whenever image request is cancelled, that is whenever image view is reused without // * setting final image first // */ // public void reportCancellation(long waitTime) { // mSumOfWaitTime += waitTime; // mCancelledRequests++; // } // // /** // * Called whenver new request is started. // */ // public void reportStart() { // mStartedRequests++; // } // // /** // * @return average wait time, that is sum of reported wait times divided by number of completed // * requests // */ // public long getAverageWaitTime() { // final long completedRequests = getCompletedRequests(); // return completedRequests > 0 ? mSumOfWaitTime / completedRequests : 0; // } // // /** // * @return difference between number of started requests and number of completed requests // */ // public long getOutstandingRequests() { // return mStartedRequests - getCompletedRequests(); // } // // /** // * @return number of cancelled requests // */ // public long getCancelledRequests() { // return mCancelledRequests; // } // // /** // * @return number of completed requests, either by seting final image, failure or cancellation // */ // public long getCompletedRequests() { // return mSuccessfulRequests + mCancelledRequests + mFailedRequests; // } // } // Path: app/src/main/java/com/choices/imagecompare/holders/PicassoHolder.java import android.content.Context; import android.view.View; import com.choices.imagecompare.Drawables; import com.choices.imagecompare.instrumentation.InstrumentedImageView; import com.choices.imagecompare.instrumentation.PerfListener; import com.squareup.picasso.Picasso; /* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * 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 * FACEBOOK 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 com.choices.imagecompare.holders; /** * This is the Holder class for the RecycleView to use with Picasso */ public class PicassoHolder extends BaseViewHolder<InstrumentedImageView> { private final Picasso mPicasso; public PicassoHolder( Context context, Picasso picasso, View parent, InstrumentedImageView view, PerfListener perfListener) { super(context, parent, view, perfListener); mPicasso = picasso; } @Override protected void onBind(String uri) { mPicasso.load(uri)
.placeholder(Drawables.sPlaceholderDrawable)
evgeniy-polyakov/jsfl-support
JSFLSupport 3.0/src/org/jsflsupport/actions/RunJSFLFileAction.java
// Path: JSFLSupport 1.0/src/org/jsflsupport/JSFLFileType.java // public class JSFLFileType extends LanguageFileType { // // private static final Icon ICON = IconLoader.getIcon("/org/jsflsupport/icons/jsfl.png"); // public static final JSFLFileType INSTANCE = new JSFLFileType(); // // public JSFLFileType() { // super(JavascriptLanguage.INSTANCE); // } // // @NotNull // public String getName() { // return "JSFL"; // } // // @NotNull // public String getDescription() { // return "JSFL Files"; // } // // @NotNull // public String getDefaultExtension() { // return "jsfl"; // } // // public Icon getIcon() { // return ICON; // } // }
import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.vfs.VirtualFile; import org.jsflsupport.JSFLFileType; import java.awt.*; import java.io.File; import java.io.IOException;
package org.jsflsupport.actions; /* * Copyright 2011 Evgeniy Polyakov * * 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. */ public class RunJSFLFileAction extends AnAction { @Override public void actionPerformed(AnActionEvent _anActionEvent) { VirtualFile file = _anActionEvent.getData(PlatformDataKeys.VIRTUAL_FILE);
// Path: JSFLSupport 1.0/src/org/jsflsupport/JSFLFileType.java // public class JSFLFileType extends LanguageFileType { // // private static final Icon ICON = IconLoader.getIcon("/org/jsflsupport/icons/jsfl.png"); // public static final JSFLFileType INSTANCE = new JSFLFileType(); // // public JSFLFileType() { // super(JavascriptLanguage.INSTANCE); // } // // @NotNull // public String getName() { // return "JSFL"; // } // // @NotNull // public String getDescription() { // return "JSFL Files"; // } // // @NotNull // public String getDefaultExtension() { // return "jsfl"; // } // // public Icon getIcon() { // return ICON; // } // } // Path: JSFLSupport 3.0/src/org/jsflsupport/actions/RunJSFLFileAction.java import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.vfs.VirtualFile; import org.jsflsupport.JSFLFileType; import java.awt.*; import java.io.File; import java.io.IOException; package org.jsflsupport.actions; /* * Copyright 2011 Evgeniy Polyakov * * 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. */ public class RunJSFLFileAction extends AnAction { @Override public void actionPerformed(AnActionEvent _anActionEvent) { VirtualFile file = _anActionEvent.getData(PlatformDataKeys.VIRTUAL_FILE);
if (file != null && file.getFileType() instanceof JSFLFileType) {
evgeniy-polyakov/jsfl-support
JSFLSupport/src/org/jsflsupport/actions/CreateJSFLFileAction.java
// Path: JSFLSupport 1.0/src/org/jsflsupport/JSFLFileType.java // public class JSFLFileType extends LanguageFileType { // // private static final Icon ICON = IconLoader.getIcon("/org/jsflsupport/icons/jsfl.png"); // public static final JSFLFileType INSTANCE = new JSFLFileType(); // // public JSFLFileType() { // super(JavascriptLanguage.INSTANCE); // } // // @NotNull // public String getName() { // return "JSFL"; // } // // @NotNull // public String getDescription() { // return "JSFL Files"; // } // // @NotNull // public String getDefaultExtension() { // return "jsfl"; // } // // public Icon getIcon() { // return ICON; // } // }
import com.intellij.ide.actions.CreateFileFromTemplateAction; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDirectory; import org.jetbrains.annotations.NotNull; import org.jsflsupport.JSFLFileType;
/* * Copyright 2011 Evgeniy Polyakov * * 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 org.jsflsupport.actions; public class CreateJSFLFileAction extends CreateFileFromTemplateAction { public CreateJSFLFileAction() {
// Path: JSFLSupport 1.0/src/org/jsflsupport/JSFLFileType.java // public class JSFLFileType extends LanguageFileType { // // private static final Icon ICON = IconLoader.getIcon("/org/jsflsupport/icons/jsfl.png"); // public static final JSFLFileType INSTANCE = new JSFLFileType(); // // public JSFLFileType() { // super(JavascriptLanguage.INSTANCE); // } // // @NotNull // public String getName() { // return "JSFL"; // } // // @NotNull // public String getDescription() { // return "JSFL Files"; // } // // @NotNull // public String getDefaultExtension() { // return "jsfl"; // } // // public Icon getIcon() { // return ICON; // } // } // Path: JSFLSupport/src/org/jsflsupport/actions/CreateJSFLFileAction.java import com.intellij.ide.actions.CreateFileFromTemplateAction; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDirectory; import org.jetbrains.annotations.NotNull; import org.jsflsupport.JSFLFileType; /* * Copyright 2011 Evgeniy Polyakov * * 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 org.jsflsupport.actions; public class CreateJSFLFileAction extends CreateFileFromTemplateAction { public CreateJSFLFileAction() {
super("JSFL File", "Creates a JSFL file from the specified template", JSFLFileType.INSTANCE.getIcon());
evgeniy-polyakov/jsfl-support
JSFLSupport/src/org/jsflsupport/JSFLFileType.java
// Path: JSFLSupport/src/org/jsflsupport/lang/JS16SupportLoader.java // public interface JS16SupportLoader { // DialectOptionHolder DIALECT_OPTION_HOLDER = new JS16DialectOptionHolder(); // JSLanguageDialect LANGUAGE_DIALECT = new JS16LanguageDialect(); // JSFileElementType FILE_ELEMENT_TYPE = JSFileElementType.create(JS16SupportLoader.LANGUAGE_DIALECT); // }
import com.intellij.lang.javascript.JSLanguageDialect; import com.intellij.lang.javascript.types.JavaScriptDialectFileType; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.ui.IconManager; import org.jetbrains.annotations.NotNull; import org.jsflsupport.lang.JS16SupportLoader; import javax.swing.*;
/* * Copyright 2011 Evgeniy Polyakov * * 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 org.jsflsupport; public class JSFLFileType extends LanguageFileType implements JavaScriptDialectFileType { private static final Icon ICON = IconManager.getInstance().getIcon("/org/jsflsupport/icons/jsfl.svg", JSFLFileType.class); public static final JSFLFileType INSTANCE = new JSFLFileType(); public JSFLFileType() {
// Path: JSFLSupport/src/org/jsflsupport/lang/JS16SupportLoader.java // public interface JS16SupportLoader { // DialectOptionHolder DIALECT_OPTION_HOLDER = new JS16DialectOptionHolder(); // JSLanguageDialect LANGUAGE_DIALECT = new JS16LanguageDialect(); // JSFileElementType FILE_ELEMENT_TYPE = JSFileElementType.create(JS16SupportLoader.LANGUAGE_DIALECT); // } // Path: JSFLSupport/src/org/jsflsupport/JSFLFileType.java import com.intellij.lang.javascript.JSLanguageDialect; import com.intellij.lang.javascript.types.JavaScriptDialectFileType; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.ui.IconManager; import org.jetbrains.annotations.NotNull; import org.jsflsupport.lang.JS16SupportLoader; import javax.swing.*; /* * Copyright 2011 Evgeniy Polyakov * * 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 org.jsflsupport; public class JSFLFileType extends LanguageFileType implements JavaScriptDialectFileType { private static final Icon ICON = IconManager.getInstance().getIcon("/org/jsflsupport/icons/jsfl.svg", JSFLFileType.class); public static final JSFLFileType INSTANCE = new JSFLFileType(); public JSFLFileType() {
super(JS16SupportLoader.LANGUAGE_DIALECT);
evgeniy-polyakov/jsfl-support
JSFLSupport/src/org/jsflsupport/JSFLSyntaxHighlighterProvider.java
// Path: JSFLSupport/src/org/jsflsupport/lang/JS16SupportLoader.java // public interface JS16SupportLoader { // DialectOptionHolder DIALECT_OPTION_HOLDER = new JS16DialectOptionHolder(); // JSLanguageDialect LANGUAGE_DIALECT = new JS16LanguageDialect(); // JSFileElementType FILE_ELEMENT_TYPE = JSFileElementType.create(JS16SupportLoader.LANGUAGE_DIALECT); // }
import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory; import com.intellij.openapi.fileTypes.SyntaxHighlighterProvider; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jsflsupport.lang.JS16SupportLoader;
/* * Copyright 2011 Evgeniy Polyakov * * 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 org.jsflsupport; public class JSFLSyntaxHighlighterProvider implements SyntaxHighlighterProvider { public SyntaxHighlighter create(@NotNull FileType fileType, Project project, VirtualFile virtualFile) {
// Path: JSFLSupport/src/org/jsflsupport/lang/JS16SupportLoader.java // public interface JS16SupportLoader { // DialectOptionHolder DIALECT_OPTION_HOLDER = new JS16DialectOptionHolder(); // JSLanguageDialect LANGUAGE_DIALECT = new JS16LanguageDialect(); // JSFileElementType FILE_ELEMENT_TYPE = JSFileElementType.create(JS16SupportLoader.LANGUAGE_DIALECT); // } // Path: JSFLSupport/src/org/jsflsupport/JSFLSyntaxHighlighterProvider.java import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory; import com.intellij.openapi.fileTypes.SyntaxHighlighterProvider; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jsflsupport.lang.JS16SupportLoader; /* * Copyright 2011 Evgeniy Polyakov * * 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 org.jsflsupport; public class JSFLSyntaxHighlighterProvider implements SyntaxHighlighterProvider { public SyntaxHighlighter create(@NotNull FileType fileType, Project project, VirtualFile virtualFile) {
return SyntaxHighlighterFactory.getSyntaxHighlighter(JS16SupportLoader.LANGUAGE_DIALECT, project, virtualFile);
evgeniy-polyakov/jsfl-support
JSFLSupport/src/org/jsflsupport/actions/RunJSFLFileAction.java
// Path: JSFLSupport 1.0/src/org/jsflsupport/JSFLFileType.java // public class JSFLFileType extends LanguageFileType { // // private static final Icon ICON = IconLoader.getIcon("/org/jsflsupport/icons/jsfl.png"); // public static final JSFLFileType INSTANCE = new JSFLFileType(); // // public JSFLFileType() { // super(JavascriptLanguage.INSTANCE); // } // // @NotNull // public String getName() { // return "JSFL"; // } // // @NotNull // public String getDescription() { // return "JSFL Files"; // } // // @NotNull // public String getDefaultExtension() { // return "jsfl"; // } // // public Icon getIcon() { // return ICON; // } // }
import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.vfs.VirtualFile; import org.jsflsupport.JSFLFileType; import java.awt.*; import java.io.File; import java.io.IOException;
/* * Copyright 2011 Evgeniy Polyakov * * 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 org.jsflsupport.actions; public class RunJSFLFileAction extends AnAction { @Override public void actionPerformed(AnActionEvent _anActionEvent) { VirtualFile file = _anActionEvent.getData(PlatformDataKeys.VIRTUAL_FILE);
// Path: JSFLSupport 1.0/src/org/jsflsupport/JSFLFileType.java // public class JSFLFileType extends LanguageFileType { // // private static final Icon ICON = IconLoader.getIcon("/org/jsflsupport/icons/jsfl.png"); // public static final JSFLFileType INSTANCE = new JSFLFileType(); // // public JSFLFileType() { // super(JavascriptLanguage.INSTANCE); // } // // @NotNull // public String getName() { // return "JSFL"; // } // // @NotNull // public String getDescription() { // return "JSFL Files"; // } // // @NotNull // public String getDefaultExtension() { // return "jsfl"; // } // // public Icon getIcon() { // return ICON; // } // } // Path: JSFLSupport/src/org/jsflsupport/actions/RunJSFLFileAction.java import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.vfs.VirtualFile; import org.jsflsupport.JSFLFileType; import java.awt.*; import java.io.File; import java.io.IOException; /* * Copyright 2011 Evgeniy Polyakov * * 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 org.jsflsupport.actions; public class RunJSFLFileAction extends AnAction { @Override public void actionPerformed(AnActionEvent _anActionEvent) { VirtualFile file = _anActionEvent.getData(PlatformDataKeys.VIRTUAL_FILE);
if (file != null && file.getFileType() instanceof JSFLFileType) {
evgeniy-polyakov/jsfl-support
JSFLSupport 3.0/src/org/jsflsupport/actions/CreateJSFLFileAction.java
// Path: JSFLSupport 1.0/src/org/jsflsupport/JSFLFileType.java // public class JSFLFileType extends LanguageFileType { // // private static final Icon ICON = IconLoader.getIcon("/org/jsflsupport/icons/jsfl.png"); // public static final JSFLFileType INSTANCE = new JSFLFileType(); // // public JSFLFileType() { // super(JavascriptLanguage.INSTANCE); // } // // @NotNull // public String getName() { // return "JSFL"; // } // // @NotNull // public String getDescription() { // return "JSFL Files"; // } // // @NotNull // public String getDefaultExtension() { // return "jsfl"; // } // // public Icon getIcon() { // return ICON; // } // }
import com.intellij.ide.actions.CreateFileFromTemplateAction; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDirectory; import org.jsflsupport.JSFLFileType;
package org.jsflsupport.actions; /* * Copyright 2011 Evgeniy Polyakov * * 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. */ public class CreateJSFLFileAction extends CreateFileFromTemplateAction { public CreateJSFLFileAction() {
// Path: JSFLSupport 1.0/src/org/jsflsupport/JSFLFileType.java // public class JSFLFileType extends LanguageFileType { // // private static final Icon ICON = IconLoader.getIcon("/org/jsflsupport/icons/jsfl.png"); // public static final JSFLFileType INSTANCE = new JSFLFileType(); // // public JSFLFileType() { // super(JavascriptLanguage.INSTANCE); // } // // @NotNull // public String getName() { // return "JSFL"; // } // // @NotNull // public String getDescription() { // return "JSFL Files"; // } // // @NotNull // public String getDefaultExtension() { // return "jsfl"; // } // // public Icon getIcon() { // return ICON; // } // } // Path: JSFLSupport 3.0/src/org/jsflsupport/actions/CreateJSFLFileAction.java import com.intellij.ide.actions.CreateFileFromTemplateAction; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDirectory; import org.jsflsupport.JSFLFileType; package org.jsflsupport.actions; /* * Copyright 2011 Evgeniy Polyakov * * 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. */ public class CreateJSFLFileAction extends CreateFileFromTemplateAction { public CreateJSFLFileAction() {
super("JSFL File", "Creates a JSFL file from the specified template", JSFLFileType.INSTANCE.getIcon());
idega/is.idega.block.family
src/java/is/idega/block/family/data/Child.java
// Path: src/java/is/idega/block/family/business/NoCustodianFound.java // public class NoCustodianFound extends javax.ejb.FinderException { // // public NoCustodianFound(String UserName) { // super("No custodian found for user "+UserName); // } // }
import is.idega.block.family.business.NoCustodianFound; import java.util.Collection; import java.util.Collections; import java.util.List; import com.idega.data.IDOEntity; import com.idega.user.data.User;
package is.idega.block.family.data; public interface Child extends IDOEntity, User { /** * * @return all siblings for this {@link Child} or * {@link Collections#emptyList()} on failure; */ public Collection<User> getSiblings(); /** * @see is.idega.block.family.data.ChildBMPBean#getCustodians */
// Path: src/java/is/idega/block/family/business/NoCustodianFound.java // public class NoCustodianFound extends javax.ejb.FinderException { // // public NoCustodianFound(String UserName) { // super("No custodian found for user "+UserName); // } // } // Path: src/java/is/idega/block/family/data/Child.java import is.idega.block.family.business.NoCustodianFound; import java.util.Collection; import java.util.Collections; import java.util.List; import com.idega.data.IDOEntity; import com.idega.user.data.User; package is.idega.block.family.data; public interface Child extends IDOEntity, User { /** * * @return all siblings for this {@link Child} or * {@link Collections#emptyList()} on failure; */ public Collection<User> getSiblings(); /** * @see is.idega.block.family.data.ChildBMPBean#getCustodians */
public Collection<Custodian> getCustodians() throws NoCustodianFound;
idega/is.idega.block.family
src/java/is/idega/block/family/data/Custodian.java
// Path: src/java/is/idega/block/family/business/NoChildrenFound.java // public class NoChildrenFound extends javax.ejb.FinderException { // // public NoChildrenFound(String UserName) { // super("No children found for user "+UserName); // } // } // // Path: src/java/is/idega/block/family/business/NoCohabitantFound.java // public class NoCohabitantFound extends javax.ejb.FinderException { // // public NoCohabitantFound(String UserName) { // super("No cohabitant found for user "+UserName); // } // } // // Path: src/java/is/idega/block/family/business/NoSpouseFound.java // public class NoSpouseFound extends javax.ejb.FinderException { // // public NoSpouseFound(String UserName) { // super("No spouse found for user "+UserName); // } // }
import is.idega.block.family.business.NoChildrenFound; import is.idega.block.family.business.NoCohabitantFound; import is.idega.block.family.business.NoSpouseFound; import java.sql.Date; import java.util.Collection; import com.idega.core.contact.data.Email; import com.idega.core.contact.data.Phone; import com.idega.data.IDOEntity; import com.idega.user.business.NoEmailFoundException; import com.idega.user.business.NoPhoneFoundException; import com.idega.user.data.User;
/* * $Id$ * Created on Apr 1, 2006 * * Copyright (C) 2006 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package is.idega.block.family.data; /** * <p> * TODO laddi Describe Type Custodian * </p> * Last modified: $Date$ by $Author$ * * @author <a href="mailto:[email protected]">laddi</a> * @version $Revision$ */ public interface Custodian extends IDOEntity, User { /** * @see is.idega.block.family.data.CustodianBMPBean#getChildrenInCustody */ public Collection<User> getChildrenInCustody() throws NoChildrenFound; /** * @see is.idega.block.family.data.CustodianBMPBean#isCustodianOf */ public boolean isCustodianOf(Child child); /** * @see is.idega.block.family.data.CustodianBMPBean#getSpouse */
// Path: src/java/is/idega/block/family/business/NoChildrenFound.java // public class NoChildrenFound extends javax.ejb.FinderException { // // public NoChildrenFound(String UserName) { // super("No children found for user "+UserName); // } // } // // Path: src/java/is/idega/block/family/business/NoCohabitantFound.java // public class NoCohabitantFound extends javax.ejb.FinderException { // // public NoCohabitantFound(String UserName) { // super("No cohabitant found for user "+UserName); // } // } // // Path: src/java/is/idega/block/family/business/NoSpouseFound.java // public class NoSpouseFound extends javax.ejb.FinderException { // // public NoSpouseFound(String UserName) { // super("No spouse found for user "+UserName); // } // } // Path: src/java/is/idega/block/family/data/Custodian.java import is.idega.block.family.business.NoChildrenFound; import is.idega.block.family.business.NoCohabitantFound; import is.idega.block.family.business.NoSpouseFound; import java.sql.Date; import java.util.Collection; import com.idega.core.contact.data.Email; import com.idega.core.contact.data.Phone; import com.idega.data.IDOEntity; import com.idega.user.business.NoEmailFoundException; import com.idega.user.business.NoPhoneFoundException; import com.idega.user.data.User; /* * $Id$ * Created on Apr 1, 2006 * * Copyright (C) 2006 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package is.idega.block.family.data; /** * <p> * TODO laddi Describe Type Custodian * </p> * Last modified: $Date$ by $Author$ * * @author <a href="mailto:[email protected]">laddi</a> * @version $Revision$ */ public interface Custodian extends IDOEntity, User { /** * @see is.idega.block.family.data.CustodianBMPBean#getChildrenInCustody */ public Collection<User> getChildrenInCustody() throws NoChildrenFound; /** * @see is.idega.block.family.data.CustodianBMPBean#isCustodianOf */ public boolean isCustodianOf(Child child); /** * @see is.idega.block.family.data.CustodianBMPBean#getSpouse */
public User getSpouse() throws NoSpouseFound;
idega/is.idega.block.family
src/java/is/idega/block/family/data/Custodian.java
// Path: src/java/is/idega/block/family/business/NoChildrenFound.java // public class NoChildrenFound extends javax.ejb.FinderException { // // public NoChildrenFound(String UserName) { // super("No children found for user "+UserName); // } // } // // Path: src/java/is/idega/block/family/business/NoCohabitantFound.java // public class NoCohabitantFound extends javax.ejb.FinderException { // // public NoCohabitantFound(String UserName) { // super("No cohabitant found for user "+UserName); // } // } // // Path: src/java/is/idega/block/family/business/NoSpouseFound.java // public class NoSpouseFound extends javax.ejb.FinderException { // // public NoSpouseFound(String UserName) { // super("No spouse found for user "+UserName); // } // }
import is.idega.block.family.business.NoChildrenFound; import is.idega.block.family.business.NoCohabitantFound; import is.idega.block.family.business.NoSpouseFound; import java.sql.Date; import java.util.Collection; import com.idega.core.contact.data.Email; import com.idega.core.contact.data.Phone; import com.idega.data.IDOEntity; import com.idega.user.business.NoEmailFoundException; import com.idega.user.business.NoPhoneFoundException; import com.idega.user.data.User;
/* * $Id$ * Created on Apr 1, 2006 * * Copyright (C) 2006 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package is.idega.block.family.data; /** * <p> * TODO laddi Describe Type Custodian * </p> * Last modified: $Date$ by $Author$ * * @author <a href="mailto:[email protected]">laddi</a> * @version $Revision$ */ public interface Custodian extends IDOEntity, User { /** * @see is.idega.block.family.data.CustodianBMPBean#getChildrenInCustody */ public Collection<User> getChildrenInCustody() throws NoChildrenFound; /** * @see is.idega.block.family.data.CustodianBMPBean#isCustodianOf */ public boolean isCustodianOf(Child child); /** * @see is.idega.block.family.data.CustodianBMPBean#getSpouse */ public User getSpouse() throws NoSpouseFound; /** * @see is.idega.block.family.data.CustodianBMPBean#getCohabitant */
// Path: src/java/is/idega/block/family/business/NoChildrenFound.java // public class NoChildrenFound extends javax.ejb.FinderException { // // public NoChildrenFound(String UserName) { // super("No children found for user "+UserName); // } // } // // Path: src/java/is/idega/block/family/business/NoCohabitantFound.java // public class NoCohabitantFound extends javax.ejb.FinderException { // // public NoCohabitantFound(String UserName) { // super("No cohabitant found for user "+UserName); // } // } // // Path: src/java/is/idega/block/family/business/NoSpouseFound.java // public class NoSpouseFound extends javax.ejb.FinderException { // // public NoSpouseFound(String UserName) { // super("No spouse found for user "+UserName); // } // } // Path: src/java/is/idega/block/family/data/Custodian.java import is.idega.block.family.business.NoChildrenFound; import is.idega.block.family.business.NoCohabitantFound; import is.idega.block.family.business.NoSpouseFound; import java.sql.Date; import java.util.Collection; import com.idega.core.contact.data.Email; import com.idega.core.contact.data.Phone; import com.idega.data.IDOEntity; import com.idega.user.business.NoEmailFoundException; import com.idega.user.business.NoPhoneFoundException; import com.idega.user.data.User; /* * $Id$ * Created on Apr 1, 2006 * * Copyright (C) 2006 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package is.idega.block.family.data; /** * <p> * TODO laddi Describe Type Custodian * </p> * Last modified: $Date$ by $Author$ * * @author <a href="mailto:[email protected]">laddi</a> * @version $Revision$ */ public interface Custodian extends IDOEntity, User { /** * @see is.idega.block.family.data.CustodianBMPBean#getChildrenInCustody */ public Collection<User> getChildrenInCustody() throws NoChildrenFound; /** * @see is.idega.block.family.data.CustodianBMPBean#isCustodianOf */ public boolean isCustodianOf(Child child); /** * @see is.idega.block.family.data.CustodianBMPBean#getSpouse */ public User getSpouse() throws NoSpouseFound; /** * @see is.idega.block.family.data.CustodianBMPBean#getCohabitant */
public User getCohabitant() throws NoCohabitantFound;
idega/is.idega.block.family
src/java/is/idega/block/family/IWBundleStarter.java
// Path: src/java/is/idega/block/family/business/LinkToFamilyLogicImpl.java // public class LinkToFamilyLogicImpl implements LinkToFamilyLogic { // // public Collection getCustodiansFor(User user, IWContext iwc) { // Collection custodians = null; // FamilyLogic familyLogic = null; // try { // familyLogic = (FamilyLogic) com.idega.business.IBOLookup.getServiceInstance(iwc, FamilyLogic.class); // custodians = familyLogic.getCustodiansFor(user); // } // catch (NoCustodianFound e) { // //No custodian found for user. Ignoring exception // } // catch (Exception e) { // e.printStackTrace(); // } // return custodians; // } // }
import is.idega.block.family.business.LinkToFamilyLogicImpl; import javax.ejb.CreateException; import javax.ejb.FinderException; import com.idega.data.IDOLookupException; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWBundleStartable; import com.idega.repository.data.ImplementorRepository; import com.idega.user.data.GroupRelationType; import com.idega.user.data.GroupRelationTypeHome; import com.idega.user.presentation.LinkToFamilyLogic;
package is.idega.block.family; /** * <p>Title: idegaWeb</p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2003</p> * <p>Company: idega Software</p> * @author <a href="[email protected]">Thomas Hilbig</a> * @version 1.0 * Created on Jun 10, 2004 */ public class IWBundleStarter implements IWBundleStartable { public void start(IWBundle starterBundle) { insertStartData(); ImplementorRepository repository = ImplementorRepository.getInstance();
// Path: src/java/is/idega/block/family/business/LinkToFamilyLogicImpl.java // public class LinkToFamilyLogicImpl implements LinkToFamilyLogic { // // public Collection getCustodiansFor(User user, IWContext iwc) { // Collection custodians = null; // FamilyLogic familyLogic = null; // try { // familyLogic = (FamilyLogic) com.idega.business.IBOLookup.getServiceInstance(iwc, FamilyLogic.class); // custodians = familyLogic.getCustodiansFor(user); // } // catch (NoCustodianFound e) { // //No custodian found for user. Ignoring exception // } // catch (Exception e) { // e.printStackTrace(); // } // return custodians; // } // } // Path: src/java/is/idega/block/family/IWBundleStarter.java import is.idega.block.family.business.LinkToFamilyLogicImpl; import javax.ejb.CreateException; import javax.ejb.FinderException; import com.idega.data.IDOLookupException; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWBundleStartable; import com.idega.repository.data.ImplementorRepository; import com.idega.user.data.GroupRelationType; import com.idega.user.data.GroupRelationTypeHome; import com.idega.user.presentation.LinkToFamilyLogic; package is.idega.block.family; /** * <p>Title: idegaWeb</p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2003</p> * <p>Company: idega Software</p> * @author <a href="[email protected]">Thomas Hilbig</a> * @version 1.0 * Created on Jun 10, 2004 */ public class IWBundleStarter implements IWBundleStartable { public void start(IWBundle starterBundle) { insertStartData(); ImplementorRepository repository = ImplementorRepository.getInstance();
repository.addImplementor(LinkToFamilyLogic.class, LinkToFamilyLogicImpl.class);
1fish2/BBQTimer
app/src/androidTest/java/com/onefishtwo/bbqtimer/InAppUITest.java
// Path: app/src/androidTest/java/com/onefishtwo/bbqtimer/CustomMatchers.java // @SuppressWarnings("SpellCheckingInspection") // @NonNull // static Matcher<View> withCompoundDrawable(@DrawableRes final int resourceId) { // return new BoundedMatcher<View, TextView>(TextView.class) { // @Override // public void describeTo(@NonNull Description description) { // description.appendText("has compound drawable resource " + resourceId); // } // // @Override // public boolean matchesSafely(@NonNull TextView textView) { // for (Drawable drawable : textView.getCompoundDrawables()) { // if (sameBitmap(textView.getContext(), drawable, resourceId)) { // return true; // } // } // return false; // } // }; // } // // Path: app/src/androidTest/java/com/onefishtwo/bbqtimer/CustomViewActions.java // @NonNull // static ViewAction waitMsec(final long msec) { // return new ViewAction() { // @NonNull // @Override // public Matcher<View> getConstraints() { // return any(View.class); // } // // @NonNull // @Override // public String getDescription() { // return "Wait " + msec + " msec."; // } // // @Override // public void perform(@NonNull UiController uiController, View view) { // uiController.loopMainThreadForAtLeast(msec); // } // }; // } // // Path: app/src/androidTest/java/com/onefishtwo/bbqtimer/TimeIntervalMatcher.java // @NonNull // public static TimeIntervalMatcher inTimeInterval(long min, long max) { // return new TimeIntervalMatcher(min, max); // }
import android.content.Context; import android.os.Build; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import androidx.annotation.NonNull; import androidx.test.core.app.ApplicationProvider; import androidx.test.espresso.ViewInteraction; import androidx.test.ext.junit.rules.ActivityScenarioRule; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.LargeTest; import androidx.test.platform.app.InstrumentationRegistry; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.action.ViewActions.pressImeActionButton; import static androidx.test.espresso.action.ViewActions.replaceText; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.hasFocus; import static androidx.test.espresso.matcher.ViewMatchers.isChecked; import static androidx.test.espresso.matcher.ViewMatchers.isCompletelyDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.isEnabled; import static androidx.test.espresso.matcher.ViewMatchers.isFocusable; import static androidx.test.espresso.matcher.ViewMatchers.isFocused; import static androidx.test.espresso.matcher.ViewMatchers.isNotChecked; import static androidx.test.espresso.matcher.ViewMatchers.isNotEnabled; import static androidx.test.espresso.matcher.ViewMatchers.isNotFocused; import static androidx.test.espresso.matcher.ViewMatchers.withClassName; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withParent; import static androidx.test.espresso.matcher.ViewMatchers.withText; import static com.onefishtwo.bbqtimer.CustomMatchers.withCompoundDrawable; import static com.onefishtwo.bbqtimer.CustomViewActions.waitMsec; import static com.onefishtwo.bbqtimer.TimeIntervalMatcher.inTimeInterval; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.core.AllOf.allOf; import static org.junit.Assert.assertEquals;
playPauseButton.perform(waitMsec(1000)); playPauseButton.perform(click()); // Pause checkPausedAt(time1); } /** Checks the enable-reminders checkbox and the minutes picker. */ private void checkReminder(boolean expectEnabled) { enableRemindersToggle.check(matches(isCompletelyDisplayed())); minutesPicker.check(matches(isCompletelyDisplayed())); if (expectEnabled) { enableRemindersToggle.check(matches(isChecked())); minutesPicker.check(matches(isEnabled())); minutesPicker.check(matches(isFocusable())); } else { enableRemindersToggle.check(matches(isNotChecked())); minutesPicker.check(matches(isNotEnabled())); if (Build.VERSION.SDK_INT > 27) { // disabled but still has focus on API ≤ 27! minutesPicker.check(matches(isNotFocused())); } } } /** Checks that the UI is in the fully Stopped at 00:00 state. */ private void checkStopped() { playPauseButton.check(matches(isCompletelyDisplayed())); resetButton.check(matches(isCompletelyDisplayed())); stopButton.check(matches(not(isDisplayed()))); timeView.check(matches(withText("00:00.0")));
// Path: app/src/androidTest/java/com/onefishtwo/bbqtimer/CustomMatchers.java // @SuppressWarnings("SpellCheckingInspection") // @NonNull // static Matcher<View> withCompoundDrawable(@DrawableRes final int resourceId) { // return new BoundedMatcher<View, TextView>(TextView.class) { // @Override // public void describeTo(@NonNull Description description) { // description.appendText("has compound drawable resource " + resourceId); // } // // @Override // public boolean matchesSafely(@NonNull TextView textView) { // for (Drawable drawable : textView.getCompoundDrawables()) { // if (sameBitmap(textView.getContext(), drawable, resourceId)) { // return true; // } // } // return false; // } // }; // } // // Path: app/src/androidTest/java/com/onefishtwo/bbqtimer/CustomViewActions.java // @NonNull // static ViewAction waitMsec(final long msec) { // return new ViewAction() { // @NonNull // @Override // public Matcher<View> getConstraints() { // return any(View.class); // } // // @NonNull // @Override // public String getDescription() { // return "Wait " + msec + " msec."; // } // // @Override // public void perform(@NonNull UiController uiController, View view) { // uiController.loopMainThreadForAtLeast(msec); // } // }; // } // // Path: app/src/androidTest/java/com/onefishtwo/bbqtimer/TimeIntervalMatcher.java // @NonNull // public static TimeIntervalMatcher inTimeInterval(long min, long max) { // return new TimeIntervalMatcher(min, max); // } // Path: app/src/androidTest/java/com/onefishtwo/bbqtimer/InAppUITest.java import android.content.Context; import android.os.Build; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import androidx.annotation.NonNull; import androidx.test.core.app.ApplicationProvider; import androidx.test.espresso.ViewInteraction; import androidx.test.ext.junit.rules.ActivityScenarioRule; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.LargeTest; import androidx.test.platform.app.InstrumentationRegistry; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.action.ViewActions.pressImeActionButton; import static androidx.test.espresso.action.ViewActions.replaceText; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.hasFocus; import static androidx.test.espresso.matcher.ViewMatchers.isChecked; import static androidx.test.espresso.matcher.ViewMatchers.isCompletelyDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.isEnabled; import static androidx.test.espresso.matcher.ViewMatchers.isFocusable; import static androidx.test.espresso.matcher.ViewMatchers.isFocused; import static androidx.test.espresso.matcher.ViewMatchers.isNotChecked; import static androidx.test.espresso.matcher.ViewMatchers.isNotEnabled; import static androidx.test.espresso.matcher.ViewMatchers.isNotFocused; import static androidx.test.espresso.matcher.ViewMatchers.withClassName; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withParent; import static androidx.test.espresso.matcher.ViewMatchers.withText; import static com.onefishtwo.bbqtimer.CustomMatchers.withCompoundDrawable; import static com.onefishtwo.bbqtimer.CustomViewActions.waitMsec; import static com.onefishtwo.bbqtimer.TimeIntervalMatcher.inTimeInterval; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.core.AllOf.allOf; import static org.junit.Assert.assertEquals; playPauseButton.perform(waitMsec(1000)); playPauseButton.perform(click()); // Pause checkPausedAt(time1); } /** Checks the enable-reminders checkbox and the minutes picker. */ private void checkReminder(boolean expectEnabled) { enableRemindersToggle.check(matches(isCompletelyDisplayed())); minutesPicker.check(matches(isCompletelyDisplayed())); if (expectEnabled) { enableRemindersToggle.check(matches(isChecked())); minutesPicker.check(matches(isEnabled())); minutesPicker.check(matches(isFocusable())); } else { enableRemindersToggle.check(matches(isNotChecked())); minutesPicker.check(matches(isNotEnabled())); if (Build.VERSION.SDK_INT > 27) { // disabled but still has focus on API ≤ 27! minutesPicker.check(matches(isNotFocused())); } } } /** Checks that the UI is in the fully Stopped at 00:00 state. */ private void checkStopped() { playPauseButton.check(matches(isCompletelyDisplayed())); resetButton.check(matches(isCompletelyDisplayed())); stopButton.check(matches(not(isDisplayed()))); timeView.check(matches(withText("00:00.0")));
playPauseButton.check(matches(withCompoundDrawable(R.drawable.ic_play)));
hanks-zyh/HTextView
htextview-line/src/main/java/com/hanks/htextview/line/LineTextView.java
// Path: htextview-base/src/main/java/com/hanks/htextview/base/AnimationListener.java // public interface AnimationListener { // void onAnimationEnd(HTextView hTextView); // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // }
import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import com.hanks.htextview.base.AnimationListener; import com.hanks.htextview.base.HTextView;
package com.hanks.htextview.line; /** * line effect view * Created by hanks on 2017/3/13. */ public class LineTextView extends HTextView { private LineText lineText; public LineTextView(Context context) { this(context, null); } public LineTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public LineTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr); } @Override
// Path: htextview-base/src/main/java/com/hanks/htextview/base/AnimationListener.java // public interface AnimationListener { // void onAnimationEnd(HTextView hTextView); // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // } // Path: htextview-line/src/main/java/com/hanks/htextview/line/LineTextView.java import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import com.hanks.htextview.base.AnimationListener; import com.hanks.htextview.base.HTextView; package com.hanks.htextview.line; /** * line effect view * Created by hanks on 2017/3/13. */ public class LineTextView extends HTextView { private LineText lineText; public LineTextView(Context context) { this(context, null); } public LineTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public LineTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr); } @Override
public void setAnimationListener(AnimationListener listener) {
hanks-zyh/HTextView
htextview-evaporate/src/main/java/com/hanks/htextview/evaporate/EvaporateTextView.java
// Path: htextview-base/src/main/java/com/hanks/htextview/base/AnimationListener.java // public interface AnimationListener { // void onAnimationEnd(HTextView hTextView); // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // }
import android.content.Context; import android.graphics.Canvas; import android.text.TextUtils; import android.util.AttributeSet; import com.hanks.htextview.base.AnimationListener; import com.hanks.htextview.base.HTextView;
package com.hanks.htextview.evaporate; /** * EvaporateTextView * Created by hanks on 2017/3/16. */ public class EvaporateTextView extends HTextView { private EvaporateText evaporateText; public EvaporateTextView(Context context) { this(context, null); } public EvaporateTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public EvaporateTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr); } @Override
// Path: htextview-base/src/main/java/com/hanks/htextview/base/AnimationListener.java // public interface AnimationListener { // void onAnimationEnd(HTextView hTextView); // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // } // Path: htextview-evaporate/src/main/java/com/hanks/htextview/evaporate/EvaporateTextView.java import android.content.Context; import android.graphics.Canvas; import android.text.TextUtils; import android.util.AttributeSet; import com.hanks.htextview.base.AnimationListener; import com.hanks.htextview.base.HTextView; package com.hanks.htextview.evaporate; /** * EvaporateTextView * Created by hanks on 2017/3/16. */ public class EvaporateTextView extends HTextView { private EvaporateText evaporateText; public EvaporateTextView(Context context) { this(context, null); } public EvaporateTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public EvaporateTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr); } @Override
public void setAnimationListener(AnimationListener listener) {
hanks-zyh/HTextView
htextview-fade/src/main/java/com/hanks/htextview/fade/FadeText.java
// Path: htextview-base/src/main/java/com/hanks/htextview/base/DefaultAnimatorListener.java // public class DefaultAnimatorListener implements Animator.AnimatorListener { // @Override // public void onAnimationStart(Animator animation) { // // no-op // } // // @Override // public void onAnimationEnd(Animator animation) { // // no-op // } // // @Override // public void onAnimationCancel(Animator animation) { // // no-op // } // // @Override // public void onAnimationRepeat(Animator animation) { // // no-op // } // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HText.java // public abstract class HText implements IHText { // // protected int mHeight, mWidth; // protected CharSequence mText, mOldText; // protected TextPaint mPaint, mOldPaint; // protected HTextView mHTextView; // protected List<Float> gapList = new ArrayList<>(); // protected List<Float> oldGapList = new ArrayList<>(); // protected float progress; // 0 ~ 1 // protected float mTextSize; // protected float oldStartX = 0; // protected AnimationListener animationListener; // // public void setProgress(float progress) { // this.progress = progress; // mHTextView.invalidate(); // } // // @Override // public void init(HTextView hTextView, AttributeSet attrs, int defStyle) { // mHTextView = hTextView; // mOldText = ""; // mText = hTextView.getText(); // progress = 1; // // mPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); // mOldPaint = new TextPaint(mPaint); // // mHTextView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { // @Override // public void onGlobalLayout() { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // mHTextView.getViewTreeObserver().removeOnGlobalLayoutListener(this); // } else { // mHTextView.getViewTreeObserver().removeGlobalOnLayoutListener(this); // } // mTextSize = mHTextView.getTextSize(); // mWidth = mHTextView.getWidth(); // mHeight = mHTextView.getHeight(); // oldStartX = 0; // // try { // int layoutDirection = ViewCompat.getLayoutDirection(mHTextView); // // oldStartX = layoutDirection == LAYOUT_DIRECTION_LTR // ? mHTextView.getLayout().getLineLeft(0) // : mHTextView.getLayout().getLineRight(0); // // } catch (Exception e) { // e.printStackTrace(); // } // // initVariables(); // } // }); // prepareAnimate(); // } // // private void prepareAnimate() { // mTextSize = mHTextView.getTextSize(); // mPaint.setTextSize(mTextSize); // mPaint.setColor(mHTextView.getCurrentTextColor()); // mPaint.setTypeface(mHTextView.getTypeface()); // gapList.clear(); // for (int i = 0; i < mText.length(); i++) { // gapList.add(mPaint.measureText(String.valueOf(mText.charAt(i)))); // } // mOldPaint.setTextSize(mTextSize); // mOldPaint.setColor(mHTextView.getCurrentTextColor()); // mOldPaint.setTypeface(mHTextView.getTypeface()); // oldGapList.clear(); // for (int i = 0; i < mOldText.length(); i++) { // oldGapList.add(mOldPaint.measureText(String.valueOf(mOldText.charAt(i)))); // } // } // // @Override // public void animateText(CharSequence text) { // mHTextView.setText(text); // mOldText = mText; // mText = text; // prepareAnimate(); // animatePrepare(text); // animateStart(text); // } // // @Override // public void setAnimationListener(AnimationListener listener) { // animationListener = listener; // } // // @Override // public void onDraw(Canvas canvas) { // drawFrame(canvas); // } // // protected abstract void initVariables(); // // protected abstract void animateStart(CharSequence text); // // protected abstract void animatePrepare(CharSequence text); // // protected abstract void drawFrame(Canvas canvas); // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // }
import android.animation.Animator; import android.animation.ValueAnimator; import android.content.res.TypedArray; import android.graphics.Canvas; import android.text.Layout; import android.util.AttributeSet; import android.view.animation.LinearInterpolator; import com.hanks.htextview.base.DefaultAnimatorListener; import com.hanks.htextview.base.HText; import com.hanks.htextview.base.HTextView; import java.util.ArrayList; import java.util.List; import java.util.Random;
package com.hanks.htextview.fade; /** * fade effect * Created by hanks on 2017/3/14. */ public class FadeText extends HText { private Random random; private int animationDuration; private List<Integer> alphaList; private int DEFAULT_DURATION = 2000; @Override
// Path: htextview-base/src/main/java/com/hanks/htextview/base/DefaultAnimatorListener.java // public class DefaultAnimatorListener implements Animator.AnimatorListener { // @Override // public void onAnimationStart(Animator animation) { // // no-op // } // // @Override // public void onAnimationEnd(Animator animation) { // // no-op // } // // @Override // public void onAnimationCancel(Animator animation) { // // no-op // } // // @Override // public void onAnimationRepeat(Animator animation) { // // no-op // } // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HText.java // public abstract class HText implements IHText { // // protected int mHeight, mWidth; // protected CharSequence mText, mOldText; // protected TextPaint mPaint, mOldPaint; // protected HTextView mHTextView; // protected List<Float> gapList = new ArrayList<>(); // protected List<Float> oldGapList = new ArrayList<>(); // protected float progress; // 0 ~ 1 // protected float mTextSize; // protected float oldStartX = 0; // protected AnimationListener animationListener; // // public void setProgress(float progress) { // this.progress = progress; // mHTextView.invalidate(); // } // // @Override // public void init(HTextView hTextView, AttributeSet attrs, int defStyle) { // mHTextView = hTextView; // mOldText = ""; // mText = hTextView.getText(); // progress = 1; // // mPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); // mOldPaint = new TextPaint(mPaint); // // mHTextView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { // @Override // public void onGlobalLayout() { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // mHTextView.getViewTreeObserver().removeOnGlobalLayoutListener(this); // } else { // mHTextView.getViewTreeObserver().removeGlobalOnLayoutListener(this); // } // mTextSize = mHTextView.getTextSize(); // mWidth = mHTextView.getWidth(); // mHeight = mHTextView.getHeight(); // oldStartX = 0; // // try { // int layoutDirection = ViewCompat.getLayoutDirection(mHTextView); // // oldStartX = layoutDirection == LAYOUT_DIRECTION_LTR // ? mHTextView.getLayout().getLineLeft(0) // : mHTextView.getLayout().getLineRight(0); // // } catch (Exception e) { // e.printStackTrace(); // } // // initVariables(); // } // }); // prepareAnimate(); // } // // private void prepareAnimate() { // mTextSize = mHTextView.getTextSize(); // mPaint.setTextSize(mTextSize); // mPaint.setColor(mHTextView.getCurrentTextColor()); // mPaint.setTypeface(mHTextView.getTypeface()); // gapList.clear(); // for (int i = 0; i < mText.length(); i++) { // gapList.add(mPaint.measureText(String.valueOf(mText.charAt(i)))); // } // mOldPaint.setTextSize(mTextSize); // mOldPaint.setColor(mHTextView.getCurrentTextColor()); // mOldPaint.setTypeface(mHTextView.getTypeface()); // oldGapList.clear(); // for (int i = 0; i < mOldText.length(); i++) { // oldGapList.add(mOldPaint.measureText(String.valueOf(mOldText.charAt(i)))); // } // } // // @Override // public void animateText(CharSequence text) { // mHTextView.setText(text); // mOldText = mText; // mText = text; // prepareAnimate(); // animatePrepare(text); // animateStart(text); // } // // @Override // public void setAnimationListener(AnimationListener listener) { // animationListener = listener; // } // // @Override // public void onDraw(Canvas canvas) { // drawFrame(canvas); // } // // protected abstract void initVariables(); // // protected abstract void animateStart(CharSequence text); // // protected abstract void animatePrepare(CharSequence text); // // protected abstract void drawFrame(Canvas canvas); // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // } // Path: htextview-fade/src/main/java/com/hanks/htextview/fade/FadeText.java import android.animation.Animator; import android.animation.ValueAnimator; import android.content.res.TypedArray; import android.graphics.Canvas; import android.text.Layout; import android.util.AttributeSet; import android.view.animation.LinearInterpolator; import com.hanks.htextview.base.DefaultAnimatorListener; import com.hanks.htextview.base.HText; import com.hanks.htextview.base.HTextView; import java.util.ArrayList; import java.util.List; import java.util.Random; package com.hanks.htextview.fade; /** * fade effect * Created by hanks on 2017/3/14. */ public class FadeText extends HText { private Random random; private int animationDuration; private List<Integer> alphaList; private int DEFAULT_DURATION = 2000; @Override
public void init(HTextView hTextView, AttributeSet attrs, int defStyle) {
hanks-zyh/HTextView
htextview-typer/src/main/java/com/hanks/htextview/typer/TyperTextView.java
// Path: htextview-base/src/main/java/com/hanks/htextview/base/AnimationListener.java // public interface AnimationListener { // void onAnimationEnd(HTextView hTextView); // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // }
import android.content.Context; import android.content.res.TypedArray; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import com.hanks.htextview.base.AnimationListener; import com.hanks.htextview.base.HTextView; import java.util.Random;
package com.hanks.htextview.typer; /** * Typer Effect * Created by hanks on 2017/3/15. */ public class TyperTextView extends HTextView { public static final int INVALIDATE = 0x767; private Random random; private CharSequence mText; private Handler handler; private int charIncrease; private int typerSpeed;
// Path: htextview-base/src/main/java/com/hanks/htextview/base/AnimationListener.java // public interface AnimationListener { // void onAnimationEnd(HTextView hTextView); // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // } // Path: htextview-typer/src/main/java/com/hanks/htextview/typer/TyperTextView.java import android.content.Context; import android.content.res.TypedArray; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import com.hanks.htextview.base.AnimationListener; import com.hanks.htextview.base.HTextView; import java.util.Random; package com.hanks.htextview.typer; /** * Typer Effect * Created by hanks on 2017/3/15. */ public class TyperTextView extends HTextView { public static final int INVALIDATE = 0x767; private Random random; private CharSequence mText; private Handler handler; private int charIncrease; private int typerSpeed;
private AnimationListener animationListener;
hanks-zyh/HTextView
htextview-rainbow/src/main/java/com/hanks/htextview/rainbow/RainbowTextView.java
// Path: htextview-base/src/main/java/com/hanks/htextview/base/AnimationListener.java // public interface AnimationListener { // void onAnimationEnd(HTextView hTextView); // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/DisplayUtils.java // public final class DisplayUtils { // // public static DisplayMetrics getDisplayMetrics() { // return Resources.getSystem().getDisplayMetrics(); // } // // public static int dp2px(float dp) { // return Math.round(dp * getDisplayMetrics().density); // } // // public static int getScreenWidth() { // return getDisplayMetrics().widthPixels; // } // // public static int getScreenHeight() { // return getDisplayMetrics().heightPixels; // } // // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // }
import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Shader; import android.util.AttributeSet; import com.hanks.htextview.base.AnimationListener; import com.hanks.htextview.base.DisplayUtils; import com.hanks.htextview.base.HTextView;
package com.hanks.htextview.rainbow; /** * RainbowTextView * Created by hanks on 2017/3/14. */ public class RainbowTextView extends HTextView { private Matrix mMatrix; private float mTranslate; private float colorSpeed; private float colorSpace; private int[] colors = {0xFFFF2B22, 0xFFFF7F22, 0xFFEDFF22, 0xFF22FF22, 0xFF22F4FF, 0xFF2239FF, 0xFF5400F7}; private LinearGradient mLinearGradient; public RainbowTextView(Context context) { this(context, null); } public RainbowTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RainbowTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr); } @Override
// Path: htextview-base/src/main/java/com/hanks/htextview/base/AnimationListener.java // public interface AnimationListener { // void onAnimationEnd(HTextView hTextView); // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/DisplayUtils.java // public final class DisplayUtils { // // public static DisplayMetrics getDisplayMetrics() { // return Resources.getSystem().getDisplayMetrics(); // } // // public static int dp2px(float dp) { // return Math.round(dp * getDisplayMetrics().density); // } // // public static int getScreenWidth() { // return getDisplayMetrics().widthPixels; // } // // public static int getScreenHeight() { // return getDisplayMetrics().heightPixels; // } // // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // } // Path: htextview-rainbow/src/main/java/com/hanks/htextview/rainbow/RainbowTextView.java import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Shader; import android.util.AttributeSet; import com.hanks.htextview.base.AnimationListener; import com.hanks.htextview.base.DisplayUtils; import com.hanks.htextview.base.HTextView; package com.hanks.htextview.rainbow; /** * RainbowTextView * Created by hanks on 2017/3/14. */ public class RainbowTextView extends HTextView { private Matrix mMatrix; private float mTranslate; private float colorSpeed; private float colorSpace; private int[] colors = {0xFFFF2B22, 0xFFFF7F22, 0xFFEDFF22, 0xFF22FF22, 0xFF22F4FF, 0xFF2239FF, 0xFF5400F7}; private LinearGradient mLinearGradient; public RainbowTextView(Context context) { this(context, null); } public RainbowTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RainbowTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr); } @Override
public void setAnimationListener(AnimationListener listener) {
hanks-zyh/HTextView
htextview-rainbow/src/main/java/com/hanks/htextview/rainbow/RainbowTextView.java
// Path: htextview-base/src/main/java/com/hanks/htextview/base/AnimationListener.java // public interface AnimationListener { // void onAnimationEnd(HTextView hTextView); // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/DisplayUtils.java // public final class DisplayUtils { // // public static DisplayMetrics getDisplayMetrics() { // return Resources.getSystem().getDisplayMetrics(); // } // // public static int dp2px(float dp) { // return Math.round(dp * getDisplayMetrics().density); // } // // public static int getScreenWidth() { // return getDisplayMetrics().widthPixels; // } // // public static int getScreenHeight() { // return getDisplayMetrics().heightPixels; // } // // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // }
import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Shader; import android.util.AttributeSet; import com.hanks.htextview.base.AnimationListener; import com.hanks.htextview.base.DisplayUtils; import com.hanks.htextview.base.HTextView;
package com.hanks.htextview.rainbow; /** * RainbowTextView * Created by hanks on 2017/3/14. */ public class RainbowTextView extends HTextView { private Matrix mMatrix; private float mTranslate; private float colorSpeed; private float colorSpace; private int[] colors = {0xFFFF2B22, 0xFFFF7F22, 0xFFEDFF22, 0xFF22FF22, 0xFF22F4FF, 0xFF2239FF, 0xFF5400F7}; private LinearGradient mLinearGradient; public RainbowTextView(Context context) { this(context, null); } public RainbowTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RainbowTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr); } @Override public void setAnimationListener(AnimationListener listener) { throw new UnsupportedOperationException("Invalid operation for rainbow"); } private void init(AttributeSet attrs, int defStyleAttr) { TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.RainbowTextView);
// Path: htextview-base/src/main/java/com/hanks/htextview/base/AnimationListener.java // public interface AnimationListener { // void onAnimationEnd(HTextView hTextView); // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/DisplayUtils.java // public final class DisplayUtils { // // public static DisplayMetrics getDisplayMetrics() { // return Resources.getSystem().getDisplayMetrics(); // } // // public static int dp2px(float dp) { // return Math.round(dp * getDisplayMetrics().density); // } // // public static int getScreenWidth() { // return getDisplayMetrics().widthPixels; // } // // public static int getScreenHeight() { // return getDisplayMetrics().heightPixels; // } // // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // } // Path: htextview-rainbow/src/main/java/com/hanks/htextview/rainbow/RainbowTextView.java import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Shader; import android.util.AttributeSet; import com.hanks.htextview.base.AnimationListener; import com.hanks.htextview.base.DisplayUtils; import com.hanks.htextview.base.HTextView; package com.hanks.htextview.rainbow; /** * RainbowTextView * Created by hanks on 2017/3/14. */ public class RainbowTextView extends HTextView { private Matrix mMatrix; private float mTranslate; private float colorSpeed; private float colorSpace; private int[] colors = {0xFFFF2B22, 0xFFFF7F22, 0xFFEDFF22, 0xFF22FF22, 0xFF22F4FF, 0xFF2239FF, 0xFF5400F7}; private LinearGradient mLinearGradient; public RainbowTextView(Context context) { this(context, null); } public RainbowTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RainbowTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr); } @Override public void setAnimationListener(AnimationListener listener) { throw new UnsupportedOperationException("Invalid operation for rainbow"); } private void init(AttributeSet attrs, int defStyleAttr) { TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.RainbowTextView);
colorSpace = typedArray.getDimension(R.styleable.RainbowTextView_colorSpace, DisplayUtils.dp2px(150));
hanks-zyh/HTextView
demoapp/src/main/java/com/example/demoapp/TyperTextViewActivity.java
// Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // }
import android.os.Bundle; import com.hanks.htextview.base.HTextView;
package com.example.demoapp; public class TyperTextViewActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_typer_text_view);
// Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // } // Path: demoapp/src/main/java/com/example/demoapp/TyperTextViewActivity.java import android.os.Bundle; import com.hanks.htextview.base.HTextView; package com.example.demoapp; public class TyperTextViewActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_typer_text_view);
final HTextView textView1 = (HTextView) findViewById(R.id.textview);
hanks-zyh/HTextView
htextview-fall/src/main/java/com/hanks/htextview/fall/FallTextView.java
// Path: htextview-base/src/main/java/com/hanks/htextview/base/AnimationListener.java // public interface AnimationListener { // void onAnimationEnd(HTextView hTextView); // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // }
import android.content.Context; import android.graphics.Canvas; import android.text.TextUtils; import android.util.AttributeSet; import com.hanks.htextview.base.AnimationListener; import com.hanks.htextview.base.HTextView;
package com.hanks.htextview.fall; /** * Created by hanks on 2017/3/16. */ public class FallTextView extends HTextView { private FallText fallText; public FallTextView(Context context) { this(context,null); } public FallTextView(Context context, AttributeSet attrs) { this(context, attrs,0); } public FallTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr); } @Override
// Path: htextview-base/src/main/java/com/hanks/htextview/base/AnimationListener.java // public interface AnimationListener { // void onAnimationEnd(HTextView hTextView); // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // } // Path: htextview-fall/src/main/java/com/hanks/htextview/fall/FallTextView.java import android.content.Context; import android.graphics.Canvas; import android.text.TextUtils; import android.util.AttributeSet; import com.hanks.htextview.base.AnimationListener; import com.hanks.htextview.base.HTextView; package com.hanks.htextview.fall; /** * Created by hanks on 2017/3/16. */ public class FallTextView extends HTextView { private FallText fallText; public FallTextView(Context context) { this(context,null); } public FallTextView(Context context, AttributeSet attrs) { this(context, attrs,0); } public FallTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr); } @Override
public void setAnimationListener(AnimationListener listener) {
hanks-zyh/HTextView
htextview-library/src/main/java/com/hanks/htextview/animatetext/ScaleText.java
// Path: htextview-library/src/main/java/com/hanks/htextview/util/CharacterUtils.java // public class CharacterUtils { // // public static List<CharacterDiffResult> diff(CharSequence oldText, CharSequence newText) { // // List<CharacterDiffResult> differentList = new ArrayList<>(); // Set<Integer> skip = new HashSet<>(); // // for (int i = 0; i < oldText.length(); i++) { // char c = oldText.charAt(i); // for (int j = 0; j < newText.length(); j++) { // if (!skip.contains(j) && c == newText.charAt(j)) { // skip.add(j); // CharacterDiffResult different = new CharacterDiffResult(); // different.c = c; // different.fromIndex = i; // different.moveIndex = j; // differentList.add(different); // break; // } // } // } // return differentList; // } // // public static int needMove(int index, List<CharacterDiffResult> differentList) { // for (CharacterDiffResult different : differentList) { // if (different.fromIndex == index) { // return different.moveIndex; // } // } // return -1; // } // // public static boolean stayHere(int index, List<CharacterDiffResult> differentList) { // for (CharacterDiffResult different : differentList) { // if (different.moveIndex == index) { // return true; // } // } // return false; // } // // /** // * @return // */ // public static float getOffset(int from, int move, float progress, float startX, float oldStartX, float[] gaps, float[] oldGaps) { // // float dist = startX; // for (int i = 0; i < move; i++) { // dist += gaps[i]; // } // // float cur = oldStartX; // for (int i = 0; i < from; i++) { // cur += oldGaps[i]; // } // // return cur + (dist - cur) * progress; // // } // // }
import android.animation.ValueAnimator; import android.graphics.Canvas; import android.view.animation.AccelerateDecelerateInterpolator; import com.hanks.htextview.util.CharacterUtils;
n = n <= 0 ? 1 : n; duration = (long) (charTime + charTime / mostCount * (n - 1)); ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, duration).setDuration(duration); valueAnimator.setInterpolator(new AccelerateDecelerateInterpolator()); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { progress = (float) animation.getAnimatedValue(); mHTextView.invalidate(); } }); valueAnimator.start(); } @Override protected void animatePrepare(CharSequence text) { } @Override public void drawFrame(Canvas canvas) { float offset = startX; float oldOffset = oldStartX; int maxLength = Math.max(mText.length(), mOldText.length()); for (int i = 0; i < maxLength; i++) { // draw old text if (i < mOldText.length()) { float percent = progress / duration;
// Path: htextview-library/src/main/java/com/hanks/htextview/util/CharacterUtils.java // public class CharacterUtils { // // public static List<CharacterDiffResult> diff(CharSequence oldText, CharSequence newText) { // // List<CharacterDiffResult> differentList = new ArrayList<>(); // Set<Integer> skip = new HashSet<>(); // // for (int i = 0; i < oldText.length(); i++) { // char c = oldText.charAt(i); // for (int j = 0; j < newText.length(); j++) { // if (!skip.contains(j) && c == newText.charAt(j)) { // skip.add(j); // CharacterDiffResult different = new CharacterDiffResult(); // different.c = c; // different.fromIndex = i; // different.moveIndex = j; // differentList.add(different); // break; // } // } // } // return differentList; // } // // public static int needMove(int index, List<CharacterDiffResult> differentList) { // for (CharacterDiffResult different : differentList) { // if (different.fromIndex == index) { // return different.moveIndex; // } // } // return -1; // } // // public static boolean stayHere(int index, List<CharacterDiffResult> differentList) { // for (CharacterDiffResult different : differentList) { // if (different.moveIndex == index) { // return true; // } // } // return false; // } // // /** // * @return // */ // public static float getOffset(int from, int move, float progress, float startX, float oldStartX, float[] gaps, float[] oldGaps) { // // float dist = startX; // for (int i = 0; i < move; i++) { // dist += gaps[i]; // } // // float cur = oldStartX; // for (int i = 0; i < from; i++) { // cur += oldGaps[i]; // } // // return cur + (dist - cur) * progress; // // } // // } // Path: htextview-library/src/main/java/com/hanks/htextview/animatetext/ScaleText.java import android.animation.ValueAnimator; import android.graphics.Canvas; import android.view.animation.AccelerateDecelerateInterpolator; import com.hanks.htextview.util.CharacterUtils; n = n <= 0 ? 1 : n; duration = (long) (charTime + charTime / mostCount * (n - 1)); ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, duration).setDuration(duration); valueAnimator.setInterpolator(new AccelerateDecelerateInterpolator()); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { progress = (float) animation.getAnimatedValue(); mHTextView.invalidate(); } }); valueAnimator.start(); } @Override protected void animatePrepare(CharSequence text) { } @Override public void drawFrame(Canvas canvas) { float offset = startX; float oldOffset = oldStartX; int maxLength = Math.max(mText.length(), mOldText.length()); for (int i = 0; i < maxLength; i++) { // draw old text if (i < mOldText.length()) { float percent = progress / duration;
int move = CharacterUtils.needMove(i, differentList);
hanks-zyh/HTextView
htextview-library/src/main/java/com/hanks/htextview/animatetext/SparkleText.java
// Path: htextview-library/src/main/java/com/hanks/htextview/util/CharacterUtils.java // public class CharacterUtils { // // public static List<CharacterDiffResult> diff(CharSequence oldText, CharSequence newText) { // // List<CharacterDiffResult> differentList = new ArrayList<>(); // Set<Integer> skip = new HashSet<>(); // // for (int i = 0; i < oldText.length(); i++) { // char c = oldText.charAt(i); // for (int j = 0; j < newText.length(); j++) { // if (!skip.contains(j) && c == newText.charAt(j)) { // skip.add(j); // CharacterDiffResult different = new CharacterDiffResult(); // different.c = c; // different.fromIndex = i; // different.moveIndex = j; // differentList.add(different); // break; // } // } // } // return differentList; // } // // public static int needMove(int index, List<CharacterDiffResult> differentList) { // for (CharacterDiffResult different : differentList) { // if (different.fromIndex == index) { // return different.moveIndex; // } // } // return -1; // } // // public static boolean stayHere(int index, List<CharacterDiffResult> differentList) { // for (CharacterDiffResult different : differentList) { // if (different.moveIndex == index) { // return true; // } // } // return false; // } // // /** // * @return // */ // public static float getOffset(int from, int move, float progress, float startX, float oldStartX, float[] gaps, float[] oldGaps) { // // float dist = startX; // for (int i = 0; i < move; i++) { // dist += gaps[i]; // } // // float cur = oldStartX; // for (int i = 0; i < from; i++) { // cur += oldGaps[i]; // } // // return cur + (dist - cur) * progress; // // } // // }
import android.animation.ValueAnimator; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.ColorDrawable; import com.hanks.htextview.R; import com.hanks.htextview.util.CharacterUtils; import java.util.Random;
@Override public void onAnimationUpdate(ValueAnimator animation) { progress = (float) animation.getAnimatedValue(); mHTextView.invalidate(); } }); valueAnimator.start(); } @Override protected void animatePrepare(CharSequence text) { Rect bounds = new Rect(); mPaint.getTextBounds(mText.toString(), 0, mText.length(), bounds); upDistance = bounds.height(); } @Override protected void drawFrame(Canvas canvas) { float offset = startX; float oldOffset = oldStartX; int maxLength = Math.max(mText.length(), mOldText.length()); float percent = progress / (charTime + charTime / mostCount * (mText.length() - 1)); mPaint.setAlpha(255); mPaint.setTextSize(mTextSize); for (int i = 0; i < maxLength; i++) { // draw new text if (i < mText.length()) {
// Path: htextview-library/src/main/java/com/hanks/htextview/util/CharacterUtils.java // public class CharacterUtils { // // public static List<CharacterDiffResult> diff(CharSequence oldText, CharSequence newText) { // // List<CharacterDiffResult> differentList = new ArrayList<>(); // Set<Integer> skip = new HashSet<>(); // // for (int i = 0; i < oldText.length(); i++) { // char c = oldText.charAt(i); // for (int j = 0; j < newText.length(); j++) { // if (!skip.contains(j) && c == newText.charAt(j)) { // skip.add(j); // CharacterDiffResult different = new CharacterDiffResult(); // different.c = c; // different.fromIndex = i; // different.moveIndex = j; // differentList.add(different); // break; // } // } // } // return differentList; // } // // public static int needMove(int index, List<CharacterDiffResult> differentList) { // for (CharacterDiffResult different : differentList) { // if (different.fromIndex == index) { // return different.moveIndex; // } // } // return -1; // } // // public static boolean stayHere(int index, List<CharacterDiffResult> differentList) { // for (CharacterDiffResult different : differentList) { // if (different.moveIndex == index) { // return true; // } // } // return false; // } // // /** // * @return // */ // public static float getOffset(int from, int move, float progress, float startX, float oldStartX, float[] gaps, float[] oldGaps) { // // float dist = startX; // for (int i = 0; i < move; i++) { // dist += gaps[i]; // } // // float cur = oldStartX; // for (int i = 0; i < from; i++) { // cur += oldGaps[i]; // } // // return cur + (dist - cur) * progress; // // } // // } // Path: htextview-library/src/main/java/com/hanks/htextview/animatetext/SparkleText.java import android.animation.ValueAnimator; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.ColorDrawable; import com.hanks.htextview.R; import com.hanks.htextview.util.CharacterUtils; import java.util.Random; @Override public void onAnimationUpdate(ValueAnimator animation) { progress = (float) animation.getAnimatedValue(); mHTextView.invalidate(); } }); valueAnimator.start(); } @Override protected void animatePrepare(CharSequence text) { Rect bounds = new Rect(); mPaint.getTextBounds(mText.toString(), 0, mText.length(), bounds); upDistance = bounds.height(); } @Override protected void drawFrame(Canvas canvas) { float offset = startX; float oldOffset = oldStartX; int maxLength = Math.max(mText.length(), mOldText.length()); float percent = progress / (charTime + charTime / mostCount * (mText.length() - 1)); mPaint.setAlpha(255); mPaint.setTextSize(mTextSize); for (int i = 0; i < maxLength; i++) { // draw new text if (i < mText.length()) {
if (!CharacterUtils.stayHere(i, differentList)) {
hanks-zyh/HTextView
htextview-scale/src/main/java/com/hanks/htextview/scale/ScaleTextView.java
// Path: htextview-base/src/main/java/com/hanks/htextview/base/AnimationListener.java // public interface AnimationListener { // void onAnimationEnd(HTextView hTextView); // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // }
import android.content.Context; import android.graphics.Canvas; import android.text.TextUtils; import android.util.AttributeSet; import com.hanks.htextview.base.AnimationListener; import com.hanks.htextview.base.HTextView;
package com.hanks.htextview.scale; /** * ScaleTextView * Created by hanks on 2017/3/15. */ public class ScaleTextView extends HTextView { private ScaleText scaleText; public ScaleTextView(Context context) { this(context, null); } public ScaleTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ScaleTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); scaleText = new ScaleText(); scaleText.init(this, attrs, defStyleAttr); setMaxLines(1); setEllipsize(TextUtils.TruncateAt.END); } @Override
// Path: htextview-base/src/main/java/com/hanks/htextview/base/AnimationListener.java // public interface AnimationListener { // void onAnimationEnd(HTextView hTextView); // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // } // Path: htextview-scale/src/main/java/com/hanks/htextview/scale/ScaleTextView.java import android.content.Context; import android.graphics.Canvas; import android.text.TextUtils; import android.util.AttributeSet; import com.hanks.htextview.base.AnimationListener; import com.hanks.htextview.base.HTextView; package com.hanks.htextview.scale; /** * ScaleTextView * Created by hanks on 2017/3/15. */ public class ScaleTextView extends HTextView { private ScaleText scaleText; public ScaleTextView(Context context) { this(context, null); } public ScaleTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ScaleTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); scaleText = new ScaleText(); scaleText.init(this, attrs, defStyleAttr); setMaxLines(1); setEllipsize(TextUtils.TruncateAt.END); } @Override
public void setAnimationListener(AnimationListener listener) {
hanks-zyh/HTextView
htextview-library/src/main/java/com/hanks/htextview/animatetext/AnvilText.java
// Path: htextview-library/src/main/java/com/hanks/htextview/util/CharacterUtils.java // public class CharacterUtils { // // public static List<CharacterDiffResult> diff(CharSequence oldText, CharSequence newText) { // // List<CharacterDiffResult> differentList = new ArrayList<>(); // Set<Integer> skip = new HashSet<>(); // // for (int i = 0; i < oldText.length(); i++) { // char c = oldText.charAt(i); // for (int j = 0; j < newText.length(); j++) { // if (!skip.contains(j) && c == newText.charAt(j)) { // skip.add(j); // CharacterDiffResult different = new CharacterDiffResult(); // different.c = c; // different.fromIndex = i; // different.moveIndex = j; // differentList.add(different); // break; // } // } // } // return differentList; // } // // public static int needMove(int index, List<CharacterDiffResult> differentList) { // for (CharacterDiffResult different : differentList) { // if (different.fromIndex == index) { // return different.moveIndex; // } // } // return -1; // } // // public static boolean stayHere(int index, List<CharacterDiffResult> differentList) { // for (CharacterDiffResult different : differentList) { // if (different.moveIndex == index) { // return true; // } // } // return false; // } // // /** // * @return // */ // public static float getOffset(int from, int move, float progress, float startX, float oldStartX, float[] gaps, float[] oldGaps) { // // float dist = startX; // for (int i = 0; i < move; i++) { // dist += gaps[i]; // } // // float cur = oldStartX; // for (int i = 0; i < from; i++) { // cur += oldGaps[i]; // } // // return cur + (dist - cur) * progress; // // } // // }
import android.animation.ValueAnimator; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Rect; import android.view.animation.BounceInterpolator; import com.hanks.htextview.R; import com.hanks.htextview.util.CharacterUtils; import java.lang.reflect.Field;
dstWidth = mTextWidth * 1.2f; if (dstWidth < 404f) dstWidth = 404f; mMatrix.postScale(dstWidth / (float) smokes[0].getWidth(), 1f); } } @Override protected void animatePrepare(CharSequence text) { Rect bounds = new Rect(); mPaint.getTextBounds(mText.toString(), 0, mText.length(), bounds); mTextHeight = bounds.height(); mTextWidth = bounds.width(); } @Override protected void drawFrame(Canvas canvas) { float offset = startX; float oldOffset = oldStartX; int maxLength = Math.max(mText.length(), mOldText.length()); float percent = progress; boolean showSmoke = false; for (int i = 0; i < maxLength; i++) { // draw old text if (i < mOldText.length()) { mOldPaint.setTextSize(mTextSize);
// Path: htextview-library/src/main/java/com/hanks/htextview/util/CharacterUtils.java // public class CharacterUtils { // // public static List<CharacterDiffResult> diff(CharSequence oldText, CharSequence newText) { // // List<CharacterDiffResult> differentList = new ArrayList<>(); // Set<Integer> skip = new HashSet<>(); // // for (int i = 0; i < oldText.length(); i++) { // char c = oldText.charAt(i); // for (int j = 0; j < newText.length(); j++) { // if (!skip.contains(j) && c == newText.charAt(j)) { // skip.add(j); // CharacterDiffResult different = new CharacterDiffResult(); // different.c = c; // different.fromIndex = i; // different.moveIndex = j; // differentList.add(different); // break; // } // } // } // return differentList; // } // // public static int needMove(int index, List<CharacterDiffResult> differentList) { // for (CharacterDiffResult different : differentList) { // if (different.fromIndex == index) { // return different.moveIndex; // } // } // return -1; // } // // public static boolean stayHere(int index, List<CharacterDiffResult> differentList) { // for (CharacterDiffResult different : differentList) { // if (different.moveIndex == index) { // return true; // } // } // return false; // } // // /** // * @return // */ // public static float getOffset(int from, int move, float progress, float startX, float oldStartX, float[] gaps, float[] oldGaps) { // // float dist = startX; // for (int i = 0; i < move; i++) { // dist += gaps[i]; // } // // float cur = oldStartX; // for (int i = 0; i < from; i++) { // cur += oldGaps[i]; // } // // return cur + (dist - cur) * progress; // // } // // } // Path: htextview-library/src/main/java/com/hanks/htextview/animatetext/AnvilText.java import android.animation.ValueAnimator; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Rect; import android.view.animation.BounceInterpolator; import com.hanks.htextview.R; import com.hanks.htextview.util.CharacterUtils; import java.lang.reflect.Field; dstWidth = mTextWidth * 1.2f; if (dstWidth < 404f) dstWidth = 404f; mMatrix.postScale(dstWidth / (float) smokes[0].getWidth(), 1f); } } @Override protected void animatePrepare(CharSequence text) { Rect bounds = new Rect(); mPaint.getTextBounds(mText.toString(), 0, mText.length(), bounds); mTextHeight = bounds.height(); mTextWidth = bounds.width(); } @Override protected void drawFrame(Canvas canvas) { float offset = startX; float oldOffset = oldStartX; int maxLength = Math.max(mText.length(), mOldText.length()); float percent = progress; boolean showSmoke = false; for (int i = 0; i < maxLength; i++) { // draw old text if (i < mOldText.length()) { mOldPaint.setTextSize(mTextSize);
int move = CharacterUtils.needMove(i, differentList);
hanks-zyh/HTextView
htextview-fade/src/main/java/com/hanks/htextview/fade/FadeTextView.java
// Path: htextview-base/src/main/java/com/hanks/htextview/base/AnimationListener.java // public interface AnimationListener { // void onAnimationEnd(HTextView hTextView); // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // }
import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import com.hanks.htextview.base.AnimationListener; import com.hanks.htextview.base.HTextView;
package com.hanks.htextview.fade; /** * Fade Effect * Created by hanks on 2017/3/14. */ public class FadeTextView extends HTextView { private FadeText fadeText; public FadeTextView(Context context) { this(context, null); } public FadeTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public FadeTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr); } @Override
// Path: htextview-base/src/main/java/com/hanks/htextview/base/AnimationListener.java // public interface AnimationListener { // void onAnimationEnd(HTextView hTextView); // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // } // Path: htextview-fade/src/main/java/com/hanks/htextview/fade/FadeTextView.java import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import com.hanks.htextview.base.AnimationListener; import com.hanks.htextview.base.HTextView; package com.hanks.htextview.fade; /** * Fade Effect * Created by hanks on 2017/3/14. */ public class FadeTextView extends HTextView { private FadeText fadeText; public FadeTextView(Context context) { this(context, null); } public FadeTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public FadeTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr); } @Override
public void setAnimationListener(AnimationListener listener) {
hanks-zyh/HTextView
demoapp/src/main/java/com/example/demoapp/RainbowTextViewActivity.java
// Path: htextview-rainbow/src/main/java/com/hanks/htextview/rainbow/RainbowTextView.java // public class RainbowTextView extends HTextView { // // private Matrix mMatrix; // private float mTranslate; // private float colorSpeed; // private float colorSpace; // private int[] colors = {0xFFFF2B22, 0xFFFF7F22, 0xFFEDFF22, 0xFF22FF22, 0xFF22F4FF, 0xFF2239FF, 0xFF5400F7}; // private LinearGradient mLinearGradient; // // public RainbowTextView(Context context) { // this(context, null); // } // // public RainbowTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public RainbowTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // init(attrs, defStyleAttr); // } // // @Override // public void setAnimationListener(AnimationListener listener) { // throw new UnsupportedOperationException("Invalid operation for rainbow"); // } // // private void init(AttributeSet attrs, int defStyleAttr) { // // TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.RainbowTextView); // colorSpace = typedArray.getDimension(R.styleable.RainbowTextView_colorSpace, DisplayUtils.dp2px(150)); // colorSpeed = typedArray.getDimension(R.styleable.RainbowTextView_colorSpeed, DisplayUtils.dp2px(5)); // typedArray.recycle(); // // mMatrix = new Matrix(); // initPaint(); // } // // public float getColorSpace() { // return colorSpace; // } // // public void setColorSpace(float colorSpace) { // this.colorSpace = colorSpace; // } // // public float getColorSpeed() { // return colorSpeed; // } // // public void setColorSpeed(float colorSpeed) { // this.colorSpeed = colorSpeed; // } // // public void setColors(int... colors) { // this.colors = colors; // initPaint(); // } // // private void initPaint() { // mLinearGradient = new LinearGradient(0, 0, colorSpace, 0, colors, null, Shader.TileMode.MIRROR); // getPaint().setShader(mLinearGradient); // } // // @Override // public void setProgress(float progress) { // } // // @Override // public void animateText(CharSequence text) { // setText(text); // } // // @Override // protected void onDraw(Canvas canvas) { // if (mMatrix == null) { // mMatrix = new Matrix(); // } // mTranslate += colorSpeed; // mMatrix.setTranslate(mTranslate, 0); // mLinearGradient.setLocalMatrix(mMatrix); // super.onDraw(canvas); // postInvalidateDelayed(100); // } // }
import android.os.Bundle; import com.hanks.htextview.rainbow.RainbowTextView;
package com.example.demoapp; public class RainbowTextViewActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rainbow_text_view);
// Path: htextview-rainbow/src/main/java/com/hanks/htextview/rainbow/RainbowTextView.java // public class RainbowTextView extends HTextView { // // private Matrix mMatrix; // private float mTranslate; // private float colorSpeed; // private float colorSpace; // private int[] colors = {0xFFFF2B22, 0xFFFF7F22, 0xFFEDFF22, 0xFF22FF22, 0xFF22F4FF, 0xFF2239FF, 0xFF5400F7}; // private LinearGradient mLinearGradient; // // public RainbowTextView(Context context) { // this(context, null); // } // // public RainbowTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public RainbowTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // init(attrs, defStyleAttr); // } // // @Override // public void setAnimationListener(AnimationListener listener) { // throw new UnsupportedOperationException("Invalid operation for rainbow"); // } // // private void init(AttributeSet attrs, int defStyleAttr) { // // TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.RainbowTextView); // colorSpace = typedArray.getDimension(R.styleable.RainbowTextView_colorSpace, DisplayUtils.dp2px(150)); // colorSpeed = typedArray.getDimension(R.styleable.RainbowTextView_colorSpeed, DisplayUtils.dp2px(5)); // typedArray.recycle(); // // mMatrix = new Matrix(); // initPaint(); // } // // public float getColorSpace() { // return colorSpace; // } // // public void setColorSpace(float colorSpace) { // this.colorSpace = colorSpace; // } // // public float getColorSpeed() { // return colorSpeed; // } // // public void setColorSpeed(float colorSpeed) { // this.colorSpeed = colorSpeed; // } // // public void setColors(int... colors) { // this.colors = colors; // initPaint(); // } // // private void initPaint() { // mLinearGradient = new LinearGradient(0, 0, colorSpace, 0, colors, null, Shader.TileMode.MIRROR); // getPaint().setShader(mLinearGradient); // } // // @Override // public void setProgress(float progress) { // } // // @Override // public void animateText(CharSequence text) { // setText(text); // } // // @Override // protected void onDraw(Canvas canvas) { // if (mMatrix == null) { // mMatrix = new Matrix(); // } // mTranslate += colorSpeed; // mMatrix.setTranslate(mTranslate, 0); // mLinearGradient.setLocalMatrix(mMatrix); // super.onDraw(canvas); // postInvalidateDelayed(100); // } // } // Path: demoapp/src/main/java/com/example/demoapp/RainbowTextViewActivity.java import android.os.Bundle; import com.hanks.htextview.rainbow.RainbowTextView; package com.example.demoapp; public class RainbowTextViewActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rainbow_text_view);
RainbowTextView textView = (RainbowTextView) findViewById(R.id.textview);
hanks-zyh/HTextView
demoapp/src/main/java/com/example/demoapp/BaseActivity.java
// Path: htextview-base/src/main/java/com/hanks/htextview/base/AnimationListener.java // public interface AnimationListener { // void onAnimationEnd(HTextView hTextView); // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // }
import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; import com.hanks.htextview.base.AnimationListener; import com.hanks.htextview.base.HTextView;
package com.example.demoapp; /** * Created by hanks on 2017/3/14. */ public class BaseActivity extends AppCompatActivity { String[] sentences = {"What is design?", "Design is not just", "what it looks like and feels like.", "Design is how it works. \n- Steve Jobs", "Older people", "sit down and ask,", "'What is it?'", "but the boy asks,", "'What can I do with it?'. \n- Steve Jobs", "Swift", "Objective-C", "iPhone", "iPad", "Mac Mini", "MacBook Pro", "Mac Pro", "爱老婆", "老婆和女儿"}; int index; class ClickListener implements View.OnClickListener { @Override public void onClick(View v) {
// Path: htextview-base/src/main/java/com/hanks/htextview/base/AnimationListener.java // public interface AnimationListener { // void onAnimationEnd(HTextView hTextView); // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // } // Path: demoapp/src/main/java/com/example/demoapp/BaseActivity.java import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; import com.hanks.htextview.base.AnimationListener; import com.hanks.htextview.base.HTextView; package com.example.demoapp; /** * Created by hanks on 2017/3/14. */ public class BaseActivity extends AppCompatActivity { String[] sentences = {"What is design?", "Design is not just", "what it looks like and feels like.", "Design is how it works. \n- Steve Jobs", "Older people", "sit down and ask,", "'What is it?'", "but the boy asks,", "'What can I do with it?'. \n- Steve Jobs", "Swift", "Objective-C", "iPhone", "iPad", "Mac Mini", "MacBook Pro", "Mac Pro", "爱老婆", "老婆和女儿"}; int index; class ClickListener implements View.OnClickListener { @Override public void onClick(View v) {
if (v instanceof HTextView) {
hanks-zyh/HTextView
demoapp/src/main/java/com/example/demoapp/BaseActivity.java
// Path: htextview-base/src/main/java/com/hanks/htextview/base/AnimationListener.java // public interface AnimationListener { // void onAnimationEnd(HTextView hTextView); // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // }
import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; import com.hanks.htextview.base.AnimationListener; import com.hanks.htextview.base.HTextView;
package com.example.demoapp; /** * Created by hanks on 2017/3/14. */ public class BaseActivity extends AppCompatActivity { String[] sentences = {"What is design?", "Design is not just", "what it looks like and feels like.", "Design is how it works. \n- Steve Jobs", "Older people", "sit down and ask,", "'What is it?'", "but the boy asks,", "'What can I do with it?'. \n- Steve Jobs", "Swift", "Objective-C", "iPhone", "iPad", "Mac Mini", "MacBook Pro", "Mac Pro", "爱老婆", "老婆和女儿"}; int index; class ClickListener implements View.OnClickListener { @Override public void onClick(View v) { if (v instanceof HTextView) { if (index + 1 >= sentences.length) { index = 0; } ((HTextView) v).animateText(sentences[index++]); } } }
// Path: htextview-base/src/main/java/com/hanks/htextview/base/AnimationListener.java // public interface AnimationListener { // void onAnimationEnd(HTextView hTextView); // } // // Path: htextview-base/src/main/java/com/hanks/htextview/base/HTextView.java // public abstract class HTextView extends TextView { // public HTextView(Context context) { // this(context, null); // } // // public HTextView(Context context, AttributeSet attrs) { // this(context, attrs, 0); // } // // public HTextView(Context context, AttributeSet attrs, int defStyleAttr) { // super(context, attrs, defStyleAttr); // } // // public abstract void setAnimationListener(AnimationListener listener); // // public abstract void setProgress(float progress); // // public abstract void animateText(CharSequence text); // } // Path: demoapp/src/main/java/com/example/demoapp/BaseActivity.java import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; import com.hanks.htextview.base.AnimationListener; import com.hanks.htextview.base.HTextView; package com.example.demoapp; /** * Created by hanks on 2017/3/14. */ public class BaseActivity extends AppCompatActivity { String[] sentences = {"What is design?", "Design is not just", "what it looks like and feels like.", "Design is how it works. \n- Steve Jobs", "Older people", "sit down and ask,", "'What is it?'", "but the boy asks,", "'What can I do with it?'. \n- Steve Jobs", "Swift", "Objective-C", "iPhone", "iPad", "Mac Mini", "MacBook Pro", "Mac Pro", "爱老婆", "老婆和女儿"}; int index; class ClickListener implements View.OnClickListener { @Override public void onClick(View v) { if (v instanceof HTextView) { if (index + 1 >= sentences.length) { index = 0; } ((HTextView) v).animateText(sentences[index++]); } } }
class SimpleAnimationListener implements AnimationListener {
manuelsc/Lunary-Ethereum-Wallet
app/src/main/java/rehanced/com/simpleetherwallet/receiver/BootReceiver.java
// Path: app/src/main/java/rehanced/com/simpleetherwallet/services/NotificationLauncher.java // public class NotificationLauncher { // // private PendingIntent pintent; // private AlarmManager service; // private static NotificationLauncher instance; // // private NotificationLauncher() { // } // // public void start(Context c) { // SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c); // if (prefs.getBoolean("notifications_new_message", true) && WalletStorage.getInstance(c).get().size() >= 1) { // service = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE); // Intent i = new Intent(c, NotificationService.class); // pintent = PendingIntent.getService(c, 23, i, 0); // // int syncInt = Integer.parseInt(prefs.getString("sync_frequency", "4")); // // service.setInexactRepeating(AlarmManager.RTC_WAKEUP, // System.currentTimeMillis(), AlarmManager.INTERVAL_HOUR * syncInt, pintent); // } // } // // public void stop() { // if (service == null || pintent == null) return; // service.cancel(pintent); // } // // public static NotificationLauncher getInstance() { // if (instance == null) // instance = new NotificationLauncher(); // return instance; // } // // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import rehanced.com.simpleetherwallet.services.NotificationLauncher;
package rehanced.com.simpleetherwallet.receiver; public class BootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) {
// Path: app/src/main/java/rehanced/com/simpleetherwallet/services/NotificationLauncher.java // public class NotificationLauncher { // // private PendingIntent pintent; // private AlarmManager service; // private static NotificationLauncher instance; // // private NotificationLauncher() { // } // // public void start(Context c) { // SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c); // if (prefs.getBoolean("notifications_new_message", true) && WalletStorage.getInstance(c).get().size() >= 1) { // service = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE); // Intent i = new Intent(c, NotificationService.class); // pintent = PendingIntent.getService(c, 23, i, 0); // // int syncInt = Integer.parseInt(prefs.getString("sync_frequency", "4")); // // service.setInexactRepeating(AlarmManager.RTC_WAKEUP, // System.currentTimeMillis(), AlarmManager.INTERVAL_HOUR * syncInt, pintent); // } // } // // public void stop() { // if (service == null || pintent == null) return; // service.cancel(pintent); // } // // public static NotificationLauncher getInstance() { // if (instance == null) // instance = new NotificationLauncher(); // return instance; // } // // } // Path: app/src/main/java/rehanced/com/simpleetherwallet/receiver/BootReceiver.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import rehanced.com.simpleetherwallet.services.NotificationLauncher; package rehanced.com.simpleetherwallet.receiver; public class BootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) {
NotificationLauncher.getInstance().start(context);
manuelsc/Lunary-Ethereum-Wallet
app/src/main/java/rehanced/com/simpleetherwallet/utils/TransactionAdapter.java
// Path: app/src/main/java/rehanced/com/simpleetherwallet/data/TransactionDisplay.java // public class TransactionDisplay implements Comparable { // // public static final byte NORMAL = 0; // public static final byte CONTRACT = 1; // // private String fromAddress; // private String toAddress; // private BigInteger amount; // private int confirmationStatus; // private long date; // private String walletName; // private byte type; // private String txHash; // private String nounce; // private long block; // private int gasUsed; // private long gasprice; // private boolean error; // // public TransactionDisplay(String fromAddress, String toAddress, BigInteger amount, int confirmationStatus, long date, String walletName, byte type, String txHash, String nounce, long block, int gasUsed, long gasprice, boolean error) { // this.fromAddress = fromAddress; // this.toAddress = toAddress; // this.amount = amount; // this.confirmationStatus = confirmationStatus; // this.date = date; // this.walletName = walletName; // this.type = type; // this.txHash = txHash; // this.nounce = nounce; // this.block = block; // this.gasUsed = gasUsed; // this.gasprice = gasprice; // this.error = error; // } // // public boolean isError() { // return error; // } // // public void setError(boolean error) { // this.error = error; // } // // public long getBlock() { // return block; // } // // public void setBlock(long block) { // this.block = block; // } // // public int getGasUsed() { // return gasUsed; // } // // public void setGasUsed(int gasUsed) { // this.gasUsed = gasUsed; // } // // public long getGasprice() { // return gasprice; // } // // public void setGasprice(long gasprice) { // this.gasprice = gasprice; // } // // public String getTxHash() { // return txHash; // } // // public void setTxHash(String txHash) { // this.txHash = txHash; // } // // public byte getType() { // return type; // } // // public void setType(byte type) { // this.type = type; // } // // public String getWalletName() { // return walletName; // } // // public void setWalletName(String walletName) { // this.walletName = walletName; // } // // public String getFromAddress() { // return fromAddress.toLowerCase(); // } // // public void setFromAddress(String fromAddress) { // this.fromAddress = fromAddress; // } // // public String getToAddress() { // return toAddress.toLowerCase(); // } // // public void setToAddress(String toAddress) { // this.toAddress = toAddress; // } // // public BigInteger getAmountNative() { // return amount; // } // // public double getAmount() { // return new BigDecimal(amount).divide(new BigDecimal(1000000000000000000d), 8, BigDecimal.ROUND_UP).doubleValue(); // } // // public void setAmount(BigInteger amount) { // this.amount = amount; // } // // public int getConfirmationStatus() { // return confirmationStatus; // } // // public void setConfirmationStatus(int confirmationStatus) { // this.confirmationStatus = confirmationStatus; // } // // // public long getDate() { // return date; // } // // public void setDate(long date) { // this.date = date; // } // // public String getNounce() { // return nounce; // } // // public void setNounce(String nounce) { // this.nounce = nounce; // } // // @Override // public String toString() { // return "TransactionDisplay{" + // "fromAddress='" + fromAddress + '\'' + // ", toAddress='" + toAddress + '\'' + // ", amount=" + amount + // ", confirmationStatus=" + confirmationStatus + // ", date='" + date + '\'' + // ", walletName='" + walletName + '\'' + // '}'; // } // // @Override // public int compareTo(Object o) { // if (this.getDate() < ((TransactionDisplay) o).getDate()) // return 1; // if (this.getDate() == ((TransactionDisplay) o).getDate()) // return 0; // return -1; // } // }
import android.content.Context; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import rehanced.com.simpleetherwallet.R; import rehanced.com.simpleetherwallet.data.TransactionDisplay;
package rehanced.com.simpleetherwallet.utils; public class TransactionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context context;
// Path: app/src/main/java/rehanced/com/simpleetherwallet/data/TransactionDisplay.java // public class TransactionDisplay implements Comparable { // // public static final byte NORMAL = 0; // public static final byte CONTRACT = 1; // // private String fromAddress; // private String toAddress; // private BigInteger amount; // private int confirmationStatus; // private long date; // private String walletName; // private byte type; // private String txHash; // private String nounce; // private long block; // private int gasUsed; // private long gasprice; // private boolean error; // // public TransactionDisplay(String fromAddress, String toAddress, BigInteger amount, int confirmationStatus, long date, String walletName, byte type, String txHash, String nounce, long block, int gasUsed, long gasprice, boolean error) { // this.fromAddress = fromAddress; // this.toAddress = toAddress; // this.amount = amount; // this.confirmationStatus = confirmationStatus; // this.date = date; // this.walletName = walletName; // this.type = type; // this.txHash = txHash; // this.nounce = nounce; // this.block = block; // this.gasUsed = gasUsed; // this.gasprice = gasprice; // this.error = error; // } // // public boolean isError() { // return error; // } // // public void setError(boolean error) { // this.error = error; // } // // public long getBlock() { // return block; // } // // public void setBlock(long block) { // this.block = block; // } // // public int getGasUsed() { // return gasUsed; // } // // public void setGasUsed(int gasUsed) { // this.gasUsed = gasUsed; // } // // public long getGasprice() { // return gasprice; // } // // public void setGasprice(long gasprice) { // this.gasprice = gasprice; // } // // public String getTxHash() { // return txHash; // } // // public void setTxHash(String txHash) { // this.txHash = txHash; // } // // public byte getType() { // return type; // } // // public void setType(byte type) { // this.type = type; // } // // public String getWalletName() { // return walletName; // } // // public void setWalletName(String walletName) { // this.walletName = walletName; // } // // public String getFromAddress() { // return fromAddress.toLowerCase(); // } // // public void setFromAddress(String fromAddress) { // this.fromAddress = fromAddress; // } // // public String getToAddress() { // return toAddress.toLowerCase(); // } // // public void setToAddress(String toAddress) { // this.toAddress = toAddress; // } // // public BigInteger getAmountNative() { // return amount; // } // // public double getAmount() { // return new BigDecimal(amount).divide(new BigDecimal(1000000000000000000d), 8, BigDecimal.ROUND_UP).doubleValue(); // } // // public void setAmount(BigInteger amount) { // this.amount = amount; // } // // public int getConfirmationStatus() { // return confirmationStatus; // } // // public void setConfirmationStatus(int confirmationStatus) { // this.confirmationStatus = confirmationStatus; // } // // // public long getDate() { // return date; // } // // public void setDate(long date) { // this.date = date; // } // // public String getNounce() { // return nounce; // } // // public void setNounce(String nounce) { // this.nounce = nounce; // } // // @Override // public String toString() { // return "TransactionDisplay{" + // "fromAddress='" + fromAddress + '\'' + // ", toAddress='" + toAddress + '\'' + // ", amount=" + amount + // ", confirmationStatus=" + confirmationStatus + // ", date='" + date + '\'' + // ", walletName='" + walletName + '\'' + // '}'; // } // // @Override // public int compareTo(Object o) { // if (this.getDate() < ((TransactionDisplay) o).getDate()) // return 1; // if (this.getDate() == ((TransactionDisplay) o).getDate()) // return 0; // return -1; // } // } // Path: app/src/main/java/rehanced/com/simpleetherwallet/utils/TransactionAdapter.java import android.content.Context; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import rehanced.com.simpleetherwallet.R; import rehanced.com.simpleetherwallet.data.TransactionDisplay; package rehanced.com.simpleetherwallet.utils; public class TransactionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context context;
private List<TransactionDisplay> boxlist;
manuelsc/Lunary-Ethereum-Wallet
app/src/main/java/rehanced/com/simpleetherwallet/utils/AddressNameConverter.java
// Path: app/src/main/java/rehanced/com/simpleetherwallet/data/WalletDisplay.java // public class WalletDisplay implements Comparable { // // public static final byte NORMAL = 0; // public static final byte WATCH_ONLY = 1; // public static final byte CONTACT = 2; // // private String name; // private String publicKey; // private BigInteger balance; // private byte type; // // public WalletDisplay(String name, String publicKey, BigInteger balance, byte type) { // this.name = name; // this.publicKey = publicKey; // this.balance = balance; // this.type = type; // } // // public WalletDisplay(String name, String publicKey) { // this.name = name; // this.publicKey = publicKey; // this.balance = null; // this.type = CONTACT; // } // // public byte getType() { // return type; // } // // public void setType(byte type) { // this.type = type; // } // // public BigInteger getBalanceNative() { // return balance; // } // // public void setBalance(BigInteger balance) { // this.balance = balance; // } // // public double getBalance() { // return new BigDecimal(balance).divide(ExchangeCalculator.ONE_ETHER, 8, BigDecimal.ROUND_UP).doubleValue(); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPublicKey() { // return publicKey.toLowerCase(); // } // // public void setPublicKey(String publicKey) { // this.publicKey = publicKey; // } // // @Override // public int compareTo(@NonNull Object o) { // return name.compareTo(((WalletDisplay) o).getName()); // } // }
import android.content.Context; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import rehanced.com.simpleetherwallet.data.WalletDisplay;
private AddressNameConverter(Context context) { try { load(context); if (!contains("0xa9981a33f6b1a18da5db58148b2357f22b44e1e0")) { put("0xa9981a33f6b1a18da5db58148b2357f22b44e1e0", "Lunary Development ✓", context); } } catch (Exception e) { addressbook = new HashMap<String, String>(); put("0xa9981a33f6b1a18da5db58148b2357f22b44e1e0", "Lunary Development ✓", context); } wellknown_addresses = new WellKnownAddresses(); } public synchronized void put(String addresse, String name, Context context) { if (name == null || name.length() == 0) addressbook.remove(addresse); else addressbook.put(addresse, name.length() > 22 ? name.substring(0, 22) : name); save(context); } public String get(String addresse) { return addressbook.get(addresse); } public boolean contains(String addresse) { return addressbook.containsKey(addresse); }
// Path: app/src/main/java/rehanced/com/simpleetherwallet/data/WalletDisplay.java // public class WalletDisplay implements Comparable { // // public static final byte NORMAL = 0; // public static final byte WATCH_ONLY = 1; // public static final byte CONTACT = 2; // // private String name; // private String publicKey; // private BigInteger balance; // private byte type; // // public WalletDisplay(String name, String publicKey, BigInteger balance, byte type) { // this.name = name; // this.publicKey = publicKey; // this.balance = balance; // this.type = type; // } // // public WalletDisplay(String name, String publicKey) { // this.name = name; // this.publicKey = publicKey; // this.balance = null; // this.type = CONTACT; // } // // public byte getType() { // return type; // } // // public void setType(byte type) { // this.type = type; // } // // public BigInteger getBalanceNative() { // return balance; // } // // public void setBalance(BigInteger balance) { // this.balance = balance; // } // // public double getBalance() { // return new BigDecimal(balance).divide(ExchangeCalculator.ONE_ETHER, 8, BigDecimal.ROUND_UP).doubleValue(); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPublicKey() { // return publicKey.toLowerCase(); // } // // public void setPublicKey(String publicKey) { // this.publicKey = publicKey; // } // // @Override // public int compareTo(@NonNull Object o) { // return name.compareTo(((WalletDisplay) o).getName()); // } // } // Path: app/src/main/java/rehanced/com/simpleetherwallet/utils/AddressNameConverter.java import android.content.Context; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import rehanced.com.simpleetherwallet.data.WalletDisplay; private AddressNameConverter(Context context) { try { load(context); if (!contains("0xa9981a33f6b1a18da5db58148b2357f22b44e1e0")) { put("0xa9981a33f6b1a18da5db58148b2357f22b44e1e0", "Lunary Development ✓", context); } } catch (Exception e) { addressbook = new HashMap<String, String>(); put("0xa9981a33f6b1a18da5db58148b2357f22b44e1e0", "Lunary Development ✓", context); } wellknown_addresses = new WellKnownAddresses(); } public synchronized void put(String addresse, String name, Context context) { if (name == null || name.length() == 0) addressbook.remove(addresse); else addressbook.put(addresse, name.length() > 22 ? name.substring(0, 22) : name); save(context); } public String get(String addresse) { return addressbook.get(addresse); } public boolean contains(String addresse) { return addressbook.containsKey(addresse); }
public ArrayList<WalletDisplay> getAsAddressbook() {
manuelsc/Lunary-Ethereum-Wallet
app/src/main/java/rehanced/com/simpleetherwallet/activities/AppIntroActivity.java
// Path: app/src/main/java/rehanced/com/simpleetherwallet/fragments/ToSFragment.java // public class ToSFragment extends Fragment { // // private TextView tos; // private CheckBox read; // private boolean checked = false; // // @SuppressWarnings("ConstantConditions") // @Override // public void onActivityCreated(@Nullable Bundle savedInstanceState) { // super.onActivityCreated(savedInstanceState); // // tos = (TextView) getView().findViewById(R.id.tostext); // tos.setText(Html.fromHtml(loadTerms())); // read = (CheckBox) getView().findViewById(R.id.checkBox); // // read.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // checked = read.isChecked(); // } // }); // } // // private String loadTerms() { // StringBuilder termsString = new StringBuilder(); // BufferedReader reader; // try { // reader = new BufferedReader( // new InputStreamReader(getActivity().getAssets().open("gpl.txt"))); // // String str; // while ((str = reader.readLine()) != null) { // termsString.append(str); // } // // reader.close(); // return termsString.toString(); // } catch (IOException e) { // e.printStackTrace(); // } // return null; // } // // public boolean isToSChecked() { // return checked; // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // return inflater.inflate(R.layout.tos_layout, container, false); // } // }
import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.widget.Toast; import com.github.paolorotolo.appintro.AppIntro2; import com.github.paolorotolo.appintro.AppIntroFragment; import rehanced.com.simpleetherwallet.R; import rehanced.com.simpleetherwallet.fragments.ToSFragment;
package rehanced.com.simpleetherwallet.activities; public class AppIntroActivity extends AppIntro2 { public static final int REQUEST_CODE = 602;
// Path: app/src/main/java/rehanced/com/simpleetherwallet/fragments/ToSFragment.java // public class ToSFragment extends Fragment { // // private TextView tos; // private CheckBox read; // private boolean checked = false; // // @SuppressWarnings("ConstantConditions") // @Override // public void onActivityCreated(@Nullable Bundle savedInstanceState) { // super.onActivityCreated(savedInstanceState); // // tos = (TextView) getView().findViewById(R.id.tostext); // tos.setText(Html.fromHtml(loadTerms())); // read = (CheckBox) getView().findViewById(R.id.checkBox); // // read.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // checked = read.isChecked(); // } // }); // } // // private String loadTerms() { // StringBuilder termsString = new StringBuilder(); // BufferedReader reader; // try { // reader = new BufferedReader( // new InputStreamReader(getActivity().getAssets().open("gpl.txt"))); // // String str; // while ((str = reader.readLine()) != null) { // termsString.append(str); // } // // reader.close(); // return termsString.toString(); // } catch (IOException e) { // e.printStackTrace(); // } // return null; // } // // public boolean isToSChecked() { // return checked; // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // return inflater.inflate(R.layout.tos_layout, container, false); // } // } // Path: app/src/main/java/rehanced/com/simpleetherwallet/activities/AppIntroActivity.java import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.widget.Toast; import com.github.paolorotolo.appintro.AppIntro2; import com.github.paolorotolo.appintro.AppIntroFragment; import rehanced.com.simpleetherwallet.R; import rehanced.com.simpleetherwallet.fragments.ToSFragment; package rehanced.com.simpleetherwallet.activities; public class AppIntroActivity extends AppIntro2 { public static final int REQUEST_CODE = 602;
private ToSFragment tosFragment;
manuelsc/Lunary-Ethereum-Wallet
app/src/main/java/rehanced/com/simpleetherwallet/utils/TokenAdapter.java
// Path: app/src/main/java/rehanced/com/simpleetherwallet/data/TokenDisplay.java // public class TokenDisplay implements Comparable { // // private String name; // private String shorty; // private BigDecimal balance; // private int digits; // private double usdprice; // private String contractAddr; // private String totalSupply; // private long holderCount; // private long createdAt; // // public TokenDisplay(String name, String shorty, BigDecimal balance, int digits, double usdprice, String contractAddr, String totalSupply, long holderCount, long createdAt) { // this.name = name; // this.shorty = shorty; // this.balance = balance; // this.digits = digits; // this.usdprice = usdprice; // this.contractAddr = contractAddr; // this.totalSupply = totalSupply; // this.holderCount = holderCount; // this.createdAt = createdAt; // } // // public long getCreatedAt() { // return createdAt; // } // // public void setCreatedAt(long createdAt) { // this.createdAt = createdAt; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getShorty() { // return shorty; // } // // public void setShorty(String shorty) { // this.shorty = shorty; // } // // public BigDecimal getBalance() { // return balance; // } // // /** // * Uses digits and balance to create a double value // * // * @return Token balance in double // */ // public double getBalanceDouble() { // return balance.divide((new BigDecimal("10").pow(digits))).doubleValue(); // } // // /** // * Uses digits and total supply to create a long value // * // * @return Token supply in long // */ // public long getTotalSupplyLong() { // return new BigInteger(totalSupply).divide((new BigInteger("10").pow(digits))).longValue(); // } // // public void setBalance(BigDecimal balance) { // this.balance = balance; // } // // public int getDigits() { // return digits; // } // // public void setDigits(int digits) { // this.digits = digits; // } // // public double getUsdprice() { // return usdprice; // } // // public void setUsdprice(double usdprice) { // this.usdprice = usdprice; // } // // public String getContractAddr() { // return contractAddr; // } // // public void setContractAddr(String contractAddr) { // this.contractAddr = contractAddr; // } // // public String getTotalSupply() { // return totalSupply; // } // // public void setTotalSupply(String totalSupply) { // this.totalSupply = totalSupply; // } // // public long getHolderCount() { // return holderCount; // } // // public void setHolderCount(long holderCount) { // this.holderCount = holderCount; // } // // @Override // public int compareTo(@NonNull Object o) { // return ((TokenDisplay) o).getShorty().compareTo(shorty); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TokenDisplay that = (TokenDisplay) o; // // if (digits != that.digits) return false; // if (!name.equals(that.name)) return false; // return shorty.equals(that.shorty); // // } // // @Override // public int hashCode() { // int result = name.hashCode(); // result = 31 * result + shorty.hashCode(); // result = 31 * result + digits; // return result; // } // }
import android.content.Context; import android.graphics.drawable.BitmapDrawable; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; import rehanced.com.simpleetherwallet.R; import rehanced.com.simpleetherwallet.data.TokenDisplay;
package rehanced.com.simpleetherwallet.utils; public class TokenAdapter extends RecyclerView.Adapter<TokenAdapter.MyViewHolder> { private Context context;
// Path: app/src/main/java/rehanced/com/simpleetherwallet/data/TokenDisplay.java // public class TokenDisplay implements Comparable { // // private String name; // private String shorty; // private BigDecimal balance; // private int digits; // private double usdprice; // private String contractAddr; // private String totalSupply; // private long holderCount; // private long createdAt; // // public TokenDisplay(String name, String shorty, BigDecimal balance, int digits, double usdprice, String contractAddr, String totalSupply, long holderCount, long createdAt) { // this.name = name; // this.shorty = shorty; // this.balance = balance; // this.digits = digits; // this.usdprice = usdprice; // this.contractAddr = contractAddr; // this.totalSupply = totalSupply; // this.holderCount = holderCount; // this.createdAt = createdAt; // } // // public long getCreatedAt() { // return createdAt; // } // // public void setCreatedAt(long createdAt) { // this.createdAt = createdAt; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getShorty() { // return shorty; // } // // public void setShorty(String shorty) { // this.shorty = shorty; // } // // public BigDecimal getBalance() { // return balance; // } // // /** // * Uses digits and balance to create a double value // * // * @return Token balance in double // */ // public double getBalanceDouble() { // return balance.divide((new BigDecimal("10").pow(digits))).doubleValue(); // } // // /** // * Uses digits and total supply to create a long value // * // * @return Token supply in long // */ // public long getTotalSupplyLong() { // return new BigInteger(totalSupply).divide((new BigInteger("10").pow(digits))).longValue(); // } // // public void setBalance(BigDecimal balance) { // this.balance = balance; // } // // public int getDigits() { // return digits; // } // // public void setDigits(int digits) { // this.digits = digits; // } // // public double getUsdprice() { // return usdprice; // } // // public void setUsdprice(double usdprice) { // this.usdprice = usdprice; // } // // public String getContractAddr() { // return contractAddr; // } // // public void setContractAddr(String contractAddr) { // this.contractAddr = contractAddr; // } // // public String getTotalSupply() { // return totalSupply; // } // // public void setTotalSupply(String totalSupply) { // this.totalSupply = totalSupply; // } // // public long getHolderCount() { // return holderCount; // } // // public void setHolderCount(long holderCount) { // this.holderCount = holderCount; // } // // @Override // public int compareTo(@NonNull Object o) { // return ((TokenDisplay) o).getShorty().compareTo(shorty); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TokenDisplay that = (TokenDisplay) o; // // if (digits != that.digits) return false; // if (!name.equals(that.name)) return false; // return shorty.equals(that.shorty); // // } // // @Override // public int hashCode() { // int result = name.hashCode(); // result = 31 * result + shorty.hashCode(); // result = 31 * result + digits; // return result; // } // } // Path: app/src/main/java/rehanced/com/simpleetherwallet/utils/TokenAdapter.java import android.content.Context; import android.graphics.drawable.BitmapDrawable; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; import rehanced.com.simpleetherwallet.R; import rehanced.com.simpleetherwallet.data.TokenDisplay; package rehanced.com.simpleetherwallet.utils; public class TokenAdapter extends RecyclerView.Adapter<TokenAdapter.MyViewHolder> { private Context context;
private List<TokenDisplay> boxlist;
manuelsc/Lunary-Ethereum-Wallet
app/src/googleplay/java/rehanced/com/simpleetherwallet/fragments/FragmentWallets.java
// Path: app/src/fdroid/java/rehanced/com/simpleetherwallet/activities/AnalyticsApplication.java // public class AnalyticsApplication extends Application { // // private boolean isGooglePlayBuild = false; // // @Override // protected void attachBaseContext(Context base) { // super.attachBaseContext(base); // MultiDex.install(this); // } // // public boolean isGooglePlayBuild() { // return isGooglePlayBuild; // } // // public void track(String s) { // return; // } // // public void event(String s) { // return; // } // // } // // Path: app/src/main/java/rehanced/com/simpleetherwallet/utils/Settings.java // public class Settings { // // public static boolean showTransactionsWithZero = false; // // public static boolean startWithWalletTab = false; // // public static boolean walletBeingGenerated = false; // // public static boolean displayAds = true; // // public static void initiate(Context c) { // SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c); // showTransactionsWithZero = prefs.getBoolean("zeroAmountSwitch", false); // startWithWalletTab = prefs.getBoolean("startAtWallet", true); // } // // }
import android.view.View; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.MobileAds; import rehanced.com.simpleetherwallet.R; import rehanced.com.simpleetherwallet.activities.AnalyticsApplication; import rehanced.com.simpleetherwallet.utils.Settings;
package rehanced.com.simpleetherwallet.fragments; public class FragmentWallets extends FragmentWalletsAbstract{ @Override public void adHandling(View rootView) { // Ads
// Path: app/src/fdroid/java/rehanced/com/simpleetherwallet/activities/AnalyticsApplication.java // public class AnalyticsApplication extends Application { // // private boolean isGooglePlayBuild = false; // // @Override // protected void attachBaseContext(Context base) { // super.attachBaseContext(base); // MultiDex.install(this); // } // // public boolean isGooglePlayBuild() { // return isGooglePlayBuild; // } // // public void track(String s) { // return; // } // // public void event(String s) { // return; // } // // } // // Path: app/src/main/java/rehanced/com/simpleetherwallet/utils/Settings.java // public class Settings { // // public static boolean showTransactionsWithZero = false; // // public static boolean startWithWalletTab = false; // // public static boolean walletBeingGenerated = false; // // public static boolean displayAds = true; // // public static void initiate(Context c) { // SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c); // showTransactionsWithZero = prefs.getBoolean("zeroAmountSwitch", false); // startWithWalletTab = prefs.getBoolean("startAtWallet", true); // } // // } // Path: app/src/googleplay/java/rehanced/com/simpleetherwallet/fragments/FragmentWallets.java import android.view.View; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.MobileAds; import rehanced.com.simpleetherwallet.R; import rehanced.com.simpleetherwallet.activities.AnalyticsApplication; import rehanced.com.simpleetherwallet.utils.Settings; package rehanced.com.simpleetherwallet.fragments; public class FragmentWallets extends FragmentWalletsAbstract{ @Override public void adHandling(View rootView) { // Ads
if (((AnalyticsApplication) ac.getApplication()).isGooglePlayBuild()) {
manuelsc/Lunary-Ethereum-Wallet
app/src/googleplay/java/rehanced/com/simpleetherwallet/fragments/FragmentWallets.java
// Path: app/src/fdroid/java/rehanced/com/simpleetherwallet/activities/AnalyticsApplication.java // public class AnalyticsApplication extends Application { // // private boolean isGooglePlayBuild = false; // // @Override // protected void attachBaseContext(Context base) { // super.attachBaseContext(base); // MultiDex.install(this); // } // // public boolean isGooglePlayBuild() { // return isGooglePlayBuild; // } // // public void track(String s) { // return; // } // // public void event(String s) { // return; // } // // } // // Path: app/src/main/java/rehanced/com/simpleetherwallet/utils/Settings.java // public class Settings { // // public static boolean showTransactionsWithZero = false; // // public static boolean startWithWalletTab = false; // // public static boolean walletBeingGenerated = false; // // public static boolean displayAds = true; // // public static void initiate(Context c) { // SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c); // showTransactionsWithZero = prefs.getBoolean("zeroAmountSwitch", false); // startWithWalletTab = prefs.getBoolean("startAtWallet", true); // } // // }
import android.view.View; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.MobileAds; import rehanced.com.simpleetherwallet.R; import rehanced.com.simpleetherwallet.activities.AnalyticsApplication; import rehanced.com.simpleetherwallet.utils.Settings;
package rehanced.com.simpleetherwallet.fragments; public class FragmentWallets extends FragmentWalletsAbstract{ @Override public void adHandling(View rootView) { // Ads if (((AnalyticsApplication) ac.getApplication()).isGooglePlayBuild()) { AdView mAdView = (AdView) rootView.findViewById(R.id.adView);
// Path: app/src/fdroid/java/rehanced/com/simpleetherwallet/activities/AnalyticsApplication.java // public class AnalyticsApplication extends Application { // // private boolean isGooglePlayBuild = false; // // @Override // protected void attachBaseContext(Context base) { // super.attachBaseContext(base); // MultiDex.install(this); // } // // public boolean isGooglePlayBuild() { // return isGooglePlayBuild; // } // // public void track(String s) { // return; // } // // public void event(String s) { // return; // } // // } // // Path: app/src/main/java/rehanced/com/simpleetherwallet/utils/Settings.java // public class Settings { // // public static boolean showTransactionsWithZero = false; // // public static boolean startWithWalletTab = false; // // public static boolean walletBeingGenerated = false; // // public static boolean displayAds = true; // // public static void initiate(Context c) { // SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c); // showTransactionsWithZero = prefs.getBoolean("zeroAmountSwitch", false); // startWithWalletTab = prefs.getBoolean("startAtWallet", true); // } // // } // Path: app/src/googleplay/java/rehanced/com/simpleetherwallet/fragments/FragmentWallets.java import android.view.View; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.MobileAds; import rehanced.com.simpleetherwallet.R; import rehanced.com.simpleetherwallet.activities.AnalyticsApplication; import rehanced.com.simpleetherwallet.utils.Settings; package rehanced.com.simpleetherwallet.fragments; public class FragmentWallets extends FragmentWalletsAbstract{ @Override public void adHandling(View rootView) { // Ads if (((AnalyticsApplication) ac.getApplication()).isGooglePlayBuild()) { AdView mAdView = (AdView) rootView.findViewById(R.id.adView);
if (Settings.displayAds) {
manuelsc/Lunary-Ethereum-Wallet
app/src/main/java/rehanced/com/simpleetherwallet/activities/AppLockActivity.java
// Path: app/src/main/java/rehanced/com/simpleetherwallet/interfaces/FingerprintListener.java // public interface FingerprintListener { // public void authenticationFailed(String error); // // public void authenticationSucceeded(FingerprintManager.AuthenticationResult result); // } // // Path: app/src/main/java/rehanced/com/simpleetherwallet/utils/AppLockUtils.java // public class AppLockUtils { // // public static boolean hasDeviceFingerprintSupport(Context context) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // FingerprintManager fingerprintManager = (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE); // if (ActivityCompat.checkSelfPermission(context, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) { // return false; // } // return fingerprintManager.isHardwareDetected() && fingerprintManager.hasEnrolledFingerprints(); // } else { // return false; // } // } // // } // // Path: app/src/main/java/rehanced/com/simpleetherwallet/utils/FingerprintHelper.java // @RequiresApi(api = Build.VERSION_CODES.M) // public class FingerprintHelper extends FingerprintManager.AuthenticationCallback { // // private FingerprintListener listener; // // public FingerprintHelper(FingerprintListener listener) { // this.listener = listener; // } // // private CancellationSignal cancellationSignal; // // public void startAuth(FingerprintManager manager, FingerprintManager.CryptoObject cryptoObject) { // cancellationSignal = new CancellationSignal(); // // try { // manager.authenticate(cryptoObject, cancellationSignal, 0, this, null); // } catch (SecurityException ex) { // listener.authenticationFailed("An error occurred:\n" + ex.getMessage()); // } catch (Exception ex) { // listener.authenticationFailed("An error occurred\n" + ex.getMessage()); // } // } // // public void cancel() { // if (cancellationSignal != null) // cancellationSignal.cancel(); // } // // @Override // public void onAuthenticationError(int errMsgId, CharSequence errString) { // listener.authenticationFailed(errString.toString()); // } // // @Override // public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) { // listener.authenticationFailed(helpString.toString()); // } // // @Override // public void onAuthenticationFailed() { // listener.authenticationFailed("Authentication failed"); // } // // @Override // public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) { // listener.authenticationSucceeded(result); // } // // }
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.hardware.fingerprint.FingerprintManager; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.security.keystore.KeyGenParameterSpec; import android.security.keystore.KeyProperties; import androidx.annotation.RequiresApi; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import android.widget.Toast; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.util.List; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import me.zhanghai.android.patternlock.PatternUtils; import me.zhanghai.android.patternlock.PatternView; import rehanced.com.simpleetherwallet.R; import rehanced.com.simpleetherwallet.interfaces.FingerprintListener; import rehanced.com.simpleetherwallet.utils.AppLockUtils; import rehanced.com.simpleetherwallet.utils.FingerprintHelper;
package rehanced.com.simpleetherwallet.activities; public class AppLockActivity extends BasePatternActivity implements PatternView.OnPatternListener, FingerprintListener { public static final int REQUEST_CODE = 1000; private int mNumFailedAttempts = 0; private LinearLayout fingerprintcontainer; private boolean hasFingerprintSupport = false;
// Path: app/src/main/java/rehanced/com/simpleetherwallet/interfaces/FingerprintListener.java // public interface FingerprintListener { // public void authenticationFailed(String error); // // public void authenticationSucceeded(FingerprintManager.AuthenticationResult result); // } // // Path: app/src/main/java/rehanced/com/simpleetherwallet/utils/AppLockUtils.java // public class AppLockUtils { // // public static boolean hasDeviceFingerprintSupport(Context context) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // FingerprintManager fingerprintManager = (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE); // if (ActivityCompat.checkSelfPermission(context, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) { // return false; // } // return fingerprintManager.isHardwareDetected() && fingerprintManager.hasEnrolledFingerprints(); // } else { // return false; // } // } // // } // // Path: app/src/main/java/rehanced/com/simpleetherwallet/utils/FingerprintHelper.java // @RequiresApi(api = Build.VERSION_CODES.M) // public class FingerprintHelper extends FingerprintManager.AuthenticationCallback { // // private FingerprintListener listener; // // public FingerprintHelper(FingerprintListener listener) { // this.listener = listener; // } // // private CancellationSignal cancellationSignal; // // public void startAuth(FingerprintManager manager, FingerprintManager.CryptoObject cryptoObject) { // cancellationSignal = new CancellationSignal(); // // try { // manager.authenticate(cryptoObject, cancellationSignal, 0, this, null); // } catch (SecurityException ex) { // listener.authenticationFailed("An error occurred:\n" + ex.getMessage()); // } catch (Exception ex) { // listener.authenticationFailed("An error occurred\n" + ex.getMessage()); // } // } // // public void cancel() { // if (cancellationSignal != null) // cancellationSignal.cancel(); // } // // @Override // public void onAuthenticationError(int errMsgId, CharSequence errString) { // listener.authenticationFailed(errString.toString()); // } // // @Override // public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) { // listener.authenticationFailed(helpString.toString()); // } // // @Override // public void onAuthenticationFailed() { // listener.authenticationFailed("Authentication failed"); // } // // @Override // public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) { // listener.authenticationSucceeded(result); // } // // } // Path: app/src/main/java/rehanced/com/simpleetherwallet/activities/AppLockActivity.java import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.hardware.fingerprint.FingerprintManager; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.security.keystore.KeyGenParameterSpec; import android.security.keystore.KeyProperties; import androidx.annotation.RequiresApi; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import android.widget.Toast; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.util.List; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import me.zhanghai.android.patternlock.PatternUtils; import me.zhanghai.android.patternlock.PatternView; import rehanced.com.simpleetherwallet.R; import rehanced.com.simpleetherwallet.interfaces.FingerprintListener; import rehanced.com.simpleetherwallet.utils.AppLockUtils; import rehanced.com.simpleetherwallet.utils.FingerprintHelper; package rehanced.com.simpleetherwallet.activities; public class AppLockActivity extends BasePatternActivity implements PatternView.OnPatternListener, FingerprintListener { public static final int REQUEST_CODE = 1000; private int mNumFailedAttempts = 0; private LinearLayout fingerprintcontainer; private boolean hasFingerprintSupport = false;
private FingerprintHelper fingerprintHelper;
manuelsc/Lunary-Ethereum-Wallet
app/src/main/java/rehanced/com/simpleetherwallet/activities/AppLockActivity.java
// Path: app/src/main/java/rehanced/com/simpleetherwallet/interfaces/FingerprintListener.java // public interface FingerprintListener { // public void authenticationFailed(String error); // // public void authenticationSucceeded(FingerprintManager.AuthenticationResult result); // } // // Path: app/src/main/java/rehanced/com/simpleetherwallet/utils/AppLockUtils.java // public class AppLockUtils { // // public static boolean hasDeviceFingerprintSupport(Context context) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // FingerprintManager fingerprintManager = (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE); // if (ActivityCompat.checkSelfPermission(context, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) { // return false; // } // return fingerprintManager.isHardwareDetected() && fingerprintManager.hasEnrolledFingerprints(); // } else { // return false; // } // } // // } // // Path: app/src/main/java/rehanced/com/simpleetherwallet/utils/FingerprintHelper.java // @RequiresApi(api = Build.VERSION_CODES.M) // public class FingerprintHelper extends FingerprintManager.AuthenticationCallback { // // private FingerprintListener listener; // // public FingerprintHelper(FingerprintListener listener) { // this.listener = listener; // } // // private CancellationSignal cancellationSignal; // // public void startAuth(FingerprintManager manager, FingerprintManager.CryptoObject cryptoObject) { // cancellationSignal = new CancellationSignal(); // // try { // manager.authenticate(cryptoObject, cancellationSignal, 0, this, null); // } catch (SecurityException ex) { // listener.authenticationFailed("An error occurred:\n" + ex.getMessage()); // } catch (Exception ex) { // listener.authenticationFailed("An error occurred\n" + ex.getMessage()); // } // } // // public void cancel() { // if (cancellationSignal != null) // cancellationSignal.cancel(); // } // // @Override // public void onAuthenticationError(int errMsgId, CharSequence errString) { // listener.authenticationFailed(errString.toString()); // } // // @Override // public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) { // listener.authenticationFailed(helpString.toString()); // } // // @Override // public void onAuthenticationFailed() { // listener.authenticationFailed("Authentication failed"); // } // // @Override // public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) { // listener.authenticationSucceeded(result); // } // // }
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.hardware.fingerprint.FingerprintManager; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.security.keystore.KeyGenParameterSpec; import android.security.keystore.KeyProperties; import androidx.annotation.RequiresApi; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import android.widget.Toast; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.util.List; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import me.zhanghai.android.patternlock.PatternUtils; import me.zhanghai.android.patternlock.PatternView; import rehanced.com.simpleetherwallet.R; import rehanced.com.simpleetherwallet.interfaces.FingerprintListener; import rehanced.com.simpleetherwallet.utils.AppLockUtils; import rehanced.com.simpleetherwallet.utils.FingerprintHelper;
c.startActivityForResult(patternLock, AppLockActivity.REQUEST_CODE); } pausedFirst = onResume; } public static void handleLockResponse(Activity c, int resultCode) { if (resultCode != RESULT_OK) { c.finish(); unlockedFirst = false; } else { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(c.getApplicationContext()); SharedPreferences.Editor editor = preferences.edit(); editor.putLong("APP_UNLOCKED", System.currentTimeMillis()); editor.apply(); unlockedFirst = true; } } public void onBackPressed() { unlockedFirst = false; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mMessageText.setText(R.string.pl_draw_pattern_to_unlock); //mPatternView.setInStealthMode(true); mPatternView.setOnPatternListener(this); fingerprintcontainer = (LinearLayout) findViewById(R.id.fingerprintcontainer);
// Path: app/src/main/java/rehanced/com/simpleetherwallet/interfaces/FingerprintListener.java // public interface FingerprintListener { // public void authenticationFailed(String error); // // public void authenticationSucceeded(FingerprintManager.AuthenticationResult result); // } // // Path: app/src/main/java/rehanced/com/simpleetherwallet/utils/AppLockUtils.java // public class AppLockUtils { // // public static boolean hasDeviceFingerprintSupport(Context context) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // FingerprintManager fingerprintManager = (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE); // if (ActivityCompat.checkSelfPermission(context, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) { // return false; // } // return fingerprintManager.isHardwareDetected() && fingerprintManager.hasEnrolledFingerprints(); // } else { // return false; // } // } // // } // // Path: app/src/main/java/rehanced/com/simpleetherwallet/utils/FingerprintHelper.java // @RequiresApi(api = Build.VERSION_CODES.M) // public class FingerprintHelper extends FingerprintManager.AuthenticationCallback { // // private FingerprintListener listener; // // public FingerprintHelper(FingerprintListener listener) { // this.listener = listener; // } // // private CancellationSignal cancellationSignal; // // public void startAuth(FingerprintManager manager, FingerprintManager.CryptoObject cryptoObject) { // cancellationSignal = new CancellationSignal(); // // try { // manager.authenticate(cryptoObject, cancellationSignal, 0, this, null); // } catch (SecurityException ex) { // listener.authenticationFailed("An error occurred:\n" + ex.getMessage()); // } catch (Exception ex) { // listener.authenticationFailed("An error occurred\n" + ex.getMessage()); // } // } // // public void cancel() { // if (cancellationSignal != null) // cancellationSignal.cancel(); // } // // @Override // public void onAuthenticationError(int errMsgId, CharSequence errString) { // listener.authenticationFailed(errString.toString()); // } // // @Override // public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) { // listener.authenticationFailed(helpString.toString()); // } // // @Override // public void onAuthenticationFailed() { // listener.authenticationFailed("Authentication failed"); // } // // @Override // public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) { // listener.authenticationSucceeded(result); // } // // } // Path: app/src/main/java/rehanced/com/simpleetherwallet/activities/AppLockActivity.java import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.hardware.fingerprint.FingerprintManager; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.security.keystore.KeyGenParameterSpec; import android.security.keystore.KeyProperties; import androidx.annotation.RequiresApi; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import android.widget.Toast; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.util.List; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import me.zhanghai.android.patternlock.PatternUtils; import me.zhanghai.android.patternlock.PatternView; import rehanced.com.simpleetherwallet.R; import rehanced.com.simpleetherwallet.interfaces.FingerprintListener; import rehanced.com.simpleetherwallet.utils.AppLockUtils; import rehanced.com.simpleetherwallet.utils.FingerprintHelper; c.startActivityForResult(patternLock, AppLockActivity.REQUEST_CODE); } pausedFirst = onResume; } public static void handleLockResponse(Activity c, int resultCode) { if (resultCode != RESULT_OK) { c.finish(); unlockedFirst = false; } else { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(c.getApplicationContext()); SharedPreferences.Editor editor = preferences.edit(); editor.putLong("APP_UNLOCKED", System.currentTimeMillis()); editor.apply(); unlockedFirst = true; } } public void onBackPressed() { unlockedFirst = false; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mMessageText.setText(R.string.pl_draw_pattern_to_unlock); //mPatternView.setInStealthMode(true); mPatternView.setOnPatternListener(this); fingerprintcontainer = (LinearLayout) findViewById(R.id.fingerprintcontainer);
hasFingerprintSupport = AppLockUtils.hasDeviceFingerprintSupport(this);
manuelsc/Lunary-Ethereum-Wallet
app/src/main/java/rehanced/com/simpleetherwallet/utils/FingerprintHelper.java
// Path: app/src/main/java/rehanced/com/simpleetherwallet/interfaces/FingerprintListener.java // public interface FingerprintListener { // public void authenticationFailed(String error); // // public void authenticationSucceeded(FingerprintManager.AuthenticationResult result); // }
import android.hardware.fingerprint.FingerprintManager; import android.os.Build; import android.os.CancellationSignal; import androidx.annotation.RequiresApi; import rehanced.com.simpleetherwallet.interfaces.FingerprintListener;
package rehanced.com.simpleetherwallet.utils; @RequiresApi(api = Build.VERSION_CODES.M) public class FingerprintHelper extends FingerprintManager.AuthenticationCallback {
// Path: app/src/main/java/rehanced/com/simpleetherwallet/interfaces/FingerprintListener.java // public interface FingerprintListener { // public void authenticationFailed(String error); // // public void authenticationSucceeded(FingerprintManager.AuthenticationResult result); // } // Path: app/src/main/java/rehanced/com/simpleetherwallet/utils/FingerprintHelper.java import android.hardware.fingerprint.FingerprintManager; import android.os.Build; import android.os.CancellationSignal; import androidx.annotation.RequiresApi; import rehanced.com.simpleetherwallet.interfaces.FingerprintListener; package rehanced.com.simpleetherwallet.utils; @RequiresApi(api = Build.VERSION_CODES.M) public class FingerprintHelper extends FingerprintManager.AuthenticationCallback {
private FingerprintListener listener;
conekta/conekta-java
src/io/conekta/OfflineRecurrentReference.java
// Path: src/locales/Lang.java // public abstract class Lang { // public static final String EN = "en"; // public static final String ES = "es"; // public static Properties en = new Properties(); // public static Properties es = new Properties(); // // public static String translate(String key, HashMap parameters, String locale) { // try { // readDirectory(); // } catch (IOException ex) { // System.out.println(ex.getMessage()); // Logger.getLogger(Lang.class.getName()).log(Level.SEVERE, null, ex); // } // String translate = ""; // if (locale.equals("en")) // translate = en.getProperty(key); // if (locale.equals("es")) // translate = es.getProperty(key); // if (!parameters.isEmpty()) { // Iterator it = parameters.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pair = (Map.Entry)it.next(); // String k = (String) pair.getKey(); // String v = (String) pair.getValue(); // translate = translate.replace("%{"+ k.toLowerCase() +"}", v); // it.remove(); // avoids a ConcurrentModificationException // } // } // return translate; // } // // protected static void readDirectory() throws IOException { // if (!en.isEmpty() && !es.isEmpty()) { // return; // } // InputStream inEn = Lang.class.getClassLoader().getResourceAsStream("locales/messages/en.properties"); // InputStream inEs = Lang.class.getClassLoader().getResourceAsStream("locales/messages/es.properties"); // en.load(inEn); // es.load(inEs); // } // }
import locales.Lang; import java.util.HashMap;
package io.conekta; public class OfflineRecurrentReference extends PaymentSource { public String reference; public String barcode; public String barcode_url; public String provider; public String expires_at; @Override public String instanceUrl() throws Error { if (id == null || id.length() == 0) { HashMap parameters = new HashMap(); parameters.put("RESOURCE", this.getClass().getSimpleName());
// Path: src/locales/Lang.java // public abstract class Lang { // public static final String EN = "en"; // public static final String ES = "es"; // public static Properties en = new Properties(); // public static Properties es = new Properties(); // // public static String translate(String key, HashMap parameters, String locale) { // try { // readDirectory(); // } catch (IOException ex) { // System.out.println(ex.getMessage()); // Logger.getLogger(Lang.class.getName()).log(Level.SEVERE, null, ex); // } // String translate = ""; // if (locale.equals("en")) // translate = en.getProperty(key); // if (locale.equals("es")) // translate = es.getProperty(key); // if (!parameters.isEmpty()) { // Iterator it = parameters.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pair = (Map.Entry)it.next(); // String k = (String) pair.getKey(); // String v = (String) pair.getValue(); // translate = translate.replace("%{"+ k.toLowerCase() +"}", v); // it.remove(); // avoids a ConcurrentModificationException // } // } // return translate; // } // // protected static void readDirectory() throws IOException { // if (!en.isEmpty() && !es.isEmpty()) { // return; // } // InputStream inEn = Lang.class.getClassLoader().getResourceAsStream("locales/messages/en.properties"); // InputStream inEs = Lang.class.getClassLoader().getResourceAsStream("locales/messages/es.properties"); // en.load(inEn); // es.load(inEs); // } // } // Path: src/io/conekta/OfflineRecurrentReference.java import locales.Lang; import java.util.HashMap; package io.conekta; public class OfflineRecurrentReference extends PaymentSource { public String reference; public String barcode; public String barcode_url; public String provider; public String expires_at; @Override public String instanceUrl() throws Error { if (id == null || id.length() == 0) { HashMap parameters = new HashMap(); parameters.put("RESOURCE", this.getClass().getSimpleName());
throw new Error(Lang.translate("error.resource.id", parameters, Lang.EN),
conekta/conekta-java
src/io/conekta/ShippingContact.java
// Path: src/locales/Lang.java // public abstract class Lang { // public static final String EN = "en"; // public static final String ES = "es"; // public static Properties en = new Properties(); // public static Properties es = new Properties(); // // public static String translate(String key, HashMap parameters, String locale) { // try { // readDirectory(); // } catch (IOException ex) { // System.out.println(ex.getMessage()); // Logger.getLogger(Lang.class.getName()).log(Level.SEVERE, null, ex); // } // String translate = ""; // if (locale.equals("en")) // translate = en.getProperty(key); // if (locale.equals("es")) // translate = es.getProperty(key); // if (!parameters.isEmpty()) { // Iterator it = parameters.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pair = (Map.Entry)it.next(); // String k = (String) pair.getKey(); // String v = (String) pair.getValue(); // translate = translate.replace("%{"+ k.toLowerCase() +"}", v); // it.remove(); // avoids a ConcurrentModificationException // } // } // return translate; // } // // protected static void readDirectory() throws IOException { // if (!en.isEmpty() && !es.isEmpty()) { // return; // } // InputStream inEn = Lang.class.getClassLoader().getResourceAsStream("locales/messages/en.properties"); // InputStream inEs = Lang.class.getClassLoader().getResourceAsStream("locales/messages/es.properties"); // en.load(inEn); // es.load(inEs); // } // }
import java.util.HashMap; import locales.Lang; import org.json.JSONObject;
package io.conekta; /** * * @author L.Carlos */ public class ShippingContact extends Resource{ public Customer customer; public String name; public String phone; public String receiver; public Boolean deleted; public Address address; @Override public String instanceUrl() throws Error { if (id == null || id.length() == 0) { HashMap parameters = new HashMap(); parameters.put("RESOURCE", this.getClass().getSimpleName());
// Path: src/locales/Lang.java // public abstract class Lang { // public static final String EN = "en"; // public static final String ES = "es"; // public static Properties en = new Properties(); // public static Properties es = new Properties(); // // public static String translate(String key, HashMap parameters, String locale) { // try { // readDirectory(); // } catch (IOException ex) { // System.out.println(ex.getMessage()); // Logger.getLogger(Lang.class.getName()).log(Level.SEVERE, null, ex); // } // String translate = ""; // if (locale.equals("en")) // translate = en.getProperty(key); // if (locale.equals("es")) // translate = es.getProperty(key); // if (!parameters.isEmpty()) { // Iterator it = parameters.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pair = (Map.Entry)it.next(); // String k = (String) pair.getKey(); // String v = (String) pair.getValue(); // translate = translate.replace("%{"+ k.toLowerCase() +"}", v); // it.remove(); // avoids a ConcurrentModificationException // } // } // return translate; // } // // protected static void readDirectory() throws IOException { // if (!en.isEmpty() && !es.isEmpty()) { // return; // } // InputStream inEn = Lang.class.getClassLoader().getResourceAsStream("locales/messages/en.properties"); // InputStream inEs = Lang.class.getClassLoader().getResourceAsStream("locales/messages/es.properties"); // en.load(inEn); // es.load(inEs); // } // } // Path: src/io/conekta/ShippingContact.java import java.util.HashMap; import locales.Lang; import org.json.JSONObject; package io.conekta; /** * * @author L.Carlos */ public class ShippingContact extends Resource{ public Customer customer; public String name; public String phone; public String receiver; public Boolean deleted; public Address address; @Override public String instanceUrl() throws Error { if (id == null || id.length() == 0) { HashMap parameters = new HashMap(); parameters.put("RESOURCE", this.getClass().getSimpleName());
throw new Error(Lang.translate("error.resource.id", parameters, Lang.EN),
conekta/conekta-java
src/io/conekta/LineItems.java
// Path: src/locales/Lang.java // public abstract class Lang { // public static final String EN = "en"; // public static final String ES = "es"; // public static Properties en = new Properties(); // public static Properties es = new Properties(); // // public static String translate(String key, HashMap parameters, String locale) { // try { // readDirectory(); // } catch (IOException ex) { // System.out.println(ex.getMessage()); // Logger.getLogger(Lang.class.getName()).log(Level.SEVERE, null, ex); // } // String translate = ""; // if (locale.equals("en")) // translate = en.getProperty(key); // if (locale.equals("es")) // translate = es.getProperty(key); // if (!parameters.isEmpty()) { // Iterator it = parameters.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pair = (Map.Entry)it.next(); // String k = (String) pair.getKey(); // String v = (String) pair.getValue(); // translate = translate.replace("%{"+ k.toLowerCase() +"}", v); // it.remove(); // avoids a ConcurrentModificationException // } // } // return translate; // } // // protected static void readDirectory() throws IOException { // if (!en.isEmpty() && !es.isEmpty()) { // return; // } // InputStream inEn = Lang.class.getClassLoader().getResourceAsStream("locales/messages/en.properties"); // InputStream inEs = Lang.class.getClassLoader().getResourceAsStream("locales/messages/es.properties"); // en.load(inEn); // es.load(inEs); // } // }
import java.lang.reflect.Field; import java.util.HashMap; import locales.Lang; import org.json.JSONArray; import org.json.JSONObject;
public ConektaObject tags; public String brand; public String parent_id; public String object; public HashMap metadata; public Boolean deleted; // Helper method to access line item fields public String get(String key) { try { Field field; field = this.getClass().getField(key); return (String) field.get(this); } catch(NoSuchFieldException e) { return (String) antifraud_info.get(key); } catch(IllegalAccessException e) { return ""; } } // Helper method to push key values to vertical related fields public void addVerticalRelatedField(String key, String value) { antifraud_info.put(key, value); } @Override public String instanceUrl() throws Error { if (id == null || id.length() == 0) { HashMap parameters = new HashMap(); parameters.put("RESOURCE", this.getClass().getSimpleName());
// Path: src/locales/Lang.java // public abstract class Lang { // public static final String EN = "en"; // public static final String ES = "es"; // public static Properties en = new Properties(); // public static Properties es = new Properties(); // // public static String translate(String key, HashMap parameters, String locale) { // try { // readDirectory(); // } catch (IOException ex) { // System.out.println(ex.getMessage()); // Logger.getLogger(Lang.class.getName()).log(Level.SEVERE, null, ex); // } // String translate = ""; // if (locale.equals("en")) // translate = en.getProperty(key); // if (locale.equals("es")) // translate = es.getProperty(key); // if (!parameters.isEmpty()) { // Iterator it = parameters.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pair = (Map.Entry)it.next(); // String k = (String) pair.getKey(); // String v = (String) pair.getValue(); // translate = translate.replace("%{"+ k.toLowerCase() +"}", v); // it.remove(); // avoids a ConcurrentModificationException // } // } // return translate; // } // // protected static void readDirectory() throws IOException { // if (!en.isEmpty() && !es.isEmpty()) { // return; // } // InputStream inEn = Lang.class.getClassLoader().getResourceAsStream("locales/messages/en.properties"); // InputStream inEs = Lang.class.getClassLoader().getResourceAsStream("locales/messages/es.properties"); // en.load(inEn); // es.load(inEs); // } // } // Path: src/io/conekta/LineItems.java import java.lang.reflect.Field; import java.util.HashMap; import locales.Lang; import org.json.JSONArray; import org.json.JSONObject; public ConektaObject tags; public String brand; public String parent_id; public String object; public HashMap metadata; public Boolean deleted; // Helper method to access line item fields public String get(String key) { try { Field field; field = this.getClass().getField(key); return (String) field.get(this); } catch(NoSuchFieldException e) { return (String) antifraud_info.get(key); } catch(IllegalAccessException e) { return ""; } } // Helper method to push key values to vertical related fields public void addVerticalRelatedField(String key, String value) { antifraud_info.put(key, value); } @Override public String instanceUrl() throws Error { if (id == null || id.length() == 0) { HashMap parameters = new HashMap(); parameters.put("RESOURCE", this.getClass().getSimpleName());
throw new Error(Lang.translate("error.resource.id", parameters, Lang.EN),
conekta/conekta-java
src/io/conekta/Subscription.java
// Path: src/locales/Lang.java // public abstract class Lang { // public static final String EN = "en"; // public static final String ES = "es"; // public static Properties en = new Properties(); // public static Properties es = new Properties(); // // public static String translate(String key, HashMap parameters, String locale) { // try { // readDirectory(); // } catch (IOException ex) { // System.out.println(ex.getMessage()); // Logger.getLogger(Lang.class.getName()).log(Level.SEVERE, null, ex); // } // String translate = ""; // if (locale.equals("en")) // translate = en.getProperty(key); // if (locale.equals("es")) // translate = es.getProperty(key); // if (!parameters.isEmpty()) { // Iterator it = parameters.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pair = (Map.Entry)it.next(); // String k = (String) pair.getKey(); // String v = (String) pair.getValue(); // translate = translate.replace("%{"+ k.toLowerCase() +"}", v); // it.remove(); // avoids a ConcurrentModificationException // } // } // return translate; // } // // protected static void readDirectory() throws IOException { // if (!en.isEmpty() && !es.isEmpty()) { // return; // } // InputStream inEn = Lang.class.getClassLoader().getResourceAsStream("locales/messages/en.properties"); // InputStream inEs = Lang.class.getClassLoader().getResourceAsStream("locales/messages/es.properties"); // en.load(inEn); // es.load(inEs); // } // }
import java.util.HashMap; import locales.Lang; import org.json.JSONObject;
package io.conekta; /** * * @author mauricio */ public class Subscription extends Resource { public Customer customer; public String status; public Integer created_at; public Integer billing_cycle_start; public Integer billing_cycle_end; public String plan_id; public String customer_id; public String card_id; @Override public String instanceUrl() throws Error { if (id == null || id.length() == 0) { HashMap parameters = new HashMap(); parameters.put("RESOURCE", this.getClass().getSimpleName());
// Path: src/locales/Lang.java // public abstract class Lang { // public static final String EN = "en"; // public static final String ES = "es"; // public static Properties en = new Properties(); // public static Properties es = new Properties(); // // public static String translate(String key, HashMap parameters, String locale) { // try { // readDirectory(); // } catch (IOException ex) { // System.out.println(ex.getMessage()); // Logger.getLogger(Lang.class.getName()).log(Level.SEVERE, null, ex); // } // String translate = ""; // if (locale.equals("en")) // translate = en.getProperty(key); // if (locale.equals("es")) // translate = es.getProperty(key); // if (!parameters.isEmpty()) { // Iterator it = parameters.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pair = (Map.Entry)it.next(); // String k = (String) pair.getKey(); // String v = (String) pair.getValue(); // translate = translate.replace("%{"+ k.toLowerCase() +"}", v); // it.remove(); // avoids a ConcurrentModificationException // } // } // return translate; // } // // protected static void readDirectory() throws IOException { // if (!en.isEmpty() && !es.isEmpty()) { // return; // } // InputStream inEn = Lang.class.getClassLoader().getResourceAsStream("locales/messages/en.properties"); // InputStream inEs = Lang.class.getClassLoader().getResourceAsStream("locales/messages/es.properties"); // en.load(inEn); // es.load(inEs); // } // } // Path: src/io/conekta/Subscription.java import java.util.HashMap; import locales.Lang; import org.json.JSONObject; package io.conekta; /** * * @author mauricio */ public class Subscription extends Resource { public Customer customer; public String status; public Integer created_at; public Integer billing_cycle_start; public Integer billing_cycle_end; public String plan_id; public String customer_id; public String card_id; @Override public String instanceUrl() throws Error { if (id == null || id.length() == 0) { HashMap parameters = new HashMap(); parameters.put("RESOURCE", this.getClass().getSimpleName());
throw new Error(Lang.translate("error.resource.id", parameters, Lang.EN),
conekta/conekta-java
src/io/conekta/PaymentSource.java
// Path: src/locales/Lang.java // public abstract class Lang { // public static final String EN = "en"; // public static final String ES = "es"; // public static Properties en = new Properties(); // public static Properties es = new Properties(); // // public static String translate(String key, HashMap parameters, String locale) { // try { // readDirectory(); // } catch (IOException ex) { // System.out.println(ex.getMessage()); // Logger.getLogger(Lang.class.getName()).log(Level.SEVERE, null, ex); // } // String translate = ""; // if (locale.equals("en")) // translate = en.getProperty(key); // if (locale.equals("es")) // translate = es.getProperty(key); // if (!parameters.isEmpty()) { // Iterator it = parameters.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pair = (Map.Entry)it.next(); // String k = (String) pair.getKey(); // String v = (String) pair.getValue(); // translate = translate.replace("%{"+ k.toLowerCase() +"}", v); // it.remove(); // avoids a ConcurrentModificationException // } // } // return translate; // } // // protected static void readDirectory() throws IOException { // if (!en.isEmpty() && !es.isEmpty()) { // return; // } // InputStream inEn = Lang.class.getClassLoader().getResourceAsStream("locales/messages/en.properties"); // InputStream inEs = Lang.class.getClassLoader().getResourceAsStream("locales/messages/es.properties"); // en.load(inEn); // es.load(inEs); // } // }
import java.util.HashMap; import locales.Lang; import org.json.JSONObject;
package io.conekta; /** * * @author L.Carlos */ public class PaymentSource extends Resource{ public Customer customer; public Boolean deleted; public String type; @Override public String instanceUrl() throws Error { if (id == null || id.length() == 0) { HashMap parameters = new HashMap(); parameters.put("RESOURCE", this.getClass().getSimpleName());
// Path: src/locales/Lang.java // public abstract class Lang { // public static final String EN = "en"; // public static final String ES = "es"; // public static Properties en = new Properties(); // public static Properties es = new Properties(); // // public static String translate(String key, HashMap parameters, String locale) { // try { // readDirectory(); // } catch (IOException ex) { // System.out.println(ex.getMessage()); // Logger.getLogger(Lang.class.getName()).log(Level.SEVERE, null, ex); // } // String translate = ""; // if (locale.equals("en")) // translate = en.getProperty(key); // if (locale.equals("es")) // translate = es.getProperty(key); // if (!parameters.isEmpty()) { // Iterator it = parameters.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pair = (Map.Entry)it.next(); // String k = (String) pair.getKey(); // String v = (String) pair.getValue(); // translate = translate.replace("%{"+ k.toLowerCase() +"}", v); // it.remove(); // avoids a ConcurrentModificationException // } // } // return translate; // } // // protected static void readDirectory() throws IOException { // if (!en.isEmpty() && !es.isEmpty()) { // return; // } // InputStream inEn = Lang.class.getClassLoader().getResourceAsStream("locales/messages/en.properties"); // InputStream inEs = Lang.class.getClassLoader().getResourceAsStream("locales/messages/es.properties"); // en.load(inEn); // es.load(inEs); // } // } // Path: src/io/conekta/PaymentSource.java import java.util.HashMap; import locales.Lang; import org.json.JSONObject; package io.conekta; /** * * @author L.Carlos */ public class PaymentSource extends Resource{ public Customer customer; public Boolean deleted; public String type; @Override public String instanceUrl() throws Error { if (id == null || id.length() == 0) { HashMap parameters = new HashMap(); parameters.put("RESOURCE", this.getClass().getSimpleName());
throw new Error(Lang.translate("error.resource.id", parameters, Lang.EN),
conekta/conekta-java
src/io/conekta/DiscountLine.java
// Path: src/locales/Lang.java // public abstract class Lang { // public static final String EN = "en"; // public static final String ES = "es"; // public static Properties en = new Properties(); // public static Properties es = new Properties(); // // public static String translate(String key, HashMap parameters, String locale) { // try { // readDirectory(); // } catch (IOException ex) { // System.out.println(ex.getMessage()); // Logger.getLogger(Lang.class.getName()).log(Level.SEVERE, null, ex); // } // String translate = ""; // if (locale.equals("en")) // translate = en.getProperty(key); // if (locale.equals("es")) // translate = es.getProperty(key); // if (!parameters.isEmpty()) { // Iterator it = parameters.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pair = (Map.Entry)it.next(); // String k = (String) pair.getKey(); // String v = (String) pair.getValue(); // translate = translate.replace("%{"+ k.toLowerCase() +"}", v); // it.remove(); // avoids a ConcurrentModificationException // } // } // return translate; // } // // protected static void readDirectory() throws IOException { // if (!en.isEmpty() && !es.isEmpty()) { // return; // } // InputStream inEn = Lang.class.getClassLoader().getResourceAsStream("locales/messages/en.properties"); // InputStream inEs = Lang.class.getClassLoader().getResourceAsStream("locales/messages/es.properties"); // en.load(inEn); // es.load(inEs); // } // }
import java.util.HashMap; import locales.Lang; import org.json.JSONObject;
package io.conekta; /** * * @author L.Carlos */ public class DiscountLine extends Resource { public Order order; public String description; public String code; public String type; public Integer amount; public Boolean deleted; @Override public String instanceUrl() throws Error { if (id == null || id.length() == 0) { HashMap parameters = new HashMap(); parameters.put("RESOURCE", this.getClass().getSimpleName());
// Path: src/locales/Lang.java // public abstract class Lang { // public static final String EN = "en"; // public static final String ES = "es"; // public static Properties en = new Properties(); // public static Properties es = new Properties(); // // public static String translate(String key, HashMap parameters, String locale) { // try { // readDirectory(); // } catch (IOException ex) { // System.out.println(ex.getMessage()); // Logger.getLogger(Lang.class.getName()).log(Level.SEVERE, null, ex); // } // String translate = ""; // if (locale.equals("en")) // translate = en.getProperty(key); // if (locale.equals("es")) // translate = es.getProperty(key); // if (!parameters.isEmpty()) { // Iterator it = parameters.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pair = (Map.Entry)it.next(); // String k = (String) pair.getKey(); // String v = (String) pair.getValue(); // translate = translate.replace("%{"+ k.toLowerCase() +"}", v); // it.remove(); // avoids a ConcurrentModificationException // } // } // return translate; // } // // protected static void readDirectory() throws IOException { // if (!en.isEmpty() && !es.isEmpty()) { // return; // } // InputStream inEn = Lang.class.getClassLoader().getResourceAsStream("locales/messages/en.properties"); // InputStream inEs = Lang.class.getClassLoader().getResourceAsStream("locales/messages/es.properties"); // en.load(inEn); // es.load(inEs); // } // } // Path: src/io/conekta/DiscountLine.java import java.util.HashMap; import locales.Lang; import org.json.JSONObject; package io.conekta; /** * * @author L.Carlos */ public class DiscountLine extends Resource { public Order order; public String description; public String code; public String type; public Integer amount; public Boolean deleted; @Override public String instanceUrl() throws Error { if (id == null || id.length() == 0) { HashMap parameters = new HashMap(); parameters.put("RESOURCE", this.getClass().getSimpleName());
throw new Error(Lang.translate("error.resource.id", parameters, Lang.EN),
conekta/conekta-java
src/io/conekta/Card.java
// Path: src/locales/Lang.java // public abstract class Lang { // public static final String EN = "en"; // public static final String ES = "es"; // public static Properties en = new Properties(); // public static Properties es = new Properties(); // // public static String translate(String key, HashMap parameters, String locale) { // try { // readDirectory(); // } catch (IOException ex) { // System.out.println(ex.getMessage()); // Logger.getLogger(Lang.class.getName()).log(Level.SEVERE, null, ex); // } // String translate = ""; // if (locale.equals("en")) // translate = en.getProperty(key); // if (locale.equals("es")) // translate = es.getProperty(key); // if (!parameters.isEmpty()) { // Iterator it = parameters.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pair = (Map.Entry)it.next(); // String k = (String) pair.getKey(); // String v = (String) pair.getValue(); // translate = translate.replace("%{"+ k.toLowerCase() +"}", v); // it.remove(); // avoids a ConcurrentModificationException // } // } // return translate; // } // // protected static void readDirectory() throws IOException { // if (!en.isEmpty() && !es.isEmpty()) { // return; // } // InputStream inEn = Lang.class.getClassLoader().getResourceAsStream("locales/messages/en.properties"); // InputStream inEs = Lang.class.getClassLoader().getResourceAsStream("locales/messages/es.properties"); // en.load(inEn); // es.load(inEs); // } // }
import java.util.HashMap; import locales.Lang; import org.json.JSONObject;
package io.conekta; /** * * @author mauricio */ public class Card extends PaymentSource { public String name; public String last4; public String bin; public String brand; public String cvc; public Address address; public String exp_month; public String exp_year; @Override public String instanceUrl() throws Error { if (id == null || id.length() == 0) { HashMap parameters = new HashMap(); parameters.put("RESOURCE", this.getClass().getSimpleName());
// Path: src/locales/Lang.java // public abstract class Lang { // public static final String EN = "en"; // public static final String ES = "es"; // public static Properties en = new Properties(); // public static Properties es = new Properties(); // // public static String translate(String key, HashMap parameters, String locale) { // try { // readDirectory(); // } catch (IOException ex) { // System.out.println(ex.getMessage()); // Logger.getLogger(Lang.class.getName()).log(Level.SEVERE, null, ex); // } // String translate = ""; // if (locale.equals("en")) // translate = en.getProperty(key); // if (locale.equals("es")) // translate = es.getProperty(key); // if (!parameters.isEmpty()) { // Iterator it = parameters.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pair = (Map.Entry)it.next(); // String k = (String) pair.getKey(); // String v = (String) pair.getValue(); // translate = translate.replace("%{"+ k.toLowerCase() +"}", v); // it.remove(); // avoids a ConcurrentModificationException // } // } // return translate; // } // // protected static void readDirectory() throws IOException { // if (!en.isEmpty() && !es.isEmpty()) { // return; // } // InputStream inEn = Lang.class.getClassLoader().getResourceAsStream("locales/messages/en.properties"); // InputStream inEs = Lang.class.getClassLoader().getResourceAsStream("locales/messages/es.properties"); // en.load(inEn); // es.load(inEs); // } // } // Path: src/io/conekta/Card.java import java.util.HashMap; import locales.Lang; import org.json.JSONObject; package io.conekta; /** * * @author mauricio */ public class Card extends PaymentSource { public String name; public String last4; public String bin; public String brand; public String cvc; public Address address; public String exp_month; public String exp_year; @Override public String instanceUrl() throws Error { if (id == null || id.length() == 0) { HashMap parameters = new HashMap(); parameters.put("RESOURCE", this.getClass().getSimpleName());
throw new Error(Lang.translate("error.resource.id", parameters, Lang.EN),
conekta/conekta-java
src/io/conekta/TaxLine.java
// Path: src/locales/Lang.java // public abstract class Lang { // public static final String EN = "en"; // public static final String ES = "es"; // public static Properties en = new Properties(); // public static Properties es = new Properties(); // // public static String translate(String key, HashMap parameters, String locale) { // try { // readDirectory(); // } catch (IOException ex) { // System.out.println(ex.getMessage()); // Logger.getLogger(Lang.class.getName()).log(Level.SEVERE, null, ex); // } // String translate = ""; // if (locale.equals("en")) // translate = en.getProperty(key); // if (locale.equals("es")) // translate = es.getProperty(key); // if (!parameters.isEmpty()) { // Iterator it = parameters.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pair = (Map.Entry)it.next(); // String k = (String) pair.getKey(); // String v = (String) pair.getValue(); // translate = translate.replace("%{"+ k.toLowerCase() +"}", v); // it.remove(); // avoids a ConcurrentModificationException // } // } // return translate; // } // // protected static void readDirectory() throws IOException { // if (!en.isEmpty() && !es.isEmpty()) { // return; // } // InputStream inEn = Lang.class.getClassLoader().getResourceAsStream("locales/messages/en.properties"); // InputStream inEs = Lang.class.getClassLoader().getResourceAsStream("locales/messages/es.properties"); // en.load(inEn); // es.load(inEs); // } // }
import java.util.HashMap; import locales.Lang; import org.json.JSONObject;
package io.conekta; /** * * @author L.Carlos */ public class TaxLine extends Resource { public Order order; public Integer amount; public String description; public Boolean deleted; public HashMap metadata; @Override public String instanceUrl() throws Error { if (id == null || id.length() == 0) { HashMap parameters = new HashMap(); parameters.put("RESOURCE", this.getClass().getSimpleName());
// Path: src/locales/Lang.java // public abstract class Lang { // public static final String EN = "en"; // public static final String ES = "es"; // public static Properties en = new Properties(); // public static Properties es = new Properties(); // // public static String translate(String key, HashMap parameters, String locale) { // try { // readDirectory(); // } catch (IOException ex) { // System.out.println(ex.getMessage()); // Logger.getLogger(Lang.class.getName()).log(Level.SEVERE, null, ex); // } // String translate = ""; // if (locale.equals("en")) // translate = en.getProperty(key); // if (locale.equals("es")) // translate = es.getProperty(key); // if (!parameters.isEmpty()) { // Iterator it = parameters.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pair = (Map.Entry)it.next(); // String k = (String) pair.getKey(); // String v = (String) pair.getValue(); // translate = translate.replace("%{"+ k.toLowerCase() +"}", v); // it.remove(); // avoids a ConcurrentModificationException // } // } // return translate; // } // // protected static void readDirectory() throws IOException { // if (!en.isEmpty() && !es.isEmpty()) { // return; // } // InputStream inEn = Lang.class.getClassLoader().getResourceAsStream("locales/messages/en.properties"); // InputStream inEs = Lang.class.getClassLoader().getResourceAsStream("locales/messages/es.properties"); // en.load(inEn); // es.load(inEs); // } // } // Path: src/io/conekta/TaxLine.java import java.util.HashMap; import locales.Lang; import org.json.JSONObject; package io.conekta; /** * * @author L.Carlos */ public class TaxLine extends Resource { public Order order; public Integer amount; public String description; public Boolean deleted; public HashMap metadata; @Override public String instanceUrl() throws Error { if (id == null || id.length() == 0) { HashMap parameters = new HashMap(); parameters.put("RESOURCE", this.getClass().getSimpleName());
throw new Error(Lang.translate("error.resource.id", parameters, Lang.EN),
conekta/conekta-java
src/io/conekta/Resource.java
// Path: src/locales/Lang.java // public abstract class Lang { // public static final String EN = "en"; // public static final String ES = "es"; // public static Properties en = new Properties(); // public static Properties es = new Properties(); // // public static String translate(String key, HashMap parameters, String locale) { // try { // readDirectory(); // } catch (IOException ex) { // System.out.println(ex.getMessage()); // Logger.getLogger(Lang.class.getName()).log(Level.SEVERE, null, ex); // } // String translate = ""; // if (locale.equals("en")) // translate = en.getProperty(key); // if (locale.equals("es")) // translate = es.getProperty(key); // if (!parameters.isEmpty()) { // Iterator it = parameters.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pair = (Map.Entry)it.next(); // String k = (String) pair.getKey(); // String v = (String) pair.getValue(); // translate = translate.replace("%{"+ k.toLowerCase() +"}", v); // it.remove(); // avoids a ConcurrentModificationException // } // } // return translate; // } // // protected static void readDirectory() throws IOException { // if (!en.isEmpty() && !es.isEmpty()) { // return; // } // InputStream inEn = Lang.class.getClassLoader().getResourceAsStream("locales/messages/en.properties"); // InputStream inEs = Lang.class.getClassLoader().getResourceAsStream("locales/messages/es.properties"); // en.load(inEn); // es.load(inEs); // } // }
import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.HashMap; import locales.Lang; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;
package io.conekta; /** * * @author mauricio */ public class Resource extends ConektaObject { public Resource(String id) { super(id); } public Resource() { super(); } public static String classUrl(String className) { String base = "/" + className.toLowerCase().replace("io.conekta.", "") + "s"; return base; } public String instanceUrl() throws Error { String className = this.getClass().getSimpleName(); if (id == null || id.length() == 0) { HashMap parameters = new HashMap(); parameters.put("RESOURCE", className);
// Path: src/locales/Lang.java // public abstract class Lang { // public static final String EN = "en"; // public static final String ES = "es"; // public static Properties en = new Properties(); // public static Properties es = new Properties(); // // public static String translate(String key, HashMap parameters, String locale) { // try { // readDirectory(); // } catch (IOException ex) { // System.out.println(ex.getMessage()); // Logger.getLogger(Lang.class.getName()).log(Level.SEVERE, null, ex); // } // String translate = ""; // if (locale.equals("en")) // translate = en.getProperty(key); // if (locale.equals("es")) // translate = es.getProperty(key); // if (!parameters.isEmpty()) { // Iterator it = parameters.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pair = (Map.Entry)it.next(); // String k = (String) pair.getKey(); // String v = (String) pair.getValue(); // translate = translate.replace("%{"+ k.toLowerCase() +"}", v); // it.remove(); // avoids a ConcurrentModificationException // } // } // return translate; // } // // protected static void readDirectory() throws IOException { // if (!en.isEmpty() && !es.isEmpty()) { // return; // } // InputStream inEn = Lang.class.getClassLoader().getResourceAsStream("locales/messages/en.properties"); // InputStream inEs = Lang.class.getClassLoader().getResourceAsStream("locales/messages/es.properties"); // en.load(inEn); // es.load(inEs); // } // } // Path: src/io/conekta/Resource.java import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.HashMap; import locales.Lang; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; package io.conekta; /** * * @author mauricio */ public class Resource extends ConektaObject { public Resource(String id) { super(id); } public Resource() { super(); } public static String classUrl(String className) { String base = "/" + className.toLowerCase().replace("io.conekta.", "") + "s"; return base; } public String instanceUrl() throws Error { String className = this.getClass().getSimpleName(); if (id == null || id.length() == 0) { HashMap parameters = new HashMap(); parameters.put("RESOURCE", className);
throw new Error(Lang.translate("error.resource.id", parameters, Lang.EN),
conekta/conekta-java
src/io/conekta/Error.java
// Path: src/locales/Lang.java // public abstract class Lang { // public static final String EN = "en"; // public static final String ES = "es"; // public static Properties en = new Properties(); // public static Properties es = new Properties(); // // public static String translate(String key, HashMap parameters, String locale) { // try { // readDirectory(); // } catch (IOException ex) { // System.out.println(ex.getMessage()); // Logger.getLogger(Lang.class.getName()).log(Level.SEVERE, null, ex); // } // String translate = ""; // if (locale.equals("en")) // translate = en.getProperty(key); // if (locale.equals("es")) // translate = es.getProperty(key); // if (!parameters.isEmpty()) { // Iterator it = parameters.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pair = (Map.Entry)it.next(); // String k = (String) pair.getKey(); // String v = (String) pair.getValue(); // translate = translate.replace("%{"+ k.toLowerCase() +"}", v); // it.remove(); // avoids a ConcurrentModificationException // } // } // return translate; // } // // protected static void readDirectory() throws IOException { // if (!en.isEmpty() && !es.isEmpty()) { // return; // } // InputStream inEn = Lang.class.getClassLoader().getResourceAsStream("locales/messages/en.properties"); // InputStream inEs = Lang.class.getClassLoader().getResourceAsStream("locales/messages/es.properties"); // en.load(inEn); // es.load(inEs); // } // }
import java.util.HashMap; import locales.Lang; import org.json.JSONException; import org.json.JSONObject;
package io.conekta; /** * * @author mauricio */ public class Error extends Exception { public String message; public String message_to_purchaser; public String debug_message; public String type; public Integer code; public String params; public Error(String message, String message_to_purchaser, String type, Integer code, String params) { super(message); HashMap parameters = new HashMap(); parameters.put("BASE", Conekta.apiBase); if (message != null) { this.message = message; } else {
// Path: src/locales/Lang.java // public abstract class Lang { // public static final String EN = "en"; // public static final String ES = "es"; // public static Properties en = new Properties(); // public static Properties es = new Properties(); // // public static String translate(String key, HashMap parameters, String locale) { // try { // readDirectory(); // } catch (IOException ex) { // System.out.println(ex.getMessage()); // Logger.getLogger(Lang.class.getName()).log(Level.SEVERE, null, ex); // } // String translate = ""; // if (locale.equals("en")) // translate = en.getProperty(key); // if (locale.equals("es")) // translate = es.getProperty(key); // if (!parameters.isEmpty()) { // Iterator it = parameters.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pair = (Map.Entry)it.next(); // String k = (String) pair.getKey(); // String v = (String) pair.getValue(); // translate = translate.replace("%{"+ k.toLowerCase() +"}", v); // it.remove(); // avoids a ConcurrentModificationException // } // } // return translate; // } // // protected static void readDirectory() throws IOException { // if (!en.isEmpty() && !es.isEmpty()) { // return; // } // InputStream inEn = Lang.class.getClassLoader().getResourceAsStream("locales/messages/en.properties"); // InputStream inEs = Lang.class.getClassLoader().getResourceAsStream("locales/messages/es.properties"); // en.load(inEn); // es.load(inEs); // } // } // Path: src/io/conekta/Error.java import java.util.HashMap; import locales.Lang; import org.json.JSONException; import org.json.JSONObject; package io.conekta; /** * * @author mauricio */ public class Error extends Exception { public String message; public String message_to_purchaser; public String debug_message; public String type; public Integer code; public String params; public Error(String message, String message_to_purchaser, String type, Integer code, String params) { super(message); HashMap parameters = new HashMap(); parameters.put("BASE", Conekta.apiBase); if (message != null) { this.message = message; } else {
this.message = Lang.translate("error.requestor.connection", parameters, Lang.EN);
conekta/conekta-java
src/io/conekta/ShippingLine.java
// Path: src/locales/Lang.java // public abstract class Lang { // public static final String EN = "en"; // public static final String ES = "es"; // public static Properties en = new Properties(); // public static Properties es = new Properties(); // // public static String translate(String key, HashMap parameters, String locale) { // try { // readDirectory(); // } catch (IOException ex) { // System.out.println(ex.getMessage()); // Logger.getLogger(Lang.class.getName()).log(Level.SEVERE, null, ex); // } // String translate = ""; // if (locale.equals("en")) // translate = en.getProperty(key); // if (locale.equals("es")) // translate = es.getProperty(key); // if (!parameters.isEmpty()) { // Iterator it = parameters.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pair = (Map.Entry)it.next(); // String k = (String) pair.getKey(); // String v = (String) pair.getValue(); // translate = translate.replace("%{"+ k.toLowerCase() +"}", v); // it.remove(); // avoids a ConcurrentModificationException // } // } // return translate; // } // // protected static void readDirectory() throws IOException { // if (!en.isEmpty() && !es.isEmpty()) { // return; // } // InputStream inEn = Lang.class.getClassLoader().getResourceAsStream("locales/messages/en.properties"); // InputStream inEs = Lang.class.getClassLoader().getResourceAsStream("locales/messages/es.properties"); // en.load(inEn); // es.load(inEs); // } // }
import java.util.HashMap; import locales.Lang; import org.json.JSONObject;
package io.conekta; /** * * @author L.Carlos */ public class ShippingLine extends Resource { public Order order; public Boolean deleted; public String tracking_number; public String carrier; public Integer amount; public Integer method; public HashMap metadata = new HashMap(); @Override public String instanceUrl() throws Error { if (id == null || id.length() == 0) { HashMap parameters = new HashMap(); parameters.put("RESOURCE", this.getClass().getSimpleName());
// Path: src/locales/Lang.java // public abstract class Lang { // public static final String EN = "en"; // public static final String ES = "es"; // public static Properties en = new Properties(); // public static Properties es = new Properties(); // // public static String translate(String key, HashMap parameters, String locale) { // try { // readDirectory(); // } catch (IOException ex) { // System.out.println(ex.getMessage()); // Logger.getLogger(Lang.class.getName()).log(Level.SEVERE, null, ex); // } // String translate = ""; // if (locale.equals("en")) // translate = en.getProperty(key); // if (locale.equals("es")) // translate = es.getProperty(key); // if (!parameters.isEmpty()) { // Iterator it = parameters.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry pair = (Map.Entry)it.next(); // String k = (String) pair.getKey(); // String v = (String) pair.getValue(); // translate = translate.replace("%{"+ k.toLowerCase() +"}", v); // it.remove(); // avoids a ConcurrentModificationException // } // } // return translate; // } // // protected static void readDirectory() throws IOException { // if (!en.isEmpty() && !es.isEmpty()) { // return; // } // InputStream inEn = Lang.class.getClassLoader().getResourceAsStream("locales/messages/en.properties"); // InputStream inEs = Lang.class.getClassLoader().getResourceAsStream("locales/messages/es.properties"); // en.load(inEn); // es.load(inEs); // } // } // Path: src/io/conekta/ShippingLine.java import java.util.HashMap; import locales.Lang; import org.json.JSONObject; package io.conekta; /** * * @author L.Carlos */ public class ShippingLine extends Resource { public Order order; public Boolean deleted; public String tracking_number; public String carrier; public Integer amount; public Integer method; public HashMap metadata = new HashMap(); @Override public String instanceUrl() throws Error { if (id == null || id.length() == 0) { HashMap parameters = new HashMap(); parameters.put("RESOURCE", this.getClass().getSimpleName());
throw new Error(Lang.translate("error.resource.id", parameters, Lang.EN),
DDTH/ddth-kafka
src/main/java/com/github/ddth/kafka/internal/KafkaHelper.java
// Path: src/main/java/com/github/ddth/kafka/KafkaClient.java // public enum ProducerType {NO_ACK, LEADER_ACK, ALL_ACKS; // public final static ProducerType[] ALL_TYPES = { NO_ACK, LEADER_ACK, ALL_ACKS };} // // Path: src/main/java/com/github/ddth/kafka/KafkaTopicPartitionOffset.java // public class KafkaTopicPartitionOffset { // public final String topic; // public final int partition; // public final long offset; // // public KafkaTopicPartitionOffset(String topic, int partition, long offset) { // this.topic = topic; // this.partition = partition; // this.offset = offset; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // ToStringBuilder tsb = new ToStringBuilder(this); // tsb.append("topic", topic).append("partition", partition).append("offset", offset); // return tsb.build(); // } // }
import com.github.ddth.kafka.KafkaClient.ProducerType; import com.github.ddth.kafka.KafkaTopicPartitionOffset; import org.apache.commons.lang3.StringUtils; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.serialization.ByteArrayDeserializer; import org.apache.kafka.common.serialization.ByteArraySerializer; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import java.util.Arrays; import java.util.Properties; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
package com.github.ddth.kafka.internal; /** * Helper utility class. * * @author Thanh Ba Nguyen <[email protected]> * @since 1.2.0 */ public class KafkaHelper { /** * Helper method to create a {@link ExecutorService} instance (internal use). * * @param es * @return */ public static ExecutorService createExecutorServiceIfNull(ExecutorService es) { if (es == null) { int numThreads = Math.min(Math.max(Runtime.getRuntime().availableProcessors(), 1), 4); es = Executors.newFixedThreadPool(numThreads); } return es; } /** * Helper method to shutdown a {@link ExecutorService} instance (internal use). * * @param es */ public static void destroyExecutorService(ExecutorService es) { if (es != null) { es.shutdownNow(); } } /** * Seek to a specified offset. * * @param consumer * @param tpo * @return {@code true} if the consumer has subscribed to the specified * topic/partition, {@code false} otherwise. * @since 1.3.2 */
// Path: src/main/java/com/github/ddth/kafka/KafkaClient.java // public enum ProducerType {NO_ACK, LEADER_ACK, ALL_ACKS; // public final static ProducerType[] ALL_TYPES = { NO_ACK, LEADER_ACK, ALL_ACKS };} // // Path: src/main/java/com/github/ddth/kafka/KafkaTopicPartitionOffset.java // public class KafkaTopicPartitionOffset { // public final String topic; // public final int partition; // public final long offset; // // public KafkaTopicPartitionOffset(String topic, int partition, long offset) { // this.topic = topic; // this.partition = partition; // this.offset = offset; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // ToStringBuilder tsb = new ToStringBuilder(this); // tsb.append("topic", topic).append("partition", partition).append("offset", offset); // return tsb.build(); // } // } // Path: src/main/java/com/github/ddth/kafka/internal/KafkaHelper.java import com.github.ddth.kafka.KafkaClient.ProducerType; import com.github.ddth.kafka.KafkaTopicPartitionOffset; import org.apache.commons.lang3.StringUtils; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.serialization.ByteArrayDeserializer; import org.apache.kafka.common.serialization.ByteArraySerializer; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import java.util.Arrays; import java.util.Properties; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; package com.github.ddth.kafka.internal; /** * Helper utility class. * * @author Thanh Ba Nguyen <[email protected]> * @since 1.2.0 */ public class KafkaHelper { /** * Helper method to create a {@link ExecutorService} instance (internal use). * * @param es * @return */ public static ExecutorService createExecutorServiceIfNull(ExecutorService es) { if (es == null) { int numThreads = Math.min(Math.max(Runtime.getRuntime().availableProcessors(), 1), 4); es = Executors.newFixedThreadPool(numThreads); } return es; } /** * Helper method to shutdown a {@link ExecutorService} instance (internal use). * * @param es */ public static void destroyExecutorService(ExecutorService es) { if (es != null) { es.shutdownNow(); } } /** * Seek to a specified offset. * * @param consumer * @param tpo * @return {@code true} if the consumer has subscribed to the specified * topic/partition, {@code false} otherwise. * @since 1.3.2 */
public static boolean seek(KafkaConsumer<?, ?> consumer, KafkaTopicPartitionOffset tpo) {
DDTH/ddth-kafka
src/main/java/com/github/ddth/kafka/internal/KafkaHelper.java
// Path: src/main/java/com/github/ddth/kafka/KafkaClient.java // public enum ProducerType {NO_ACK, LEADER_ACK, ALL_ACKS; // public final static ProducerType[] ALL_TYPES = { NO_ACK, LEADER_ACK, ALL_ACKS };} // // Path: src/main/java/com/github/ddth/kafka/KafkaTopicPartitionOffset.java // public class KafkaTopicPartitionOffset { // public final String topic; // public final int partition; // public final long offset; // // public KafkaTopicPartitionOffset(String topic, int partition, long offset) { // this.topic = topic; // this.partition = partition; // this.offset = offset; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // ToStringBuilder tsb = new ToStringBuilder(this); // tsb.append("topic", topic).append("partition", partition).append("offset", offset); // return tsb.build(); // } // }
import com.github.ddth.kafka.KafkaClient.ProducerType; import com.github.ddth.kafka.KafkaTopicPartitionOffset; import org.apache.commons.lang3.StringUtils; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.serialization.ByteArrayDeserializer; import org.apache.kafka.common.serialization.ByteArraySerializer; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import java.util.Arrays; import java.util.Properties; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
public static boolean seekToEnd(KafkaConsumer<?, ?> consumer, String topic) { boolean result = false; synchronized (consumer) { Set<TopicPartition> topicParts = consumer.assignment(); if (topicParts != null) { for (TopicPartition tp : topicParts) { if (StringUtils.equals(topic, tp.topic())) { consumer.seekToEnd(Arrays.asList(tp)); /* we want to seek as soon as possible since seekToEnd evaluates lazily, * invoke position() so that seeking will be committed. */ consumer.position(tp); result = true; } } if (result) { consumer.commitSync(); } } } return result; } /** * Create a new {@link KafkaProducer} instance, with default configurations. * * @param type * @param bootstrapServers * @return */
// Path: src/main/java/com/github/ddth/kafka/KafkaClient.java // public enum ProducerType {NO_ACK, LEADER_ACK, ALL_ACKS; // public final static ProducerType[] ALL_TYPES = { NO_ACK, LEADER_ACK, ALL_ACKS };} // // Path: src/main/java/com/github/ddth/kafka/KafkaTopicPartitionOffset.java // public class KafkaTopicPartitionOffset { // public final String topic; // public final int partition; // public final long offset; // // public KafkaTopicPartitionOffset(String topic, int partition, long offset) { // this.topic = topic; // this.partition = partition; // this.offset = offset; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // ToStringBuilder tsb = new ToStringBuilder(this); // tsb.append("topic", topic).append("partition", partition).append("offset", offset); // return tsb.build(); // } // } // Path: src/main/java/com/github/ddth/kafka/internal/KafkaHelper.java import com.github.ddth.kafka.KafkaClient.ProducerType; import com.github.ddth.kafka.KafkaTopicPartitionOffset; import org.apache.commons.lang3.StringUtils; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.serialization.ByteArrayDeserializer; import org.apache.kafka.common.serialization.ByteArraySerializer; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import java.util.Arrays; import java.util.Properties; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public static boolean seekToEnd(KafkaConsumer<?, ?> consumer, String topic) { boolean result = false; synchronized (consumer) { Set<TopicPartition> topicParts = consumer.assignment(); if (topicParts != null) { for (TopicPartition tp : topicParts) { if (StringUtils.equals(topic, tp.topic())) { consumer.seekToEnd(Arrays.asList(tp)); /* we want to seek as soon as possible since seekToEnd evaluates lazily, * invoke position() so that seeking will be committed. */ consumer.position(tp); result = true; } } if (result) { consumer.commitSync(); } } } return result; } /** * Create a new {@link KafkaProducer} instance, with default configurations. * * @param type * @param bootstrapServers * @return */
public static KafkaProducer<String, byte[]> createKafkaProducer(ProducerType type, String bootstrapServers) {
ameba-proteus/triton-server
src/main/java/com/amebame/triton/server/TritonServerSetup.java
// Path: src/main/java/com/amebame/triton/service/TritonManagementMethods.java // public class TritonManagementMethods { // // public TritonManagementMethods() { // } // // /** // * Ping method respond pong with server clock. // * @return // */ // @TritonMethod("triton.heartbeat") // public long ping() { // return (int) (System.currentTimeMillis() / 1000L); // } // // /** // * Echo method return received json to the client // * @param text // * @return // */ // @TritonMethod("triton.echo") // public JsonNode echo(JsonNode node) { // return node; // } // // /** // * This method let server to close client connection. // * This simulates closing from the server suddenly. // * @param channel // * @return // * @throws IOException // */ // @TritonMethod("triton.close") // public void close(ChannelHandlerContext ctx) throws IOException { // // close asynchronously // ctx.close(); // } // }
import javax.inject.Inject; import javax.inject.Singleton; import com.amebame.triton.service.TritonManagementMethods;
package com.amebame.triton.server; @Singleton public class TritonServerSetup { @Inject public TritonServerSetup( TritonServerContext context,
// Path: src/main/java/com/amebame/triton/service/TritonManagementMethods.java // public class TritonManagementMethods { // // public TritonManagementMethods() { // } // // /** // * Ping method respond pong with server clock. // * @return // */ // @TritonMethod("triton.heartbeat") // public long ping() { // return (int) (System.currentTimeMillis() / 1000L); // } // // /** // * Echo method return received json to the client // * @param text // * @return // */ // @TritonMethod("triton.echo") // public JsonNode echo(JsonNode node) { // return node; // } // // /** // * This method let server to close client connection. // * This simulates closing from the server suddenly. // * @param channel // * @return // * @throws IOException // */ // @TritonMethod("triton.close") // public void close(ChannelHandlerContext ctx) throws IOException { // // close asynchronously // ctx.close(); // } // } // Path: src/main/java/com/amebame/triton/server/TritonServerSetup.java import javax.inject.Inject; import javax.inject.Singleton; import com.amebame.triton.service.TritonManagementMethods; package com.amebame.triton.server; @Singleton public class TritonServerSetup { @Inject public TritonServerSetup( TritonServerContext context,
TritonManagementMethods heartbeat) {