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
pcdv/jflask
jflask/src/test/java/net/jflask/test/AsyncResponseTest.java
// Path: jflask/src/main/java/net/jflask/CustomResponse.java // public interface CustomResponse { // CustomResponse INSTANCE = new CustomResponse() {}; // } // // Path: jflask/src/main/java/net/jflask/Response.java // public interface Response { // // void addHeader(String header, String value); // // /** // * Warning: must be called after addHeader(). // * // * @param status // * @see java.net.HttpURLConnection // */ // void setStatus(int status); // // OutputStream getOutputStream(); // // }
import java.io.IOException; import net.jflask.CustomResponse; import net.jflask.Response; import net.jflask.Route; import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.assertEquals;
package net.jflask.test; /** * Misc POST tests. */ public class AsyncResponseTest extends AbstractAppTest { @Route("/sync")
// Path: jflask/src/main/java/net/jflask/CustomResponse.java // public interface CustomResponse { // CustomResponse INSTANCE = new CustomResponse() {}; // } // // Path: jflask/src/main/java/net/jflask/Response.java // public interface Response { // // void addHeader(String header, String value); // // /** // * Warning: must be called after addHeader(). // * // * @param status // * @see java.net.HttpURLConnection // */ // void setStatus(int status); // // OutputStream getOutputStream(); // // } // Path: jflask/src/test/java/net/jflask/test/AsyncResponseTest.java import java.io.IOException; import net.jflask.CustomResponse; import net.jflask.Response; import net.jflask.Route; import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.assertEquals; package net.jflask.test; /** * Misc POST tests. */ public class AsyncResponseTest extends AbstractAppTest { @Route("/sync")
public CustomResponse replySync() throws IOException {
pcdv/jflask
jflask/src/test/java/net/jflask/test/AsyncResponseTest.java
// Path: jflask/src/main/java/net/jflask/CustomResponse.java // public interface CustomResponse { // CustomResponse INSTANCE = new CustomResponse() {}; // } // // Path: jflask/src/main/java/net/jflask/Response.java // public interface Response { // // void addHeader(String header, String value); // // /** // * Warning: must be called after addHeader(). // * // * @param status // * @see java.net.HttpURLConnection // */ // void setStatus(int status); // // OutputStream getOutputStream(); // // }
import java.io.IOException; import net.jflask.CustomResponse; import net.jflask.Response; import net.jflask.Route; import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.assertEquals;
package net.jflask.test; /** * Misc POST tests. */ public class AsyncResponseTest extends AbstractAppTest { @Route("/sync") public CustomResponse replySync() throws IOException { reply(app.getResponse()); return CustomResponse.INSTANCE; }
// Path: jflask/src/main/java/net/jflask/CustomResponse.java // public interface CustomResponse { // CustomResponse INSTANCE = new CustomResponse() {}; // } // // Path: jflask/src/main/java/net/jflask/Response.java // public interface Response { // // void addHeader(String header, String value); // // /** // * Warning: must be called after addHeader(). // * // * @param status // * @see java.net.HttpURLConnection // */ // void setStatus(int status); // // OutputStream getOutputStream(); // // } // Path: jflask/src/test/java/net/jflask/test/AsyncResponseTest.java import java.io.IOException; import net.jflask.CustomResponse; import net.jflask.Response; import net.jflask.Route; import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.assertEquals; package net.jflask.test; /** * Misc POST tests. */ public class AsyncResponseTest extends AbstractAppTest { @Route("/sync") public CustomResponse replySync() throws IOException { reply(app.getResponse()); return CustomResponse.INSTANCE; }
private void reply(Response resp) throws IOException {
pcdv/jflask
jflask/src/test/java/net/jflask/test/LoginTest.java
// Path: jflask/src/main/java/net/jflask/CustomResponse.java // public interface CustomResponse { // CustomResponse INSTANCE = new CustomResponse() {}; // }
import net.jflask.CustomResponse; import net.jflask.LoginPage; import net.jflask.LoginRequired; import net.jflask.Route; import org.junit.Test; import static org.junit.Assert.assertEquals;
package net.jflask.test; /** * Tests basic authentication mechanisms. * * @author pcdv */ public class LoginTest extends AbstractAppTest { @LoginPage @Route("/login") public String loginPage() { return "Please login"; } @Route("/logout")
// Path: jflask/src/main/java/net/jflask/CustomResponse.java // public interface CustomResponse { // CustomResponse INSTANCE = new CustomResponse() {}; // } // Path: jflask/src/test/java/net/jflask/test/LoginTest.java import net.jflask.CustomResponse; import net.jflask.LoginPage; import net.jflask.LoginRequired; import net.jflask.Route; import org.junit.Test; import static org.junit.Assert.assertEquals; package net.jflask.test; /** * Tests basic authentication mechanisms. * * @author pcdv */ public class LoginTest extends AbstractAppTest { @LoginPage @Route("/login") public String loginPage() { return "Please login"; } @Route("/logout")
public CustomResponse logout() {
pcdv/jflask
jflask/src/test/java/net/jflask/test/LoginTest3.java
// Path: jflask/src/main/java/net/jflask/CustomResponse.java // public interface CustomResponse { // CustomResponse INSTANCE = new CustomResponse() {}; // }
import net.jflask.CustomResponse; import net.jflask.LoginPage; import net.jflask.LoginRequired; import net.jflask.Route; import org.junit.Test; import static org.junit.Assert.assertEquals;
package net.jflask.test; /** * Reproduces bug when old cookies are set in browser. * * @author pcdv */ public class LoginTest3 extends AbstractAppTest { @LoginPage @Route("/login") public String loginPage() { return "Please login"; } @Route("/logout")
// Path: jflask/src/main/java/net/jflask/CustomResponse.java // public interface CustomResponse { // CustomResponse INSTANCE = new CustomResponse() {}; // } // Path: jflask/src/test/java/net/jflask/test/LoginTest3.java import net.jflask.CustomResponse; import net.jflask.LoginPage; import net.jflask.LoginRequired; import net.jflask.Route; import org.junit.Test; import static org.junit.Assert.assertEquals; package net.jflask.test; /** * Reproduces bug when old cookies are set in browser. * * @author pcdv */ public class LoginTest3 extends AbstractAppTest { @LoginPage @Route("/login") public String loginPage() { return "Please login"; } @Route("/logout")
public CustomResponse logout() {
pcdv/jflask
jflask/src/test/java/net/jflask/test/HookTest.java
// Path: jflask/src/main/java/net/jflask/ErrorHandler.java // public interface ErrorHandler { // /** // * Handles an error (either a 404 error due to invalid URL or a 500 error // * due to an exception thrown by a handler). // * // * @param status the request status sent back to client // * @param request the request sent by client // * @param t optional error (null in case of 404) // */ // void onError(int status, Request request, Throwable t); // } // // Path: jflask/src/main/java/net/jflask/Request.java // public interface Request { // // /** // * Returns the part of this request's URL from the protocol name up to the // * query string in the first line of the HTTP request. // */ // String getRequestURI(); // // /** // * Returns the query string contained in request URL after the path. This // * method returns <code>null</code> if the URL does not have a query string. // * Same as the value of the CGI variable QUERY_STRING. // * // * @return a <code>String</code> containing the query string or // * <code>null</code> if the URL contains no query string // */ // // String getQueryString(); // // /** // * Returns the HTTP verb (GET, POST, etc.) used in the request. // */ // String getMethod(); // // /** // * Returns parameter submitted in the query string, eg. if URL = // * "...?key=value", getArg("key", null) returns "value". // * // * @param name // * @param def the default value to return if specified parameter in unset // * @return the parameter found in the query string or specified default value // */ // String getArg(String name, String def); // // /** // * Returns a field from form data (only valid for POST requests). // */ // String getForm(String field); // // /** // * Returns a list containing all occurrences of a given parameter in query // * string, or an empty list if none is found. // * // * @param name the parameter's name // */ // List<String> getArgs(String name); // // InputStream getInputStream(); // } // // Path: jflask/src/main/java/net/jflask/SuccessHandler.java // public interface SuccessHandler { // /** // * Called when a route handler was successfully called. // * // * @param r the request // * @param method the java method invoked by reflection // * @param args the arguments passed to method // * @param result the value returned by the handler method // */ // void onSuccess(Request r, Method method, Object[] args, Object result); // }
import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Test; import net.jflask.ErrorHandler; import net.jflask.Request; import net.jflask.Route; import net.jflask.SuccessHandler;
package net.jflask.test; public class HookTest extends AbstractAppTest { /** This one conflicts with initial declaration for ErrorHandler. */ @Route("/") public String root() { return "root"; } @Route("/barf") public String barf() { throw new RuntimeException("barf"); } @Route("/hello/:name") public String getOk(String name) { return "Hello " + name; } /** * Check that 404 and other errors can be handled by ErrorHandlers. */ @Test public void testErrorHook() throws Exception { final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();
// Path: jflask/src/main/java/net/jflask/ErrorHandler.java // public interface ErrorHandler { // /** // * Handles an error (either a 404 error due to invalid URL or a 500 error // * due to an exception thrown by a handler). // * // * @param status the request status sent back to client // * @param request the request sent by client // * @param t optional error (null in case of 404) // */ // void onError(int status, Request request, Throwable t); // } // // Path: jflask/src/main/java/net/jflask/Request.java // public interface Request { // // /** // * Returns the part of this request's URL from the protocol name up to the // * query string in the first line of the HTTP request. // */ // String getRequestURI(); // // /** // * Returns the query string contained in request URL after the path. This // * method returns <code>null</code> if the URL does not have a query string. // * Same as the value of the CGI variable QUERY_STRING. // * // * @return a <code>String</code> containing the query string or // * <code>null</code> if the URL contains no query string // */ // // String getQueryString(); // // /** // * Returns the HTTP verb (GET, POST, etc.) used in the request. // */ // String getMethod(); // // /** // * Returns parameter submitted in the query string, eg. if URL = // * "...?key=value", getArg("key", null) returns "value". // * // * @param name // * @param def the default value to return if specified parameter in unset // * @return the parameter found in the query string or specified default value // */ // String getArg(String name, String def); // // /** // * Returns a field from form data (only valid for POST requests). // */ // String getForm(String field); // // /** // * Returns a list containing all occurrences of a given parameter in query // * string, or an empty list if none is found. // * // * @param name the parameter's name // */ // List<String> getArgs(String name); // // InputStream getInputStream(); // } // // Path: jflask/src/main/java/net/jflask/SuccessHandler.java // public interface SuccessHandler { // /** // * Called when a route handler was successfully called. // * // * @param r the request // * @param method the java method invoked by reflection // * @param args the arguments passed to method // * @param result the value returned by the handler method // */ // void onSuccess(Request r, Method method, Object[] args, Object result); // } // Path: jflask/src/test/java/net/jflask/test/HookTest.java import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Test; import net.jflask.ErrorHandler; import net.jflask.Request; import net.jflask.Route; import net.jflask.SuccessHandler; package net.jflask.test; public class HookTest extends AbstractAppTest { /** This one conflicts with initial declaration for ErrorHandler. */ @Route("/") public String root() { return "root"; } @Route("/barf") public String barf() { throw new RuntimeException("barf"); } @Route("/hello/:name") public String getOk(String name) { return "Hello " + name; } /** * Check that 404 and other errors can be handled by ErrorHandlers. */ @Test public void testErrorHook() throws Exception { final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();
app.addErrorHandler(new ErrorHandler() {
pcdv/jflask
jflask/src/test/java/net/jflask/test/HookTest.java
// Path: jflask/src/main/java/net/jflask/ErrorHandler.java // public interface ErrorHandler { // /** // * Handles an error (either a 404 error due to invalid URL or a 500 error // * due to an exception thrown by a handler). // * // * @param status the request status sent back to client // * @param request the request sent by client // * @param t optional error (null in case of 404) // */ // void onError(int status, Request request, Throwable t); // } // // Path: jflask/src/main/java/net/jflask/Request.java // public interface Request { // // /** // * Returns the part of this request's URL from the protocol name up to the // * query string in the first line of the HTTP request. // */ // String getRequestURI(); // // /** // * Returns the query string contained in request URL after the path. This // * method returns <code>null</code> if the URL does not have a query string. // * Same as the value of the CGI variable QUERY_STRING. // * // * @return a <code>String</code> containing the query string or // * <code>null</code> if the URL contains no query string // */ // // String getQueryString(); // // /** // * Returns the HTTP verb (GET, POST, etc.) used in the request. // */ // String getMethod(); // // /** // * Returns parameter submitted in the query string, eg. if URL = // * "...?key=value", getArg("key", null) returns "value". // * // * @param name // * @param def the default value to return if specified parameter in unset // * @return the parameter found in the query string or specified default value // */ // String getArg(String name, String def); // // /** // * Returns a field from form data (only valid for POST requests). // */ // String getForm(String field); // // /** // * Returns a list containing all occurrences of a given parameter in query // * string, or an empty list if none is found. // * // * @param name the parameter's name // */ // List<String> getArgs(String name); // // InputStream getInputStream(); // } // // Path: jflask/src/main/java/net/jflask/SuccessHandler.java // public interface SuccessHandler { // /** // * Called when a route handler was successfully called. // * // * @param r the request // * @param method the java method invoked by reflection // * @param args the arguments passed to method // * @param result the value returned by the handler method // */ // void onSuccess(Request r, Method method, Object[] args, Object result); // }
import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Test; import net.jflask.ErrorHandler; import net.jflask.Request; import net.jflask.Route; import net.jflask.SuccessHandler;
package net.jflask.test; public class HookTest extends AbstractAppTest { /** This one conflicts with initial declaration for ErrorHandler. */ @Route("/") public String root() { return "root"; } @Route("/barf") public String barf() { throw new RuntimeException("barf"); } @Route("/hello/:name") public String getOk(String name) { return "Hello " + name; } /** * Check that 404 and other errors can be handled by ErrorHandlers. */ @Test public void testErrorHook() throws Exception { final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>(); app.addErrorHandler(new ErrorHandler() { @Override
// Path: jflask/src/main/java/net/jflask/ErrorHandler.java // public interface ErrorHandler { // /** // * Handles an error (either a 404 error due to invalid URL or a 500 error // * due to an exception thrown by a handler). // * // * @param status the request status sent back to client // * @param request the request sent by client // * @param t optional error (null in case of 404) // */ // void onError(int status, Request request, Throwable t); // } // // Path: jflask/src/main/java/net/jflask/Request.java // public interface Request { // // /** // * Returns the part of this request's URL from the protocol name up to the // * query string in the first line of the HTTP request. // */ // String getRequestURI(); // // /** // * Returns the query string contained in request URL after the path. This // * method returns <code>null</code> if the URL does not have a query string. // * Same as the value of the CGI variable QUERY_STRING. // * // * @return a <code>String</code> containing the query string or // * <code>null</code> if the URL contains no query string // */ // // String getQueryString(); // // /** // * Returns the HTTP verb (GET, POST, etc.) used in the request. // */ // String getMethod(); // // /** // * Returns parameter submitted in the query string, eg. if URL = // * "...?key=value", getArg("key", null) returns "value". // * // * @param name // * @param def the default value to return if specified parameter in unset // * @return the parameter found in the query string or specified default value // */ // String getArg(String name, String def); // // /** // * Returns a field from form data (only valid for POST requests). // */ // String getForm(String field); // // /** // * Returns a list containing all occurrences of a given parameter in query // * string, or an empty list if none is found. // * // * @param name the parameter's name // */ // List<String> getArgs(String name); // // InputStream getInputStream(); // } // // Path: jflask/src/main/java/net/jflask/SuccessHandler.java // public interface SuccessHandler { // /** // * Called when a route handler was successfully called. // * // * @param r the request // * @param method the java method invoked by reflection // * @param args the arguments passed to method // * @param result the value returned by the handler method // */ // void onSuccess(Request r, Method method, Object[] args, Object result); // } // Path: jflask/src/test/java/net/jflask/test/HookTest.java import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Test; import net.jflask.ErrorHandler; import net.jflask.Request; import net.jflask.Route; import net.jflask.SuccessHandler; package net.jflask.test; public class HookTest extends AbstractAppTest { /** This one conflicts with initial declaration for ErrorHandler. */ @Route("/") public String root() { return "root"; } @Route("/barf") public String barf() { throw new RuntimeException("barf"); } @Route("/hello/:name") public String getOk(String name) { return "Hello " + name; } /** * Check that 404 and other errors can be handled by ErrorHandlers. */ @Test public void testErrorHook() throws Exception { final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>(); app.addErrorHandler(new ErrorHandler() { @Override
public void onError(int status, Request request, Throwable t) {
pcdv/jflask
jflask/src/test/java/net/jflask/test/HookTest.java
// Path: jflask/src/main/java/net/jflask/ErrorHandler.java // public interface ErrorHandler { // /** // * Handles an error (either a 404 error due to invalid URL or a 500 error // * due to an exception thrown by a handler). // * // * @param status the request status sent back to client // * @param request the request sent by client // * @param t optional error (null in case of 404) // */ // void onError(int status, Request request, Throwable t); // } // // Path: jflask/src/main/java/net/jflask/Request.java // public interface Request { // // /** // * Returns the part of this request's URL from the protocol name up to the // * query string in the first line of the HTTP request. // */ // String getRequestURI(); // // /** // * Returns the query string contained in request URL after the path. This // * method returns <code>null</code> if the URL does not have a query string. // * Same as the value of the CGI variable QUERY_STRING. // * // * @return a <code>String</code> containing the query string or // * <code>null</code> if the URL contains no query string // */ // // String getQueryString(); // // /** // * Returns the HTTP verb (GET, POST, etc.) used in the request. // */ // String getMethod(); // // /** // * Returns parameter submitted in the query string, eg. if URL = // * "...?key=value", getArg("key", null) returns "value". // * // * @param name // * @param def the default value to return if specified parameter in unset // * @return the parameter found in the query string or specified default value // */ // String getArg(String name, String def); // // /** // * Returns a field from form data (only valid for POST requests). // */ // String getForm(String field); // // /** // * Returns a list containing all occurrences of a given parameter in query // * string, or an empty list if none is found. // * // * @param name the parameter's name // */ // List<String> getArgs(String name); // // InputStream getInputStream(); // } // // Path: jflask/src/main/java/net/jflask/SuccessHandler.java // public interface SuccessHandler { // /** // * Called when a route handler was successfully called. // * // * @param r the request // * @param method the java method invoked by reflection // * @param args the arguments passed to method // * @param result the value returned by the handler method // */ // void onSuccess(Request r, Method method, Object[] args, Object result); // }
import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Test; import net.jflask.ErrorHandler; import net.jflask.Request; import net.jflask.Route; import net.jflask.SuccessHandler;
package net.jflask.test; public class HookTest extends AbstractAppTest { /** This one conflicts with initial declaration for ErrorHandler. */ @Route("/") public String root() { return "root"; } @Route("/barf") public String barf() { throw new RuntimeException("barf"); } @Route("/hello/:name") public String getOk(String name) { return "Hello " + name; } /** * Check that 404 and other errors can be handled by ErrorHandlers. */ @Test public void testErrorHook() throws Exception { final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>(); app.addErrorHandler(new ErrorHandler() { @Override public void onError(int status, Request request, Throwable t) { queue.offer(status + " " + request.getMethod() + " " + request.getRequestURI() + " " + t); } }); try { client.get("/unknown"); } catch (IOException e) { } Assert.assertEquals("404 GET /unknown null", queue.poll(1, TimeUnit.SECONDS)); try { client.get("/barf"); } catch (IOException e) { } Assert.assertEquals("500 GET /barf java.lang.RuntimeException: barf", queue.poll(1, TimeUnit.SECONDS)); Assert.assertEquals("root", client.get("/")); Assert.assertNull(queue.poll(500, TimeUnit.MILLISECONDS)); } @Test public void testSuccessHook() throws Exception { final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();
// Path: jflask/src/main/java/net/jflask/ErrorHandler.java // public interface ErrorHandler { // /** // * Handles an error (either a 404 error due to invalid URL or a 500 error // * due to an exception thrown by a handler). // * // * @param status the request status sent back to client // * @param request the request sent by client // * @param t optional error (null in case of 404) // */ // void onError(int status, Request request, Throwable t); // } // // Path: jflask/src/main/java/net/jflask/Request.java // public interface Request { // // /** // * Returns the part of this request's URL from the protocol name up to the // * query string in the first line of the HTTP request. // */ // String getRequestURI(); // // /** // * Returns the query string contained in request URL after the path. This // * method returns <code>null</code> if the URL does not have a query string. // * Same as the value of the CGI variable QUERY_STRING. // * // * @return a <code>String</code> containing the query string or // * <code>null</code> if the URL contains no query string // */ // // String getQueryString(); // // /** // * Returns the HTTP verb (GET, POST, etc.) used in the request. // */ // String getMethod(); // // /** // * Returns parameter submitted in the query string, eg. if URL = // * "...?key=value", getArg("key", null) returns "value". // * // * @param name // * @param def the default value to return if specified parameter in unset // * @return the parameter found in the query string or specified default value // */ // String getArg(String name, String def); // // /** // * Returns a field from form data (only valid for POST requests). // */ // String getForm(String field); // // /** // * Returns a list containing all occurrences of a given parameter in query // * string, or an empty list if none is found. // * // * @param name the parameter's name // */ // List<String> getArgs(String name); // // InputStream getInputStream(); // } // // Path: jflask/src/main/java/net/jflask/SuccessHandler.java // public interface SuccessHandler { // /** // * Called when a route handler was successfully called. // * // * @param r the request // * @param method the java method invoked by reflection // * @param args the arguments passed to method // * @param result the value returned by the handler method // */ // void onSuccess(Request r, Method method, Object[] args, Object result); // } // Path: jflask/src/test/java/net/jflask/test/HookTest.java import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Test; import net.jflask.ErrorHandler; import net.jflask.Request; import net.jflask.Route; import net.jflask.SuccessHandler; package net.jflask.test; public class HookTest extends AbstractAppTest { /** This one conflicts with initial declaration for ErrorHandler. */ @Route("/") public String root() { return "root"; } @Route("/barf") public String barf() { throw new RuntimeException("barf"); } @Route("/hello/:name") public String getOk(String name) { return "Hello " + name; } /** * Check that 404 and other errors can be handled by ErrorHandlers. */ @Test public void testErrorHook() throws Exception { final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>(); app.addErrorHandler(new ErrorHandler() { @Override public void onError(int status, Request request, Throwable t) { queue.offer(status + " " + request.getMethod() + " " + request.getRequestURI() + " " + t); } }); try { client.get("/unknown"); } catch (IOException e) { } Assert.assertEquals("404 GET /unknown null", queue.poll(1, TimeUnit.SECONDS)); try { client.get("/barf"); } catch (IOException e) { } Assert.assertEquals("500 GET /barf java.lang.RuntimeException: barf", queue.poll(1, TimeUnit.SECONDS)); Assert.assertEquals("root", client.get("/")); Assert.assertNull(queue.poll(500, TimeUnit.MILLISECONDS)); } @Test public void testSuccessHook() throws Exception { final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();
app.addSuccessHandler(new SuccessHandler() {
pcdv/jflask
jflask/src/main/java/net/jflask/SunRequest.java
// Path: jflask/src/main/java/net/jflask/util/IO.java // public class IO { // // /** // * Reads specified input stream until it reaches EOF. // */ // public static byte[] readFully(InputStream in) throws IOException { // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // pipe(in, bout, false); // return bout.toByteArray(); // } // // /** // * Reads input stream until EOF and writes all read data into output stream, // * then closes it. // */ // public static void pipe(InputStream in, OutputStream out, boolean closeOutput) // throws IOException { // byte[] buf = new byte[1024]; // while (true) { // int len = in.read(buf); // if (len >= 0) { // out.write(buf, 0, len); // out.flush(); // } // else { // if (closeOutput) // out.close(); // break; // } // } // } // // }
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import com.sun.net.httpserver.HttpExchange; import net.jflask.util.IO;
public HttpExchange getExchange() { return exchange; } public String getMethod() { return exchange.getRequestMethod(); } public String getArg(String name, String def) { if (qsMark == -1) return def; return parseArg(name, def, getQueryString()); } private String parseArg(String name, String def, String encoded) { String[] tok = encoded.split("&"); for (String s : tok) { if (s.startsWith(name)) { if (s.length() > name.length() && s.charAt(name.length()) == '=') return s.substring(name.length() + 1); } } return def; } @Override public String getForm(String field) { try { if (form == null)
// Path: jflask/src/main/java/net/jflask/util/IO.java // public class IO { // // /** // * Reads specified input stream until it reaches EOF. // */ // public static byte[] readFully(InputStream in) throws IOException { // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // pipe(in, bout, false); // return bout.toByteArray(); // } // // /** // * Reads input stream until EOF and writes all read data into output stream, // * then closes it. // */ // public static void pipe(InputStream in, OutputStream out, boolean closeOutput) // throws IOException { // byte[] buf = new byte[1024]; // while (true) { // int len = in.read(buf); // if (len >= 0) { // out.write(buf, 0, len); // out.flush(); // } // else { // if (closeOutput) // out.close(); // break; // } // } // } // // } // Path: jflask/src/main/java/net/jflask/SunRequest.java import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import com.sun.net.httpserver.HttpExchange; import net.jflask.util.IO; public HttpExchange getExchange() { return exchange; } public String getMethod() { return exchange.getRequestMethod(); } public String getArg(String name, String def) { if (qsMark == -1) return def; return parseArg(name, def, getQueryString()); } private String parseArg(String name, String def, String encoded) { String[] tok = encoded.split("&"); for (String s : tok) { if (s.startsWith(name)) { if (s.length() > name.length() && s.charAt(name.length()) == '=') return s.substring(name.length() + 1); } } return def; } @Override public String getForm(String field) { try { if (form == null)
form = new String(IO.readFully(getInputStream()));
pcdv/jflask
jflask/src/test/java/net/jflask/test/ConverterTest.java
// Path: jflask/src/main/java/net/jflask/Response.java // public interface Response { // // void addHeader(String header, String value); // // /** // * Warning: must be called after addHeader(). // * // * @param status // * @see java.net.HttpURLConnection // */ // void setStatus(int status); // // OutputStream getOutputStream(); // // } // // Path: jflask/src/main/java/net/jflask/ResponseConverter.java // public interface ResponseConverter<T> { // // void convert(T data, Response resp) throws Exception; // }
import net.jflask.Convert; import net.jflask.Response; import net.jflask.ResponseConverter; import net.jflask.Route; import org.junit.Test; import static org.junit.Assert.assertEquals;
package net.jflask.test; public class ConverterTest extends AbstractAppTest { @Convert("STAR") @Route("/hello/:name") public String hello(String name) { return "Hello " + name; } @Override protected void preScan() {
// Path: jflask/src/main/java/net/jflask/Response.java // public interface Response { // // void addHeader(String header, String value); // // /** // * Warning: must be called after addHeader(). // * // * @param status // * @see java.net.HttpURLConnection // */ // void setStatus(int status); // // OutputStream getOutputStream(); // // } // // Path: jflask/src/main/java/net/jflask/ResponseConverter.java // public interface ResponseConverter<T> { // // void convert(T data, Response resp) throws Exception; // } // Path: jflask/src/test/java/net/jflask/test/ConverterTest.java import net.jflask.Convert; import net.jflask.Response; import net.jflask.ResponseConverter; import net.jflask.Route; import org.junit.Test; import static org.junit.Assert.assertEquals; package net.jflask.test; public class ConverterTest extends AbstractAppTest { @Convert("STAR") @Route("/hello/:name") public String hello(String name) { return "Hello " + name; } @Override protected void preScan() {
app.addConverter("FOO", new ResponseConverter<String>() {
pcdv/jflask
jflask/src/test/java/net/jflask/test/ConverterTest.java
// Path: jflask/src/main/java/net/jflask/Response.java // public interface Response { // // void addHeader(String header, String value); // // /** // * Warning: must be called after addHeader(). // * // * @param status // * @see java.net.HttpURLConnection // */ // void setStatus(int status); // // OutputStream getOutputStream(); // // } // // Path: jflask/src/main/java/net/jflask/ResponseConverter.java // public interface ResponseConverter<T> { // // void convert(T data, Response resp) throws Exception; // }
import net.jflask.Convert; import net.jflask.Response; import net.jflask.ResponseConverter; import net.jflask.Route; import org.junit.Test; import static org.junit.Assert.assertEquals;
package net.jflask.test; public class ConverterTest extends AbstractAppTest { @Convert("STAR") @Route("/hello/:name") public String hello(String name) { return "Hello " + name; } @Override protected void preScan() { app.addConverter("FOO", new ResponseConverter<String>() {
// Path: jflask/src/main/java/net/jflask/Response.java // public interface Response { // // void addHeader(String header, String value); // // /** // * Warning: must be called after addHeader(). // * // * @param status // * @see java.net.HttpURLConnection // */ // void setStatus(int status); // // OutputStream getOutputStream(); // // } // // Path: jflask/src/main/java/net/jflask/ResponseConverter.java // public interface ResponseConverter<T> { // // void convert(T data, Response resp) throws Exception; // } // Path: jflask/src/test/java/net/jflask/test/ConverterTest.java import net.jflask.Convert; import net.jflask.Response; import net.jflask.ResponseConverter; import net.jflask.Route; import org.junit.Test; import static org.junit.Assert.assertEquals; package net.jflask.test; public class ConverterTest extends AbstractAppTest { @Convert("STAR") @Route("/hello/:name") public String hello(String name) { return "Hello " + name; } @Override protected void preScan() { app.addConverter("FOO", new ResponseConverter<String>() {
public void convert(String data, Response resp) throws Exception {
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/keyword/MECOMSValuesKeywords.java
// Path: src/main/java/org/robotframework/formslibrary/operator/MECOMSValuesOperator.java // public class MECOMSValuesOperator extends AbstractComponentOperator { // // /** // * Initialize a MECOMS Values operator. // */ // public MECOMSValuesOperator() { // super(new ByComponentTypeChooser(0, ComponentType.MECOMS_VALUES)); // } // // public MECOMSValuesOperator(ComponentChooser chooser) { // super(chooser); // } // // @SuppressWarnings("unchecked") // public List<Map<String, Object>> getValues() { // List<Object> values = (List<Object>) ObjectUtil.getField(getSource(), "values"); // // returns list of fcs.validationgraph.data.Value // List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); // for (Object value : values) { // results.add(copyValue(value)); // } // return results; // } // // private Map<String, Object> copyValue(Object value) { // Map<String, Object> map = new HashMap<String, Object>(); // if (value == null) { // return map; // } // List<String> fieldNames = ObjectUtil.getFieldNames(value); // for (String name : fieldNames) { // map.put(name, ObjectUtil.getField(value, name)); // } // return map; // } // // private Object getMECOMSValue(String date) { // @SuppressWarnings("unchecked") // List<Object> values = (List<Object>) ObjectUtil.getField(getSource(), "values"); // // for (Object value : values) { // String timestamp = (String) ObjectUtil.getField(value, "timestamp").toString(); // if (timestamp.startsWith(date)) { // return value; // } // } // return null; // // } // // private int getMECOMSValueIndex(String date) { // @SuppressWarnings("unchecked") // List<Object> values = (List<Object>) ObjectUtil.getField(getSource(), "values"); // for (int i = 0; i < values.size(); i++) { // Object value = values.get(i); // String timestamp = ObjectUtil.getField(value, "timestamp").toString(); // if (timestamp.startsWith(date)) { // return i; // } // } // throw new FormsLibraryException("Date " + date + " not found"); // // } // // public Map<String, Object> getValue(String date) { // Object value = getMECOMSValue(date); // return copyValue(value); // } // // public void selectValue(String dateFrom, String dateTo) { // int valueFrom = getMECOMSValueIndex(dateFrom); // int valueTo; // if (dateTo != null) { // valueTo = getMECOMSValueIndex(dateTo); // } else { // valueTo = valueFrom; // } // Component component = getSource(); // // ObjectUtil.invokeMethodWithIntArg(component, "setSelectionStart", valueFrom); // ObjectUtil.invokeMethodWithIntArg(component, "setSelectionEnd", valueTo); // Object graphPane = ObjectUtil.getField(component, "graphPane"); // ObjectUtil.invokeMethod(graphPane, "refresh"); // ObjectUtil.invokeMethod(graphPane, "tableToGraph"); // } // // }
import org.robotframework.formslibrary.operator.MECOMSValuesOperator; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywordOverload; import org.robotframework.javalib.annotation.RobotKeywords;
package org.robotframework.formslibrary.keyword; @RobotKeywords public class MECOMSValuesKeywords { @RobotKeyword("Returns a List with Dictionary Like data structure containing all the MECOMS values\n\n" + " Example:\n | Get MECOMS Values | \n\"") public Object getMECOMSValues() {
// Path: src/main/java/org/robotframework/formslibrary/operator/MECOMSValuesOperator.java // public class MECOMSValuesOperator extends AbstractComponentOperator { // // /** // * Initialize a MECOMS Values operator. // */ // public MECOMSValuesOperator() { // super(new ByComponentTypeChooser(0, ComponentType.MECOMS_VALUES)); // } // // public MECOMSValuesOperator(ComponentChooser chooser) { // super(chooser); // } // // @SuppressWarnings("unchecked") // public List<Map<String, Object>> getValues() { // List<Object> values = (List<Object>) ObjectUtil.getField(getSource(), "values"); // // returns list of fcs.validationgraph.data.Value // List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); // for (Object value : values) { // results.add(copyValue(value)); // } // return results; // } // // private Map<String, Object> copyValue(Object value) { // Map<String, Object> map = new HashMap<String, Object>(); // if (value == null) { // return map; // } // List<String> fieldNames = ObjectUtil.getFieldNames(value); // for (String name : fieldNames) { // map.put(name, ObjectUtil.getField(value, name)); // } // return map; // } // // private Object getMECOMSValue(String date) { // @SuppressWarnings("unchecked") // List<Object> values = (List<Object>) ObjectUtil.getField(getSource(), "values"); // // for (Object value : values) { // String timestamp = (String) ObjectUtil.getField(value, "timestamp").toString(); // if (timestamp.startsWith(date)) { // return value; // } // } // return null; // // } // // private int getMECOMSValueIndex(String date) { // @SuppressWarnings("unchecked") // List<Object> values = (List<Object>) ObjectUtil.getField(getSource(), "values"); // for (int i = 0; i < values.size(); i++) { // Object value = values.get(i); // String timestamp = ObjectUtil.getField(value, "timestamp").toString(); // if (timestamp.startsWith(date)) { // return i; // } // } // throw new FormsLibraryException("Date " + date + " not found"); // // } // // public Map<String, Object> getValue(String date) { // Object value = getMECOMSValue(date); // return copyValue(value); // } // // public void selectValue(String dateFrom, String dateTo) { // int valueFrom = getMECOMSValueIndex(dateFrom); // int valueTo; // if (dateTo != null) { // valueTo = getMECOMSValueIndex(dateTo); // } else { // valueTo = valueFrom; // } // Component component = getSource(); // // ObjectUtil.invokeMethodWithIntArg(component, "setSelectionStart", valueFrom); // ObjectUtil.invokeMethodWithIntArg(component, "setSelectionEnd", valueTo); // Object graphPane = ObjectUtil.getField(component, "graphPane"); // ObjectUtil.invokeMethod(graphPane, "refresh"); // ObjectUtil.invokeMethod(graphPane, "tableToGraph"); // } // // } // Path: src/main/java/org/robotframework/formslibrary/keyword/MECOMSValuesKeywords.java import org.robotframework.formslibrary.operator.MECOMSValuesOperator; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywordOverload; import org.robotframework.javalib.annotation.RobotKeywords; package org.robotframework.formslibrary.keyword; @RobotKeywords public class MECOMSValuesKeywords { @RobotKeyword("Returns a List with Dictionary Like data structure containing all the MECOMS values\n\n" + " Example:\n | Get MECOMS Values | \n\"") public Object getMECOMSValues() {
return new MECOMSValuesOperator().getValues();
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/keyword/TabKeywords.java
// Path: src/main/java/org/robotframework/formslibrary/operator/TabOperator.java // public class TabOperator extends AbstractComponentOperator { // // /** // * Initialize a TabOperator with the first tabbar found in the current // * context. // */ // public TabOperator() { // super(new ByComponentTypeChooser(0, ComponentType.TAB_BAR)); // } // // /** // * Select the tab with the given name. // */ // public void select(String name) { // // int tabCount = (Integer) ObjectUtil.invokeMethod(getSource(), "getItemCount"); // // for (int i = 0; i < tabCount; i++) { // Object tabItem = ObjectUtil.invokeMethodWithIntArg(getSource(), "getItem()", i); // String label = ObjectUtil.getString(tabItem, "getLabel()"); // Logger.debug("Found tab " + label); // if (name.equalsIgnoreCase(label)) { // ObjectUtil.invokeMethodWithTypedArg(tabItem, "setSelected()", "boolean", Boolean.TRUE); // return; // } // } // // throw new FormsLibraryException("Tab '" + name + "' not found."); // } // }
import org.robotframework.formslibrary.operator.TabOperator; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords;
package org.robotframework.formslibrary.keyword; @RobotKeywords public class TabKeywords { @RobotKeyword("Select a tab by name.\n\n Example:\n | Select Forms Tab | _name_ | \n") @ArgumentNames({ "tabname" }) public void selectFormsTab(String name) {
// Path: src/main/java/org/robotframework/formslibrary/operator/TabOperator.java // public class TabOperator extends AbstractComponentOperator { // // /** // * Initialize a TabOperator with the first tabbar found in the current // * context. // */ // public TabOperator() { // super(new ByComponentTypeChooser(0, ComponentType.TAB_BAR)); // } // // /** // * Select the tab with the given name. // */ // public void select(String name) { // // int tabCount = (Integer) ObjectUtil.invokeMethod(getSource(), "getItemCount"); // // for (int i = 0; i < tabCount; i++) { // Object tabItem = ObjectUtil.invokeMethodWithIntArg(getSource(), "getItem()", i); // String label = ObjectUtil.getString(tabItem, "getLabel()"); // Logger.debug("Found tab " + label); // if (name.equalsIgnoreCase(label)) { // ObjectUtil.invokeMethodWithTypedArg(tabItem, "setSelected()", "boolean", Boolean.TRUE); // return; // } // } // // throw new FormsLibraryException("Tab '" + name + "' not found."); // } // } // Path: src/main/java/org/robotframework/formslibrary/keyword/TabKeywords.java import org.robotframework.formslibrary.operator.TabOperator; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords; package org.robotframework.formslibrary.keyword; @RobotKeywords public class TabKeywords { @RobotKeyword("Select a tab by name.\n\n Example:\n | Select Forms Tab | _name_ | \n") @ArgumentNames({ "tabname" }) public void selectFormsTab(String name) {
new TabOperator().select(name);
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/keyword/CheckBoxKeywords.java
// Path: src/main/java/org/robotframework/formslibrary/operator/CheckboxOperator.java // public class CheckboxOperator extends AbstractComponentOperator { // // /** // * Initialize an CheckboxOperator with the given check box component. // */ // public CheckboxOperator(Component checkBox) { // super(checkBox); // } // // /** // * Initialize a CheckboxOperator with a check box that has the specified // * name in the current context. // * // * @param identifier // * checkbox label or ToolTip text. // */ // public CheckboxOperator(String identifier) { // super(new ByNameChooser(identifier, ComponentType.CHECK_BOX)); // } // // public boolean isChecked() { // return ObjectUtil.getBoolean(getSource(), "getState()"); // } // // public void verifyNotChecked() { // if (isChecked()) { // throw new FormsLibraryException("Checkbox is checked."); // } // } // // public void verifyChecked() { // if (!isChecked()) { // throw new FormsLibraryException("Checkbox is not checked."); // } // } // // public void check() { // if (!isChecked()) { // ObjectUtil.invokeMethod(getSource(), "simulatePush()"); // } // } // // public void uncheck() { // if (isChecked()) { // ObjectUtil.invokeMethod(getSource(), "simulatePush()"); // } // } // }
import org.robotframework.formslibrary.operator.CheckboxOperator; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords;
package org.robotframework.formslibrary.keyword; @RobotKeywords public class CheckBoxKeywords { @RobotKeyword("Verify checkbox is not checked.\n\nExample:\n| Verify Checkbox Is Checked | _checkboxname_ | \n") @ArgumentNames({ "identifier" }) public void verifyCheckboxIsChecked(String identifier) {
// Path: src/main/java/org/robotframework/formslibrary/operator/CheckboxOperator.java // public class CheckboxOperator extends AbstractComponentOperator { // // /** // * Initialize an CheckboxOperator with the given check box component. // */ // public CheckboxOperator(Component checkBox) { // super(checkBox); // } // // /** // * Initialize a CheckboxOperator with a check box that has the specified // * name in the current context. // * // * @param identifier // * checkbox label or ToolTip text. // */ // public CheckboxOperator(String identifier) { // super(new ByNameChooser(identifier, ComponentType.CHECK_BOX)); // } // // public boolean isChecked() { // return ObjectUtil.getBoolean(getSource(), "getState()"); // } // // public void verifyNotChecked() { // if (isChecked()) { // throw new FormsLibraryException("Checkbox is checked."); // } // } // // public void verifyChecked() { // if (!isChecked()) { // throw new FormsLibraryException("Checkbox is not checked."); // } // } // // public void check() { // if (!isChecked()) { // ObjectUtil.invokeMethod(getSource(), "simulatePush()"); // } // } // // public void uncheck() { // if (isChecked()) { // ObjectUtil.invokeMethod(getSource(), "simulatePush()"); // } // } // } // Path: src/main/java/org/robotframework/formslibrary/keyword/CheckBoxKeywords.java import org.robotframework.formslibrary.operator.CheckboxOperator; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords; package org.robotframework.formslibrary.keyword; @RobotKeywords public class CheckBoxKeywords { @RobotKeyword("Verify checkbox is not checked.\n\nExample:\n| Verify Checkbox Is Checked | _checkboxname_ | \n") @ArgumentNames({ "identifier" }) public void verifyCheckboxIsChecked(String identifier) {
new CheckboxOperator(identifier).verifyChecked();
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/keyword/ListKeyword.java
// Path: src/main/java/org/robotframework/formslibrary/operator/ListOperator.java // public class ListOperator extends AbstractComponentOperator { // // /** // * Initialize an ListOperator with the given list component. // */ // public ListOperator(Component list) { // super(list); // } // // /** // * Initialize a CheckboxOperator with a check box that has the specified // * name in the current context. // * // * @param identifier // * checkbox label or ToolTip text. // */ // public ListOperator(String identifier) { // super(getComponentChooser(identifier)); // } // // private static ComponentChooser getComponentChooser(String identifier) { // if (TextUtil.isNumeric(identifier)) { // return new ByComponentTypeChooser(Integer.parseInt(identifier), ComponentType.LWList); // } else { // return new ByNameChooser(identifier, ComponentType.LWList); // } // } // // public void select(String identifier) { // int index; // if (TextUtil.isNumeric(identifier)) { // index = Integer.parseInt(identifier); // } else { // String[] items = getItems(); // index = Arrays.asList(items).indexOf(identifier); // if (index == -1) { // throw new FormsLibraryException("Value '" + identifier + "' not fond in list: " + items); // } // } // ObjectUtil.invokeMethodWithIntArg(getSource(), "select()", index); // // Method m; // try { // m = getSource().getClass().getSuperclass().getDeclaredMethod("_postItemEvent", String.class, int.class); // m.setAccessible(true); // m.invoke(getSource(), getItem(index), ItemEvent.SELECTED); // } catch (Exception e) { // e.printStackTrace(); // throw new FormsLibraryException("Could not call method _selectItem"); // } // // } // // public String getSelected() { // return (String) ObjectUtil.invokeMethod(getSource(), "getSelectedItem()"); // } // // public String getItem(int i) { // return (String) ObjectUtil.invokeMethodWithIntArg(getSource(), "getItem()", i); // } // // public String[] getItems() { // return (String[]) ObjectUtil.invokeMethod(getSource(), "getItems()"); // } // // }
import org.robotframework.formslibrary.operator.ListOperator; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords;
package org.robotframework.formslibrary.keyword; @RobotKeywords public class ListKeyword { @RobotKeyword("Select List Item .\n\nExample:\\n| Select List Item | _1_ | _1_ | \n| Select List Item | _listname_ | 1 | \n" + "\n| Select List Item | _listname_ | _value_ | \\n") @ArgumentNames({ "listIdentifier", "valueIdentifier" }) public void selectListItem(String listIdentifier, String valueIdentifier) {
// Path: src/main/java/org/robotframework/formslibrary/operator/ListOperator.java // public class ListOperator extends AbstractComponentOperator { // // /** // * Initialize an ListOperator with the given list component. // */ // public ListOperator(Component list) { // super(list); // } // // /** // * Initialize a CheckboxOperator with a check box that has the specified // * name in the current context. // * // * @param identifier // * checkbox label or ToolTip text. // */ // public ListOperator(String identifier) { // super(getComponentChooser(identifier)); // } // // private static ComponentChooser getComponentChooser(String identifier) { // if (TextUtil.isNumeric(identifier)) { // return new ByComponentTypeChooser(Integer.parseInt(identifier), ComponentType.LWList); // } else { // return new ByNameChooser(identifier, ComponentType.LWList); // } // } // // public void select(String identifier) { // int index; // if (TextUtil.isNumeric(identifier)) { // index = Integer.parseInt(identifier); // } else { // String[] items = getItems(); // index = Arrays.asList(items).indexOf(identifier); // if (index == -1) { // throw new FormsLibraryException("Value '" + identifier + "' not fond in list: " + items); // } // } // ObjectUtil.invokeMethodWithIntArg(getSource(), "select()", index); // // Method m; // try { // m = getSource().getClass().getSuperclass().getDeclaredMethod("_postItemEvent", String.class, int.class); // m.setAccessible(true); // m.invoke(getSource(), getItem(index), ItemEvent.SELECTED); // } catch (Exception e) { // e.printStackTrace(); // throw new FormsLibraryException("Could not call method _selectItem"); // } // // } // // public String getSelected() { // return (String) ObjectUtil.invokeMethod(getSource(), "getSelectedItem()"); // } // // public String getItem(int i) { // return (String) ObjectUtil.invokeMethodWithIntArg(getSource(), "getItem()", i); // } // // public String[] getItems() { // return (String[]) ObjectUtil.invokeMethod(getSource(), "getItems()"); // } // // } // Path: src/main/java/org/robotframework/formslibrary/keyword/ListKeyword.java import org.robotframework.formslibrary.operator.ListOperator; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords; package org.robotframework.formslibrary.keyword; @RobotKeywords public class ListKeyword { @RobotKeyword("Select List Item .\n\nExample:\\n| Select List Item | _1_ | _1_ | \n| Select List Item | _listname_ | 1 | \n" + "\n| Select List Item | _listname_ | _value_ | \\n") @ArgumentNames({ "listIdentifier", "valueIdentifier" }) public void selectListItem(String listIdentifier, String valueIdentifier) {
new ListOperator(listIdentifier).select(valueIdentifier);
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/keyword/TextFieldKeywords.java
// Path: src/main/java/org/robotframework/formslibrary/operator/LabelOperator.java // public class LabelOperator extends AbstractComponentOperator { // // /** // * Initialize a LabelOperator for the given label. // */ // public LabelOperator(Component component) { // super(component); // } // // /** // * Initialize a LabelOperator with a label with the specified name in the // * current context. // * // * @param identifier // * label. // */ // public LabelOperator(String identifier) { // super(new ByNameChooser(identifier, ComponentType.LABEL, ComponentType.JRADIO_BUTTON, ComponentType.JLABEL)); // } // // /** // * @return field content. // */ // public String getValue() { // return ObjectUtil.getString(getSource(), "getText()"); // } // // /** // * Verify that the field contains the given value. // */ // public void verifyValue(String value) { // if (!TextUtil.matches(getValue(), value)) { // throw new FormsLibraryException("Label value '" + getValue() + "' does not match " + value); // } // Logger.info("Value '" + getValue() + "' matches '" + value + "'."); // } // // } // // Path: src/main/java/org/robotframework/formslibrary/operator/TextFieldOperatorFactory.java // public class TextFieldOperatorFactory { // // /** // * Create an operator for the given component. // * // * @return TextFieldOperator or SelectFieldOperator depending on the type of // * component that was provided. // */ // public static TextFieldOperator getOperator(Component component) { // // if (component != null) { // if (ComponentType.SELECT_FIELD.matches(component)) { // return new SelectFieldOperator(component); // } else { // return new TextFieldOperator(component); // } // } // // return null; // } // // /** // * Create a field operator for a component with the given name. // * // * @return TextFieldOperator or SelectFieldOperator depending on the type of // * component that was found. // */ // public static TextFieldOperator getOperator(String identifier) { // // Component component = new ContextOperator().findTextField(new ByNameChooser(identifier, ComponentType.ALL_TEXTFIELD_TYPES)); // if (component != null) { // return getOperator(component); // } // // return new TextFieldOperator(new ByPrecedingLabelChooser(identifier)); // } // // /** // * Create a field operator for a component with the given name. // * // * @return TextFieldOperator or SelectFieldOperator depending on the type of // * component that was found. // */ // public static TextFieldOperator getOperator(LabelOperator labelOperator) { // Point labelLocation = ComponentUtil.getLocationInWindow(labelOperator.getSource()); // List<Component> textFields = new ContextOperator().findNonTableTextFields(); // // Component textFieldToTheLeft; // try { // Stream<Component> textFieldsToTheLeft = textFields.stream() // .filter(p -> ComponentUtil.getLocationInWindow(p).getY() == labelLocation.getY() // && ComponentUtil.getLocationInWindow(p).getX() > labelLocation.getX()); // textFieldToTheLeft = textFieldsToTheLeft.min((x, y) -> Integer.compare(x.getX(), y.getX())).orElse(null); // } catch (Exception e) { // e.printStackTrace(); // throw new FormsLibraryException("Error in finding text field", e); // } // // if (textFieldToTheLeft != null) { // return getOperator(textFieldToTheLeft); // } // // return null; // } // // }
import org.robotframework.formslibrary.operator.LabelOperator; import org.robotframework.formslibrary.operator.TextFieldOperatorFactory; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords;
package org.robotframework.formslibrary.keyword; @RobotKeywords public class TextFieldKeywords { @RobotKeyword("Locate a field by name and set it to the given value. ':' in the field labels are ignored.\n\n" + "Example:\n" + "| Set Field | _username_ | _jeff_ | \n") @ArgumentNames({ "identifier", "value" }) public void setField(String identifier, String value) {
// Path: src/main/java/org/robotframework/formslibrary/operator/LabelOperator.java // public class LabelOperator extends AbstractComponentOperator { // // /** // * Initialize a LabelOperator for the given label. // */ // public LabelOperator(Component component) { // super(component); // } // // /** // * Initialize a LabelOperator with a label with the specified name in the // * current context. // * // * @param identifier // * label. // */ // public LabelOperator(String identifier) { // super(new ByNameChooser(identifier, ComponentType.LABEL, ComponentType.JRADIO_BUTTON, ComponentType.JLABEL)); // } // // /** // * @return field content. // */ // public String getValue() { // return ObjectUtil.getString(getSource(), "getText()"); // } // // /** // * Verify that the field contains the given value. // */ // public void verifyValue(String value) { // if (!TextUtil.matches(getValue(), value)) { // throw new FormsLibraryException("Label value '" + getValue() + "' does not match " + value); // } // Logger.info("Value '" + getValue() + "' matches '" + value + "'."); // } // // } // // Path: src/main/java/org/robotframework/formslibrary/operator/TextFieldOperatorFactory.java // public class TextFieldOperatorFactory { // // /** // * Create an operator for the given component. // * // * @return TextFieldOperator or SelectFieldOperator depending on the type of // * component that was provided. // */ // public static TextFieldOperator getOperator(Component component) { // // if (component != null) { // if (ComponentType.SELECT_FIELD.matches(component)) { // return new SelectFieldOperator(component); // } else { // return new TextFieldOperator(component); // } // } // // return null; // } // // /** // * Create a field operator for a component with the given name. // * // * @return TextFieldOperator or SelectFieldOperator depending on the type of // * component that was found. // */ // public static TextFieldOperator getOperator(String identifier) { // // Component component = new ContextOperator().findTextField(new ByNameChooser(identifier, ComponentType.ALL_TEXTFIELD_TYPES)); // if (component != null) { // return getOperator(component); // } // // return new TextFieldOperator(new ByPrecedingLabelChooser(identifier)); // } // // /** // * Create a field operator for a component with the given name. // * // * @return TextFieldOperator or SelectFieldOperator depending on the type of // * component that was found. // */ // public static TextFieldOperator getOperator(LabelOperator labelOperator) { // Point labelLocation = ComponentUtil.getLocationInWindow(labelOperator.getSource()); // List<Component> textFields = new ContextOperator().findNonTableTextFields(); // // Component textFieldToTheLeft; // try { // Stream<Component> textFieldsToTheLeft = textFields.stream() // .filter(p -> ComponentUtil.getLocationInWindow(p).getY() == labelLocation.getY() // && ComponentUtil.getLocationInWindow(p).getX() > labelLocation.getX()); // textFieldToTheLeft = textFieldsToTheLeft.min((x, y) -> Integer.compare(x.getX(), y.getX())).orElse(null); // } catch (Exception e) { // e.printStackTrace(); // throw new FormsLibraryException("Error in finding text field", e); // } // // if (textFieldToTheLeft != null) { // return getOperator(textFieldToTheLeft); // } // // return null; // } // // } // Path: src/main/java/org/robotframework/formslibrary/keyword/TextFieldKeywords.java import org.robotframework.formslibrary.operator.LabelOperator; import org.robotframework.formslibrary.operator.TextFieldOperatorFactory; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords; package org.robotframework.formslibrary.keyword; @RobotKeywords public class TextFieldKeywords { @RobotKeyword("Locate a field by name and set it to the given value. ':' in the field labels are ignored.\n\n" + "Example:\n" + "| Set Field | _username_ | _jeff_ | \n") @ArgumentNames({ "identifier", "value" }) public void setField(String identifier, String value) {
TextFieldOperatorFactory.getOperator(identifier).setValue(value);
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/keyword/TextFieldKeywords.java
// Path: src/main/java/org/robotframework/formslibrary/operator/LabelOperator.java // public class LabelOperator extends AbstractComponentOperator { // // /** // * Initialize a LabelOperator for the given label. // */ // public LabelOperator(Component component) { // super(component); // } // // /** // * Initialize a LabelOperator with a label with the specified name in the // * current context. // * // * @param identifier // * label. // */ // public LabelOperator(String identifier) { // super(new ByNameChooser(identifier, ComponentType.LABEL, ComponentType.JRADIO_BUTTON, ComponentType.JLABEL)); // } // // /** // * @return field content. // */ // public String getValue() { // return ObjectUtil.getString(getSource(), "getText()"); // } // // /** // * Verify that the field contains the given value. // */ // public void verifyValue(String value) { // if (!TextUtil.matches(getValue(), value)) { // throw new FormsLibraryException("Label value '" + getValue() + "' does not match " + value); // } // Logger.info("Value '" + getValue() + "' matches '" + value + "'."); // } // // } // // Path: src/main/java/org/robotframework/formslibrary/operator/TextFieldOperatorFactory.java // public class TextFieldOperatorFactory { // // /** // * Create an operator for the given component. // * // * @return TextFieldOperator or SelectFieldOperator depending on the type of // * component that was provided. // */ // public static TextFieldOperator getOperator(Component component) { // // if (component != null) { // if (ComponentType.SELECT_FIELD.matches(component)) { // return new SelectFieldOperator(component); // } else { // return new TextFieldOperator(component); // } // } // // return null; // } // // /** // * Create a field operator for a component with the given name. // * // * @return TextFieldOperator or SelectFieldOperator depending on the type of // * component that was found. // */ // public static TextFieldOperator getOperator(String identifier) { // // Component component = new ContextOperator().findTextField(new ByNameChooser(identifier, ComponentType.ALL_TEXTFIELD_TYPES)); // if (component != null) { // return getOperator(component); // } // // return new TextFieldOperator(new ByPrecedingLabelChooser(identifier)); // } // // /** // * Create a field operator for a component with the given name. // * // * @return TextFieldOperator or SelectFieldOperator depending on the type of // * component that was found. // */ // public static TextFieldOperator getOperator(LabelOperator labelOperator) { // Point labelLocation = ComponentUtil.getLocationInWindow(labelOperator.getSource()); // List<Component> textFields = new ContextOperator().findNonTableTextFields(); // // Component textFieldToTheLeft; // try { // Stream<Component> textFieldsToTheLeft = textFields.stream() // .filter(p -> ComponentUtil.getLocationInWindow(p).getY() == labelLocation.getY() // && ComponentUtil.getLocationInWindow(p).getX() > labelLocation.getX()); // textFieldToTheLeft = textFieldsToTheLeft.min((x, y) -> Integer.compare(x.getX(), y.getX())).orElse(null); // } catch (Exception e) { // e.printStackTrace(); // throw new FormsLibraryException("Error in finding text field", e); // } // // if (textFieldToTheLeft != null) { // return getOperator(textFieldToTheLeft); // } // // return null; // } // // }
import org.robotframework.formslibrary.operator.LabelOperator; import org.robotframework.formslibrary.operator.TextFieldOperatorFactory; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords;
package org.robotframework.formslibrary.keyword; @RobotKeywords public class TextFieldKeywords { @RobotKeyword("Locate a field by name and set it to the given value. ':' in the field labels are ignored.\n\n" + "Example:\n" + "| Set Field | _username_ | _jeff_ | \n") @ArgumentNames({ "identifier", "value" }) public void setField(String identifier, String value) { TextFieldOperatorFactory.getOperator(identifier).setValue(value); } @RobotKeyword("Locate a field by a label on the same height to the left of the text field. ':' in the field labels are ignored.\n" + "Should only be used for fields which do not have a link with the label\n\n" + "Example:\n" + "| Set Field Next To Label | _username_ | _jeff_ | \n") @ArgumentNames({ "identifier", "value" }) public void setFieldNextToLabel(String identifier, String value) {
// Path: src/main/java/org/robotframework/formslibrary/operator/LabelOperator.java // public class LabelOperator extends AbstractComponentOperator { // // /** // * Initialize a LabelOperator for the given label. // */ // public LabelOperator(Component component) { // super(component); // } // // /** // * Initialize a LabelOperator with a label with the specified name in the // * current context. // * // * @param identifier // * label. // */ // public LabelOperator(String identifier) { // super(new ByNameChooser(identifier, ComponentType.LABEL, ComponentType.JRADIO_BUTTON, ComponentType.JLABEL)); // } // // /** // * @return field content. // */ // public String getValue() { // return ObjectUtil.getString(getSource(), "getText()"); // } // // /** // * Verify that the field contains the given value. // */ // public void verifyValue(String value) { // if (!TextUtil.matches(getValue(), value)) { // throw new FormsLibraryException("Label value '" + getValue() + "' does not match " + value); // } // Logger.info("Value '" + getValue() + "' matches '" + value + "'."); // } // // } // // Path: src/main/java/org/robotframework/formslibrary/operator/TextFieldOperatorFactory.java // public class TextFieldOperatorFactory { // // /** // * Create an operator for the given component. // * // * @return TextFieldOperator or SelectFieldOperator depending on the type of // * component that was provided. // */ // public static TextFieldOperator getOperator(Component component) { // // if (component != null) { // if (ComponentType.SELECT_FIELD.matches(component)) { // return new SelectFieldOperator(component); // } else { // return new TextFieldOperator(component); // } // } // // return null; // } // // /** // * Create a field operator for a component with the given name. // * // * @return TextFieldOperator or SelectFieldOperator depending on the type of // * component that was found. // */ // public static TextFieldOperator getOperator(String identifier) { // // Component component = new ContextOperator().findTextField(new ByNameChooser(identifier, ComponentType.ALL_TEXTFIELD_TYPES)); // if (component != null) { // return getOperator(component); // } // // return new TextFieldOperator(new ByPrecedingLabelChooser(identifier)); // } // // /** // * Create a field operator for a component with the given name. // * // * @return TextFieldOperator or SelectFieldOperator depending on the type of // * component that was found. // */ // public static TextFieldOperator getOperator(LabelOperator labelOperator) { // Point labelLocation = ComponentUtil.getLocationInWindow(labelOperator.getSource()); // List<Component> textFields = new ContextOperator().findNonTableTextFields(); // // Component textFieldToTheLeft; // try { // Stream<Component> textFieldsToTheLeft = textFields.stream() // .filter(p -> ComponentUtil.getLocationInWindow(p).getY() == labelLocation.getY() // && ComponentUtil.getLocationInWindow(p).getX() > labelLocation.getX()); // textFieldToTheLeft = textFieldsToTheLeft.min((x, y) -> Integer.compare(x.getX(), y.getX())).orElse(null); // } catch (Exception e) { // e.printStackTrace(); // throw new FormsLibraryException("Error in finding text field", e); // } // // if (textFieldToTheLeft != null) { // return getOperator(textFieldToTheLeft); // } // // return null; // } // // } // Path: src/main/java/org/robotframework/formslibrary/keyword/TextFieldKeywords.java import org.robotframework.formslibrary.operator.LabelOperator; import org.robotframework.formslibrary.operator.TextFieldOperatorFactory; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords; package org.robotframework.formslibrary.keyword; @RobotKeywords public class TextFieldKeywords { @RobotKeyword("Locate a field by name and set it to the given value. ':' in the field labels are ignored.\n\n" + "Example:\n" + "| Set Field | _username_ | _jeff_ | \n") @ArgumentNames({ "identifier", "value" }) public void setField(String identifier, String value) { TextFieldOperatorFactory.getOperator(identifier).setValue(value); } @RobotKeyword("Locate a field by a label on the same height to the left of the text field. ':' in the field labels are ignored.\n" + "Should only be used for fields which do not have a link with the label\n\n" + "Example:\n" + "| Set Field Next To Label | _username_ | _jeff_ | \n") @ArgumentNames({ "identifier", "value" }) public void setFieldNextToLabel(String identifier, String value) {
LabelOperator label = new LabelOperator(identifier);
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/operator/PanelOperator.java
// Path: src/main/java/org/robotframework/formslibrary/chooser/ByComponentFreeTypeChooser.java // public class ByComponentFreeTypeChooser implements ComponentChooser { // // private String type; // private int index; // // /** // * @param index // * Specifies which occurrence of the component in the context to // * select. Use -1 to select all occurrences. // * @param type // * Specifies which component types to include. // */ // public ByComponentFreeTypeChooser(int index, String type) { // this.index = index; // this.type = type; // } // // @Override // public boolean checkComponent(Component component) { // // if (type.matches(component.getClass().getName()) && component.isShowing()) { // if (index <= 0) { // return true; // } else { // index--; // } // } // return false; // } // // @Override // public String getDescription() { // return type; // } // // }
import org.robotframework.formslibrary.chooser.ByComponentFreeTypeChooser; import org.robotframework.swing.context.ContainerOperator; import org.robotframework.swing.context.Context;
package org.robotframework.formslibrary.operator; /** * Operator for working with Panels. */ public class PanelOperator extends ContainerOperator { /** * Initialize a PanelOperator with the given type in the current context. * * @param type * class type of the panel. */ public PanelOperator(String type) {
// Path: src/main/java/org/robotframework/formslibrary/chooser/ByComponentFreeTypeChooser.java // public class ByComponentFreeTypeChooser implements ComponentChooser { // // private String type; // private int index; // // /** // * @param index // * Specifies which occurrence of the component in the context to // * select. Use -1 to select all occurrences. // * @param type // * Specifies which component types to include. // */ // public ByComponentFreeTypeChooser(int index, String type) { // this.index = index; // this.type = type; // } // // @Override // public boolean checkComponent(Component component) { // // if (type.matches(component.getClass().getName()) && component.isShowing()) { // if (index <= 0) { // return true; // } else { // index--; // } // } // return false; // } // // @Override // public String getDescription() { // return type; // } // // } // Path: src/main/java/org/robotframework/formslibrary/operator/PanelOperator.java import org.robotframework.formslibrary.chooser.ByComponentFreeTypeChooser; import org.robotframework.swing.context.ContainerOperator; import org.robotframework.swing.context.Context; package org.robotframework.formslibrary.operator; /** * Operator for working with Panels. */ public class PanelOperator extends ContainerOperator { /** * Initialize a PanelOperator with the given type in the current context. * * @param type * class type of the panel. */ public PanelOperator(String type) {
super((org.netbeans.jemmy.operators.ContainerOperator) Context.getContext(), new ByComponentFreeTypeChooser(0, type));
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/util/ObjectUtil.java
// Path: src/main/java/org/robotframework/formslibrary/FormsLibraryException.java // public class FormsLibraryException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public static final boolean ROBOT_SUPPRESS_NAME = true; // // public FormsLibraryException(String message) { // super(message); // } // // public FormsLibraryException(Throwable t) { // super(t); // } // // public FormsLibraryException(String message, Throwable t) { // super(message, t); // } // }
import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.robotframework.formslibrary.FormsLibraryException;
package org.robotframework.formslibrary.util; /** * Adding frmall.jar (which contains all the Oracle Forms classes) to the java * agent path prevents the application from launching. As a workaround, we don't * include the jar, but use reflection to interact with the oracle forms * objects. */ public class ObjectUtil { /** * Remove brackets () from method path. */ private static String cleanMethodPath(String methodPath) { if (methodPath == null || methodPath.trim().length() == 0) { return null; } return methodPath.replaceAll("\\(", "").replaceAll("\\)", ""); } /** * Invoke an object method that returns a boolean result. */ public static boolean getBoolean(Object object, String methodName) { try { Method m = object.getClass().getMethod(cleanMethodPath(methodName)); return (Boolean) m.invoke(object); } catch (Exception e) {
// Path: src/main/java/org/robotframework/formslibrary/FormsLibraryException.java // public class FormsLibraryException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public static final boolean ROBOT_SUPPRESS_NAME = true; // // public FormsLibraryException(String message) { // super(message); // } // // public FormsLibraryException(Throwable t) { // super(t); // } // // public FormsLibraryException(String message, Throwable t) { // super(message, t); // } // } // Path: src/main/java/org/robotframework/formslibrary/util/ObjectUtil.java import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.robotframework.formslibrary.FormsLibraryException; package org.robotframework.formslibrary.util; /** * Adding frmall.jar (which contains all the Oracle Forms classes) to the java * agent path prevents the application from launching. As a workaround, we don't * include the jar, but use reflection to interact with the oracle forms * objects. */ public class ObjectUtil { /** * Remove brackets () from method path. */ private static String cleanMethodPath(String methodPath) { if (methodPath == null || methodPath.trim().length() == 0) { return null; } return methodPath.replaceAll("\\(", "").replaceAll("\\)", ""); } /** * Invoke an object method that returns a boolean result. */ public static boolean getBoolean(Object object, String methodName) { try { Method m = object.getClass().getMethod(cleanMethodPath(methodName)); return (Boolean) m.invoke(object); } catch (Exception e) {
throw new FormsLibraryException("Could not invoke method " + methodName, e);
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/keyword/ListViewKeywords.java
// Path: src/main/java/org/robotframework/formslibrary/operator/ListViewOperator.java // public class ListViewOperator extends AbstractRootComponentOperator { // // /** // * Initialize a ListViewOperator with the first list view found in the // * current context. // */ // public ListViewOperator() { // super(new ByComponentTypeChooser(0, ComponentType.LIST_VIEW)); // } // // /** // * Search for row in the list view by content and select it. // * // * @param columnValues // * key column values to search for. // */ // public void selectRow(String[] columnValues) { // // int rowCount = (Integer) ObjectUtil.invokeMethod(getSource(), "getRowCount"); // // for (int i = 0; i < rowCount; i++) { // // boolean foundRow = true; // for (int j = 0; j < columnValues.length; j++) { // String cellData = (String) ObjectUtil.invokeMethodWith2IntArgs(getSource(), "getCellData()", j, i); // Logger.debug("Found list cell [" + j + "," + i + "] : " + cellData); // if (!TextUtil.matches(cellData, columnValues[j])) { // foundRow = false; // break; // } // Logger.info("Found list cell [" + j + "," + i + "] : " + cellData); // } // // if (foundRow) { // ObjectUtil.invokeMethodWithIntArg(getSource(), "setSelectedRow()", i); // return; // } // } // // throw new FormsLibraryException("Could not find row. Maybe it was not visible and you need to scroll down first?"); // } // // }
import org.robotframework.formslibrary.operator.ListViewOperator; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords;
package org.robotframework.formslibrary.keyword; @RobotKeywords public class ListViewKeywords { @RobotKeyword("Select a row in a list view table by content.\n\n" + "Example:\n" + "| Select List Row | _market_ | _gas_ | \n") @ArgumentNames({ "*columnvalues" }) public void selectListRow(String... columnValues) {
// Path: src/main/java/org/robotframework/formslibrary/operator/ListViewOperator.java // public class ListViewOperator extends AbstractRootComponentOperator { // // /** // * Initialize a ListViewOperator with the first list view found in the // * current context. // */ // public ListViewOperator() { // super(new ByComponentTypeChooser(0, ComponentType.LIST_VIEW)); // } // // /** // * Search for row in the list view by content and select it. // * // * @param columnValues // * key column values to search for. // */ // public void selectRow(String[] columnValues) { // // int rowCount = (Integer) ObjectUtil.invokeMethod(getSource(), "getRowCount"); // // for (int i = 0; i < rowCount; i++) { // // boolean foundRow = true; // for (int j = 0; j < columnValues.length; j++) { // String cellData = (String) ObjectUtil.invokeMethodWith2IntArgs(getSource(), "getCellData()", j, i); // Logger.debug("Found list cell [" + j + "," + i + "] : " + cellData); // if (!TextUtil.matches(cellData, columnValues[j])) { // foundRow = false; // break; // } // Logger.info("Found list cell [" + j + "," + i + "] : " + cellData); // } // // if (foundRow) { // ObjectUtil.invokeMethodWithIntArg(getSource(), "setSelectedRow()", i); // return; // } // } // // throw new FormsLibraryException("Could not find row. Maybe it was not visible and you need to scroll down first?"); // } // // } // Path: src/main/java/org/robotframework/formslibrary/keyword/ListViewKeywords.java import org.robotframework.formslibrary.operator.ListViewOperator; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords; package org.robotframework.formslibrary.keyword; @RobotKeywords public class ListViewKeywords { @RobotKeyword("Select a row in a list view table by content.\n\n" + "Example:\n" + "| Select List Row | _market_ | _gas_ | \n") @ArgumentNames({ "*columnvalues" }) public void selectListRow(String... columnValues) {
new ListViewOperator().selectRow(columnValues);
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/util/DebugUtil.java
// Path: src/main/java/org/robotframework/formslibrary/FormsLibraryException.java // public class FormsLibraryException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public static final boolean ROBOT_SUPPRESS_NAME = true; // // public FormsLibraryException(String message) { // super(message); // } // // public FormsLibraryException(Throwable t) { // super(t); // } // // public FormsLibraryException(String message, Throwable t) { // super(message, t); // } // }
import org.robotframework.formslibrary.FormsLibraryException;
package org.robotframework.formslibrary.util; /** * Utility class to keep track of the debug logging level and debug delays. */ public class DebugUtil { private static boolean debugEnabled; private static int keywordDelay = 0; /** * @return true if debug logging is enabled. */ public static boolean isDebugEnabled() { return debugEnabled; } /** * Enable forms library debug logging. */ public static void setDebugEnabled(boolean debugEnabled) { DebugUtil.debugEnabled = debugEnabled; } /** * Delay each operation creation with the given delay. * * @param keywordDelay * time in ms */ public static void setKeywordDelay(int keywordDelay) { DebugUtil.keywordDelay = keywordDelay; } /** * To prevent screen actions from happening so fast that it is not possible * to view what is happening, we delay the constructing of operators with * the specified keyword delay. */ public static void applyKeywordDelay() { if (keywordDelay > 0) { try { Thread.sleep(keywordDelay); } catch (InterruptedException e) {
// Path: src/main/java/org/robotframework/formslibrary/FormsLibraryException.java // public class FormsLibraryException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public static final boolean ROBOT_SUPPRESS_NAME = true; // // public FormsLibraryException(String message) { // super(message); // } // // public FormsLibraryException(Throwable t) { // super(t); // } // // public FormsLibraryException(String message, Throwable t) { // super(message, t); // } // } // Path: src/main/java/org/robotframework/formslibrary/util/DebugUtil.java import org.robotframework.formslibrary.FormsLibraryException; package org.robotframework.formslibrary.util; /** * Utility class to keep track of the debug logging level and debug delays. */ public class DebugUtil { private static boolean debugEnabled; private static int keywordDelay = 0; /** * @return true if debug logging is enabled. */ public static boolean isDebugEnabled() { return debugEnabled; } /** * Enable forms library debug logging. */ public static void setDebugEnabled(boolean debugEnabled) { DebugUtil.debugEnabled = debugEnabled; } /** * Delay each operation creation with the given delay. * * @param keywordDelay * time in ms */ public static void setKeywordDelay(int keywordDelay) { DebugUtil.keywordDelay = keywordDelay; } /** * To prevent screen actions from happening so fast that it is not possible * to view what is happening, we delay the constructing of operators with * the specified keyword delay. */ public static void applyKeywordDelay() { if (keywordDelay > 0) { try { Thread.sleep(keywordDelay); } catch (InterruptedException e) {
throw new FormsLibraryException(e);
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/util/ComponentUtil.java
// Path: src/main/java/org/robotframework/formslibrary/FormsLibraryException.java // public class FormsLibraryException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public static final boolean ROBOT_SUPPRESS_NAME = true; // // public FormsLibraryException(String message) { // super(message); // } // // public FormsLibraryException(Throwable t) { // super(t); // } // // public FormsLibraryException(String message, Throwable t) { // super(message, t); // } // }
import java.awt.Component; import java.awt.Container; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.accessibility.AccessibleContext; import javax.imageio.ImageIO; import org.robotframework.formslibrary.FormsLibraryException;
*/ public static Point getLocationInWindow(Component component) { int x = component.getX(); int y = component.getY(); Component parent = component.getParent(); while (parent != null && !ComponentType.EXTENDED_FRAME.matches(parent) && !ComponentType.FORM_DESKTOP.matches(parent)) { x = x + parent.getX(); y = y + parent.getY(); parent = parent.getParent(); } return new Point(x, y); } /** * Get the tooltip text for a component. * * @return text or null if no tooltip is available. */ private static String getToolTipText(Component component) { String text = null; try { Object toolTip = ObjectUtil.invokeMethod(component, "getToolTipValue()"); if (toolTip != null) { text = (String) ObjectUtil.invokeMethodWithIntArg(toolTip, "getToolTipProperty()", 409); }
// Path: src/main/java/org/robotframework/formslibrary/FormsLibraryException.java // public class FormsLibraryException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public static final boolean ROBOT_SUPPRESS_NAME = true; // // public FormsLibraryException(String message) { // super(message); // } // // public FormsLibraryException(Throwable t) { // super(t); // } // // public FormsLibraryException(String message, Throwable t) { // super(message, t); // } // } // Path: src/main/java/org/robotframework/formslibrary/util/ComponentUtil.java import java.awt.Component; import java.awt.Container; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.accessibility.AccessibleContext; import javax.imageio.ImageIO; import org.robotframework.formslibrary.FormsLibraryException; */ public static Point getLocationInWindow(Component component) { int x = component.getX(); int y = component.getY(); Component parent = component.getParent(); while (parent != null && !ComponentType.EXTENDED_FRAME.matches(parent) && !ComponentType.FORM_DESKTOP.matches(parent)) { x = x + parent.getX(); y = y + parent.getY(); parent = parent.getParent(); } return new Point(x, y); } /** * Get the tooltip text for a component. * * @return text or null if no tooltip is available. */ private static String getToolTipText(Component component) { String text = null; try { Object toolTip = ObjectUtil.invokeMethod(component, "getToolTipValue()"); if (toolTip != null) { text = (String) ObjectUtil.invokeMethodWithIntArg(toolTip, "getToolTipProperty()", 409); }
} catch (FormsLibraryException e) {
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/keyword/TreeKeywords.java
// Path: src/main/java/org/robotframework/formslibrary/operator/TreeOperator.java // public class TreeOperator extends AbstractComponentOperator { // // /** // * Initialize a TreeOperator with the navigation tree found in the current // * context. // */ // public TreeOperator() { // super(new ByComponentTypeChooser(0, ComponentType.TREE)); // } // // /** // * Select entries matching the given path // * // * @param path // * e.g. level1 > level2 > level3 // */ // public void select(String path) { // // Object dTreeRootItem = ObjectUtil.invokeMethod(getSource(), "getRoot()"); // Object treeItem = findTreeItem(dTreeRootItem, path); // if (treeItem == null) { // throw new FormsLibraryException("Could not find tree path " + path); // } // // Object tree = ObjectUtil.invokeMethod(dTreeRootItem, "getTree()"); // Object selection = ObjectUtil.invokeMethod(tree, "getSelection()"); // ObjectUtil.invokeMethodWithTypedArg(selection, "selectItem()", ComponentType.TREE_ITEM.toString(), treeItem); // // } // // private Object findTreeItem(Object parentItem, String path) { // // boolean isLastLevel = path.indexOf(Constants.LEVEL_SEPARATOR) == -1; // String labelToSelect = TextUtil.getFirstSegment(path, Constants.LEVEL_SEPARATOR); // // int itemCount = (Integer) ObjectUtil.invokeMethod(parentItem, "getItemCount()"); // for (int i = 0; i < itemCount; i++) { // // Object treeItem = ObjectUtil.invokeMethodWithIntArg(parentItem, "getItem()", i); // String itemLabel = ObjectUtil.getString(treeItem, "getLabel()"); // boolean isExpanded = ObjectUtil.getBoolean(treeItem, "isExpanded()"); // Logger.debug("Found tree item '" + itemLabel + "' (expanded=" + isExpanded + ")"); // // if (!TextUtil.matches(itemLabel, labelToSelect)) { // continue; // } // // if (isLastLevel) { // return treeItem; // } else { // if (!isExpanded) { // ObjectUtil.invokeMethodWithBoolArg(treeItem, "setExpanded()", true); // isExpanded = ObjectUtil.getBoolean(treeItem, "isExpanded()"); // Logger.debug("Tree item '" + itemLabel + "' (expanded=" + isExpanded + ")"); // getSource().invalidate(); // } // return findTreeItem(treeItem, TextUtil.getNextSegments(path, Constants.LEVEL_SEPARATOR)); // } // } // // return null; // } // // }
import org.robotframework.formslibrary.operator.TreeOperator; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords;
package org.robotframework.formslibrary.keyword; @RobotKeywords public class TreeKeywords { @RobotKeyword("Select a tree entry by its label. Use '>' between different levels.\n\n Example:\n" + "| Select Tree | _root > branch1 > branch1.1_ |\n") @ArgumentNames({ "treePath" }) public void selectTree(String treePath) { // locate the DTree by index walk the menu in the select
// Path: src/main/java/org/robotframework/formslibrary/operator/TreeOperator.java // public class TreeOperator extends AbstractComponentOperator { // // /** // * Initialize a TreeOperator with the navigation tree found in the current // * context. // */ // public TreeOperator() { // super(new ByComponentTypeChooser(0, ComponentType.TREE)); // } // // /** // * Select entries matching the given path // * // * @param path // * e.g. level1 > level2 > level3 // */ // public void select(String path) { // // Object dTreeRootItem = ObjectUtil.invokeMethod(getSource(), "getRoot()"); // Object treeItem = findTreeItem(dTreeRootItem, path); // if (treeItem == null) { // throw new FormsLibraryException("Could not find tree path " + path); // } // // Object tree = ObjectUtil.invokeMethod(dTreeRootItem, "getTree()"); // Object selection = ObjectUtil.invokeMethod(tree, "getSelection()"); // ObjectUtil.invokeMethodWithTypedArg(selection, "selectItem()", ComponentType.TREE_ITEM.toString(), treeItem); // // } // // private Object findTreeItem(Object parentItem, String path) { // // boolean isLastLevel = path.indexOf(Constants.LEVEL_SEPARATOR) == -1; // String labelToSelect = TextUtil.getFirstSegment(path, Constants.LEVEL_SEPARATOR); // // int itemCount = (Integer) ObjectUtil.invokeMethod(parentItem, "getItemCount()"); // for (int i = 0; i < itemCount; i++) { // // Object treeItem = ObjectUtil.invokeMethodWithIntArg(parentItem, "getItem()", i); // String itemLabel = ObjectUtil.getString(treeItem, "getLabel()"); // boolean isExpanded = ObjectUtil.getBoolean(treeItem, "isExpanded()"); // Logger.debug("Found tree item '" + itemLabel + "' (expanded=" + isExpanded + ")"); // // if (!TextUtil.matches(itemLabel, labelToSelect)) { // continue; // } // // if (isLastLevel) { // return treeItem; // } else { // if (!isExpanded) { // ObjectUtil.invokeMethodWithBoolArg(treeItem, "setExpanded()", true); // isExpanded = ObjectUtil.getBoolean(treeItem, "isExpanded()"); // Logger.debug("Tree item '" + itemLabel + "' (expanded=" + isExpanded + ")"); // getSource().invalidate(); // } // return findTreeItem(treeItem, TextUtil.getNextSegments(path, Constants.LEVEL_SEPARATOR)); // } // } // // return null; // } // // } // Path: src/main/java/org/robotframework/formslibrary/keyword/TreeKeywords.java import org.robotframework.formslibrary.operator.TreeOperator; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords; package org.robotframework.formslibrary.keyword; @RobotKeywords public class TreeKeywords { @RobotKeyword("Select a tree entry by its label. Use '>' between different levels.\n\n Example:\n" + "| Select Tree | _root > branch1 > branch1.1_ |\n") @ArgumentNames({ "treePath" }) public void selectTree(String treePath) { // locate the DTree by index walk the menu in the select
new TreeOperator().select(treePath);
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/keyword/LabelKeywords.java
// Path: src/main/java/org/robotframework/formslibrary/operator/LabelOperator.java // public class LabelOperator extends AbstractComponentOperator { // // /** // * Initialize a LabelOperator for the given label. // */ // public LabelOperator(Component component) { // super(component); // } // // /** // * Initialize a LabelOperator with a label with the specified name in the // * current context. // * // * @param identifier // * label. // */ // public LabelOperator(String identifier) { // super(new ByNameChooser(identifier, ComponentType.LABEL, ComponentType.JRADIO_BUTTON, ComponentType.JLABEL)); // } // // /** // * @return field content. // */ // public String getValue() { // return ObjectUtil.getString(getSource(), "getText()"); // } // // /** // * Verify that the field contains the given value. // */ // public void verifyValue(String value) { // if (!TextUtil.matches(getValue(), value)) { // throw new FormsLibraryException("Label value '" + getValue() + "' does not match " + value); // } // Logger.info("Value '" + getValue() + "' matches '" + value + "'."); // } // // }
import org.robotframework.formslibrary.operator.LabelOperator; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords;
package org.robotframework.formslibrary.keyword; @RobotKeywords public class LabelKeywords { @RobotKeyword("Get label content.\n\n" + "Example:\n" + "| \n" + "| ${textFieldValue}= | Get Field | _username_ | \n") @ArgumentNames({ "identifier" }) public String getLabel(String identifier) {
// Path: src/main/java/org/robotframework/formslibrary/operator/LabelOperator.java // public class LabelOperator extends AbstractComponentOperator { // // /** // * Initialize a LabelOperator for the given label. // */ // public LabelOperator(Component component) { // super(component); // } // // /** // * Initialize a LabelOperator with a label with the specified name in the // * current context. // * // * @param identifier // * label. // */ // public LabelOperator(String identifier) { // super(new ByNameChooser(identifier, ComponentType.LABEL, ComponentType.JRADIO_BUTTON, ComponentType.JLABEL)); // } // // /** // * @return field content. // */ // public String getValue() { // return ObjectUtil.getString(getSource(), "getText()"); // } // // /** // * Verify that the field contains the given value. // */ // public void verifyValue(String value) { // if (!TextUtil.matches(getValue(), value)) { // throw new FormsLibraryException("Label value '" + getValue() + "' does not match " + value); // } // Logger.info("Value '" + getValue() + "' matches '" + value + "'."); // } // // } // Path: src/main/java/org/robotframework/formslibrary/keyword/LabelKeywords.java import org.robotframework.formslibrary.operator.LabelOperator; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords; package org.robotframework.formslibrary.keyword; @RobotKeywords public class LabelKeywords { @RobotKeyword("Get label content.\n\n" + "Example:\n" + "| \n" + "| ${textFieldValue}= | Get Field | _username_ | \n") @ArgumentNames({ "identifier" }) public String getLabel(String identifier) {
return new LabelOperator(identifier).getValue();
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/context/ContextChangeMonitor.java
// Path: src/main/java/org/robotframework/formslibrary/operator/LWWindowOperator.java // public class LWWindowOperator extends AbstractRootComponentOperator { // // /** // * Initialize a window operator with the main oracle forms desktop window. // */ // public LWWindowOperator() { // super(new ByComponentTypeChooser(0, ComponentType.FORM_DESKTOP)); // } // // public LWWindowOperator(ComponentChooser chooser) { // super(chooser); // } // // /** // * Retrieve a list of all window titles in the root context. // */ // public List<String> getWindowTitles() { // // List<String> frameTitles = new ArrayList<String>(); // Component[] extendedFrames = ((Container) getSource()).getComponents(); // for (Component frame : extendedFrames) { // Component[] children = ((Container) frame).getComponents(); // for (Component child : children) { // if (ComponentType.TITLE_BAR.matches(child)) { // boolean visible = ObjectUtil.getBoolean(frame, "isVisible()"); // String title = ObjectUtil.getString(child, "getLWWindow().getTitle()"); // Logger.debug("Found window '" + title + "' [visible=" + visible + "]"); // if (visible) { // frameTitles.add(title); // } // } // } // } // // return frameTitles; // } // // public String getSelectedWindowTitle() { // // Component[] extendedFrames = ((Container) getSource()).getComponents(); // for (Component frame : extendedFrames) { // if (frame.isFocusOwner()) { // Component[] children = ((Container) frame).getComponents(); // for (Component child : children) { // // if (ComponentType.TITLE_BAR.matches(child)) { // boolean visible = ObjectUtil.getBoolean(frame, "isVisible()"); // if (visible) { // return ObjectUtil.getString(child, "getLWWindow().getTitle()"); // } // } // } // } // } // return null; // } // // /** // * Change the current context to the window with the given title. // * // * @param windowTitle // * title of the window. // */ // public void setWindowAsContext(String windowTitle) { // // Component[] extendedFrames = ((Container) getSource()).getComponents(); // for (Component frame : extendedFrames) { // Component[] children = ((Container) frame).getComponents(); // for (Component child : children) { // if (ComponentType.TITLE_BAR.matches(child)) { // // String title = ObjectUtil.getString(child, "getLWWindow().getTitle()"); // if (TextUtil.matches(title, windowTitle)) { // FormsContext.setContext(new FrameOperator((Container) frame)); // frame.requestFocus(); // Logger.info("Context set to window '" + title + "'"); // return; // } // } // } // } // // throw new FormsLibraryException("No window with title '" + windowTitle + "' found."); // } // // /** // * Close all open windows in the application except the main menu. // */ // public void closeOpenWindows() { // // // reset context before closing windows // FormsContext.resetContext(); // // List<Component> framesToClose = new ArrayList<Component>(); // // Component[] extendedFrames = ((Container) getSource()).getComponents(); // for (Component frame : extendedFrames) { // Component[] children = ((Container) frame).getComponents(); // for (Component child : children) { // if (ComponentType.TITLE_BAR.matches(child)) { // if (ObjectUtil.getBoolean(frame, "isVisible()")) { // String title = ObjectUtil.getString(child, "getLWWindow().getTitle()"); // if (!title.contains("Main Menu")) { // Logger.info("Closing window '" + title + "'"); // framesToClose.add(frame); // } // } // } // } // } // // for (Component frame : framesToClose) { // ObjectUtil.invokeMethod(frame, "close()"); // } // } // // } // // Path: src/main/java/org/robotframework/formslibrary/util/Logger.java // public class Logger { // // public static void debug(String message) { // if (DebugUtil.isDebugEnabled()) { // System.out.println("~ " + message); // } // } // // public static void info(String message) { // System.out.println(message); // } // // public static void error(Throwable t) { // t.printStackTrace(); // } // }
import java.util.List; import org.robotframework.formslibrary.operator.LWWindowOperator; import org.robotframework.formslibrary.util.Logger;
package org.robotframework.formslibrary.context; /** * Monitor the open windows before and after an action. When a new window is * detected or the current window was closed, the current context will be * changed accordingly. */ public class ContextChangeMonitor { private List<String> initialOpenLWWindows; /** * Start monitoring for window changes. */ public void start() { if (FormsContext.isFormsServicesApp()) {
// Path: src/main/java/org/robotframework/formslibrary/operator/LWWindowOperator.java // public class LWWindowOperator extends AbstractRootComponentOperator { // // /** // * Initialize a window operator with the main oracle forms desktop window. // */ // public LWWindowOperator() { // super(new ByComponentTypeChooser(0, ComponentType.FORM_DESKTOP)); // } // // public LWWindowOperator(ComponentChooser chooser) { // super(chooser); // } // // /** // * Retrieve a list of all window titles in the root context. // */ // public List<String> getWindowTitles() { // // List<String> frameTitles = new ArrayList<String>(); // Component[] extendedFrames = ((Container) getSource()).getComponents(); // for (Component frame : extendedFrames) { // Component[] children = ((Container) frame).getComponents(); // for (Component child : children) { // if (ComponentType.TITLE_BAR.matches(child)) { // boolean visible = ObjectUtil.getBoolean(frame, "isVisible()"); // String title = ObjectUtil.getString(child, "getLWWindow().getTitle()"); // Logger.debug("Found window '" + title + "' [visible=" + visible + "]"); // if (visible) { // frameTitles.add(title); // } // } // } // } // // return frameTitles; // } // // public String getSelectedWindowTitle() { // // Component[] extendedFrames = ((Container) getSource()).getComponents(); // for (Component frame : extendedFrames) { // if (frame.isFocusOwner()) { // Component[] children = ((Container) frame).getComponents(); // for (Component child : children) { // // if (ComponentType.TITLE_BAR.matches(child)) { // boolean visible = ObjectUtil.getBoolean(frame, "isVisible()"); // if (visible) { // return ObjectUtil.getString(child, "getLWWindow().getTitle()"); // } // } // } // } // } // return null; // } // // /** // * Change the current context to the window with the given title. // * // * @param windowTitle // * title of the window. // */ // public void setWindowAsContext(String windowTitle) { // // Component[] extendedFrames = ((Container) getSource()).getComponents(); // for (Component frame : extendedFrames) { // Component[] children = ((Container) frame).getComponents(); // for (Component child : children) { // if (ComponentType.TITLE_BAR.matches(child)) { // // String title = ObjectUtil.getString(child, "getLWWindow().getTitle()"); // if (TextUtil.matches(title, windowTitle)) { // FormsContext.setContext(new FrameOperator((Container) frame)); // frame.requestFocus(); // Logger.info("Context set to window '" + title + "'"); // return; // } // } // } // } // // throw new FormsLibraryException("No window with title '" + windowTitle + "' found."); // } // // /** // * Close all open windows in the application except the main menu. // */ // public void closeOpenWindows() { // // // reset context before closing windows // FormsContext.resetContext(); // // List<Component> framesToClose = new ArrayList<Component>(); // // Component[] extendedFrames = ((Container) getSource()).getComponents(); // for (Component frame : extendedFrames) { // Component[] children = ((Container) frame).getComponents(); // for (Component child : children) { // if (ComponentType.TITLE_BAR.matches(child)) { // if (ObjectUtil.getBoolean(frame, "isVisible()")) { // String title = ObjectUtil.getString(child, "getLWWindow().getTitle()"); // if (!title.contains("Main Menu")) { // Logger.info("Closing window '" + title + "'"); // framesToClose.add(frame); // } // } // } // } // } // // for (Component frame : framesToClose) { // ObjectUtil.invokeMethod(frame, "close()"); // } // } // // } // // Path: src/main/java/org/robotframework/formslibrary/util/Logger.java // public class Logger { // // public static void debug(String message) { // if (DebugUtil.isDebugEnabled()) { // System.out.println("~ " + message); // } // } // // public static void info(String message) { // System.out.println(message); // } // // public static void error(Throwable t) { // t.printStackTrace(); // } // } // Path: src/main/java/org/robotframework/formslibrary/context/ContextChangeMonitor.java import java.util.List; import org.robotframework.formslibrary.operator.LWWindowOperator; import org.robotframework.formslibrary.util.Logger; package org.robotframework.formslibrary.context; /** * Monitor the open windows before and after an action. When a new window is * detected or the current window was closed, the current context will be * changed accordingly. */ public class ContextChangeMonitor { private List<String> initialOpenLWWindows; /** * Start monitoring for window changes. */ public void start() { if (FormsContext.isFormsServicesApp()) {
initialOpenLWWindows = new LWWindowOperator().getWindowTitles();
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/operator/FormsDialogOperator.java
// Path: src/main/java/org/robotframework/formslibrary/context/FormsContext.java // public class FormsContext { // private static String FORMS_TITLE = "Oracle Fusion Middleware Forms Services"; // private static ComponentWrapper context; // // private static Boolean isFormServicesApp = null; // // public static void setContext(ComponentWrapper operator) { // context = operator; // // TODO remove swing library context dependency if possible // Context.setContext(context); // } // // /** // * Get current context. If no context is set, it will be defaulted to the // * first window. // */ // public static ComponentWrapper getContext() { // // // set root context if no context exists // if (context == null) { // Logger.debug("No context found."); // resetContext(); // } // // if (isFormsServicesApp()) { // // Component contextComponent = Context.getContext().getSource(); // // // verify that the current window context is still part of the // // desktop // if (!new FrameOperator().containsComponent(contextComponent) && !isActiveDialog(context)) { // Logger.info("Context " + ComponentUtil.getFormattedComponentNames(contextComponent) + " is no longer part of desktop."); // resetContext(); // return context; // } // // // verify the type of context // // if (!ComponentType.JFRAME.matches(contextComponent) && // // !ComponentType.EXTENDED_FRAME.matches(contextComponent) // // && !ComponentType.WINDOW.matches(contextComponent) && // // !ComponentType.BUFFERED_FRAME.matches(contextComponent)) { // // throw new FormsLibraryException("Invalid context selected: " + // // contextComponent.getClass().getSimpleName()); // // } // } // // return context; // } // // private static boolean isActiveDialog(ComponentWrapper context) { // Component source = context.getSource(); // if (source instanceof Dialog) { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // if (window == source) { // return true; // } // } // } // return false; // } // // /** // * @return root context (the forms desktop window) // */ // public static ComponentWrapper getRootContext() { // return new FrameOperator(); // } // // /** // * @return root context (the forms desktop window) // */ // public static void listWindows() { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // Logger.info( // "Window - " + window.getName() + " - " + window.getClass().getName() + " title=" + ObjectUtil.getFieldIfExists(window, "title")); // } // } // // public static boolean isFormsServicesApp() { // if (isFormServicesApp == null) { // isFormServicesApp = checkFormServicesApp(); // } // return isFormServicesApp; // } // // private static boolean checkFormServicesApp() { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // Object title = ObjectUtil.getFieldIfExists(window, "title"); // if (title != null && title instanceof String) { // if (((String) title).equals(FORMS_TITLE)) { // return true; // } // } // } // return false; // } // // /** // * Change the context to the root context. // */ // public static void resetContext() { // Logger.info("Changing context to main desktop window."); // context = getRootContext(); // Context.setContext(context); // } // }
import java.awt.Component; import java.awt.Dialog; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.operators.WindowOperator; import org.robotframework.formslibrary.context.FormsContext; import org.robotframework.swing.common.Identifier; import org.robotframework.swing.operator.ComponentWrapper;
} private static ComponentChooser createComponentChooser(final String title, boolean regex) { return new ComponentChooser() { @Override public String getDescription() { return "Dialog with name or title '" + title + "'"; } @Override public boolean checkComponent(Component comp) { if (!(comp instanceof Dialog)) return false; if (regex) { String val = comp == null ? "" : ((Dialog) comp).getTitle(); return val.matches(title); } else { return eq(title, comp) || org.robotframework.swing.util.ObjectUtils.nullSafeEquals(((Dialog) comp).getTitle(), title); } } private boolean eq(final String title, Component comp) { return org.robotframework.swing.util.ObjectUtils.nullSafeEquals(comp.getName(), title); } }; } public void setAsContext() {
// Path: src/main/java/org/robotframework/formslibrary/context/FormsContext.java // public class FormsContext { // private static String FORMS_TITLE = "Oracle Fusion Middleware Forms Services"; // private static ComponentWrapper context; // // private static Boolean isFormServicesApp = null; // // public static void setContext(ComponentWrapper operator) { // context = operator; // // TODO remove swing library context dependency if possible // Context.setContext(context); // } // // /** // * Get current context. If no context is set, it will be defaulted to the // * first window. // */ // public static ComponentWrapper getContext() { // // // set root context if no context exists // if (context == null) { // Logger.debug("No context found."); // resetContext(); // } // // if (isFormsServicesApp()) { // // Component contextComponent = Context.getContext().getSource(); // // // verify that the current window context is still part of the // // desktop // if (!new FrameOperator().containsComponent(contextComponent) && !isActiveDialog(context)) { // Logger.info("Context " + ComponentUtil.getFormattedComponentNames(contextComponent) + " is no longer part of desktop."); // resetContext(); // return context; // } // // // verify the type of context // // if (!ComponentType.JFRAME.matches(contextComponent) && // // !ComponentType.EXTENDED_FRAME.matches(contextComponent) // // && !ComponentType.WINDOW.matches(contextComponent) && // // !ComponentType.BUFFERED_FRAME.matches(contextComponent)) { // // throw new FormsLibraryException("Invalid context selected: " + // // contextComponent.getClass().getSimpleName()); // // } // } // // return context; // } // // private static boolean isActiveDialog(ComponentWrapper context) { // Component source = context.getSource(); // if (source instanceof Dialog) { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // if (window == source) { // return true; // } // } // } // return false; // } // // /** // * @return root context (the forms desktop window) // */ // public static ComponentWrapper getRootContext() { // return new FrameOperator(); // } // // /** // * @return root context (the forms desktop window) // */ // public static void listWindows() { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // Logger.info( // "Window - " + window.getName() + " - " + window.getClass().getName() + " title=" + ObjectUtil.getFieldIfExists(window, "title")); // } // } // // public static boolean isFormsServicesApp() { // if (isFormServicesApp == null) { // isFormServicesApp = checkFormServicesApp(); // } // return isFormServicesApp; // } // // private static boolean checkFormServicesApp() { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // Object title = ObjectUtil.getFieldIfExists(window, "title"); // if (title != null && title instanceof String) { // if (((String) title).equals(FORMS_TITLE)) { // return true; // } // } // } // return false; // } // // /** // * Change the context to the root context. // */ // public static void resetContext() { // Logger.info("Changing context to main desktop window."); // context = getRootContext(); // Context.setContext(context); // } // } // Path: src/main/java/org/robotframework/formslibrary/operator/FormsDialogOperator.java import java.awt.Component; import java.awt.Dialog; import org.netbeans.jemmy.ComponentChooser; import org.netbeans.jemmy.operators.WindowOperator; import org.robotframework.formslibrary.context.FormsContext; import org.robotframework.swing.common.Identifier; import org.robotframework.swing.operator.ComponentWrapper; } private static ComponentChooser createComponentChooser(final String title, boolean regex) { return new ComponentChooser() { @Override public String getDescription() { return "Dialog with name or title '" + title + "'"; } @Override public boolean checkComponent(Component comp) { if (!(comp instanceof Dialog)) return false; if (regex) { String val = comp == null ? "" : ((Dialog) comp).getTitle(); return val.matches(title); } else { return eq(title, comp) || org.robotframework.swing.util.ObjectUtils.nullSafeEquals(((Dialog) comp).getTitle(), title); } } private boolean eq(final String title, Component comp) { return org.robotframework.swing.util.ObjectUtils.nullSafeEquals(comp.getName(), title); } }; } public void setAsContext() {
FormsContext.setContext(this);
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/keyword/ButtonKeywords.java
// Path: src/main/java/org/robotframework/formslibrary/FormsLibraryException.java // public class FormsLibraryException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public static final boolean ROBOT_SUPPRESS_NAME = true; // // public FormsLibraryException(String message) { // super(message); // } // // public FormsLibraryException(Throwable t) { // super(t); // } // // public FormsLibraryException(String message, Throwable t) { // super(message, t); // } // } // // Path: src/main/java/org/robotframework/formslibrary/context/ContextChangeMonitor.java // public class ContextChangeMonitor { // // private List<String> initialOpenLWWindows; // // /** // * Start monitoring for window changes. // */ // public void start() { // if (FormsContext.isFormsServicesApp()) { // initialOpenLWWindows = new LWWindowOperator().getWindowTitles(); // } else { // // } // } // // /** // * Stop monitoring for window changes and change the context if needed. When // * a new window is detected, it will be automatically set as the new // * context. When the current context window was closed, the context will be // * reset to the root context. // */ // public void stop() { // if (FormsContext.isFormsServicesApp()) { // List<String> newOpenWindows = new LWWindowOperator().getWindowTitles(); // // // check if a window was closed // if (newOpenWindows.size() < initialOpenLWWindows.size()) { // FormsContext.resetContext(); // return; // } // // // check for new windows // for (String name : newOpenWindows) { // if (!initialOpenLWWindows.contains(name)) { // // there is a new window open // Logger.info("Found new window '" + name + "', autosetting context to new window."); // new LWWindowOperator().setWindowAsContext(name); // return; // } // } // } // // } // } // // Path: src/main/java/org/robotframework/formslibrary/operator/ButtonOperator.java // public class ButtonOperator extends AbstractComponentOperator { // // /** // * Initialize a ButtonOperator with the specified button component. // */ // public ButtonOperator(Component component) { // super(component); // } // // /** // * Initialize a ButtonOperator with a button with the specified name in the // * current context. // * // * @param identifier // * button label or ToolTip text. // */ // public ButtonOperator(String identifier) { // super(new ByNameChooser(identifier, ComponentType.ALL_BUTTON_TYPES)); // } // // /** // * Simulate a push on the button. // */ // public void push() { // if (!getSource().isEnabled()) { // throw new FormsLibraryException("Button is not enabled."); // } // doPush(); // Logger.debug("Button was pushed."); // } // // private void doPush() { // if (getSource() instanceof AbstractButton) { // ((AbstractButton) getSource()).doClick(); // } else { // ObjectUtil.invokeMethod(getSource(), "simulatePush()"); // } // // } // // public void pushAsync() { // if (!getSource().isEnabled()) { // throw new FormsLibraryException("Button is not enabled."); // } // new Thread(() -> doPush()).start(); // Logger.debug("Button was pushed."); // // } // // } // // Path: src/main/java/org/robotframework/formslibrary/util/Logger.java // public class Logger { // // public static void debug(String message) { // if (DebugUtil.isDebugEnabled()) { // System.out.println("~ " + message); // } // } // // public static void info(String message) { // System.out.println(message); // } // // public static void error(Throwable t) { // t.printStackTrace(); // } // }
import org.robotframework.formslibrary.FormsLibraryException; import org.robotframework.formslibrary.context.ContextChangeMonitor; import org.robotframework.formslibrary.operator.ButtonOperator; import org.robotframework.formslibrary.util.Logger; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywordOverload; import org.robotframework.javalib.annotation.RobotKeywords;
package org.robotframework.formslibrary.keyword; @RobotKeywords public class ButtonKeywords { @RobotKeyword("Uses current context to search for a button by its label and when found, pushes it.\n\n " + " If the button opens a new window and detectWindowChange=true, the context will be set to the new window automatically. " + "Similarly if the button closes a window, the context will be reset to the root context. DetectWindowChange defaults to true. Example:\n | Click Button | _OK_ |\n") @ArgumentNames({ "identifier", "detectWindowChange=" }) public void clickButton(String identifier, boolean detectWindowChange) { if (detectWindowChange) {
// Path: src/main/java/org/robotframework/formslibrary/FormsLibraryException.java // public class FormsLibraryException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public static final boolean ROBOT_SUPPRESS_NAME = true; // // public FormsLibraryException(String message) { // super(message); // } // // public FormsLibraryException(Throwable t) { // super(t); // } // // public FormsLibraryException(String message, Throwable t) { // super(message, t); // } // } // // Path: src/main/java/org/robotframework/formslibrary/context/ContextChangeMonitor.java // public class ContextChangeMonitor { // // private List<String> initialOpenLWWindows; // // /** // * Start monitoring for window changes. // */ // public void start() { // if (FormsContext.isFormsServicesApp()) { // initialOpenLWWindows = new LWWindowOperator().getWindowTitles(); // } else { // // } // } // // /** // * Stop monitoring for window changes and change the context if needed. When // * a new window is detected, it will be automatically set as the new // * context. When the current context window was closed, the context will be // * reset to the root context. // */ // public void stop() { // if (FormsContext.isFormsServicesApp()) { // List<String> newOpenWindows = new LWWindowOperator().getWindowTitles(); // // // check if a window was closed // if (newOpenWindows.size() < initialOpenLWWindows.size()) { // FormsContext.resetContext(); // return; // } // // // check for new windows // for (String name : newOpenWindows) { // if (!initialOpenLWWindows.contains(name)) { // // there is a new window open // Logger.info("Found new window '" + name + "', autosetting context to new window."); // new LWWindowOperator().setWindowAsContext(name); // return; // } // } // } // // } // } // // Path: src/main/java/org/robotframework/formslibrary/operator/ButtonOperator.java // public class ButtonOperator extends AbstractComponentOperator { // // /** // * Initialize a ButtonOperator with the specified button component. // */ // public ButtonOperator(Component component) { // super(component); // } // // /** // * Initialize a ButtonOperator with a button with the specified name in the // * current context. // * // * @param identifier // * button label or ToolTip text. // */ // public ButtonOperator(String identifier) { // super(new ByNameChooser(identifier, ComponentType.ALL_BUTTON_TYPES)); // } // // /** // * Simulate a push on the button. // */ // public void push() { // if (!getSource().isEnabled()) { // throw new FormsLibraryException("Button is not enabled."); // } // doPush(); // Logger.debug("Button was pushed."); // } // // private void doPush() { // if (getSource() instanceof AbstractButton) { // ((AbstractButton) getSource()).doClick(); // } else { // ObjectUtil.invokeMethod(getSource(), "simulatePush()"); // } // // } // // public void pushAsync() { // if (!getSource().isEnabled()) { // throw new FormsLibraryException("Button is not enabled."); // } // new Thread(() -> doPush()).start(); // Logger.debug("Button was pushed."); // // } // // } // // Path: src/main/java/org/robotframework/formslibrary/util/Logger.java // public class Logger { // // public static void debug(String message) { // if (DebugUtil.isDebugEnabled()) { // System.out.println("~ " + message); // } // } // // public static void info(String message) { // System.out.println(message); // } // // public static void error(Throwable t) { // t.printStackTrace(); // } // } // Path: src/main/java/org/robotframework/formslibrary/keyword/ButtonKeywords.java import org.robotframework.formslibrary.FormsLibraryException; import org.robotframework.formslibrary.context.ContextChangeMonitor; import org.robotframework.formslibrary.operator.ButtonOperator; import org.robotframework.formslibrary.util.Logger; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywordOverload; import org.robotframework.javalib.annotation.RobotKeywords; package org.robotframework.formslibrary.keyword; @RobotKeywords public class ButtonKeywords { @RobotKeyword("Uses current context to search for a button by its label and when found, pushes it.\n\n " + " If the button opens a new window and detectWindowChange=true, the context will be set to the new window automatically. " + "Similarly if the button closes a window, the context will be reset to the root context. DetectWindowChange defaults to true. Example:\n | Click Button | _OK_ |\n") @ArgumentNames({ "identifier", "detectWindowChange=" }) public void clickButton(String identifier, boolean detectWindowChange) { if (detectWindowChange) {
ContextChangeMonitor monitor = new ContextChangeMonitor();
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/keyword/ButtonKeywords.java
// Path: src/main/java/org/robotframework/formslibrary/FormsLibraryException.java // public class FormsLibraryException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public static final boolean ROBOT_SUPPRESS_NAME = true; // // public FormsLibraryException(String message) { // super(message); // } // // public FormsLibraryException(Throwable t) { // super(t); // } // // public FormsLibraryException(String message, Throwable t) { // super(message, t); // } // } // // Path: src/main/java/org/robotframework/formslibrary/context/ContextChangeMonitor.java // public class ContextChangeMonitor { // // private List<String> initialOpenLWWindows; // // /** // * Start monitoring for window changes. // */ // public void start() { // if (FormsContext.isFormsServicesApp()) { // initialOpenLWWindows = new LWWindowOperator().getWindowTitles(); // } else { // // } // } // // /** // * Stop monitoring for window changes and change the context if needed. When // * a new window is detected, it will be automatically set as the new // * context. When the current context window was closed, the context will be // * reset to the root context. // */ // public void stop() { // if (FormsContext.isFormsServicesApp()) { // List<String> newOpenWindows = new LWWindowOperator().getWindowTitles(); // // // check if a window was closed // if (newOpenWindows.size() < initialOpenLWWindows.size()) { // FormsContext.resetContext(); // return; // } // // // check for new windows // for (String name : newOpenWindows) { // if (!initialOpenLWWindows.contains(name)) { // // there is a new window open // Logger.info("Found new window '" + name + "', autosetting context to new window."); // new LWWindowOperator().setWindowAsContext(name); // return; // } // } // } // // } // } // // Path: src/main/java/org/robotframework/formslibrary/operator/ButtonOperator.java // public class ButtonOperator extends AbstractComponentOperator { // // /** // * Initialize a ButtonOperator with the specified button component. // */ // public ButtonOperator(Component component) { // super(component); // } // // /** // * Initialize a ButtonOperator with a button with the specified name in the // * current context. // * // * @param identifier // * button label or ToolTip text. // */ // public ButtonOperator(String identifier) { // super(new ByNameChooser(identifier, ComponentType.ALL_BUTTON_TYPES)); // } // // /** // * Simulate a push on the button. // */ // public void push() { // if (!getSource().isEnabled()) { // throw new FormsLibraryException("Button is not enabled."); // } // doPush(); // Logger.debug("Button was pushed."); // } // // private void doPush() { // if (getSource() instanceof AbstractButton) { // ((AbstractButton) getSource()).doClick(); // } else { // ObjectUtil.invokeMethod(getSource(), "simulatePush()"); // } // // } // // public void pushAsync() { // if (!getSource().isEnabled()) { // throw new FormsLibraryException("Button is not enabled."); // } // new Thread(() -> doPush()).start(); // Logger.debug("Button was pushed."); // // } // // } // // Path: src/main/java/org/robotframework/formslibrary/util/Logger.java // public class Logger { // // public static void debug(String message) { // if (DebugUtil.isDebugEnabled()) { // System.out.println("~ " + message); // } // } // // public static void info(String message) { // System.out.println(message); // } // // public static void error(Throwable t) { // t.printStackTrace(); // } // }
import org.robotframework.formslibrary.FormsLibraryException; import org.robotframework.formslibrary.context.ContextChangeMonitor; import org.robotframework.formslibrary.operator.ButtonOperator; import org.robotframework.formslibrary.util.Logger; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywordOverload; import org.robotframework.javalib.annotation.RobotKeywords;
package org.robotframework.formslibrary.keyword; @RobotKeywords public class ButtonKeywords { @RobotKeyword("Uses current context to search for a button by its label and when found, pushes it.\n\n " + " If the button opens a new window and detectWindowChange=true, the context will be set to the new window automatically. " + "Similarly if the button closes a window, the context will be reset to the root context. DetectWindowChange defaults to true. Example:\n | Click Button | _OK_ |\n") @ArgumentNames({ "identifier", "detectWindowChange=" }) public void clickButton(String identifier, boolean detectWindowChange) { if (detectWindowChange) { ContextChangeMonitor monitor = new ContextChangeMonitor(); monitor.start();
// Path: src/main/java/org/robotframework/formslibrary/FormsLibraryException.java // public class FormsLibraryException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public static final boolean ROBOT_SUPPRESS_NAME = true; // // public FormsLibraryException(String message) { // super(message); // } // // public FormsLibraryException(Throwable t) { // super(t); // } // // public FormsLibraryException(String message, Throwable t) { // super(message, t); // } // } // // Path: src/main/java/org/robotframework/formslibrary/context/ContextChangeMonitor.java // public class ContextChangeMonitor { // // private List<String> initialOpenLWWindows; // // /** // * Start monitoring for window changes. // */ // public void start() { // if (FormsContext.isFormsServicesApp()) { // initialOpenLWWindows = new LWWindowOperator().getWindowTitles(); // } else { // // } // } // // /** // * Stop monitoring for window changes and change the context if needed. When // * a new window is detected, it will be automatically set as the new // * context. When the current context window was closed, the context will be // * reset to the root context. // */ // public void stop() { // if (FormsContext.isFormsServicesApp()) { // List<String> newOpenWindows = new LWWindowOperator().getWindowTitles(); // // // check if a window was closed // if (newOpenWindows.size() < initialOpenLWWindows.size()) { // FormsContext.resetContext(); // return; // } // // // check for new windows // for (String name : newOpenWindows) { // if (!initialOpenLWWindows.contains(name)) { // // there is a new window open // Logger.info("Found new window '" + name + "', autosetting context to new window."); // new LWWindowOperator().setWindowAsContext(name); // return; // } // } // } // // } // } // // Path: src/main/java/org/robotframework/formslibrary/operator/ButtonOperator.java // public class ButtonOperator extends AbstractComponentOperator { // // /** // * Initialize a ButtonOperator with the specified button component. // */ // public ButtonOperator(Component component) { // super(component); // } // // /** // * Initialize a ButtonOperator with a button with the specified name in the // * current context. // * // * @param identifier // * button label or ToolTip text. // */ // public ButtonOperator(String identifier) { // super(new ByNameChooser(identifier, ComponentType.ALL_BUTTON_TYPES)); // } // // /** // * Simulate a push on the button. // */ // public void push() { // if (!getSource().isEnabled()) { // throw new FormsLibraryException("Button is not enabled."); // } // doPush(); // Logger.debug("Button was pushed."); // } // // private void doPush() { // if (getSource() instanceof AbstractButton) { // ((AbstractButton) getSource()).doClick(); // } else { // ObjectUtil.invokeMethod(getSource(), "simulatePush()"); // } // // } // // public void pushAsync() { // if (!getSource().isEnabled()) { // throw new FormsLibraryException("Button is not enabled."); // } // new Thread(() -> doPush()).start(); // Logger.debug("Button was pushed."); // // } // // } // // Path: src/main/java/org/robotframework/formslibrary/util/Logger.java // public class Logger { // // public static void debug(String message) { // if (DebugUtil.isDebugEnabled()) { // System.out.println("~ " + message); // } // } // // public static void info(String message) { // System.out.println(message); // } // // public static void error(Throwable t) { // t.printStackTrace(); // } // } // Path: src/main/java/org/robotframework/formslibrary/keyword/ButtonKeywords.java import org.robotframework.formslibrary.FormsLibraryException; import org.robotframework.formslibrary.context.ContextChangeMonitor; import org.robotframework.formslibrary.operator.ButtonOperator; import org.robotframework.formslibrary.util.Logger; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywordOverload; import org.robotframework.javalib.annotation.RobotKeywords; package org.robotframework.formslibrary.keyword; @RobotKeywords public class ButtonKeywords { @RobotKeyword("Uses current context to search for a button by its label and when found, pushes it.\n\n " + " If the button opens a new window and detectWindowChange=true, the context will be set to the new window automatically. " + "Similarly if the button closes a window, the context will be reset to the root context. DetectWindowChange defaults to true. Example:\n | Click Button | _OK_ |\n") @ArgumentNames({ "identifier", "detectWindowChange=" }) public void clickButton(String identifier, boolean detectWindowChange) { if (detectWindowChange) { ContextChangeMonitor monitor = new ContextChangeMonitor(); monitor.start();
new ButtonOperator(identifier).push();
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/keyword/ButtonKeywords.java
// Path: src/main/java/org/robotframework/formslibrary/FormsLibraryException.java // public class FormsLibraryException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public static final boolean ROBOT_SUPPRESS_NAME = true; // // public FormsLibraryException(String message) { // super(message); // } // // public FormsLibraryException(Throwable t) { // super(t); // } // // public FormsLibraryException(String message, Throwable t) { // super(message, t); // } // } // // Path: src/main/java/org/robotframework/formslibrary/context/ContextChangeMonitor.java // public class ContextChangeMonitor { // // private List<String> initialOpenLWWindows; // // /** // * Start monitoring for window changes. // */ // public void start() { // if (FormsContext.isFormsServicesApp()) { // initialOpenLWWindows = new LWWindowOperator().getWindowTitles(); // } else { // // } // } // // /** // * Stop monitoring for window changes and change the context if needed. When // * a new window is detected, it will be automatically set as the new // * context. When the current context window was closed, the context will be // * reset to the root context. // */ // public void stop() { // if (FormsContext.isFormsServicesApp()) { // List<String> newOpenWindows = new LWWindowOperator().getWindowTitles(); // // // check if a window was closed // if (newOpenWindows.size() < initialOpenLWWindows.size()) { // FormsContext.resetContext(); // return; // } // // // check for new windows // for (String name : newOpenWindows) { // if (!initialOpenLWWindows.contains(name)) { // // there is a new window open // Logger.info("Found new window '" + name + "', autosetting context to new window."); // new LWWindowOperator().setWindowAsContext(name); // return; // } // } // } // // } // } // // Path: src/main/java/org/robotframework/formslibrary/operator/ButtonOperator.java // public class ButtonOperator extends AbstractComponentOperator { // // /** // * Initialize a ButtonOperator with the specified button component. // */ // public ButtonOperator(Component component) { // super(component); // } // // /** // * Initialize a ButtonOperator with a button with the specified name in the // * current context. // * // * @param identifier // * button label or ToolTip text. // */ // public ButtonOperator(String identifier) { // super(new ByNameChooser(identifier, ComponentType.ALL_BUTTON_TYPES)); // } // // /** // * Simulate a push on the button. // */ // public void push() { // if (!getSource().isEnabled()) { // throw new FormsLibraryException("Button is not enabled."); // } // doPush(); // Logger.debug("Button was pushed."); // } // // private void doPush() { // if (getSource() instanceof AbstractButton) { // ((AbstractButton) getSource()).doClick(); // } else { // ObjectUtil.invokeMethod(getSource(), "simulatePush()"); // } // // } // // public void pushAsync() { // if (!getSource().isEnabled()) { // throw new FormsLibraryException("Button is not enabled."); // } // new Thread(() -> doPush()).start(); // Logger.debug("Button was pushed."); // // } // // } // // Path: src/main/java/org/robotframework/formslibrary/util/Logger.java // public class Logger { // // public static void debug(String message) { // if (DebugUtil.isDebugEnabled()) { // System.out.println("~ " + message); // } // } // // public static void info(String message) { // System.out.println(message); // } // // public static void error(Throwable t) { // t.printStackTrace(); // } // }
import org.robotframework.formslibrary.FormsLibraryException; import org.robotframework.formslibrary.context.ContextChangeMonitor; import org.robotframework.formslibrary.operator.ButtonOperator; import org.robotframework.formslibrary.util.Logger; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywordOverload; import org.robotframework.javalib.annotation.RobotKeywords;
if (detectWindowChange) { ContextChangeMonitor monitor = new ContextChangeMonitor(); monitor.start(); new ButtonOperator(identifier).push(); monitor.stop(); } else { new ButtonOperator(identifier).push(); } } @RobotKeywordOverload public void clickButton(String identifier) { clickButton(identifier, true); } @RobotKeyword("Asynchronously Pushes button") @ArgumentNames({ "identifier" }) public void clickButtonAsync(String identifier) { ContextChangeMonitor monitor = new ContextChangeMonitor(); monitor.start(); new ButtonOperator(identifier).pushAsync(); monitor.stop(); } @RobotKeyword("Verify if a button is disabled. If fail argument is set to false this test will not fail Example:\n | Verify Button Is Disabled | _OK_ |\n") @ArgumentNames({ "identifier", "fail=" }) public boolean verifyButtonIsDisabled(String identifier, boolean fail) { boolean enabled = new ButtonOperator(identifier).isEnabled(); if (fail && enabled) {
// Path: src/main/java/org/robotframework/formslibrary/FormsLibraryException.java // public class FormsLibraryException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public static final boolean ROBOT_SUPPRESS_NAME = true; // // public FormsLibraryException(String message) { // super(message); // } // // public FormsLibraryException(Throwable t) { // super(t); // } // // public FormsLibraryException(String message, Throwable t) { // super(message, t); // } // } // // Path: src/main/java/org/robotframework/formslibrary/context/ContextChangeMonitor.java // public class ContextChangeMonitor { // // private List<String> initialOpenLWWindows; // // /** // * Start monitoring for window changes. // */ // public void start() { // if (FormsContext.isFormsServicesApp()) { // initialOpenLWWindows = new LWWindowOperator().getWindowTitles(); // } else { // // } // } // // /** // * Stop monitoring for window changes and change the context if needed. When // * a new window is detected, it will be automatically set as the new // * context. When the current context window was closed, the context will be // * reset to the root context. // */ // public void stop() { // if (FormsContext.isFormsServicesApp()) { // List<String> newOpenWindows = new LWWindowOperator().getWindowTitles(); // // // check if a window was closed // if (newOpenWindows.size() < initialOpenLWWindows.size()) { // FormsContext.resetContext(); // return; // } // // // check for new windows // for (String name : newOpenWindows) { // if (!initialOpenLWWindows.contains(name)) { // // there is a new window open // Logger.info("Found new window '" + name + "', autosetting context to new window."); // new LWWindowOperator().setWindowAsContext(name); // return; // } // } // } // // } // } // // Path: src/main/java/org/robotframework/formslibrary/operator/ButtonOperator.java // public class ButtonOperator extends AbstractComponentOperator { // // /** // * Initialize a ButtonOperator with the specified button component. // */ // public ButtonOperator(Component component) { // super(component); // } // // /** // * Initialize a ButtonOperator with a button with the specified name in the // * current context. // * // * @param identifier // * button label or ToolTip text. // */ // public ButtonOperator(String identifier) { // super(new ByNameChooser(identifier, ComponentType.ALL_BUTTON_TYPES)); // } // // /** // * Simulate a push on the button. // */ // public void push() { // if (!getSource().isEnabled()) { // throw new FormsLibraryException("Button is not enabled."); // } // doPush(); // Logger.debug("Button was pushed."); // } // // private void doPush() { // if (getSource() instanceof AbstractButton) { // ((AbstractButton) getSource()).doClick(); // } else { // ObjectUtil.invokeMethod(getSource(), "simulatePush()"); // } // // } // // public void pushAsync() { // if (!getSource().isEnabled()) { // throw new FormsLibraryException("Button is not enabled."); // } // new Thread(() -> doPush()).start(); // Logger.debug("Button was pushed."); // // } // // } // // Path: src/main/java/org/robotframework/formslibrary/util/Logger.java // public class Logger { // // public static void debug(String message) { // if (DebugUtil.isDebugEnabled()) { // System.out.println("~ " + message); // } // } // // public static void info(String message) { // System.out.println(message); // } // // public static void error(Throwable t) { // t.printStackTrace(); // } // } // Path: src/main/java/org/robotframework/formslibrary/keyword/ButtonKeywords.java import org.robotframework.formslibrary.FormsLibraryException; import org.robotframework.formslibrary.context.ContextChangeMonitor; import org.robotframework.formslibrary.operator.ButtonOperator; import org.robotframework.formslibrary.util.Logger; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywordOverload; import org.robotframework.javalib.annotation.RobotKeywords; if (detectWindowChange) { ContextChangeMonitor monitor = new ContextChangeMonitor(); monitor.start(); new ButtonOperator(identifier).push(); monitor.stop(); } else { new ButtonOperator(identifier).push(); } } @RobotKeywordOverload public void clickButton(String identifier) { clickButton(identifier, true); } @RobotKeyword("Asynchronously Pushes button") @ArgumentNames({ "identifier" }) public void clickButtonAsync(String identifier) { ContextChangeMonitor monitor = new ContextChangeMonitor(); monitor.start(); new ButtonOperator(identifier).pushAsync(); monitor.stop(); } @RobotKeyword("Verify if a button is disabled. If fail argument is set to false this test will not fail Example:\n | Verify Button Is Disabled | _OK_ |\n") @ArgumentNames({ "identifier", "fail=" }) public boolean verifyButtonIsDisabled(String identifier, boolean fail) { boolean enabled = new ButtonOperator(identifier).isEnabled(); if (fail && enabled) {
throw new FormsLibraryException("Button is enabled.");
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/keyword/ButtonKeywords.java
// Path: src/main/java/org/robotframework/formslibrary/FormsLibraryException.java // public class FormsLibraryException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public static final boolean ROBOT_SUPPRESS_NAME = true; // // public FormsLibraryException(String message) { // super(message); // } // // public FormsLibraryException(Throwable t) { // super(t); // } // // public FormsLibraryException(String message, Throwable t) { // super(message, t); // } // } // // Path: src/main/java/org/robotframework/formslibrary/context/ContextChangeMonitor.java // public class ContextChangeMonitor { // // private List<String> initialOpenLWWindows; // // /** // * Start monitoring for window changes. // */ // public void start() { // if (FormsContext.isFormsServicesApp()) { // initialOpenLWWindows = new LWWindowOperator().getWindowTitles(); // } else { // // } // } // // /** // * Stop monitoring for window changes and change the context if needed. When // * a new window is detected, it will be automatically set as the new // * context. When the current context window was closed, the context will be // * reset to the root context. // */ // public void stop() { // if (FormsContext.isFormsServicesApp()) { // List<String> newOpenWindows = new LWWindowOperator().getWindowTitles(); // // // check if a window was closed // if (newOpenWindows.size() < initialOpenLWWindows.size()) { // FormsContext.resetContext(); // return; // } // // // check for new windows // for (String name : newOpenWindows) { // if (!initialOpenLWWindows.contains(name)) { // // there is a new window open // Logger.info("Found new window '" + name + "', autosetting context to new window."); // new LWWindowOperator().setWindowAsContext(name); // return; // } // } // } // // } // } // // Path: src/main/java/org/robotframework/formslibrary/operator/ButtonOperator.java // public class ButtonOperator extends AbstractComponentOperator { // // /** // * Initialize a ButtonOperator with the specified button component. // */ // public ButtonOperator(Component component) { // super(component); // } // // /** // * Initialize a ButtonOperator with a button with the specified name in the // * current context. // * // * @param identifier // * button label or ToolTip text. // */ // public ButtonOperator(String identifier) { // super(new ByNameChooser(identifier, ComponentType.ALL_BUTTON_TYPES)); // } // // /** // * Simulate a push on the button. // */ // public void push() { // if (!getSource().isEnabled()) { // throw new FormsLibraryException("Button is not enabled."); // } // doPush(); // Logger.debug("Button was pushed."); // } // // private void doPush() { // if (getSource() instanceof AbstractButton) { // ((AbstractButton) getSource()).doClick(); // } else { // ObjectUtil.invokeMethod(getSource(), "simulatePush()"); // } // // } // // public void pushAsync() { // if (!getSource().isEnabled()) { // throw new FormsLibraryException("Button is not enabled."); // } // new Thread(() -> doPush()).start(); // Logger.debug("Button was pushed."); // // } // // } // // Path: src/main/java/org/robotframework/formslibrary/util/Logger.java // public class Logger { // // public static void debug(String message) { // if (DebugUtil.isDebugEnabled()) { // System.out.println("~ " + message); // } // } // // public static void info(String message) { // System.out.println(message); // } // // public static void error(Throwable t) { // t.printStackTrace(); // } // }
import org.robotframework.formslibrary.FormsLibraryException; import org.robotframework.formslibrary.context.ContextChangeMonitor; import org.robotframework.formslibrary.operator.ButtonOperator; import org.robotframework.formslibrary.util.Logger; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywordOverload; import org.robotframework.javalib.annotation.RobotKeywords;
ContextChangeMonitor monitor = new ContextChangeMonitor(); monitor.start(); new ButtonOperator(identifier).push(); monitor.stop(); } else { new ButtonOperator(identifier).push(); } } @RobotKeywordOverload public void clickButton(String identifier) { clickButton(identifier, true); } @RobotKeyword("Asynchronously Pushes button") @ArgumentNames({ "identifier" }) public void clickButtonAsync(String identifier) { ContextChangeMonitor monitor = new ContextChangeMonitor(); monitor.start(); new ButtonOperator(identifier).pushAsync(); monitor.stop(); } @RobotKeyword("Verify if a button is disabled. If fail argument is set to false this test will not fail Example:\n | Verify Button Is Disabled | _OK_ |\n") @ArgumentNames({ "identifier", "fail=" }) public boolean verifyButtonIsDisabled(String identifier, boolean fail) { boolean enabled = new ButtonOperator(identifier).isEnabled(); if (fail && enabled) { throw new FormsLibraryException("Button is enabled."); } else {
// Path: src/main/java/org/robotframework/formslibrary/FormsLibraryException.java // public class FormsLibraryException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public static final boolean ROBOT_SUPPRESS_NAME = true; // // public FormsLibraryException(String message) { // super(message); // } // // public FormsLibraryException(Throwable t) { // super(t); // } // // public FormsLibraryException(String message, Throwable t) { // super(message, t); // } // } // // Path: src/main/java/org/robotframework/formslibrary/context/ContextChangeMonitor.java // public class ContextChangeMonitor { // // private List<String> initialOpenLWWindows; // // /** // * Start monitoring for window changes. // */ // public void start() { // if (FormsContext.isFormsServicesApp()) { // initialOpenLWWindows = new LWWindowOperator().getWindowTitles(); // } else { // // } // } // // /** // * Stop monitoring for window changes and change the context if needed. When // * a new window is detected, it will be automatically set as the new // * context. When the current context window was closed, the context will be // * reset to the root context. // */ // public void stop() { // if (FormsContext.isFormsServicesApp()) { // List<String> newOpenWindows = new LWWindowOperator().getWindowTitles(); // // // check if a window was closed // if (newOpenWindows.size() < initialOpenLWWindows.size()) { // FormsContext.resetContext(); // return; // } // // // check for new windows // for (String name : newOpenWindows) { // if (!initialOpenLWWindows.contains(name)) { // // there is a new window open // Logger.info("Found new window '" + name + "', autosetting context to new window."); // new LWWindowOperator().setWindowAsContext(name); // return; // } // } // } // // } // } // // Path: src/main/java/org/robotframework/formslibrary/operator/ButtonOperator.java // public class ButtonOperator extends AbstractComponentOperator { // // /** // * Initialize a ButtonOperator with the specified button component. // */ // public ButtonOperator(Component component) { // super(component); // } // // /** // * Initialize a ButtonOperator with a button with the specified name in the // * current context. // * // * @param identifier // * button label or ToolTip text. // */ // public ButtonOperator(String identifier) { // super(new ByNameChooser(identifier, ComponentType.ALL_BUTTON_TYPES)); // } // // /** // * Simulate a push on the button. // */ // public void push() { // if (!getSource().isEnabled()) { // throw new FormsLibraryException("Button is not enabled."); // } // doPush(); // Logger.debug("Button was pushed."); // } // // private void doPush() { // if (getSource() instanceof AbstractButton) { // ((AbstractButton) getSource()).doClick(); // } else { // ObjectUtil.invokeMethod(getSource(), "simulatePush()"); // } // // } // // public void pushAsync() { // if (!getSource().isEnabled()) { // throw new FormsLibraryException("Button is not enabled."); // } // new Thread(() -> doPush()).start(); // Logger.debug("Button was pushed."); // // } // // } // // Path: src/main/java/org/robotframework/formslibrary/util/Logger.java // public class Logger { // // public static void debug(String message) { // if (DebugUtil.isDebugEnabled()) { // System.out.println("~ " + message); // } // } // // public static void info(String message) { // System.out.println(message); // } // // public static void error(Throwable t) { // t.printStackTrace(); // } // } // Path: src/main/java/org/robotframework/formslibrary/keyword/ButtonKeywords.java import org.robotframework.formslibrary.FormsLibraryException; import org.robotframework.formslibrary.context.ContextChangeMonitor; import org.robotframework.formslibrary.operator.ButtonOperator; import org.robotframework.formslibrary.util.Logger; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywordOverload; import org.robotframework.javalib.annotation.RobotKeywords; ContextChangeMonitor monitor = new ContextChangeMonitor(); monitor.start(); new ButtonOperator(identifier).push(); monitor.stop(); } else { new ButtonOperator(identifier).push(); } } @RobotKeywordOverload public void clickButton(String identifier) { clickButton(identifier, true); } @RobotKeyword("Asynchronously Pushes button") @ArgumentNames({ "identifier" }) public void clickButtonAsync(String identifier) { ContextChangeMonitor monitor = new ContextChangeMonitor(); monitor.start(); new ButtonOperator(identifier).pushAsync(); monitor.stop(); } @RobotKeyword("Verify if a button is disabled. If fail argument is set to false this test will not fail Example:\n | Verify Button Is Disabled | _OK_ |\n") @ArgumentNames({ "identifier", "fail=" }) public boolean verifyButtonIsDisabled(String identifier, boolean fail) { boolean enabled = new ButtonOperator(identifier).isEnabled(); if (fail && enabled) { throw new FormsLibraryException("Button is enabled."); } else {
Logger.info("Button is " + (enabled ? "enabled" : "disabled"));
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/keyword/RadioKeywords.java
// Path: src/main/java/org/robotframework/formslibrary/operator/RadioOperator.java // public class RadioOperator extends AbstractComponentOperator { // // /** // * Initialize a RadioOperator for the radio button option matching the given // * name. // */ // public RadioOperator(String identifier) { // super(new ByNameChooser(identifier, ComponentType.EXTENDED_CHECKBOX)); // } // // /** // * Select the radio option. // */ // public void select() { // ObjectUtil.invokeMethod(getSource(), "simulatePush()"); // } // // /** // * Check if this radio option is selected. // */ // public boolean isSelected() { // return ObjectUtil.getBoolean(getSource(), "getState()"); // } // }
import org.robotframework.formslibrary.operator.RadioOperator; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords;
package org.robotframework.formslibrary.keyword; @RobotKeywords public class RadioKeywords { @RobotKeyword("Select Radio Button.\n\nExample:\n| Select Radio Button | _radio option_\n") @ArgumentNames({ "identifier" }) public void selectFormsRadioButton(String identifier) {
// Path: src/main/java/org/robotframework/formslibrary/operator/RadioOperator.java // public class RadioOperator extends AbstractComponentOperator { // // /** // * Initialize a RadioOperator for the radio button option matching the given // * name. // */ // public RadioOperator(String identifier) { // super(new ByNameChooser(identifier, ComponentType.EXTENDED_CHECKBOX)); // } // // /** // * Select the radio option. // */ // public void select() { // ObjectUtil.invokeMethod(getSource(), "simulatePush()"); // } // // /** // * Check if this radio option is selected. // */ // public boolean isSelected() { // return ObjectUtil.getBoolean(getSource(), "getState()"); // } // } // Path: src/main/java/org/robotframework/formslibrary/keyword/RadioKeywords.java import org.robotframework.formslibrary.operator.RadioOperator; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords; package org.robotframework.formslibrary.keyword; @RobotKeywords public class RadioKeywords { @RobotKeyword("Select Radio Button.\n\nExample:\n| Select Radio Button | _radio option_\n") @ArgumentNames({ "identifier" }) public void selectFormsRadioButton(String identifier) {
new RadioOperator(identifier).select();
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/remoteswinglibrary/agent/ServerThread.java
// Path: src/main/java/org/robotframework/formslibrary/FormsLibrary.java // public class FormsLibrary extends SwingLibrary { // // // TODO stop extending SwingLibrary, only include classes that are really // // needed? // // public FormsLibrary() { // super("org/robotframework/formslibrary/keyword/*.class"); // } // // }
import java.io.IOException; import java.util.Map; import org.robotframework.formslibrary.FormsLibrary; import org.robotframework.remoteserver.RemoteServer; import org.robotframework.remoteswinglibrary.remote.DaemonRemoteServer;
/* * Copyright 2014 Nokia Solutions and Networks Oyj * * 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.robotframework.remoteswinglibrary.agent; public class ServerThread implements Runnable { int apport; boolean debug; RobotConnection robotConnection; public ServerThread(RobotConnection robotConnection, int apport, boolean debug) { this.robotConnection = robotConnection; this.apport = apport; this.debug = debug; } public void run() { try { RemoteServer server = new DaemonRemoteServer();
// Path: src/main/java/org/robotframework/formslibrary/FormsLibrary.java // public class FormsLibrary extends SwingLibrary { // // // TODO stop extending SwingLibrary, only include classes that are really // // needed? // // public FormsLibrary() { // super("org/robotframework/formslibrary/keyword/*.class"); // } // // } // Path: src/main/java/org/robotframework/remoteswinglibrary/agent/ServerThread.java import java.io.IOException; import java.util.Map; import org.robotframework.formslibrary.FormsLibrary; import org.robotframework.remoteserver.RemoteServer; import org.robotframework.remoteswinglibrary.remote.DaemonRemoteServer; /* * Copyright 2014 Nokia Solutions and Networks Oyj * * 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.robotframework.remoteswinglibrary.agent; public class ServerThread implements Runnable { int apport; boolean debug; RobotConnection robotConnection; public ServerThread(RobotConnection robotConnection, int apport, boolean debug) { this.robotConnection = robotConnection; this.apport = apport; this.debug = debug; } public void run() { try { RemoteServer server = new DaemonRemoteServer();
server.putLibrary("/RPC2", new FormsLibrary());
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/keyword/ScrollBarKeywords.java
// Path: src/main/java/org/robotframework/formslibrary/operator/HorizontalScrollBarOperator.java // public class HorizontalScrollBarOperator extends AbstractComponentOperator { // // /** // * Initialize a HorizontalScrollBarOperator with the n'th horizontal scroll // * bar in the current context. // * // * @param index // * 0 (first), 1 (second), ... // */ // public HorizontalScrollBarOperator(int index) { // super(new CompositeChooser(new ByOrientationChooser(ByOrientationChooser.Orientation.HORIZONTAL), // new ByComponentTypeChooser(index, ComponentType.ALL_SCROLL_BAR_TYPES))); // } // // /** // * Scroll left by pressing the left arrow button in the scroll bar. // * // * @param count // * number of times to press the button. // */ // public void scrollLeft(int count) { // Component[] buttons = ((Container) getSource()).getComponents(); // Component leftButton = null; // if (buttons[1].getX() < buttons[0].getX()) { // leftButton = buttons[1]; // } else { // leftButton = buttons[0]; // } // for (int i = 0; i < count; i++) { // ObjectUtil.invokeMethod(leftButton, "simulatePush"); // } // } // // /** // * Scroll right by pressing the right arrow button in the scroll bar. // * // * @param count // * number of times to press the button. // */ // public void scrollRight(int count) { // Component[] buttons = ((Container) getSource()).getComponents(); // Component rightButton = null; // if (buttons[1].getX() > buttons[0].getX()) { // rightButton = buttons[1]; // } else { // rightButton = buttons[0]; // } // for (int i = 0; i < count; i++) { // ObjectUtil.invokeMethod(rightButton, "simulatePush"); // } // } // } // // Path: src/main/java/org/robotframework/formslibrary/operator/VerticalScrollBarOperator.java // public class VerticalScrollBarOperator extends AbstractComponentOperator { // // /** // * Initialize a VerticalScrollBarOperator with the n'th vertical scroll bar // * in the current context. // * // * @param index // * 0 (first), 1 (second), ... // */ // public VerticalScrollBarOperator(int index) { // super(new CompositeChooser(new ByOrientationChooser(ByOrientationChooser.Orientation.VERTICAL), // new ByComponentTypeChooser(index, ComponentType.ALL_SCROLL_BAR_TYPES))); // } // // /** // * Scroll up by pressing the up arrow button in the scroll bar. // * // * @param count // * number of times to press the button. // */ // public void scrollUp(int count) { // Component[] buttons = ((Container) getSource()).getComponents(); // Component upButton = null; // if (buttons[1].getY() < buttons[0].getY()) { // upButton = buttons[1]; // } else { // upButton = buttons[0]; // } // for (int i = 0; i < count; i++) { // ObjectUtil.invokeMethod(upButton, "simulatePush"); // } // } // // /** // * Scroll down by pressing the down arrow button in the scroll bar. // * // * @param count // * number of times to press the button. // */ // public void scrollDown(int count) { // Component[] buttons = ((Container) getSource()).getComponents(); // Component downButton = null; // if (buttons[1].getY() > buttons[0].getY()) { // downButton = buttons[1]; // } else { // downButton = buttons[0]; // } // for (int i = 0; i < count; i++) { // ObjectUtil.invokeMethod(downButton, "simulatePush"); // } // } // }
import org.robotframework.formslibrary.operator.HorizontalScrollBarOperator; import org.robotframework.formslibrary.operator.VerticalScrollBarOperator; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywordOverload; import org.robotframework.javalib.annotation.RobotKeywords;
package org.robotframework.formslibrary.keyword; @RobotKeywords public class ScrollBarKeywords { @RobotKeyword("Scroll down in the current window by clicking the down arrow button on a vertical scrollbar.\\n\\n Specify how many times the button should be clicked in the count parameter. One click scrolls approximately one table row. If multiple vertical scrollbars exist in the window, you can optionnally specify the scroll bar index to indicate which scrollbar should be used. Use index 1 for the first scrollbar, 2 for the second, and so on. Example:\\n | Scroll Down | _count_ ||\\\\n | Scroll Down | _count_ | _index_ |\\n") @ArgumentNames({ "count", "index=" }) public void scrollDown(int count, int index) {
// Path: src/main/java/org/robotframework/formslibrary/operator/HorizontalScrollBarOperator.java // public class HorizontalScrollBarOperator extends AbstractComponentOperator { // // /** // * Initialize a HorizontalScrollBarOperator with the n'th horizontal scroll // * bar in the current context. // * // * @param index // * 0 (first), 1 (second), ... // */ // public HorizontalScrollBarOperator(int index) { // super(new CompositeChooser(new ByOrientationChooser(ByOrientationChooser.Orientation.HORIZONTAL), // new ByComponentTypeChooser(index, ComponentType.ALL_SCROLL_BAR_TYPES))); // } // // /** // * Scroll left by pressing the left arrow button in the scroll bar. // * // * @param count // * number of times to press the button. // */ // public void scrollLeft(int count) { // Component[] buttons = ((Container) getSource()).getComponents(); // Component leftButton = null; // if (buttons[1].getX() < buttons[0].getX()) { // leftButton = buttons[1]; // } else { // leftButton = buttons[0]; // } // for (int i = 0; i < count; i++) { // ObjectUtil.invokeMethod(leftButton, "simulatePush"); // } // } // // /** // * Scroll right by pressing the right arrow button in the scroll bar. // * // * @param count // * number of times to press the button. // */ // public void scrollRight(int count) { // Component[] buttons = ((Container) getSource()).getComponents(); // Component rightButton = null; // if (buttons[1].getX() > buttons[0].getX()) { // rightButton = buttons[1]; // } else { // rightButton = buttons[0]; // } // for (int i = 0; i < count; i++) { // ObjectUtil.invokeMethod(rightButton, "simulatePush"); // } // } // } // // Path: src/main/java/org/robotframework/formslibrary/operator/VerticalScrollBarOperator.java // public class VerticalScrollBarOperator extends AbstractComponentOperator { // // /** // * Initialize a VerticalScrollBarOperator with the n'th vertical scroll bar // * in the current context. // * // * @param index // * 0 (first), 1 (second), ... // */ // public VerticalScrollBarOperator(int index) { // super(new CompositeChooser(new ByOrientationChooser(ByOrientationChooser.Orientation.VERTICAL), // new ByComponentTypeChooser(index, ComponentType.ALL_SCROLL_BAR_TYPES))); // } // // /** // * Scroll up by pressing the up arrow button in the scroll bar. // * // * @param count // * number of times to press the button. // */ // public void scrollUp(int count) { // Component[] buttons = ((Container) getSource()).getComponents(); // Component upButton = null; // if (buttons[1].getY() < buttons[0].getY()) { // upButton = buttons[1]; // } else { // upButton = buttons[0]; // } // for (int i = 0; i < count; i++) { // ObjectUtil.invokeMethod(upButton, "simulatePush"); // } // } // // /** // * Scroll down by pressing the down arrow button in the scroll bar. // * // * @param count // * number of times to press the button. // */ // public void scrollDown(int count) { // Component[] buttons = ((Container) getSource()).getComponents(); // Component downButton = null; // if (buttons[1].getY() > buttons[0].getY()) { // downButton = buttons[1]; // } else { // downButton = buttons[0]; // } // for (int i = 0; i < count; i++) { // ObjectUtil.invokeMethod(downButton, "simulatePush"); // } // } // } // Path: src/main/java/org/robotframework/formslibrary/keyword/ScrollBarKeywords.java import org.robotframework.formslibrary.operator.HorizontalScrollBarOperator; import org.robotframework.formslibrary.operator.VerticalScrollBarOperator; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywordOverload; import org.robotframework.javalib.annotation.RobotKeywords; package org.robotframework.formslibrary.keyword; @RobotKeywords public class ScrollBarKeywords { @RobotKeyword("Scroll down in the current window by clicking the down arrow button on a vertical scrollbar.\\n\\n Specify how many times the button should be clicked in the count parameter. One click scrolls approximately one table row. If multiple vertical scrollbars exist in the window, you can optionnally specify the scroll bar index to indicate which scrollbar should be used. Use index 1 for the first scrollbar, 2 for the second, and so on. Example:\\n | Scroll Down | _count_ ||\\\\n | Scroll Down | _count_ | _index_ |\\n") @ArgumentNames({ "count", "index=" }) public void scrollDown(int count, int index) {
new VerticalScrollBarOperator(index - 1).scrollDown(count);
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/keyword/ContextKeywords.java
// Path: src/main/java/org/robotframework/formslibrary/context/FormsContext.java // public class FormsContext { // private static String FORMS_TITLE = "Oracle Fusion Middleware Forms Services"; // private static ComponentWrapper context; // // private static Boolean isFormServicesApp = null; // // public static void setContext(ComponentWrapper operator) { // context = operator; // // TODO remove swing library context dependency if possible // Context.setContext(context); // } // // /** // * Get current context. If no context is set, it will be defaulted to the // * first window. // */ // public static ComponentWrapper getContext() { // // // set root context if no context exists // if (context == null) { // Logger.debug("No context found."); // resetContext(); // } // // if (isFormsServicesApp()) { // // Component contextComponent = Context.getContext().getSource(); // // // verify that the current window context is still part of the // // desktop // if (!new FrameOperator().containsComponent(contextComponent) && !isActiveDialog(context)) { // Logger.info("Context " + ComponentUtil.getFormattedComponentNames(contextComponent) + " is no longer part of desktop."); // resetContext(); // return context; // } // // // verify the type of context // // if (!ComponentType.JFRAME.matches(contextComponent) && // // !ComponentType.EXTENDED_FRAME.matches(contextComponent) // // && !ComponentType.WINDOW.matches(contextComponent) && // // !ComponentType.BUFFERED_FRAME.matches(contextComponent)) { // // throw new FormsLibraryException("Invalid context selected: " + // // contextComponent.getClass().getSimpleName()); // // } // } // // return context; // } // // private static boolean isActiveDialog(ComponentWrapper context) { // Component source = context.getSource(); // if (source instanceof Dialog) { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // if (window == source) { // return true; // } // } // } // return false; // } // // /** // * @return root context (the forms desktop window) // */ // public static ComponentWrapper getRootContext() { // return new FrameOperator(); // } // // /** // * @return root context (the forms desktop window) // */ // public static void listWindows() { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // Logger.info( // "Window - " + window.getName() + " - " + window.getClass().getName() + " title=" + ObjectUtil.getFieldIfExists(window, "title")); // } // } // // public static boolean isFormsServicesApp() { // if (isFormServicesApp == null) { // isFormServicesApp = checkFormServicesApp(); // } // return isFormServicesApp; // } // // private static boolean checkFormServicesApp() { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // Object title = ObjectUtil.getFieldIfExists(window, "title"); // if (title != null && title instanceof String) { // if (((String) title).equals(FORMS_TITLE)) { // return true; // } // } // } // return false; // } // // /** // * Change the context to the root context. // */ // public static void resetContext() { // Logger.info("Changing context to main desktop window."); // context = getRootContext(); // Context.setContext(context); // } // } // // Path: src/main/java/org/robotframework/formslibrary/operator/PanelOperator.java // public class PanelOperator extends ContainerOperator { // // /** // * Initialize a PanelOperator with the given type in the current context. // * // * @param type // * class type of the panel. // */ // public PanelOperator(String type) { // super((org.netbeans.jemmy.operators.ContainerOperator) Context.getContext(), new ByComponentFreeTypeChooser(0, type)); // } // // } // // Path: src/main/java/org/robotframework/formslibrary/util/Logger.java // public class Logger { // // public static void debug(String message) { // if (DebugUtil.isDebugEnabled()) { // System.out.println("~ " + message); // } // } // // public static void info(String message) { // System.out.println(message); // } // // public static void error(Throwable t) { // t.printStackTrace(); // } // }
import org.robotframework.formslibrary.context.FormsContext; import org.robotframework.formslibrary.operator.PanelOperator; import org.robotframework.formslibrary.util.Logger; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords; import org.robotframework.swing.operator.ComponentWrapper;
package org.robotframework.formslibrary.keyword; @RobotKeywords public class ContextKeywords { @RobotKeyword("Set the context to a panel. The panel is selected by its class name.\n") @ArgumentNames({ "type" }) public void setContextByType(String type) {
// Path: src/main/java/org/robotframework/formslibrary/context/FormsContext.java // public class FormsContext { // private static String FORMS_TITLE = "Oracle Fusion Middleware Forms Services"; // private static ComponentWrapper context; // // private static Boolean isFormServicesApp = null; // // public static void setContext(ComponentWrapper operator) { // context = operator; // // TODO remove swing library context dependency if possible // Context.setContext(context); // } // // /** // * Get current context. If no context is set, it will be defaulted to the // * first window. // */ // public static ComponentWrapper getContext() { // // // set root context if no context exists // if (context == null) { // Logger.debug("No context found."); // resetContext(); // } // // if (isFormsServicesApp()) { // // Component contextComponent = Context.getContext().getSource(); // // // verify that the current window context is still part of the // // desktop // if (!new FrameOperator().containsComponent(contextComponent) && !isActiveDialog(context)) { // Logger.info("Context " + ComponentUtil.getFormattedComponentNames(contextComponent) + " is no longer part of desktop."); // resetContext(); // return context; // } // // // verify the type of context // // if (!ComponentType.JFRAME.matches(contextComponent) && // // !ComponentType.EXTENDED_FRAME.matches(contextComponent) // // && !ComponentType.WINDOW.matches(contextComponent) && // // !ComponentType.BUFFERED_FRAME.matches(contextComponent)) { // // throw new FormsLibraryException("Invalid context selected: " + // // contextComponent.getClass().getSimpleName()); // // } // } // // return context; // } // // private static boolean isActiveDialog(ComponentWrapper context) { // Component source = context.getSource(); // if (source instanceof Dialog) { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // if (window == source) { // return true; // } // } // } // return false; // } // // /** // * @return root context (the forms desktop window) // */ // public static ComponentWrapper getRootContext() { // return new FrameOperator(); // } // // /** // * @return root context (the forms desktop window) // */ // public static void listWindows() { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // Logger.info( // "Window - " + window.getName() + " - " + window.getClass().getName() + " title=" + ObjectUtil.getFieldIfExists(window, "title")); // } // } // // public static boolean isFormsServicesApp() { // if (isFormServicesApp == null) { // isFormServicesApp = checkFormServicesApp(); // } // return isFormServicesApp; // } // // private static boolean checkFormServicesApp() { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // Object title = ObjectUtil.getFieldIfExists(window, "title"); // if (title != null && title instanceof String) { // if (((String) title).equals(FORMS_TITLE)) { // return true; // } // } // } // return false; // } // // /** // * Change the context to the root context. // */ // public static void resetContext() { // Logger.info("Changing context to main desktop window."); // context = getRootContext(); // Context.setContext(context); // } // } // // Path: src/main/java/org/robotframework/formslibrary/operator/PanelOperator.java // public class PanelOperator extends ContainerOperator { // // /** // * Initialize a PanelOperator with the given type in the current context. // * // * @param type // * class type of the panel. // */ // public PanelOperator(String type) { // super((org.netbeans.jemmy.operators.ContainerOperator) Context.getContext(), new ByComponentFreeTypeChooser(0, type)); // } // // } // // Path: src/main/java/org/robotframework/formslibrary/util/Logger.java // public class Logger { // // public static void debug(String message) { // if (DebugUtil.isDebugEnabled()) { // System.out.println("~ " + message); // } // } // // public static void info(String message) { // System.out.println(message); // } // // public static void error(Throwable t) { // t.printStackTrace(); // } // } // Path: src/main/java/org/robotframework/formslibrary/keyword/ContextKeywords.java import org.robotframework.formslibrary.context.FormsContext; import org.robotframework.formslibrary.operator.PanelOperator; import org.robotframework.formslibrary.util.Logger; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords; import org.robotframework.swing.operator.ComponentWrapper; package org.robotframework.formslibrary.keyword; @RobotKeywords public class ContextKeywords { @RobotKeyword("Set the context to a panel. The panel is selected by its class name.\n") @ArgumentNames({ "type" }) public void setContextByType(String type) {
FormsContext.setContext(new PanelOperator(type));
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/keyword/ContextKeywords.java
// Path: src/main/java/org/robotframework/formslibrary/context/FormsContext.java // public class FormsContext { // private static String FORMS_TITLE = "Oracle Fusion Middleware Forms Services"; // private static ComponentWrapper context; // // private static Boolean isFormServicesApp = null; // // public static void setContext(ComponentWrapper operator) { // context = operator; // // TODO remove swing library context dependency if possible // Context.setContext(context); // } // // /** // * Get current context. If no context is set, it will be defaulted to the // * first window. // */ // public static ComponentWrapper getContext() { // // // set root context if no context exists // if (context == null) { // Logger.debug("No context found."); // resetContext(); // } // // if (isFormsServicesApp()) { // // Component contextComponent = Context.getContext().getSource(); // // // verify that the current window context is still part of the // // desktop // if (!new FrameOperator().containsComponent(contextComponent) && !isActiveDialog(context)) { // Logger.info("Context " + ComponentUtil.getFormattedComponentNames(contextComponent) + " is no longer part of desktop."); // resetContext(); // return context; // } // // // verify the type of context // // if (!ComponentType.JFRAME.matches(contextComponent) && // // !ComponentType.EXTENDED_FRAME.matches(contextComponent) // // && !ComponentType.WINDOW.matches(contextComponent) && // // !ComponentType.BUFFERED_FRAME.matches(contextComponent)) { // // throw new FormsLibraryException("Invalid context selected: " + // // contextComponent.getClass().getSimpleName()); // // } // } // // return context; // } // // private static boolean isActiveDialog(ComponentWrapper context) { // Component source = context.getSource(); // if (source instanceof Dialog) { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // if (window == source) { // return true; // } // } // } // return false; // } // // /** // * @return root context (the forms desktop window) // */ // public static ComponentWrapper getRootContext() { // return new FrameOperator(); // } // // /** // * @return root context (the forms desktop window) // */ // public static void listWindows() { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // Logger.info( // "Window - " + window.getName() + " - " + window.getClass().getName() + " title=" + ObjectUtil.getFieldIfExists(window, "title")); // } // } // // public static boolean isFormsServicesApp() { // if (isFormServicesApp == null) { // isFormServicesApp = checkFormServicesApp(); // } // return isFormServicesApp; // } // // private static boolean checkFormServicesApp() { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // Object title = ObjectUtil.getFieldIfExists(window, "title"); // if (title != null && title instanceof String) { // if (((String) title).equals(FORMS_TITLE)) { // return true; // } // } // } // return false; // } // // /** // * Change the context to the root context. // */ // public static void resetContext() { // Logger.info("Changing context to main desktop window."); // context = getRootContext(); // Context.setContext(context); // } // } // // Path: src/main/java/org/robotframework/formslibrary/operator/PanelOperator.java // public class PanelOperator extends ContainerOperator { // // /** // * Initialize a PanelOperator with the given type in the current context. // * // * @param type // * class type of the panel. // */ // public PanelOperator(String type) { // super((org.netbeans.jemmy.operators.ContainerOperator) Context.getContext(), new ByComponentFreeTypeChooser(0, type)); // } // // } // // Path: src/main/java/org/robotframework/formslibrary/util/Logger.java // public class Logger { // // public static void debug(String message) { // if (DebugUtil.isDebugEnabled()) { // System.out.println("~ " + message); // } // } // // public static void info(String message) { // System.out.println(message); // } // // public static void error(Throwable t) { // t.printStackTrace(); // } // }
import org.robotframework.formslibrary.context.FormsContext; import org.robotframework.formslibrary.operator.PanelOperator; import org.robotframework.formslibrary.util.Logger; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords; import org.robotframework.swing.operator.ComponentWrapper;
package org.robotframework.formslibrary.keyword; @RobotKeywords public class ContextKeywords { @RobotKeyword("Set the context to a panel. The panel is selected by its class name.\n") @ArgumentNames({ "type" }) public void setContextByType(String type) {
// Path: src/main/java/org/robotframework/formslibrary/context/FormsContext.java // public class FormsContext { // private static String FORMS_TITLE = "Oracle Fusion Middleware Forms Services"; // private static ComponentWrapper context; // // private static Boolean isFormServicesApp = null; // // public static void setContext(ComponentWrapper operator) { // context = operator; // // TODO remove swing library context dependency if possible // Context.setContext(context); // } // // /** // * Get current context. If no context is set, it will be defaulted to the // * first window. // */ // public static ComponentWrapper getContext() { // // // set root context if no context exists // if (context == null) { // Logger.debug("No context found."); // resetContext(); // } // // if (isFormsServicesApp()) { // // Component contextComponent = Context.getContext().getSource(); // // // verify that the current window context is still part of the // // desktop // if (!new FrameOperator().containsComponent(contextComponent) && !isActiveDialog(context)) { // Logger.info("Context " + ComponentUtil.getFormattedComponentNames(contextComponent) + " is no longer part of desktop."); // resetContext(); // return context; // } // // // verify the type of context // // if (!ComponentType.JFRAME.matches(contextComponent) && // // !ComponentType.EXTENDED_FRAME.matches(contextComponent) // // && !ComponentType.WINDOW.matches(contextComponent) && // // !ComponentType.BUFFERED_FRAME.matches(contextComponent)) { // // throw new FormsLibraryException("Invalid context selected: " + // // contextComponent.getClass().getSimpleName()); // // } // } // // return context; // } // // private static boolean isActiveDialog(ComponentWrapper context) { // Component source = context.getSource(); // if (source instanceof Dialog) { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // if (window == source) { // return true; // } // } // } // return false; // } // // /** // * @return root context (the forms desktop window) // */ // public static ComponentWrapper getRootContext() { // return new FrameOperator(); // } // // /** // * @return root context (the forms desktop window) // */ // public static void listWindows() { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // Logger.info( // "Window - " + window.getName() + " - " + window.getClass().getName() + " title=" + ObjectUtil.getFieldIfExists(window, "title")); // } // } // // public static boolean isFormsServicesApp() { // if (isFormServicesApp == null) { // isFormServicesApp = checkFormServicesApp(); // } // return isFormServicesApp; // } // // private static boolean checkFormServicesApp() { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // Object title = ObjectUtil.getFieldIfExists(window, "title"); // if (title != null && title instanceof String) { // if (((String) title).equals(FORMS_TITLE)) { // return true; // } // } // } // return false; // } // // /** // * Change the context to the root context. // */ // public static void resetContext() { // Logger.info("Changing context to main desktop window."); // context = getRootContext(); // Context.setContext(context); // } // } // // Path: src/main/java/org/robotframework/formslibrary/operator/PanelOperator.java // public class PanelOperator extends ContainerOperator { // // /** // * Initialize a PanelOperator with the given type in the current context. // * // * @param type // * class type of the panel. // */ // public PanelOperator(String type) { // super((org.netbeans.jemmy.operators.ContainerOperator) Context.getContext(), new ByComponentFreeTypeChooser(0, type)); // } // // } // // Path: src/main/java/org/robotframework/formslibrary/util/Logger.java // public class Logger { // // public static void debug(String message) { // if (DebugUtil.isDebugEnabled()) { // System.out.println("~ " + message); // } // } // // public static void info(String message) { // System.out.println(message); // } // // public static void error(Throwable t) { // t.printStackTrace(); // } // } // Path: src/main/java/org/robotframework/formslibrary/keyword/ContextKeywords.java import org.robotframework.formslibrary.context.FormsContext; import org.robotframework.formslibrary.operator.PanelOperator; import org.robotframework.formslibrary.util.Logger; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords; import org.robotframework.swing.operator.ComponentWrapper; package org.robotframework.formslibrary.keyword; @RobotKeywords public class ContextKeywords { @RobotKeyword("Set the context to a panel. The panel is selected by its class name.\n") @ArgumentNames({ "type" }) public void setContextByType(String type) {
FormsContext.setContext(new PanelOperator(type));
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/keyword/ContextKeywords.java
// Path: src/main/java/org/robotframework/formslibrary/context/FormsContext.java // public class FormsContext { // private static String FORMS_TITLE = "Oracle Fusion Middleware Forms Services"; // private static ComponentWrapper context; // // private static Boolean isFormServicesApp = null; // // public static void setContext(ComponentWrapper operator) { // context = operator; // // TODO remove swing library context dependency if possible // Context.setContext(context); // } // // /** // * Get current context. If no context is set, it will be defaulted to the // * first window. // */ // public static ComponentWrapper getContext() { // // // set root context if no context exists // if (context == null) { // Logger.debug("No context found."); // resetContext(); // } // // if (isFormsServicesApp()) { // // Component contextComponent = Context.getContext().getSource(); // // // verify that the current window context is still part of the // // desktop // if (!new FrameOperator().containsComponent(contextComponent) && !isActiveDialog(context)) { // Logger.info("Context " + ComponentUtil.getFormattedComponentNames(contextComponent) + " is no longer part of desktop."); // resetContext(); // return context; // } // // // verify the type of context // // if (!ComponentType.JFRAME.matches(contextComponent) && // // !ComponentType.EXTENDED_FRAME.matches(contextComponent) // // && !ComponentType.WINDOW.matches(contextComponent) && // // !ComponentType.BUFFERED_FRAME.matches(contextComponent)) { // // throw new FormsLibraryException("Invalid context selected: " + // // contextComponent.getClass().getSimpleName()); // // } // } // // return context; // } // // private static boolean isActiveDialog(ComponentWrapper context) { // Component source = context.getSource(); // if (source instanceof Dialog) { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // if (window == source) { // return true; // } // } // } // return false; // } // // /** // * @return root context (the forms desktop window) // */ // public static ComponentWrapper getRootContext() { // return new FrameOperator(); // } // // /** // * @return root context (the forms desktop window) // */ // public static void listWindows() { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // Logger.info( // "Window - " + window.getName() + " - " + window.getClass().getName() + " title=" + ObjectUtil.getFieldIfExists(window, "title")); // } // } // // public static boolean isFormsServicesApp() { // if (isFormServicesApp == null) { // isFormServicesApp = checkFormServicesApp(); // } // return isFormServicesApp; // } // // private static boolean checkFormServicesApp() { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // Object title = ObjectUtil.getFieldIfExists(window, "title"); // if (title != null && title instanceof String) { // if (((String) title).equals(FORMS_TITLE)) { // return true; // } // } // } // return false; // } // // /** // * Change the context to the root context. // */ // public static void resetContext() { // Logger.info("Changing context to main desktop window."); // context = getRootContext(); // Context.setContext(context); // } // } // // Path: src/main/java/org/robotframework/formslibrary/operator/PanelOperator.java // public class PanelOperator extends ContainerOperator { // // /** // * Initialize a PanelOperator with the given type in the current context. // * // * @param type // * class type of the panel. // */ // public PanelOperator(String type) { // super((org.netbeans.jemmy.operators.ContainerOperator) Context.getContext(), new ByComponentFreeTypeChooser(0, type)); // } // // } // // Path: src/main/java/org/robotframework/formslibrary/util/Logger.java // public class Logger { // // public static void debug(String message) { // if (DebugUtil.isDebugEnabled()) { // System.out.println("~ " + message); // } // } // // public static void info(String message) { // System.out.println(message); // } // // public static void error(Throwable t) { // t.printStackTrace(); // } // }
import org.robotframework.formslibrary.context.FormsContext; import org.robotframework.formslibrary.operator.PanelOperator; import org.robotframework.formslibrary.util.Logger; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords; import org.robotframework.swing.operator.ComponentWrapper;
package org.robotframework.formslibrary.keyword; @RobotKeywords public class ContextKeywords { @RobotKeyword("Set the context to a panel. The panel is selected by its class name.\n") @ArgumentNames({ "type" }) public void setContextByType(String type) { FormsContext.setContext(new PanelOperator(type)); ComponentWrapper context = FormsContext.getContext();
// Path: src/main/java/org/robotframework/formslibrary/context/FormsContext.java // public class FormsContext { // private static String FORMS_TITLE = "Oracle Fusion Middleware Forms Services"; // private static ComponentWrapper context; // // private static Boolean isFormServicesApp = null; // // public static void setContext(ComponentWrapper operator) { // context = operator; // // TODO remove swing library context dependency if possible // Context.setContext(context); // } // // /** // * Get current context. If no context is set, it will be defaulted to the // * first window. // */ // public static ComponentWrapper getContext() { // // // set root context if no context exists // if (context == null) { // Logger.debug("No context found."); // resetContext(); // } // // if (isFormsServicesApp()) { // // Component contextComponent = Context.getContext().getSource(); // // // verify that the current window context is still part of the // // desktop // if (!new FrameOperator().containsComponent(contextComponent) && !isActiveDialog(context)) { // Logger.info("Context " + ComponentUtil.getFormattedComponentNames(contextComponent) + " is no longer part of desktop."); // resetContext(); // return context; // } // // // verify the type of context // // if (!ComponentType.JFRAME.matches(contextComponent) && // // !ComponentType.EXTENDED_FRAME.matches(contextComponent) // // && !ComponentType.WINDOW.matches(contextComponent) && // // !ComponentType.BUFFERED_FRAME.matches(contextComponent)) { // // throw new FormsLibraryException("Invalid context selected: " + // // contextComponent.getClass().getSimpleName()); // // } // } // // return context; // } // // private static boolean isActiveDialog(ComponentWrapper context) { // Component source = context.getSource(); // if (source instanceof Dialog) { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // if (window == source) { // return true; // } // } // } // return false; // } // // /** // * @return root context (the forms desktop window) // */ // public static ComponentWrapper getRootContext() { // return new FrameOperator(); // } // // /** // * @return root context (the forms desktop window) // */ // public static void listWindows() { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // Logger.info( // "Window - " + window.getName() + " - " + window.getClass().getName() + " title=" + ObjectUtil.getFieldIfExists(window, "title")); // } // } // // public static boolean isFormsServicesApp() { // if (isFormServicesApp == null) { // isFormServicesApp = checkFormServicesApp(); // } // return isFormServicesApp; // } // // private static boolean checkFormServicesApp() { // Window[] windows = Window.getWindows(); // for (Window window : windows) { // Object title = ObjectUtil.getFieldIfExists(window, "title"); // if (title != null && title instanceof String) { // if (((String) title).equals(FORMS_TITLE)) { // return true; // } // } // } // return false; // } // // /** // * Change the context to the root context. // */ // public static void resetContext() { // Logger.info("Changing context to main desktop window."); // context = getRootContext(); // Context.setContext(context); // } // } // // Path: src/main/java/org/robotframework/formslibrary/operator/PanelOperator.java // public class PanelOperator extends ContainerOperator { // // /** // * Initialize a PanelOperator with the given type in the current context. // * // * @param type // * class type of the panel. // */ // public PanelOperator(String type) { // super((org.netbeans.jemmy.operators.ContainerOperator) Context.getContext(), new ByComponentFreeTypeChooser(0, type)); // } // // } // // Path: src/main/java/org/robotframework/formslibrary/util/Logger.java // public class Logger { // // public static void debug(String message) { // if (DebugUtil.isDebugEnabled()) { // System.out.println("~ " + message); // } // } // // public static void info(String message) { // System.out.println(message); // } // // public static void error(Throwable t) { // t.printStackTrace(); // } // } // Path: src/main/java/org/robotframework/formslibrary/keyword/ContextKeywords.java import org.robotframework.formslibrary.context.FormsContext; import org.robotframework.formslibrary.operator.PanelOperator; import org.robotframework.formslibrary.util.Logger; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords; import org.robotframework.swing.operator.ComponentWrapper; package org.robotframework.formslibrary.keyword; @RobotKeywords public class ContextKeywords { @RobotKeyword("Set the context to a panel. The panel is selected by its class name.\n") @ArgumentNames({ "type" }) public void setContextByType(String type) { FormsContext.setContext(new PanelOperator(type)); ComponentWrapper context = FormsContext.getContext();
Logger.info("Context set to " + context.getSource());
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/remoteswinglibrary/agent/JavaAgent.java
// Path: src/main/java/org/robotframework/formslibrary/util/Logger.java // public class Logger { // // public static void debug(String message) { // if (DebugUtil.isDebugEnabled()) { // System.out.println("~ " + message); // } // } // // public static void info(String message) { // System.out.println(message); // } // // public static void error(Throwable t) { // t.printStackTrace(); // } // }
import java.lang.instrument.Instrumentation; import java.util.Arrays; import org.robotframework.formslibrary.util.Logger;
package org.robotframework.remoteswinglibrary.agent; public class JavaAgent { private static final int DEFAULT_REMOTESWINGLIBRARY_PORT = 8181; public static void premain(String agentArgument, Instrumentation instrumentation) {
// Path: src/main/java/org/robotframework/formslibrary/util/Logger.java // public class Logger { // // public static void debug(String message) { // if (DebugUtil.isDebugEnabled()) { // System.out.println("~ " + message); // } // } // // public static void info(String message) { // System.out.println(message); // } // // public static void error(Throwable t) { // t.printStackTrace(); // } // } // Path: src/main/java/org/robotframework/remoteswinglibrary/agent/JavaAgent.java import java.lang.instrument.Instrumentation; import java.util.Arrays; import org.robotframework.formslibrary.util.Logger; package org.robotframework.remoteswinglibrary.agent; public class JavaAgent { private static final int DEFAULT_REMOTESWINGLIBRARY_PORT = 8181; public static void premain(String agentArgument, Instrumentation instrumentation) {
Logger.info("\nStarting formslib JavaAgent...");
dvanherbergen/robotframework-formslibrary
src/main/java/org/robotframework/formslibrary/keyword/StatusBarKeywords.java
// Path: src/main/java/org/robotframework/formslibrary/operator/StatusBarOperator.java // public class StatusBarOperator extends AbstractRootComponentOperator { // // /** // * Create a new operator for the default status bar. // */ // public StatusBarOperator() { // super(new ByComponentTypeChooser(0, ComponentType.STATUS_BAR)); // } // // /** // * @return the main message displayed in the status bar. // */ // public String getMessage() { // // Object[] statusBarItems = (Object[]) ObjectUtil.invokeMethod(getSource(), "getItems()"); // String result = ""; // for (int i = 0; i < statusBarItems.length; i++) { // if (ComponentType.STATUS_BAR_TEXT_ITEM.matches(statusBarItems[i])) { // result = ObjectUtil.getString(statusBarItems[i], "getText()"); // Logger.info("Found status message '" + result + "'"); // break; // } // } // return result; // } // // /** // * Verify that the given value is displayed in the status bar. // */ // public void verifyValue(String value) { // String message = getMessage(); // if (!TextUtil.matches(message, value)) { // throw new FormsLibraryException("Status Bar Message '" + message + "' does not match '" + value + "'."); // } // } // // }
import org.robotframework.formslibrary.operator.StatusBarOperator; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords;
package org.robotframework.formslibrary.keyword; @RobotKeywords public class StatusBarKeywords { @RobotKeyword("Get the message that is displayed in the status bar at the bottom of the screen. \n\n Example:\n | Get Status Message |\n") public String getStatusMessage() {
// Path: src/main/java/org/robotframework/formslibrary/operator/StatusBarOperator.java // public class StatusBarOperator extends AbstractRootComponentOperator { // // /** // * Create a new operator for the default status bar. // */ // public StatusBarOperator() { // super(new ByComponentTypeChooser(0, ComponentType.STATUS_BAR)); // } // // /** // * @return the main message displayed in the status bar. // */ // public String getMessage() { // // Object[] statusBarItems = (Object[]) ObjectUtil.invokeMethod(getSource(), "getItems()"); // String result = ""; // for (int i = 0; i < statusBarItems.length; i++) { // if (ComponentType.STATUS_BAR_TEXT_ITEM.matches(statusBarItems[i])) { // result = ObjectUtil.getString(statusBarItems[i], "getText()"); // Logger.info("Found status message '" + result + "'"); // break; // } // } // return result; // } // // /** // * Verify that the given value is displayed in the status bar. // */ // public void verifyValue(String value) { // String message = getMessage(); // if (!TextUtil.matches(message, value)) { // throw new FormsLibraryException("Status Bar Message '" + message + "' does not match '" + value + "'."); // } // } // // } // Path: src/main/java/org/robotframework/formslibrary/keyword/StatusBarKeywords.java import org.robotframework.formslibrary.operator.StatusBarOperator; import org.robotframework.javalib.annotation.ArgumentNames; import org.robotframework.javalib.annotation.RobotKeyword; import org.robotframework.javalib.annotation.RobotKeywords; package org.robotframework.formslibrary.keyword; @RobotKeywords public class StatusBarKeywords { @RobotKeyword("Get the message that is displayed in the status bar at the bottom of the screen. \n\n Example:\n | Get Status Message |\n") public String getStatusMessage() {
return new StatusBarOperator().getMessage();
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/sdk/MockShareClickListener.java
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppDataCache.java // public class AppDataCache { // // private final Map<String, Drawable> iconCache = new HashMap<String, Drawable>(); // private final Map<String, String> labelCache = new HashMap<String, String>(); // // static AppDataCache instance = new AppDataCache(); // // AppDataCache() {} // // public static AppDataCache getInstance() { // return instance; // } // // public void onCreate(final Context context) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // Collection<ResolveInfo> appsForContentType = getAppUtils().getAppsForContentType(context, "*/*"); // for (ResolveInfo resolveInfo : appsForContentType) { // getAppIcon(context, resolveInfo); // getAppLabel(context, resolveInfo); // } // return null; // } // }.execute(); // } // // public void onDestroy(Context context) { // iconCache.clear(); // labelCache.clear(); // } // // public synchronized Drawable getAppIcon(Context context, ResolveInfo item) { // String key = getKey(item); // Drawable icon = iconCache.get(key); // if(icon == null) { // icon = item.activityInfo.loadIcon(context.getPackageManager()); // iconCache.put(key, icon); // } // return icon; // } // // /** // * May return null! // * @param packageName The package name. // * @param className The activity class name // * @return The app (activity) label, or null // */ // public String getAppLabel(String packageName, String className) { // return labelCache.get(packageName + "." + className); // } // // public synchronized String getAppLabel(Context context, ResolveInfo item) { // String key = getKey(item); // String label = labelCache.get(key); // if(label == null) { // label = item.activityInfo.loadLabel(context.getPackageManager()).toString(); // labelCache.put(key, label); // } // return label; // } // // String getKey(ResolveInfo item) { // return item.activityInfo.packageName + "." + item.activityInfo.name; // } // // // mockable // AppUtils getAppUtils() { // return AppUtils.getInstance(); // } // // }
import com.sharethis.loopy.sdk.util.AppDataCache;
package com.sharethis.loopy.sdk; /** * @author Jason Polites */ public class MockShareClickListener extends ShareClickListener { @Override public ApiClient getApiClient() { return super.getApiClient(); } @Override
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppDataCache.java // public class AppDataCache { // // private final Map<String, Drawable> iconCache = new HashMap<String, Drawable>(); // private final Map<String, String> labelCache = new HashMap<String, String>(); // // static AppDataCache instance = new AppDataCache(); // // AppDataCache() {} // // public static AppDataCache getInstance() { // return instance; // } // // public void onCreate(final Context context) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // Collection<ResolveInfo> appsForContentType = getAppUtils().getAppsForContentType(context, "*/*"); // for (ResolveInfo resolveInfo : appsForContentType) { // getAppIcon(context, resolveInfo); // getAppLabel(context, resolveInfo); // } // return null; // } // }.execute(); // } // // public void onDestroy(Context context) { // iconCache.clear(); // labelCache.clear(); // } // // public synchronized Drawable getAppIcon(Context context, ResolveInfo item) { // String key = getKey(item); // Drawable icon = iconCache.get(key); // if(icon == null) { // icon = item.activityInfo.loadIcon(context.getPackageManager()); // iconCache.put(key, icon); // } // return icon; // } // // /** // * May return null! // * @param packageName The package name. // * @param className The activity class name // * @return The app (activity) label, or null // */ // public String getAppLabel(String packageName, String className) { // return labelCache.get(packageName + "." + className); // } // // public synchronized String getAppLabel(Context context, ResolveInfo item) { // String key = getKey(item); // String label = labelCache.get(key); // if(label == null) { // label = item.activityInfo.loadLabel(context.getPackageManager()).toString(); // labelCache.put(key, label); // } // return label; // } // // String getKey(ResolveInfo item) { // return item.activityInfo.packageName + "." + item.activityInfo.name; // } // // // mockable // AppUtils getAppUtils() { // return AppUtils.getInstance(); // } // // } // Path: test/src/com/sharethis/loopy/sdk/MockShareClickListener.java import com.sharethis.loopy.sdk.util.AppDataCache; package com.sharethis.loopy.sdk; /** * @author Jason Polites */ public class MockShareClickListener extends ShareClickListener { @Override public ApiClient getApiClient() { return super.getApiClient(); } @Override
public AppDataCache getAppDataCache() {
socialize/loopy-sdk-android
sdk/src/com/sharethis/loopy/sdk/ShareClickListener.java
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppDataCache.java // public class AppDataCache { // // private final Map<String, Drawable> iconCache = new HashMap<String, Drawable>(); // private final Map<String, String> labelCache = new HashMap<String, String>(); // // static AppDataCache instance = new AppDataCache(); // // AppDataCache() {} // // public static AppDataCache getInstance() { // return instance; // } // // public void onCreate(final Context context) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // Collection<ResolveInfo> appsForContentType = getAppUtils().getAppsForContentType(context, "*/*"); // for (ResolveInfo resolveInfo : appsForContentType) { // getAppIcon(context, resolveInfo); // getAppLabel(context, resolveInfo); // } // return null; // } // }.execute(); // } // // public void onDestroy(Context context) { // iconCache.clear(); // labelCache.clear(); // } // // public synchronized Drawable getAppIcon(Context context, ResolveInfo item) { // String key = getKey(item); // Drawable icon = iconCache.get(key); // if(icon == null) { // icon = item.activityInfo.loadIcon(context.getPackageManager()); // iconCache.put(key, icon); // } // return icon; // } // // /** // * May return null! // * @param packageName The package name. // * @param className The activity class name // * @return The app (activity) label, or null // */ // public String getAppLabel(String packageName, String className) { // return labelCache.get(packageName + "." + className); // } // // public synchronized String getAppLabel(Context context, ResolveInfo item) { // String key = getKey(item); // String label = labelCache.get(key); // if(label == null) { // label = item.activityInfo.loadLabel(context.getPackageManager()).toString(); // labelCache.put(key, label); // } // return label; // } // // String getKey(ResolveInfo item) { // return item.activityInfo.packageName + "." + item.activityInfo.name; // } // // // mockable // AppUtils getAppUtils() { // return AppUtils.getInstance(); // } // // }
import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.pm.ResolveInfo; import com.sharethis.loopy.sdk.util.AppDataCache; import org.json.JSONObject;
@Override public void onError(Throwable e) { Logger.e(e); // Launch the app with the data from the share, even if there's an error launchShareIntent(context, app, shareIntent); } }); } catch (Exception e) { Logger.e(e); // Launch the app with the data from the share, even if there's an error launchShareIntent(context, app, shareIntent); } } } void launchShareIntent(Context context, ResolveInfo app, Intent shareIntent) { if (app.activityInfo != null) { shareIntent.setClassName(app.activityInfo.packageName, app.activityInfo.name); context.startActivity(shareIntent); } } // Mockable ApiClient getApiClient() { return Loopy.getInstance().getApiClient(); } // Mockable
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppDataCache.java // public class AppDataCache { // // private final Map<String, Drawable> iconCache = new HashMap<String, Drawable>(); // private final Map<String, String> labelCache = new HashMap<String, String>(); // // static AppDataCache instance = new AppDataCache(); // // AppDataCache() {} // // public static AppDataCache getInstance() { // return instance; // } // // public void onCreate(final Context context) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // Collection<ResolveInfo> appsForContentType = getAppUtils().getAppsForContentType(context, "*/*"); // for (ResolveInfo resolveInfo : appsForContentType) { // getAppIcon(context, resolveInfo); // getAppLabel(context, resolveInfo); // } // return null; // } // }.execute(); // } // // public void onDestroy(Context context) { // iconCache.clear(); // labelCache.clear(); // } // // public synchronized Drawable getAppIcon(Context context, ResolveInfo item) { // String key = getKey(item); // Drawable icon = iconCache.get(key); // if(icon == null) { // icon = item.activityInfo.loadIcon(context.getPackageManager()); // iconCache.put(key, icon); // } // return icon; // } // // /** // * May return null! // * @param packageName The package name. // * @param className The activity class name // * @return The app (activity) label, or null // */ // public String getAppLabel(String packageName, String className) { // return labelCache.get(packageName + "." + className); // } // // public synchronized String getAppLabel(Context context, ResolveInfo item) { // String key = getKey(item); // String label = labelCache.get(key); // if(label == null) { // label = item.activityInfo.loadLabel(context.getPackageManager()).toString(); // labelCache.put(key, label); // } // return label; // } // // String getKey(ResolveInfo item) { // return item.activityInfo.packageName + "." + item.activityInfo.name; // } // // // mockable // AppUtils getAppUtils() { // return AppUtils.getInstance(); // } // // } // Path: sdk/src/com/sharethis/loopy/sdk/ShareClickListener.java import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.pm.ResolveInfo; import com.sharethis.loopy.sdk.util.AppDataCache; import org.json.JSONObject; @Override public void onError(Throwable e) { Logger.e(e); // Launch the app with the data from the share, even if there's an error launchShareIntent(context, app, shareIntent); } }); } catch (Exception e) { Logger.e(e); // Launch the app with the data from the share, even if there's an error launchShareIntent(context, app, shareIntent); } } } void launchShareIntent(Context context, ResolveInfo app, Intent shareIntent) { if (app.activityInfo != null) { shareIntent.setClassName(app.activityInfo.packageName, app.activityInfo.name); context.startActivity(shareIntent); } } // Mockable ApiClient getApiClient() { return Loopy.getInstance().getApiClient(); } // Mockable
AppDataCache getAppDataCache() {
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/sdk/LoopyAccess.java
// Path: sdk/src/com/sharethis/loopy/sdk/net/HttpClientFactory.java // public class HttpClientFactory { // // public static final int DEFAULT_CONNECTION_TIMEOUT = 1000; // public static final int DEFAULT_READ_TIMEOUT = 1000; // // private HttpParams params; // private ClientConnectionManager connectionManager; // private DefaultHttpClient client; // This should be thread safe // private IdleConnectionMonitorThread monitor; // private boolean initialized = false; // // private int connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; // private int readTimeout = DEFAULT_READ_TIMEOUT; // // public void start(int timeout) { // setConnectionTimeout(timeout); // setReadTimeout(timeout); // init(); // } // // public void stop() { // destroy(); // } // // void init() { // if(!initialized) { // // params = new BasicHttpParams(); // // HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); // HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); // HttpConnectionParams.setSoTimeout(params, readTimeout); // // SchemeRegistry registry = new SchemeRegistry(); // registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); // // connectionManager = new ThreadSafeClientConnManager(params, registry); // // monitor = new IdleConnectionMonitorThread(connectionManager); // monitor.setDaemon(true); // monitor.start(); // } // } // // void destroy() { // if(initialized) { // initialized = false; // if(monitor != null) { // monitor.shutdown(); // } // if(connectionManager != null) { // connectionManager.shutdown(); // } // } // } // // public synchronized HttpClient getClient() { // if(client == null) { // client = new DefaultHttpClient(connectionManager, params); // } // else { // monitor.trigger(); // } // // return client; // } // // public int getConnectionTimeout() { // return connectionTimeout; // } // // public void setConnectionTimeout(int connectionTimeout) { // this.connectionTimeout = connectionTimeout; // } // // public int getReadTimeout() { // return readTimeout; // } // // public void setReadTimeout(int readTimeout) { // this.readTimeout = readTimeout; // } // }
import com.sharethis.loopy.sdk.net.HttpClientFactory; import org.json.JSONException; import org.json.JSONObject; import java.util.Map;
package com.sharethis.loopy.sdk; /** * @author Jason Polites */ public class LoopyAccess { public static Loopy getLoopy() { return Loopy.getInstance(); } public static ApiClient getApiClient() { return Loopy.getInstance().getApiClient(); } public static void setApiClient(ApiClient client) { Loopy.getInstance().setApiClient(client); }
// Path: sdk/src/com/sharethis/loopy/sdk/net/HttpClientFactory.java // public class HttpClientFactory { // // public static final int DEFAULT_CONNECTION_TIMEOUT = 1000; // public static final int DEFAULT_READ_TIMEOUT = 1000; // // private HttpParams params; // private ClientConnectionManager connectionManager; // private DefaultHttpClient client; // This should be thread safe // private IdleConnectionMonitorThread monitor; // private boolean initialized = false; // // private int connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; // private int readTimeout = DEFAULT_READ_TIMEOUT; // // public void start(int timeout) { // setConnectionTimeout(timeout); // setReadTimeout(timeout); // init(); // } // // public void stop() { // destroy(); // } // // void init() { // if(!initialized) { // // params = new BasicHttpParams(); // // HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); // HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); // HttpConnectionParams.setSoTimeout(params, readTimeout); // // SchemeRegistry registry = new SchemeRegistry(); // registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); // // connectionManager = new ThreadSafeClientConnManager(params, registry); // // monitor = new IdleConnectionMonitorThread(connectionManager); // monitor.setDaemon(true); // monitor.start(); // } // } // // void destroy() { // if(initialized) { // initialized = false; // if(monitor != null) { // monitor.shutdown(); // } // if(connectionManager != null) { // connectionManager.shutdown(); // } // } // } // // public synchronized HttpClient getClient() { // if(client == null) { // client = new DefaultHttpClient(connectionManager, params); // } // else { // monitor.trigger(); // } // // return client; // } // // public int getConnectionTimeout() { // return connectionTimeout; // } // // public void setConnectionTimeout(int connectionTimeout) { // this.connectionTimeout = connectionTimeout; // } // // public int getReadTimeout() { // return readTimeout; // } // // public void setReadTimeout(int readTimeout) { // this.readTimeout = readTimeout; // } // } // Path: test/src/com/sharethis/loopy/sdk/LoopyAccess.java import com.sharethis.loopy.sdk.net.HttpClientFactory; import org.json.JSONException; import org.json.JSONObject; import java.util.Map; package com.sharethis.loopy.sdk; /** * @author Jason Polites */ public class LoopyAccess { public static Loopy getLoopy() { return Loopy.getInstance(); } public static ApiClient getApiClient() { return Loopy.getInstance().getApiClient(); } public static void setApiClient(ApiClient client) { Loopy.getInstance().setApiClient(client); }
public static void setHttpClientFactory(HttpClientFactory factory) {
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/sdk/MockConfig.java
// Path: sdk/src/com/sharethis/loopy/sdk/util/ResourceLocator.java // public class ResourceLocator { // private ClassLoaderProvider classLoaderProvider = new ClassLoaderProvider(); // // public InputStream locateInAssets(Context context, String name) throws IOException { // InputStream in = null; // // try { // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in asset path..."); // } // // in = context.getAssets().open(name); // // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in asset path"); // } // } // catch (IOException ignore) { // // Ignore this, just means no override. // if(Logger.isDebugEnabled()) { // Logger.d("No file found in assets with name [" + // name + // "]."); // } // } // // return in; // } // // public InputStream locateInClassPath(String name) throws IOException { // // InputStream in = null; // // if(classLoaderProvider != null) { // // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in classpath..."); // } // // in = classLoaderProvider.getClassLoader().getResourceAsStream(name); // // if(in != null) { // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in classpath"); // } // } // } // // return in; // } // // public InputStream locate(Context context, String name) throws IOException { // // InputStream in = locateInAssets(context, name); // // if(in == null) { // in = locateInClassPath(name); // } // // if(in == null) { // Logger.w("Could not locate [" + // name + // "] in any location"); // } // // return in; // } // // public ClassLoaderProvider getClassLoaderProvider() { // return classLoaderProvider; // } // // public void setClassLoaderProvider(ClassLoaderProvider classLoaderProvider) { // this.classLoaderProvider = classLoaderProvider; // } // }
import com.sharethis.loopy.sdk.util.ResourceLocator; import java.util.Properties;
/* * * * Copyright (c) 2013 ShareThis Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * * THE SOFTWARE. * */ package com.sharethis.loopy.sdk; /** * @author Jason Polites */ public class MockConfig extends Config { @Override public Properties newProperties() { return super.newProperties(); } @Override public String clean(String url) { return super.clean(url); } @Override
// Path: sdk/src/com/sharethis/loopy/sdk/util/ResourceLocator.java // public class ResourceLocator { // private ClassLoaderProvider classLoaderProvider = new ClassLoaderProvider(); // // public InputStream locateInAssets(Context context, String name) throws IOException { // InputStream in = null; // // try { // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in asset path..."); // } // // in = context.getAssets().open(name); // // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in asset path"); // } // } // catch (IOException ignore) { // // Ignore this, just means no override. // if(Logger.isDebugEnabled()) { // Logger.d("No file found in assets with name [" + // name + // "]."); // } // } // // return in; // } // // public InputStream locateInClassPath(String name) throws IOException { // // InputStream in = null; // // if(classLoaderProvider != null) { // // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in classpath..."); // } // // in = classLoaderProvider.getClassLoader().getResourceAsStream(name); // // if(in != null) { // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in classpath"); // } // } // } // // return in; // } // // public InputStream locate(Context context, String name) throws IOException { // // InputStream in = locateInAssets(context, name); // // if(in == null) { // in = locateInClassPath(name); // } // // if(in == null) { // Logger.w("Could not locate [" + // name + // "] in any location"); // } // // return in; // } // // public ClassLoaderProvider getClassLoaderProvider() { // return classLoaderProvider; // } // // public void setClassLoaderProvider(ClassLoaderProvider classLoaderProvider) { // this.classLoaderProvider = classLoaderProvider; // } // } // Path: test/src/com/sharethis/loopy/sdk/MockConfig.java import com.sharethis.loopy.sdk.util.ResourceLocator; import java.util.Properties; /* * * * Copyright (c) 2013 ShareThis Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * * THE SOFTWARE. * */ package com.sharethis.loopy.sdk; /** * @author Jason Polites */ public class MockConfig extends Config { @Override public Properties newProperties() { return super.newProperties(); } @Override public String clean(String url) { return super.clean(url); } @Override
public ResourceLocator newResourceLocator() {
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/ShortenCallbackTest.java
// Path: sdk/src/com/sharethis/loopy/sdk/Item.java // public class Item { // // String type = "website"; // String url; // String title; // String imageUrl; // String description; // String videoUrl; // Set<String> tags; // // String shortlink; // // /** // * The "og:type" corresponding to the content being shared. // * @return og:type // */ // public String getType() { // return type; // } // // /** // * Optional. // * Corresponds to the og:type meta element. Default is 'website' // * @param type The type of the content being shared (og:type) // * @see <a href="http://ogp.me/#types" target="_blank">http://ogp.me/#types</a> // */ // public void setType(String type) { // this.type = type; // } // // public String getUrl() { // return url; // } // // /** // * Optional. (MUST specify one of url or title!) // * The url of the content being shared. If the content does not have a url, you must at least provide a title. // * @param url The url of the content being shared. // */ // public void setUrl(String url) { // this.url = url; // } // // public String getTitle() { // return title; // } // // /** // * Optional. (MUST specify one of url or title!) // * The title of the content being shared. If the content does not have a url, you must at least provide a title. // * @param title The title of the content being shared. // */ // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // /** // * Optional. Corresponds to og:image // * @param imageUrl An image url corresponding to the content being shared. // */ // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getDescription() { // return description; // } // // /** // * Optional. Corresponds to og:description // * @param description The description of the content being shared. // */ // public void setDescription(String description) { // this.description = description; // } // // public String getVideoUrl() { // return videoUrl; // } // // /** // * Optional. Corresponds to og:video // * @param videoUrl A video url corresponding to the content being shared. // */ // public void setVideoUrl(String videoUrl) { // this.videoUrl = videoUrl; // } // // /** // * @return The custom tags associated with the item // */ // public Set<String> getTags() { // return tags; // } // // /** // * Optional. // * @param tags Any custom tags associated with the item // */ // public void setTags(Set<String> tags) { // this.tags = tags; // } // // public String getShortlink() { // return shortlink; // } // // void setShortlink(String shortlink) { // this.shortlink = shortlink; // } // // public synchronized void addTag(String tag) { // if(tags == null) { // tags = new LinkedHashSet<String>(); // } // tags.add(tag); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Item item = (Item) o; // // if (title != null ? !title.equals(item.title) : item.title != null) return false; // if (url != null ? !url.equals(item.url) : item.url != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = url != null ? url.hashCode() : 0; // result = 31 * result + (title != null ? title.hashCode() : 0); // return result; // } // // @Override // public String toString() { // if(url != null) { // return url; // } // else if(title != null) { // return title; // } // return super.toString(); // } // } // // Path: test/src/com/sharethis/loopy/sdk/MockItem.java // public class MockItem extends Item { // @Override // public void setShortlink(String shortlink) { // super.setShortlink(shortlink); // } // } // // Path: test/src/com/sharethis/loopy/sdk/MockShareCallback.java // public class MockShareCallback extends ShareCallback { // @Override // public void setItem(Item item) { // super.setItem(item); // } // // @Override // public void onBeforePost(Map<String, String> headers, JSONObject payload) { // super.onBeforePost(headers, payload); // } // // @Override // public void onResult(Item item, Throwable error) { // // } // }
import com.sharethis.loopy.sdk.Item; import com.sharethis.loopy.sdk.MockItem; import com.sharethis.loopy.sdk.MockShareCallback; import org.json.JSONException; import org.json.JSONObject; import org.mockito.Mockito;
package com.sharethis.loopy.test; /** * @author Jason Polites */ public class ShortenCallbackTest extends LoopyAndroidTestCase { public void testOnSuccess() throws JSONException {
// Path: sdk/src/com/sharethis/loopy/sdk/Item.java // public class Item { // // String type = "website"; // String url; // String title; // String imageUrl; // String description; // String videoUrl; // Set<String> tags; // // String shortlink; // // /** // * The "og:type" corresponding to the content being shared. // * @return og:type // */ // public String getType() { // return type; // } // // /** // * Optional. // * Corresponds to the og:type meta element. Default is 'website' // * @param type The type of the content being shared (og:type) // * @see <a href="http://ogp.me/#types" target="_blank">http://ogp.me/#types</a> // */ // public void setType(String type) { // this.type = type; // } // // public String getUrl() { // return url; // } // // /** // * Optional. (MUST specify one of url or title!) // * The url of the content being shared. If the content does not have a url, you must at least provide a title. // * @param url The url of the content being shared. // */ // public void setUrl(String url) { // this.url = url; // } // // public String getTitle() { // return title; // } // // /** // * Optional. (MUST specify one of url or title!) // * The title of the content being shared. If the content does not have a url, you must at least provide a title. // * @param title The title of the content being shared. // */ // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // /** // * Optional. Corresponds to og:image // * @param imageUrl An image url corresponding to the content being shared. // */ // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getDescription() { // return description; // } // // /** // * Optional. Corresponds to og:description // * @param description The description of the content being shared. // */ // public void setDescription(String description) { // this.description = description; // } // // public String getVideoUrl() { // return videoUrl; // } // // /** // * Optional. Corresponds to og:video // * @param videoUrl A video url corresponding to the content being shared. // */ // public void setVideoUrl(String videoUrl) { // this.videoUrl = videoUrl; // } // // /** // * @return The custom tags associated with the item // */ // public Set<String> getTags() { // return tags; // } // // /** // * Optional. // * @param tags Any custom tags associated with the item // */ // public void setTags(Set<String> tags) { // this.tags = tags; // } // // public String getShortlink() { // return shortlink; // } // // void setShortlink(String shortlink) { // this.shortlink = shortlink; // } // // public synchronized void addTag(String tag) { // if(tags == null) { // tags = new LinkedHashSet<String>(); // } // tags.add(tag); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Item item = (Item) o; // // if (title != null ? !title.equals(item.title) : item.title != null) return false; // if (url != null ? !url.equals(item.url) : item.url != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = url != null ? url.hashCode() : 0; // result = 31 * result + (title != null ? title.hashCode() : 0); // return result; // } // // @Override // public String toString() { // if(url != null) { // return url; // } // else if(title != null) { // return title; // } // return super.toString(); // } // } // // Path: test/src/com/sharethis/loopy/sdk/MockItem.java // public class MockItem extends Item { // @Override // public void setShortlink(String shortlink) { // super.setShortlink(shortlink); // } // } // // Path: test/src/com/sharethis/loopy/sdk/MockShareCallback.java // public class MockShareCallback extends ShareCallback { // @Override // public void setItem(Item item) { // super.setItem(item); // } // // @Override // public void onBeforePost(Map<String, String> headers, JSONObject payload) { // super.onBeforePost(headers, payload); // } // // @Override // public void onResult(Item item, Throwable error) { // // } // } // Path: test/src/com/sharethis/loopy/test/ShortenCallbackTest.java import com.sharethis.loopy.sdk.Item; import com.sharethis.loopy.sdk.MockItem; import com.sharethis.loopy.sdk.MockShareCallback; import org.json.JSONException; import org.json.JSONObject; import org.mockito.Mockito; package com.sharethis.loopy.test; /** * @author Jason Polites */ public class ShortenCallbackTest extends LoopyAndroidTestCase { public void testOnSuccess() throws JSONException {
MockShareCallback cb = new MockShareCallback() {
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/ShortenCallbackTest.java
// Path: sdk/src/com/sharethis/loopy/sdk/Item.java // public class Item { // // String type = "website"; // String url; // String title; // String imageUrl; // String description; // String videoUrl; // Set<String> tags; // // String shortlink; // // /** // * The "og:type" corresponding to the content being shared. // * @return og:type // */ // public String getType() { // return type; // } // // /** // * Optional. // * Corresponds to the og:type meta element. Default is 'website' // * @param type The type of the content being shared (og:type) // * @see <a href="http://ogp.me/#types" target="_blank">http://ogp.me/#types</a> // */ // public void setType(String type) { // this.type = type; // } // // public String getUrl() { // return url; // } // // /** // * Optional. (MUST specify one of url or title!) // * The url of the content being shared. If the content does not have a url, you must at least provide a title. // * @param url The url of the content being shared. // */ // public void setUrl(String url) { // this.url = url; // } // // public String getTitle() { // return title; // } // // /** // * Optional. (MUST specify one of url or title!) // * The title of the content being shared. If the content does not have a url, you must at least provide a title. // * @param title The title of the content being shared. // */ // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // /** // * Optional. Corresponds to og:image // * @param imageUrl An image url corresponding to the content being shared. // */ // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getDescription() { // return description; // } // // /** // * Optional. Corresponds to og:description // * @param description The description of the content being shared. // */ // public void setDescription(String description) { // this.description = description; // } // // public String getVideoUrl() { // return videoUrl; // } // // /** // * Optional. Corresponds to og:video // * @param videoUrl A video url corresponding to the content being shared. // */ // public void setVideoUrl(String videoUrl) { // this.videoUrl = videoUrl; // } // // /** // * @return The custom tags associated with the item // */ // public Set<String> getTags() { // return tags; // } // // /** // * Optional. // * @param tags Any custom tags associated with the item // */ // public void setTags(Set<String> tags) { // this.tags = tags; // } // // public String getShortlink() { // return shortlink; // } // // void setShortlink(String shortlink) { // this.shortlink = shortlink; // } // // public synchronized void addTag(String tag) { // if(tags == null) { // tags = new LinkedHashSet<String>(); // } // tags.add(tag); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Item item = (Item) o; // // if (title != null ? !title.equals(item.title) : item.title != null) return false; // if (url != null ? !url.equals(item.url) : item.url != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = url != null ? url.hashCode() : 0; // result = 31 * result + (title != null ? title.hashCode() : 0); // return result; // } // // @Override // public String toString() { // if(url != null) { // return url; // } // else if(title != null) { // return title; // } // return super.toString(); // } // } // // Path: test/src/com/sharethis/loopy/sdk/MockItem.java // public class MockItem extends Item { // @Override // public void setShortlink(String shortlink) { // super.setShortlink(shortlink); // } // } // // Path: test/src/com/sharethis/loopy/sdk/MockShareCallback.java // public class MockShareCallback extends ShareCallback { // @Override // public void setItem(Item item) { // super.setItem(item); // } // // @Override // public void onBeforePost(Map<String, String> headers, JSONObject payload) { // super.onBeforePost(headers, payload); // } // // @Override // public void onResult(Item item, Throwable error) { // // } // }
import com.sharethis.loopy.sdk.Item; import com.sharethis.loopy.sdk.MockItem; import com.sharethis.loopy.sdk.MockShareCallback; import org.json.JSONException; import org.json.JSONObject; import org.mockito.Mockito;
package com.sharethis.loopy.test; /** * @author Jason Polites */ public class ShortenCallbackTest extends LoopyAndroidTestCase { public void testOnSuccess() throws JSONException { MockShareCallback cb = new MockShareCallback() { @Override
// Path: sdk/src/com/sharethis/loopy/sdk/Item.java // public class Item { // // String type = "website"; // String url; // String title; // String imageUrl; // String description; // String videoUrl; // Set<String> tags; // // String shortlink; // // /** // * The "og:type" corresponding to the content being shared. // * @return og:type // */ // public String getType() { // return type; // } // // /** // * Optional. // * Corresponds to the og:type meta element. Default is 'website' // * @param type The type of the content being shared (og:type) // * @see <a href="http://ogp.me/#types" target="_blank">http://ogp.me/#types</a> // */ // public void setType(String type) { // this.type = type; // } // // public String getUrl() { // return url; // } // // /** // * Optional. (MUST specify one of url or title!) // * The url of the content being shared. If the content does not have a url, you must at least provide a title. // * @param url The url of the content being shared. // */ // public void setUrl(String url) { // this.url = url; // } // // public String getTitle() { // return title; // } // // /** // * Optional. (MUST specify one of url or title!) // * The title of the content being shared. If the content does not have a url, you must at least provide a title. // * @param title The title of the content being shared. // */ // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // /** // * Optional. Corresponds to og:image // * @param imageUrl An image url corresponding to the content being shared. // */ // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getDescription() { // return description; // } // // /** // * Optional. Corresponds to og:description // * @param description The description of the content being shared. // */ // public void setDescription(String description) { // this.description = description; // } // // public String getVideoUrl() { // return videoUrl; // } // // /** // * Optional. Corresponds to og:video // * @param videoUrl A video url corresponding to the content being shared. // */ // public void setVideoUrl(String videoUrl) { // this.videoUrl = videoUrl; // } // // /** // * @return The custom tags associated with the item // */ // public Set<String> getTags() { // return tags; // } // // /** // * Optional. // * @param tags Any custom tags associated with the item // */ // public void setTags(Set<String> tags) { // this.tags = tags; // } // // public String getShortlink() { // return shortlink; // } // // void setShortlink(String shortlink) { // this.shortlink = shortlink; // } // // public synchronized void addTag(String tag) { // if(tags == null) { // tags = new LinkedHashSet<String>(); // } // tags.add(tag); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Item item = (Item) o; // // if (title != null ? !title.equals(item.title) : item.title != null) return false; // if (url != null ? !url.equals(item.url) : item.url != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = url != null ? url.hashCode() : 0; // result = 31 * result + (title != null ? title.hashCode() : 0); // return result; // } // // @Override // public String toString() { // if(url != null) { // return url; // } // else if(title != null) { // return title; // } // return super.toString(); // } // } // // Path: test/src/com/sharethis/loopy/sdk/MockItem.java // public class MockItem extends Item { // @Override // public void setShortlink(String shortlink) { // super.setShortlink(shortlink); // } // } // // Path: test/src/com/sharethis/loopy/sdk/MockShareCallback.java // public class MockShareCallback extends ShareCallback { // @Override // public void setItem(Item item) { // super.setItem(item); // } // // @Override // public void onBeforePost(Map<String, String> headers, JSONObject payload) { // super.onBeforePost(headers, payload); // } // // @Override // public void onResult(Item item, Throwable error) { // // } // } // Path: test/src/com/sharethis/loopy/test/ShortenCallbackTest.java import com.sharethis.loopy.sdk.Item; import com.sharethis.loopy.sdk.MockItem; import com.sharethis.loopy.sdk.MockShareCallback; import org.json.JSONException; import org.json.JSONObject; import org.mockito.Mockito; package com.sharethis.loopy.test; /** * @author Jason Polites */ public class ShortenCallbackTest extends LoopyAndroidTestCase { public void testOnSuccess() throws JSONException { MockShareCallback cb = new MockShareCallback() { @Override
public void onResult(Item item, Throwable error) {
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/ShortenCallbackTest.java
// Path: sdk/src/com/sharethis/loopy/sdk/Item.java // public class Item { // // String type = "website"; // String url; // String title; // String imageUrl; // String description; // String videoUrl; // Set<String> tags; // // String shortlink; // // /** // * The "og:type" corresponding to the content being shared. // * @return og:type // */ // public String getType() { // return type; // } // // /** // * Optional. // * Corresponds to the og:type meta element. Default is 'website' // * @param type The type of the content being shared (og:type) // * @see <a href="http://ogp.me/#types" target="_blank">http://ogp.me/#types</a> // */ // public void setType(String type) { // this.type = type; // } // // public String getUrl() { // return url; // } // // /** // * Optional. (MUST specify one of url or title!) // * The url of the content being shared. If the content does not have a url, you must at least provide a title. // * @param url The url of the content being shared. // */ // public void setUrl(String url) { // this.url = url; // } // // public String getTitle() { // return title; // } // // /** // * Optional. (MUST specify one of url or title!) // * The title of the content being shared. If the content does not have a url, you must at least provide a title. // * @param title The title of the content being shared. // */ // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // /** // * Optional. Corresponds to og:image // * @param imageUrl An image url corresponding to the content being shared. // */ // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getDescription() { // return description; // } // // /** // * Optional. Corresponds to og:description // * @param description The description of the content being shared. // */ // public void setDescription(String description) { // this.description = description; // } // // public String getVideoUrl() { // return videoUrl; // } // // /** // * Optional. Corresponds to og:video // * @param videoUrl A video url corresponding to the content being shared. // */ // public void setVideoUrl(String videoUrl) { // this.videoUrl = videoUrl; // } // // /** // * @return The custom tags associated with the item // */ // public Set<String> getTags() { // return tags; // } // // /** // * Optional. // * @param tags Any custom tags associated with the item // */ // public void setTags(Set<String> tags) { // this.tags = tags; // } // // public String getShortlink() { // return shortlink; // } // // void setShortlink(String shortlink) { // this.shortlink = shortlink; // } // // public synchronized void addTag(String tag) { // if(tags == null) { // tags = new LinkedHashSet<String>(); // } // tags.add(tag); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Item item = (Item) o; // // if (title != null ? !title.equals(item.title) : item.title != null) return false; // if (url != null ? !url.equals(item.url) : item.url != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = url != null ? url.hashCode() : 0; // result = 31 * result + (title != null ? title.hashCode() : 0); // return result; // } // // @Override // public String toString() { // if(url != null) { // return url; // } // else if(title != null) { // return title; // } // return super.toString(); // } // } // // Path: test/src/com/sharethis/loopy/sdk/MockItem.java // public class MockItem extends Item { // @Override // public void setShortlink(String shortlink) { // super.setShortlink(shortlink); // } // } // // Path: test/src/com/sharethis/loopy/sdk/MockShareCallback.java // public class MockShareCallback extends ShareCallback { // @Override // public void setItem(Item item) { // super.setItem(item); // } // // @Override // public void onBeforePost(Map<String, String> headers, JSONObject payload) { // super.onBeforePost(headers, payload); // } // // @Override // public void onResult(Item item, Throwable error) { // // } // }
import com.sharethis.loopy.sdk.Item; import com.sharethis.loopy.sdk.MockItem; import com.sharethis.loopy.sdk.MockShareCallback; import org.json.JSONException; import org.json.JSONObject; import org.mockito.Mockito;
package com.sharethis.loopy.test; /** * @author Jason Polites */ public class ShortenCallbackTest extends LoopyAndroidTestCase { public void testOnSuccess() throws JSONException { MockShareCallback cb = new MockShareCallback() { @Override public void onResult(Item item, Throwable error) { } };
// Path: sdk/src/com/sharethis/loopy/sdk/Item.java // public class Item { // // String type = "website"; // String url; // String title; // String imageUrl; // String description; // String videoUrl; // Set<String> tags; // // String shortlink; // // /** // * The "og:type" corresponding to the content being shared. // * @return og:type // */ // public String getType() { // return type; // } // // /** // * Optional. // * Corresponds to the og:type meta element. Default is 'website' // * @param type The type of the content being shared (og:type) // * @see <a href="http://ogp.me/#types" target="_blank">http://ogp.me/#types</a> // */ // public void setType(String type) { // this.type = type; // } // // public String getUrl() { // return url; // } // // /** // * Optional. (MUST specify one of url or title!) // * The url of the content being shared. If the content does not have a url, you must at least provide a title. // * @param url The url of the content being shared. // */ // public void setUrl(String url) { // this.url = url; // } // // public String getTitle() { // return title; // } // // /** // * Optional. (MUST specify one of url or title!) // * The title of the content being shared. If the content does not have a url, you must at least provide a title. // * @param title The title of the content being shared. // */ // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // /** // * Optional. Corresponds to og:image // * @param imageUrl An image url corresponding to the content being shared. // */ // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getDescription() { // return description; // } // // /** // * Optional. Corresponds to og:description // * @param description The description of the content being shared. // */ // public void setDescription(String description) { // this.description = description; // } // // public String getVideoUrl() { // return videoUrl; // } // // /** // * Optional. Corresponds to og:video // * @param videoUrl A video url corresponding to the content being shared. // */ // public void setVideoUrl(String videoUrl) { // this.videoUrl = videoUrl; // } // // /** // * @return The custom tags associated with the item // */ // public Set<String> getTags() { // return tags; // } // // /** // * Optional. // * @param tags Any custom tags associated with the item // */ // public void setTags(Set<String> tags) { // this.tags = tags; // } // // public String getShortlink() { // return shortlink; // } // // void setShortlink(String shortlink) { // this.shortlink = shortlink; // } // // public synchronized void addTag(String tag) { // if(tags == null) { // tags = new LinkedHashSet<String>(); // } // tags.add(tag); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Item item = (Item) o; // // if (title != null ? !title.equals(item.title) : item.title != null) return false; // if (url != null ? !url.equals(item.url) : item.url != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = url != null ? url.hashCode() : 0; // result = 31 * result + (title != null ? title.hashCode() : 0); // return result; // } // // @Override // public String toString() { // if(url != null) { // return url; // } // else if(title != null) { // return title; // } // return super.toString(); // } // } // // Path: test/src/com/sharethis/loopy/sdk/MockItem.java // public class MockItem extends Item { // @Override // public void setShortlink(String shortlink) { // super.setShortlink(shortlink); // } // } // // Path: test/src/com/sharethis/loopy/sdk/MockShareCallback.java // public class MockShareCallback extends ShareCallback { // @Override // public void setItem(Item item) { // super.setItem(item); // } // // @Override // public void onBeforePost(Map<String, String> headers, JSONObject payload) { // super.onBeforePost(headers, payload); // } // // @Override // public void onResult(Item item, Throwable error) { // // } // } // Path: test/src/com/sharethis/loopy/test/ShortenCallbackTest.java import com.sharethis.loopy.sdk.Item; import com.sharethis.loopy.sdk.MockItem; import com.sharethis.loopy.sdk.MockShareCallback; import org.json.JSONException; import org.json.JSONObject; import org.mockito.Mockito; package com.sharethis.loopy.test; /** * @author Jason Polites */ public class ShortenCallbackTest extends LoopyAndroidTestCase { public void testOnSuccess() throws JSONException { MockShareCallback cb = new MockShareCallback() { @Override public void onResult(Item item, Throwable error) { } };
MockItem item = Mockito.mock(MockItem.class);
socialize/loopy-sdk-android
sdk/src/com/sharethis/loopy/sdk/util/JSONUtils.java
// Path: sdk/src/com/sharethis/loopy/sdk/Logger.java // public class Logger { // // static boolean debugEnabled = true; // static final String TAG = "Loopy"; // // public static void e(Throwable e) { // Log.e(TAG, e.getMessage(), e); // } // // public static void w(Throwable e) { // Log.w(TAG, e.getMessage(), e); // } // // public static void w(String s) { // Log.w(TAG, s); // } // // public static void e(String s) { // Log.e(TAG, s); // } // // public static boolean isDebugEnabled() { // return debugEnabled; // } // // public static void d(String s) { // Log.d(TAG, s); // } // // public static void setDebugEnabled(boolean debugEnabled) { // Logger.debugEnabled = debugEnabled; // } // }
import com.sharethis.loopy.sdk.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.Collection; import java.util.Map;
JSONArray arrayObject = new JSONArray(); Collection<?> collection = (Collection<?>) value; for (Object o : collection) { // TODO: This is not very robust. Needs to infer the type arrayObject.put(o.toString()); } object.put(key, arrayObject); } else { object.put(key, value); } return true; } else if(defaultValue != null) { object.put(key, defaultValue); return true; } return false; } public static boolean isNull(JSONObject object, String key) { return !object.has(key) || object.isNull(key); } public static String getString(JSONObject object, String key) { if(!isNull(object, key)) { try { return object.getString(key); } catch (JSONException e) {
// Path: sdk/src/com/sharethis/loopy/sdk/Logger.java // public class Logger { // // static boolean debugEnabled = true; // static final String TAG = "Loopy"; // // public static void e(Throwable e) { // Log.e(TAG, e.getMessage(), e); // } // // public static void w(Throwable e) { // Log.w(TAG, e.getMessage(), e); // } // // public static void w(String s) { // Log.w(TAG, s); // } // // public static void e(String s) { // Log.e(TAG, s); // } // // public static boolean isDebugEnabled() { // return debugEnabled; // } // // public static void d(String s) { // Log.d(TAG, s); // } // // public static void setDebugEnabled(boolean debugEnabled) { // Logger.debugEnabled = debugEnabled; // } // } // Path: sdk/src/com/sharethis/loopy/sdk/util/JSONUtils.java import com.sharethis.loopy.sdk.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.Collection; import java.util.Map; JSONArray arrayObject = new JSONArray(); Collection<?> collection = (Collection<?>) value; for (Object o : collection) { // TODO: This is not very robust. Needs to infer the type arrayObject.put(o.toString()); } object.put(key, arrayObject); } else { object.put(key, value); } return true; } else if(defaultValue != null) { object.put(key, defaultValue); return true; } return false; } public static boolean isNull(JSONObject object, String key) { return !object.has(key) || object.isNull(key); } public static String getString(JSONObject object, String key) { if(!isNull(object, key)) { try { return object.getString(key); } catch (JSONException e) {
Logger.e(e);
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/LoopyExceptionTest.java
// Path: sdk/src/com/sharethis/loopy/sdk/LoopyException.java // public class LoopyException extends RuntimeException { // // private final int code; // // public static final int INVALID_PARAMETER = 600; // public static final int PARAMETER_MISSING = 601; // public static final int PARSE_ERROR = 602; // public static final int CLIENT_TIMEOUT = 608; // // // public static final int LIFECYCLE_ERROR = 1000; // public static final int TIMEOUT = 1001; // public static final int INTERNAL_ERROR = 1200; // // public LoopyException(int code) { // super(); // this.code = code; // } // // public LoopyException(String detailMessage, int code) { // super(detailMessage); // this.code = code; // } // // public LoopyException(String detailMessage, Throwable throwable, int code) { // super(detailMessage, throwable); // this.code = code; // } // // public LoopyException(Throwable throwable, int code) { // super(throwable); // this.code = code; // } // // public int getCode() { // return code; // } // // public static LoopyException wrap(Exception e, int code) { // if(e instanceof LoopyException) { // return (LoopyException) e; // } // return new LoopyException(e, code); // } // }
import com.sharethis.loopy.sdk.LoopyException;
package com.sharethis.loopy.test; /** * @author Jason Polites */ public class LoopyExceptionTest extends LoopyAndroidTestCase { public void testExceptionConstructors() { int code = 69;
// Path: sdk/src/com/sharethis/loopy/sdk/LoopyException.java // public class LoopyException extends RuntimeException { // // private final int code; // // public static final int INVALID_PARAMETER = 600; // public static final int PARAMETER_MISSING = 601; // public static final int PARSE_ERROR = 602; // public static final int CLIENT_TIMEOUT = 608; // // // public static final int LIFECYCLE_ERROR = 1000; // public static final int TIMEOUT = 1001; // public static final int INTERNAL_ERROR = 1200; // // public LoopyException(int code) { // super(); // this.code = code; // } // // public LoopyException(String detailMessage, int code) { // super(detailMessage); // this.code = code; // } // // public LoopyException(String detailMessage, Throwable throwable, int code) { // super(detailMessage, throwable); // this.code = code; // } // // public LoopyException(Throwable throwable, int code) { // super(throwable); // this.code = code; // } // // public int getCode() { // return code; // } // // public static LoopyException wrap(Exception e, int code) { // if(e instanceof LoopyException) { // return (LoopyException) e; // } // return new LoopyException(e, code); // } // } // Path: test/src/com/sharethis/loopy/test/LoopyExceptionTest.java import com.sharethis.loopy.sdk.LoopyException; package com.sharethis.loopy.test; /** * @author Jason Polites */ public class LoopyExceptionTest extends LoopyAndroidTestCase { public void testExceptionConstructors() { int code = 69;
assertEquals(code, new LoopyException(code).getCode());
socialize/loopy-sdk-android
sdk/src/com/sharethis/loopy/sdk/util/ResourceLocator.java
// Path: sdk/src/com/sharethis/loopy/sdk/Logger.java // public class Logger { // // static boolean debugEnabled = true; // static final String TAG = "Loopy"; // // public static void e(Throwable e) { // Log.e(TAG, e.getMessage(), e); // } // // public static void w(Throwable e) { // Log.w(TAG, e.getMessage(), e); // } // // public static void w(String s) { // Log.w(TAG, s); // } // // public static void e(String s) { // Log.e(TAG, s); // } // // public static boolean isDebugEnabled() { // return debugEnabled; // } // // public static void d(String s) { // Log.d(TAG, s); // } // // public static void setDebugEnabled(boolean debugEnabled) { // Logger.debugEnabled = debugEnabled; // } // }
import android.content.Context; import com.sharethis.loopy.sdk.Logger; import java.io.IOException; import java.io.InputStream;
package com.sharethis.loopy.sdk.util; /** * @author Jason Polites */ public class ResourceLocator { private ClassLoaderProvider classLoaderProvider = new ClassLoaderProvider(); public InputStream locateInAssets(Context context, String name) throws IOException { InputStream in = null; try {
// Path: sdk/src/com/sharethis/loopy/sdk/Logger.java // public class Logger { // // static boolean debugEnabled = true; // static final String TAG = "Loopy"; // // public static void e(Throwable e) { // Log.e(TAG, e.getMessage(), e); // } // // public static void w(Throwable e) { // Log.w(TAG, e.getMessage(), e); // } // // public static void w(String s) { // Log.w(TAG, s); // } // // public static void e(String s) { // Log.e(TAG, s); // } // // public static boolean isDebugEnabled() { // return debugEnabled; // } // // public static void d(String s) { // Log.d(TAG, s); // } // // public static void setDebugEnabled(boolean debugEnabled) { // Logger.debugEnabled = debugEnabled; // } // } // Path: sdk/src/com/sharethis/loopy/sdk/util/ResourceLocator.java import android.content.Context; import com.sharethis.loopy.sdk.Logger; import java.io.IOException; import java.io.InputStream; package com.sharethis.loopy.sdk.util; /** * @author Jason Polites */ public class ResourceLocator { private ClassLoaderProvider classLoaderProvider = new ClassLoaderProvider(); public InputStream locateInAssets(Context context, String name) throws IOException { InputStream in = null; try {
if(Logger.isDebugEnabled()) {
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/IOUtilsTest.java
// Path: sdk/src/com/sharethis/loopy/sdk/util/IOUtils.java // public class IOUtils { // // /** // * Pipes input bytes to output. // * @param in The IN stream // * @param out The OUT stream // * @param bufferSize The buffer size // * @return The number of bytes written. // * @throws IOException // */ // public static long pipe(InputStream in, OutputStream out, int bufferSize) throws IOException { // int read; // long total = 0L; // byte[] buffer = new byte[bufferSize]; // while((read = in.read(buffer)) >= 0) { // total+=read; // out.write(buffer, 0, read); // } // out.flush(); // return total; // } // // public static String read(InputStream in, int bufferSize) throws IOException { // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // pipe(in, bout, bufferSize); // return new String(bout.toByteArray(), "utf-8"); // } // // }
import com.sharethis.loopy.sdk.util.IOUtils; import java.io.ByteArrayInputStream; import java.io.IOException;
package com.sharethis.loopy.test; /** * @author Jason Polites */ public class IOUtilsTest extends LoopyAndroidTestCase { public void testRead() throws IOException { String testData = "the quick brown fox jumps over the lazy dog"; ByteArrayInputStream in0 = new ByteArrayInputStream(testData.getBytes()); ByteArrayInputStream in1 = new ByteArrayInputStream(testData.getBytes());
// Path: sdk/src/com/sharethis/loopy/sdk/util/IOUtils.java // public class IOUtils { // // /** // * Pipes input bytes to output. // * @param in The IN stream // * @param out The OUT stream // * @param bufferSize The buffer size // * @return The number of bytes written. // * @throws IOException // */ // public static long pipe(InputStream in, OutputStream out, int bufferSize) throws IOException { // int read; // long total = 0L; // byte[] buffer = new byte[bufferSize]; // while((read = in.read(buffer)) >= 0) { // total+=read; // out.write(buffer, 0, read); // } // out.flush(); // return total; // } // // public static String read(InputStream in, int bufferSize) throws IOException { // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // pipe(in, bout, bufferSize); // return new String(bout.toByteArray(), "utf-8"); // } // // } // Path: test/src/com/sharethis/loopy/test/IOUtilsTest.java import com.sharethis.loopy.sdk.util.IOUtils; import java.io.ByteArrayInputStream; import java.io.IOException; package com.sharethis.loopy.test; /** * @author Jason Polites */ public class IOUtilsTest extends LoopyAndroidTestCase { public void testRead() throws IOException { String testData = "the quick brown fox jumps over the lazy dog"; ByteArrayInputStream in0 = new ByteArrayInputStream(testData.getBytes()); ByteArrayInputStream in1 = new ByteArrayInputStream(testData.getBytes());
String out0 = IOUtils.read(in0, 1024);
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/LoopyInstrumentationTestCase.java
// Path: sdk/src/com/sharethis/loopy/sdk/Logger.java // public class Logger { // // static boolean debugEnabled = true; // static final String TAG = "Loopy"; // // public static void e(Throwable e) { // Log.e(TAG, e.getMessage(), e); // } // // public static void w(Throwable e) { // Log.w(TAG, e.getMessage(), e); // } // // public static void w(String s) { // Log.w(TAG, s); // } // // public static void e(String s) { // Log.e(TAG, s); // } // // public static boolean isDebugEnabled() { // return debugEnabled; // } // // public static void d(String s) { // Log.d(TAG, s); // } // // public static void setDebugEnabled(boolean debugEnabled) { // Logger.debugEnabled = debugEnabled; // } // } // // Path: test/src/com/sharethis/loopy/test/util/SystemUtils.java // public class SystemUtils { // // static File cacheDir; // // public static File getCacheDir(Context context) { // if(cacheDir == null) { // File dataDir = new File("/data/data/" + context.getPackageName()); // cacheDir = new File(dataDir, "cache"); // if (!cacheDir.exists() && !cacheDir.mkdir()) { // Logger.w("Failed to create cache dir in [" + // cacheDir + // "]"); // cacheDir = null; // } // } // return cacheDir; // } // // public static File getCacheDir() { // return cacheDir; // } // }
import android.app.Activity; import android.content.Context; import android.test.ActivityInstrumentationTestCase2; import com.sharethis.loopy.sdk.Logger; import com.sharethis.loopy.test.util.SystemUtils; import java.io.File;
package com.sharethis.loopy.test; /** * @author Jason Polites */ public abstract class LoopyInstrumentationTestCase<T extends Activity> extends ActivityInstrumentationTestCase2<T> { public LoopyInstrumentationTestCase(Class<T> activityClass) { super(activityClass); } @Override public void setUp() throws Exception { super.setUp();
// Path: sdk/src/com/sharethis/loopy/sdk/Logger.java // public class Logger { // // static boolean debugEnabled = true; // static final String TAG = "Loopy"; // // public static void e(Throwable e) { // Log.e(TAG, e.getMessage(), e); // } // // public static void w(Throwable e) { // Log.w(TAG, e.getMessage(), e); // } // // public static void w(String s) { // Log.w(TAG, s); // } // // public static void e(String s) { // Log.e(TAG, s); // } // // public static boolean isDebugEnabled() { // return debugEnabled; // } // // public static void d(String s) { // Log.d(TAG, s); // } // // public static void setDebugEnabled(boolean debugEnabled) { // Logger.debugEnabled = debugEnabled; // } // } // // Path: test/src/com/sharethis/loopy/test/util/SystemUtils.java // public class SystemUtils { // // static File cacheDir; // // public static File getCacheDir(Context context) { // if(cacheDir == null) { // File dataDir = new File("/data/data/" + context.getPackageName()); // cacheDir = new File(dataDir, "cache"); // if (!cacheDir.exists() && !cacheDir.mkdir()) { // Logger.w("Failed to create cache dir in [" + // cacheDir + // "]"); // cacheDir = null; // } // } // return cacheDir; // } // // public static File getCacheDir() { // return cacheDir; // } // } // Path: test/src/com/sharethis/loopy/test/LoopyInstrumentationTestCase.java import android.app.Activity; import android.content.Context; import android.test.ActivityInstrumentationTestCase2; import com.sharethis.loopy.sdk.Logger; import com.sharethis.loopy.test.util.SystemUtils; import java.io.File; package com.sharethis.loopy.test; /** * @author Jason Polites */ public abstract class LoopyInstrumentationTestCase<T extends Activity> extends ActivityInstrumentationTestCase2<T> { public LoopyInstrumentationTestCase(Class<T> activityClass) { super(activityClass); } @Override public void setUp() throws Exception { super.setUp();
Logger.setDebugEnabled(true);
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/LoopyInstrumentationTestCase.java
// Path: sdk/src/com/sharethis/loopy/sdk/Logger.java // public class Logger { // // static boolean debugEnabled = true; // static final String TAG = "Loopy"; // // public static void e(Throwable e) { // Log.e(TAG, e.getMessage(), e); // } // // public static void w(Throwable e) { // Log.w(TAG, e.getMessage(), e); // } // // public static void w(String s) { // Log.w(TAG, s); // } // // public static void e(String s) { // Log.e(TAG, s); // } // // public static boolean isDebugEnabled() { // return debugEnabled; // } // // public static void d(String s) { // Log.d(TAG, s); // } // // public static void setDebugEnabled(boolean debugEnabled) { // Logger.debugEnabled = debugEnabled; // } // } // // Path: test/src/com/sharethis/loopy/test/util/SystemUtils.java // public class SystemUtils { // // static File cacheDir; // // public static File getCacheDir(Context context) { // if(cacheDir == null) { // File dataDir = new File("/data/data/" + context.getPackageName()); // cacheDir = new File(dataDir, "cache"); // if (!cacheDir.exists() && !cacheDir.mkdir()) { // Logger.w("Failed to create cache dir in [" + // cacheDir + // "]"); // cacheDir = null; // } // } // return cacheDir; // } // // public static File getCacheDir() { // return cacheDir; // } // }
import android.app.Activity; import android.content.Context; import android.test.ActivityInstrumentationTestCase2; import com.sharethis.loopy.sdk.Logger; import com.sharethis.loopy.test.util.SystemUtils; import java.io.File;
package com.sharethis.loopy.test; /** * @author Jason Polites */ public abstract class LoopyInstrumentationTestCase<T extends Activity> extends ActivityInstrumentationTestCase2<T> { public LoopyInstrumentationTestCase(Class<T> activityClass) { super(activityClass); } @Override public void setUp() throws Exception { super.setUp(); Logger.setDebugEnabled(true); // Fix for bug https://code.google.com/p/dexmaker/issues/detail?id=2
// Path: sdk/src/com/sharethis/loopy/sdk/Logger.java // public class Logger { // // static boolean debugEnabled = true; // static final String TAG = "Loopy"; // // public static void e(Throwable e) { // Log.e(TAG, e.getMessage(), e); // } // // public static void w(Throwable e) { // Log.w(TAG, e.getMessage(), e); // } // // public static void w(String s) { // Log.w(TAG, s); // } // // public static void e(String s) { // Log.e(TAG, s); // } // // public static boolean isDebugEnabled() { // return debugEnabled; // } // // public static void d(String s) { // Log.d(TAG, s); // } // // public static void setDebugEnabled(boolean debugEnabled) { // Logger.debugEnabled = debugEnabled; // } // } // // Path: test/src/com/sharethis/loopy/test/util/SystemUtils.java // public class SystemUtils { // // static File cacheDir; // // public static File getCacheDir(Context context) { // if(cacheDir == null) { // File dataDir = new File("/data/data/" + context.getPackageName()); // cacheDir = new File(dataDir, "cache"); // if (!cacheDir.exists() && !cacheDir.mkdir()) { // Logger.w("Failed to create cache dir in [" + // cacheDir + // "]"); // cacheDir = null; // } // } // return cacheDir; // } // // public static File getCacheDir() { // return cacheDir; // } // } // Path: test/src/com/sharethis/loopy/test/LoopyInstrumentationTestCase.java import android.app.Activity; import android.content.Context; import android.test.ActivityInstrumentationTestCase2; import com.sharethis.loopy.sdk.Logger; import com.sharethis.loopy.test.util.SystemUtils; import java.io.File; package com.sharethis.loopy.test; /** * @author Jason Polites */ public abstract class LoopyInstrumentationTestCase<T extends Activity> extends ActivityInstrumentationTestCase2<T> { public LoopyInstrumentationTestCase(Class<T> activityClass) { super(activityClass); } @Override public void setUp() throws Exception { super.setUp(); Logger.setDebugEnabled(true); // Fix for bug https://code.google.com/p/dexmaker/issues/detail?id=2
File cacheDir = SystemUtils.getCacheDir(getContext());
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/NetworkStateTest.java
// Path: sdk/src/com/sharethis/loopy/sdk/net/HttpClientFactory.java // public class HttpClientFactory { // // public static final int DEFAULT_CONNECTION_TIMEOUT = 1000; // public static final int DEFAULT_READ_TIMEOUT = 1000; // // private HttpParams params; // private ClientConnectionManager connectionManager; // private DefaultHttpClient client; // This should be thread safe // private IdleConnectionMonitorThread monitor; // private boolean initialized = false; // // private int connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; // private int readTimeout = DEFAULT_READ_TIMEOUT; // // public void start(int timeout) { // setConnectionTimeout(timeout); // setReadTimeout(timeout); // init(); // } // // public void stop() { // destroy(); // } // // void init() { // if(!initialized) { // // params = new BasicHttpParams(); // // HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); // HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); // HttpConnectionParams.setSoTimeout(params, readTimeout); // // SchemeRegistry registry = new SchemeRegistry(); // registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); // // connectionManager = new ThreadSafeClientConnManager(params, registry); // // monitor = new IdleConnectionMonitorThread(connectionManager); // monitor.setDaemon(true); // monitor.start(); // } // } // // void destroy() { // if(initialized) { // initialized = false; // if(monitor != null) { // monitor.shutdown(); // } // if(connectionManager != null) { // connectionManager.shutdown(); // } // } // } // // public synchronized HttpClient getClient() { // if(client == null) { // client = new DefaultHttpClient(connectionManager, params); // } // else { // monitor.trigger(); // } // // return client; // } // // public int getConnectionTimeout() { // return connectionTimeout; // } // // public void setConnectionTimeout(int connectionTimeout) { // this.connectionTimeout = connectionTimeout; // } // // public int getReadTimeout() { // return readTimeout; // } // // public void setReadTimeout(int readTimeout) { // this.readTimeout = readTimeout; // } // } // // Path: test/src/com/sharethis/loopy/test/util/Holder.java // public class Holder<T> { // // private T object; // // private List<T> objects = new ArrayList<T>(); // // public Holder() {} // // public Holder(T object) { // super(); // this.object = object; // } // // public T get() { // return object; // } // // public void set(T object) { // this.object = object; // } // // public void add(T object) { // objects.add(object); // } // // public List<T> getObjects() { // return objects; // } // }
import java.io.IOException; import java.net.SocketTimeoutException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import com.sharethis.loopy.sdk.*; import com.sharethis.loopy.sdk.net.HttpClientFactory; import com.sharethis.loopy.test.util.Holder; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.mockito.Mockito;
/* * * * Copyright (c) 2013 ShareThis Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * * THE SOFTWARE. * */ package com.sharethis.loopy.test; /** * @author Jason Polites */ public class NetworkStateTest extends LoopyAndroidTestCase { @Override public void setUp() throws Exception { super.setUp(); Loopy.onStart(getContext()); } @Override public void tearDown() throws Exception { super.tearDown(); Loopy.onStop(getContext()); } // Not a REAL test, but we can't test network because disabling network on device kills adb. public void testShortenReturnsWhenNoNetwork() throws InterruptedException, IOException { Session.getInstance().waitForStart(); final String url = "foobar";
// Path: sdk/src/com/sharethis/loopy/sdk/net/HttpClientFactory.java // public class HttpClientFactory { // // public static final int DEFAULT_CONNECTION_TIMEOUT = 1000; // public static final int DEFAULT_READ_TIMEOUT = 1000; // // private HttpParams params; // private ClientConnectionManager connectionManager; // private DefaultHttpClient client; // This should be thread safe // private IdleConnectionMonitorThread monitor; // private boolean initialized = false; // // private int connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; // private int readTimeout = DEFAULT_READ_TIMEOUT; // // public void start(int timeout) { // setConnectionTimeout(timeout); // setReadTimeout(timeout); // init(); // } // // public void stop() { // destroy(); // } // // void init() { // if(!initialized) { // // params = new BasicHttpParams(); // // HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); // HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); // HttpConnectionParams.setSoTimeout(params, readTimeout); // // SchemeRegistry registry = new SchemeRegistry(); // registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); // // connectionManager = new ThreadSafeClientConnManager(params, registry); // // monitor = new IdleConnectionMonitorThread(connectionManager); // monitor.setDaemon(true); // monitor.start(); // } // } // // void destroy() { // if(initialized) { // initialized = false; // if(monitor != null) { // monitor.shutdown(); // } // if(connectionManager != null) { // connectionManager.shutdown(); // } // } // } // // public synchronized HttpClient getClient() { // if(client == null) { // client = new DefaultHttpClient(connectionManager, params); // } // else { // monitor.trigger(); // } // // return client; // } // // public int getConnectionTimeout() { // return connectionTimeout; // } // // public void setConnectionTimeout(int connectionTimeout) { // this.connectionTimeout = connectionTimeout; // } // // public int getReadTimeout() { // return readTimeout; // } // // public void setReadTimeout(int readTimeout) { // this.readTimeout = readTimeout; // } // } // // Path: test/src/com/sharethis/loopy/test/util/Holder.java // public class Holder<T> { // // private T object; // // private List<T> objects = new ArrayList<T>(); // // public Holder() {} // // public Holder(T object) { // super(); // this.object = object; // } // // public T get() { // return object; // } // // public void set(T object) { // this.object = object; // } // // public void add(T object) { // objects.add(object); // } // // public List<T> getObjects() { // return objects; // } // } // Path: test/src/com/sharethis/loopy/test/NetworkStateTest.java import java.io.IOException; import java.net.SocketTimeoutException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import com.sharethis.loopy.sdk.*; import com.sharethis.loopy.sdk.net.HttpClientFactory; import com.sharethis.loopy.test.util.Holder; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.mockito.Mockito; /* * * * Copyright (c) 2013 ShareThis Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * * THE SOFTWARE. * */ package com.sharethis.loopy.test; /** * @author Jason Polites */ public class NetworkStateTest extends LoopyAndroidTestCase { @Override public void setUp() throws Exception { super.setUp(); Loopy.onStart(getContext()); } @Override public void tearDown() throws Exception { super.tearDown(); Loopy.onStop(getContext()); } // Not a REAL test, but we can't test network because disabling network on device kills adb. public void testShortenReturnsWhenNoNetwork() throws InterruptedException, IOException { Session.getInstance().waitForStart(); final String url = "foobar";
final Holder<Item> result = new Holder<Item>();
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/NetworkStateTest.java
// Path: sdk/src/com/sharethis/loopy/sdk/net/HttpClientFactory.java // public class HttpClientFactory { // // public static final int DEFAULT_CONNECTION_TIMEOUT = 1000; // public static final int DEFAULT_READ_TIMEOUT = 1000; // // private HttpParams params; // private ClientConnectionManager connectionManager; // private DefaultHttpClient client; // This should be thread safe // private IdleConnectionMonitorThread monitor; // private boolean initialized = false; // // private int connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; // private int readTimeout = DEFAULT_READ_TIMEOUT; // // public void start(int timeout) { // setConnectionTimeout(timeout); // setReadTimeout(timeout); // init(); // } // // public void stop() { // destroy(); // } // // void init() { // if(!initialized) { // // params = new BasicHttpParams(); // // HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); // HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); // HttpConnectionParams.setSoTimeout(params, readTimeout); // // SchemeRegistry registry = new SchemeRegistry(); // registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); // // connectionManager = new ThreadSafeClientConnManager(params, registry); // // monitor = new IdleConnectionMonitorThread(connectionManager); // monitor.setDaemon(true); // monitor.start(); // } // } // // void destroy() { // if(initialized) { // initialized = false; // if(monitor != null) { // monitor.shutdown(); // } // if(connectionManager != null) { // connectionManager.shutdown(); // } // } // } // // public synchronized HttpClient getClient() { // if(client == null) { // client = new DefaultHttpClient(connectionManager, params); // } // else { // monitor.trigger(); // } // // return client; // } // // public int getConnectionTimeout() { // return connectionTimeout; // } // // public void setConnectionTimeout(int connectionTimeout) { // this.connectionTimeout = connectionTimeout; // } // // public int getReadTimeout() { // return readTimeout; // } // // public void setReadTimeout(int readTimeout) { // this.readTimeout = readTimeout; // } // } // // Path: test/src/com/sharethis/loopy/test/util/Holder.java // public class Holder<T> { // // private T object; // // private List<T> objects = new ArrayList<T>(); // // public Holder() {} // // public Holder(T object) { // super(); // this.object = object; // } // // public T get() { // return object; // } // // public void set(T object) { // this.object = object; // } // // public void add(T object) { // objects.add(object); // } // // public List<T> getObjects() { // return objects; // } // }
import java.io.IOException; import java.net.SocketTimeoutException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import com.sharethis.loopy.sdk.*; import com.sharethis.loopy.sdk.net.HttpClientFactory; import com.sharethis.loopy.test.util.Holder; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.mockito.Mockito;
/* * * * Copyright (c) 2013 ShareThis Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * * THE SOFTWARE. * */ package com.sharethis.loopy.test; /** * @author Jason Polites */ public class NetworkStateTest extends LoopyAndroidTestCase { @Override public void setUp() throws Exception { super.setUp(); Loopy.onStart(getContext()); } @Override public void tearDown() throws Exception { super.tearDown(); Loopy.onStop(getContext()); } // Not a REAL test, but we can't test network because disabling network on device kills adb. public void testShortenReturnsWhenNoNetwork() throws InterruptedException, IOException { Session.getInstance().waitForStart(); final String url = "foobar"; final Holder<Item> result = new Holder<Item>(); final Holder<Throwable> resultThrowable = new Holder<Throwable>(); final CountDownLatch latch = new CountDownLatch(1);
// Path: sdk/src/com/sharethis/loopy/sdk/net/HttpClientFactory.java // public class HttpClientFactory { // // public static final int DEFAULT_CONNECTION_TIMEOUT = 1000; // public static final int DEFAULT_READ_TIMEOUT = 1000; // // private HttpParams params; // private ClientConnectionManager connectionManager; // private DefaultHttpClient client; // This should be thread safe // private IdleConnectionMonitorThread monitor; // private boolean initialized = false; // // private int connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; // private int readTimeout = DEFAULT_READ_TIMEOUT; // // public void start(int timeout) { // setConnectionTimeout(timeout); // setReadTimeout(timeout); // init(); // } // // public void stop() { // destroy(); // } // // void init() { // if(!initialized) { // // params = new BasicHttpParams(); // // HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); // HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); // HttpConnectionParams.setSoTimeout(params, readTimeout); // // SchemeRegistry registry = new SchemeRegistry(); // registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); // // connectionManager = new ThreadSafeClientConnManager(params, registry); // // monitor = new IdleConnectionMonitorThread(connectionManager); // monitor.setDaemon(true); // monitor.start(); // } // } // // void destroy() { // if(initialized) { // initialized = false; // if(monitor != null) { // monitor.shutdown(); // } // if(connectionManager != null) { // connectionManager.shutdown(); // } // } // } // // public synchronized HttpClient getClient() { // if(client == null) { // client = new DefaultHttpClient(connectionManager, params); // } // else { // monitor.trigger(); // } // // return client; // } // // public int getConnectionTimeout() { // return connectionTimeout; // } // // public void setConnectionTimeout(int connectionTimeout) { // this.connectionTimeout = connectionTimeout; // } // // public int getReadTimeout() { // return readTimeout; // } // // public void setReadTimeout(int readTimeout) { // this.readTimeout = readTimeout; // } // } // // Path: test/src/com/sharethis/loopy/test/util/Holder.java // public class Holder<T> { // // private T object; // // private List<T> objects = new ArrayList<T>(); // // public Holder() {} // // public Holder(T object) { // super(); // this.object = object; // } // // public T get() { // return object; // } // // public void set(T object) { // this.object = object; // } // // public void add(T object) { // objects.add(object); // } // // public List<T> getObjects() { // return objects; // } // } // Path: test/src/com/sharethis/loopy/test/NetworkStateTest.java import java.io.IOException; import java.net.SocketTimeoutException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import com.sharethis.loopy.sdk.*; import com.sharethis.loopy.sdk.net.HttpClientFactory; import com.sharethis.loopy.test.util.Holder; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.mockito.Mockito; /* * * * Copyright (c) 2013 ShareThis Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * * THE SOFTWARE. * */ package com.sharethis.loopy.test; /** * @author Jason Polites */ public class NetworkStateTest extends LoopyAndroidTestCase { @Override public void setUp() throws Exception { super.setUp(); Loopy.onStart(getContext()); } @Override public void tearDown() throws Exception { super.tearDown(); Loopy.onStop(getContext()); } // Not a REAL test, but we can't test network because disabling network on device kills adb. public void testShortenReturnsWhenNoNetwork() throws InterruptedException, IOException { Session.getInstance().waitForStart(); final String url = "foobar"; final Holder<Item> result = new Holder<Item>(); final Holder<Throwable> resultThrowable = new Holder<Throwable>(); final CountDownLatch latch = new CountDownLatch(1);
HttpClientFactory httpClientFactory = Mockito.mock(HttpClientFactory.class);
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/LoopyActivityTestCase.java
// Path: sdk/src/com/sharethis/loopy/sdk/Logger.java // public class Logger { // // static boolean debugEnabled = true; // static final String TAG = "Loopy"; // // public static void e(Throwable e) { // Log.e(TAG, e.getMessage(), e); // } // // public static void w(Throwable e) { // Log.w(TAG, e.getMessage(), e); // } // // public static void w(String s) { // Log.w(TAG, s); // } // // public static void e(String s) { // Log.e(TAG, s); // } // // public static boolean isDebugEnabled() { // return debugEnabled; // } // // public static void d(String s) { // Log.d(TAG, s); // } // // public static void setDebugEnabled(boolean debugEnabled) { // Logger.debugEnabled = debugEnabled; // } // } // // Path: test/src/com/sharethis/loopy/sdk/_EmptyActivity.java // public class _EmptyActivity extends Activity { // } // // Path: test/src/com/sharethis/loopy/test/util/SystemUtils.java // public class SystemUtils { // // static File cacheDir; // // public static File getCacheDir(Context context) { // if(cacheDir == null) { // File dataDir = new File("/data/data/" + context.getPackageName()); // cacheDir = new File(dataDir, "cache"); // if (!cacheDir.exists() && !cacheDir.mkdir()) { // Logger.w("Failed to create cache dir in [" + // cacheDir + // "]"); // cacheDir = null; // } // } // return cacheDir; // } // // public static File getCacheDir() { // return cacheDir; // } // }
import android.content.Context; import com.sharethis.loopy.sdk.Logger; import com.sharethis.loopy.sdk._EmptyActivity; import com.sharethis.loopy.test.util.SystemUtils; import java.io.File;
package com.sharethis.loopy.test; /** * @author Jason Polites */ public abstract class LoopyActivityTestCase extends LoopyInstrumentationTestCase<_EmptyActivity> { protected LoopyActivityTestCase() { super(_EmptyActivity.class); } @Override public void setUp() throws Exception { super.setUp();
// Path: sdk/src/com/sharethis/loopy/sdk/Logger.java // public class Logger { // // static boolean debugEnabled = true; // static final String TAG = "Loopy"; // // public static void e(Throwable e) { // Log.e(TAG, e.getMessage(), e); // } // // public static void w(Throwable e) { // Log.w(TAG, e.getMessage(), e); // } // // public static void w(String s) { // Log.w(TAG, s); // } // // public static void e(String s) { // Log.e(TAG, s); // } // // public static boolean isDebugEnabled() { // return debugEnabled; // } // // public static void d(String s) { // Log.d(TAG, s); // } // // public static void setDebugEnabled(boolean debugEnabled) { // Logger.debugEnabled = debugEnabled; // } // } // // Path: test/src/com/sharethis/loopy/sdk/_EmptyActivity.java // public class _EmptyActivity extends Activity { // } // // Path: test/src/com/sharethis/loopy/test/util/SystemUtils.java // public class SystemUtils { // // static File cacheDir; // // public static File getCacheDir(Context context) { // if(cacheDir == null) { // File dataDir = new File("/data/data/" + context.getPackageName()); // cacheDir = new File(dataDir, "cache"); // if (!cacheDir.exists() && !cacheDir.mkdir()) { // Logger.w("Failed to create cache dir in [" + // cacheDir + // "]"); // cacheDir = null; // } // } // return cacheDir; // } // // public static File getCacheDir() { // return cacheDir; // } // } // Path: test/src/com/sharethis/loopy/test/LoopyActivityTestCase.java import android.content.Context; import com.sharethis.loopy.sdk.Logger; import com.sharethis.loopy.sdk._EmptyActivity; import com.sharethis.loopy.test.util.SystemUtils; import java.io.File; package com.sharethis.loopy.test; /** * @author Jason Polites */ public abstract class LoopyActivityTestCase extends LoopyInstrumentationTestCase<_EmptyActivity> { protected LoopyActivityTestCase() { super(_EmptyActivity.class); } @Override public void setUp() throws Exception { super.setUp();
Logger.setDebugEnabled(true);
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/LoopyActivityTestCase.java
// Path: sdk/src/com/sharethis/loopy/sdk/Logger.java // public class Logger { // // static boolean debugEnabled = true; // static final String TAG = "Loopy"; // // public static void e(Throwable e) { // Log.e(TAG, e.getMessage(), e); // } // // public static void w(Throwable e) { // Log.w(TAG, e.getMessage(), e); // } // // public static void w(String s) { // Log.w(TAG, s); // } // // public static void e(String s) { // Log.e(TAG, s); // } // // public static boolean isDebugEnabled() { // return debugEnabled; // } // // public static void d(String s) { // Log.d(TAG, s); // } // // public static void setDebugEnabled(boolean debugEnabled) { // Logger.debugEnabled = debugEnabled; // } // } // // Path: test/src/com/sharethis/loopy/sdk/_EmptyActivity.java // public class _EmptyActivity extends Activity { // } // // Path: test/src/com/sharethis/loopy/test/util/SystemUtils.java // public class SystemUtils { // // static File cacheDir; // // public static File getCacheDir(Context context) { // if(cacheDir == null) { // File dataDir = new File("/data/data/" + context.getPackageName()); // cacheDir = new File(dataDir, "cache"); // if (!cacheDir.exists() && !cacheDir.mkdir()) { // Logger.w("Failed to create cache dir in [" + // cacheDir + // "]"); // cacheDir = null; // } // } // return cacheDir; // } // // public static File getCacheDir() { // return cacheDir; // } // }
import android.content.Context; import com.sharethis.loopy.sdk.Logger; import com.sharethis.loopy.sdk._EmptyActivity; import com.sharethis.loopy.test.util.SystemUtils; import java.io.File;
package com.sharethis.loopy.test; /** * @author Jason Polites */ public abstract class LoopyActivityTestCase extends LoopyInstrumentationTestCase<_EmptyActivity> { protected LoopyActivityTestCase() { super(_EmptyActivity.class); } @Override public void setUp() throws Exception { super.setUp(); Logger.setDebugEnabled(true); // Fix for bug https://code.google.com/p/dexmaker/issues/detail?id=2
// Path: sdk/src/com/sharethis/loopy/sdk/Logger.java // public class Logger { // // static boolean debugEnabled = true; // static final String TAG = "Loopy"; // // public static void e(Throwable e) { // Log.e(TAG, e.getMessage(), e); // } // // public static void w(Throwable e) { // Log.w(TAG, e.getMessage(), e); // } // // public static void w(String s) { // Log.w(TAG, s); // } // // public static void e(String s) { // Log.e(TAG, s); // } // // public static boolean isDebugEnabled() { // return debugEnabled; // } // // public static void d(String s) { // Log.d(TAG, s); // } // // public static void setDebugEnabled(boolean debugEnabled) { // Logger.debugEnabled = debugEnabled; // } // } // // Path: test/src/com/sharethis/loopy/sdk/_EmptyActivity.java // public class _EmptyActivity extends Activity { // } // // Path: test/src/com/sharethis/loopy/test/util/SystemUtils.java // public class SystemUtils { // // static File cacheDir; // // public static File getCacheDir(Context context) { // if(cacheDir == null) { // File dataDir = new File("/data/data/" + context.getPackageName()); // cacheDir = new File(dataDir, "cache"); // if (!cacheDir.exists() && !cacheDir.mkdir()) { // Logger.w("Failed to create cache dir in [" + // cacheDir + // "]"); // cacheDir = null; // } // } // return cacheDir; // } // // public static File getCacheDir() { // return cacheDir; // } // } // Path: test/src/com/sharethis/loopy/test/LoopyActivityTestCase.java import android.content.Context; import com.sharethis.loopy.sdk.Logger; import com.sharethis.loopy.sdk._EmptyActivity; import com.sharethis.loopy.test.util.SystemUtils; import java.io.File; package com.sharethis.loopy.test; /** * @author Jason Polites */ public abstract class LoopyActivityTestCase extends LoopyInstrumentationTestCase<_EmptyActivity> { protected LoopyActivityTestCase() { super(_EmptyActivity.class); } @Override public void setUp() throws Exception { super.setUp(); Logger.setDebugEnabled(true); // Fix for bug https://code.google.com/p/dexmaker/issues/detail?id=2
File cacheDir = SystemUtils.getCacheDir(getInstrumentation().getTargetContext());
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/util/SystemUtils.java
// Path: sdk/src/com/sharethis/loopy/sdk/Logger.java // public class Logger { // // static boolean debugEnabled = true; // static final String TAG = "Loopy"; // // public static void e(Throwable e) { // Log.e(TAG, e.getMessage(), e); // } // // public static void w(Throwable e) { // Log.w(TAG, e.getMessage(), e); // } // // public static void w(String s) { // Log.w(TAG, s); // } // // public static void e(String s) { // Log.e(TAG, s); // } // // public static boolean isDebugEnabled() { // return debugEnabled; // } // // public static void d(String s) { // Log.d(TAG, s); // } // // public static void setDebugEnabled(boolean debugEnabled) { // Logger.debugEnabled = debugEnabled; // } // }
import android.content.Context; import com.sharethis.loopy.sdk.Logger; import java.io.File;
package com.sharethis.loopy.test.util; /** * @author Jason Polites */ public class SystemUtils { static File cacheDir; public static File getCacheDir(Context context) { if(cacheDir == null) { File dataDir = new File("/data/data/" + context.getPackageName()); cacheDir = new File(dataDir, "cache"); if (!cacheDir.exists() && !cacheDir.mkdir()) {
// Path: sdk/src/com/sharethis/loopy/sdk/Logger.java // public class Logger { // // static boolean debugEnabled = true; // static final String TAG = "Loopy"; // // public static void e(Throwable e) { // Log.e(TAG, e.getMessage(), e); // } // // public static void w(Throwable e) { // Log.w(TAG, e.getMessage(), e); // } // // public static void w(String s) { // Log.w(TAG, s); // } // // public static void e(String s) { // Log.e(TAG, s); // } // // public static boolean isDebugEnabled() { // return debugEnabled; // } // // public static void d(String s) { // Log.d(TAG, s); // } // // public static void setDebugEnabled(boolean debugEnabled) { // Logger.debugEnabled = debugEnabled; // } // } // Path: test/src/com/sharethis/loopy/test/util/SystemUtils.java import android.content.Context; import com.sharethis.loopy.sdk.Logger; import java.io.File; package com.sharethis.loopy.test.util; /** * @author Jason Polites */ public class SystemUtils { static File cacheDir; public static File getCacheDir(Context context) { if(cacheDir == null) { File dataDir = new File("/data/data/" + context.getPackageName()); cacheDir = new File(dataDir, "cache"); if (!cacheDir.exists() && !cacheDir.mkdir()) {
Logger.w("Failed to create cache dir in [" +
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/ShareDialogAdapterTest.java
// Path: test/src/android/app/MockAlertDialog.java // public class MockAlertDialog extends AlertDialog { // public MockAlertDialog(Context context) { // super(context, AlertDialog.THEME_TRADITIONAL); // } // // @Override // public void show() { // // Nothing // } // } // // Path: sdk/src/com/sharethis/loopy/sdk/util/AppDataCache.java // public class AppDataCache { // // private final Map<String, Drawable> iconCache = new HashMap<String, Drawable>(); // private final Map<String, String> labelCache = new HashMap<String, String>(); // // static AppDataCache instance = new AppDataCache(); // // AppDataCache() {} // // public static AppDataCache getInstance() { // return instance; // } // // public void onCreate(final Context context) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // Collection<ResolveInfo> appsForContentType = getAppUtils().getAppsForContentType(context, "*/*"); // for (ResolveInfo resolveInfo : appsForContentType) { // getAppIcon(context, resolveInfo); // getAppLabel(context, resolveInfo); // } // return null; // } // }.execute(); // } // // public void onDestroy(Context context) { // iconCache.clear(); // labelCache.clear(); // } // // public synchronized Drawable getAppIcon(Context context, ResolveInfo item) { // String key = getKey(item); // Drawable icon = iconCache.get(key); // if(icon == null) { // icon = item.activityInfo.loadIcon(context.getPackageManager()); // iconCache.put(key, icon); // } // return icon; // } // // /** // * May return null! // * @param packageName The package name. // * @param className The activity class name // * @return The app (activity) label, or null // */ // public String getAppLabel(String packageName, String className) { // return labelCache.get(packageName + "." + className); // } // // public synchronized String getAppLabel(Context context, ResolveInfo item) { // String key = getKey(item); // String label = labelCache.get(key); // if(label == null) { // label = item.activityInfo.loadLabel(context.getPackageManager()).toString(); // labelCache.put(key, label); // } // return label; // } // // String getKey(ResolveInfo item) { // return item.activityInfo.packageName + "." + item.activityInfo.name; // } // // // mockable // AppUtils getAppUtils() { // return AppUtils.getInstance(); // } // // }
import android.view.View; import com.sharethis.loopy.sdk.*; import com.sharethis.loopy.sdk.util.AppDataCache; import org.mockito.Mockito; import java.util.Arrays; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import android.app.AlertDialog; import android.app.MockAlertDialog; import android.content.Context; import android.content.Intent; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable;
/* * * * Copyright (c) 2013 ShareThis Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * * THE SOFTWARE. * */ package com.sharethis.loopy.test; /** * @author Jason Polites */ public class ShareDialogAdapterTest extends LoopyActivityTestCase { public void testGetView() throws Throwable { final Context context = getContext(); final MockShareClickListener shareDialogListener = Mockito.mock(MockShareClickListener.class);
// Path: test/src/android/app/MockAlertDialog.java // public class MockAlertDialog extends AlertDialog { // public MockAlertDialog(Context context) { // super(context, AlertDialog.THEME_TRADITIONAL); // } // // @Override // public void show() { // // Nothing // } // } // // Path: sdk/src/com/sharethis/loopy/sdk/util/AppDataCache.java // public class AppDataCache { // // private final Map<String, Drawable> iconCache = new HashMap<String, Drawable>(); // private final Map<String, String> labelCache = new HashMap<String, String>(); // // static AppDataCache instance = new AppDataCache(); // // AppDataCache() {} // // public static AppDataCache getInstance() { // return instance; // } // // public void onCreate(final Context context) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // Collection<ResolveInfo> appsForContentType = getAppUtils().getAppsForContentType(context, "*/*"); // for (ResolveInfo resolveInfo : appsForContentType) { // getAppIcon(context, resolveInfo); // getAppLabel(context, resolveInfo); // } // return null; // } // }.execute(); // } // // public void onDestroy(Context context) { // iconCache.clear(); // labelCache.clear(); // } // // public synchronized Drawable getAppIcon(Context context, ResolveInfo item) { // String key = getKey(item); // Drawable icon = iconCache.get(key); // if(icon == null) { // icon = item.activityInfo.loadIcon(context.getPackageManager()); // iconCache.put(key, icon); // } // return icon; // } // // /** // * May return null! // * @param packageName The package name. // * @param className The activity class name // * @return The app (activity) label, or null // */ // public String getAppLabel(String packageName, String className) { // return labelCache.get(packageName + "." + className); // } // // public synchronized String getAppLabel(Context context, ResolveInfo item) { // String key = getKey(item); // String label = labelCache.get(key); // if(label == null) { // label = item.activityInfo.loadLabel(context.getPackageManager()).toString(); // labelCache.put(key, label); // } // return label; // } // // String getKey(ResolveInfo item) { // return item.activityInfo.packageName + "." + item.activityInfo.name; // } // // // mockable // AppUtils getAppUtils() { // return AppUtils.getInstance(); // } // // } // Path: test/src/com/sharethis/loopy/test/ShareDialogAdapterTest.java import android.view.View; import com.sharethis.loopy.sdk.*; import com.sharethis.loopy.sdk.util.AppDataCache; import org.mockito.Mockito; import java.util.Arrays; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import android.app.AlertDialog; import android.app.MockAlertDialog; import android.content.Context; import android.content.Intent; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; /* * * * Copyright (c) 2013 ShareThis Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * * THE SOFTWARE. * */ package com.sharethis.loopy.test; /** * @author Jason Polites */ public class ShareDialogAdapterTest extends LoopyActivityTestCase { public void testGetView() throws Throwable { final Context context = getContext(); final MockShareClickListener shareDialogListener = Mockito.mock(MockShareClickListener.class);
final AlertDialog dlg = Mockito.spy(new MockAlertDialog( context ));
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/ShareDialogAdapterTest.java
// Path: test/src/android/app/MockAlertDialog.java // public class MockAlertDialog extends AlertDialog { // public MockAlertDialog(Context context) { // super(context, AlertDialog.THEME_TRADITIONAL); // } // // @Override // public void show() { // // Nothing // } // } // // Path: sdk/src/com/sharethis/loopy/sdk/util/AppDataCache.java // public class AppDataCache { // // private final Map<String, Drawable> iconCache = new HashMap<String, Drawable>(); // private final Map<String, String> labelCache = new HashMap<String, String>(); // // static AppDataCache instance = new AppDataCache(); // // AppDataCache() {} // // public static AppDataCache getInstance() { // return instance; // } // // public void onCreate(final Context context) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // Collection<ResolveInfo> appsForContentType = getAppUtils().getAppsForContentType(context, "*/*"); // for (ResolveInfo resolveInfo : appsForContentType) { // getAppIcon(context, resolveInfo); // getAppLabel(context, resolveInfo); // } // return null; // } // }.execute(); // } // // public void onDestroy(Context context) { // iconCache.clear(); // labelCache.clear(); // } // // public synchronized Drawable getAppIcon(Context context, ResolveInfo item) { // String key = getKey(item); // Drawable icon = iconCache.get(key); // if(icon == null) { // icon = item.activityInfo.loadIcon(context.getPackageManager()); // iconCache.put(key, icon); // } // return icon; // } // // /** // * May return null! // * @param packageName The package name. // * @param className The activity class name // * @return The app (activity) label, or null // */ // public String getAppLabel(String packageName, String className) { // return labelCache.get(packageName + "." + className); // } // // public synchronized String getAppLabel(Context context, ResolveInfo item) { // String key = getKey(item); // String label = labelCache.get(key); // if(label == null) { // label = item.activityInfo.loadLabel(context.getPackageManager()).toString(); // labelCache.put(key, label); // } // return label; // } // // String getKey(ResolveInfo item) { // return item.activityInfo.packageName + "." + item.activityInfo.name; // } // // // mockable // AppUtils getAppUtils() { // return AppUtils.getInstance(); // } // // }
import android.view.View; import com.sharethis.loopy.sdk.*; import com.sharethis.loopy.sdk.util.AppDataCache; import org.mockito.Mockito; import java.util.Arrays; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import android.app.AlertDialog; import android.app.MockAlertDialog; import android.content.Context; import android.content.Intent; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable;
/* * * * Copyright (c) 2013 ShareThis Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * * THE SOFTWARE. * */ package com.sharethis.loopy.test; /** * @author Jason Polites */ public class ShareDialogAdapterTest extends LoopyActivityTestCase { public void testGetView() throws Throwable { final Context context = getContext(); final MockShareClickListener shareDialogListener = Mockito.mock(MockShareClickListener.class); final AlertDialog dlg = Mockito.spy(new MockAlertDialog( context )); final MockShareConfig config = Mockito.mock(MockShareConfig.class); final Intent intent = Mockito.mock(Intent.class); final MockItem item = Mockito.mock(MockItem.class);
// Path: test/src/android/app/MockAlertDialog.java // public class MockAlertDialog extends AlertDialog { // public MockAlertDialog(Context context) { // super(context, AlertDialog.THEME_TRADITIONAL); // } // // @Override // public void show() { // // Nothing // } // } // // Path: sdk/src/com/sharethis/loopy/sdk/util/AppDataCache.java // public class AppDataCache { // // private final Map<String, Drawable> iconCache = new HashMap<String, Drawable>(); // private final Map<String, String> labelCache = new HashMap<String, String>(); // // static AppDataCache instance = new AppDataCache(); // // AppDataCache() {} // // public static AppDataCache getInstance() { // return instance; // } // // public void onCreate(final Context context) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // Collection<ResolveInfo> appsForContentType = getAppUtils().getAppsForContentType(context, "*/*"); // for (ResolveInfo resolveInfo : appsForContentType) { // getAppIcon(context, resolveInfo); // getAppLabel(context, resolveInfo); // } // return null; // } // }.execute(); // } // // public void onDestroy(Context context) { // iconCache.clear(); // labelCache.clear(); // } // // public synchronized Drawable getAppIcon(Context context, ResolveInfo item) { // String key = getKey(item); // Drawable icon = iconCache.get(key); // if(icon == null) { // icon = item.activityInfo.loadIcon(context.getPackageManager()); // iconCache.put(key, icon); // } // return icon; // } // // /** // * May return null! // * @param packageName The package name. // * @param className The activity class name // * @return The app (activity) label, or null // */ // public String getAppLabel(String packageName, String className) { // return labelCache.get(packageName + "." + className); // } // // public synchronized String getAppLabel(Context context, ResolveInfo item) { // String key = getKey(item); // String label = labelCache.get(key); // if(label == null) { // label = item.activityInfo.loadLabel(context.getPackageManager()).toString(); // labelCache.put(key, label); // } // return label; // } // // String getKey(ResolveInfo item) { // return item.activityInfo.packageName + "." + item.activityInfo.name; // } // // // mockable // AppUtils getAppUtils() { // return AppUtils.getInstance(); // } // // } // Path: test/src/com/sharethis/loopy/test/ShareDialogAdapterTest.java import android.view.View; import com.sharethis.loopy.sdk.*; import com.sharethis.loopy.sdk.util.AppDataCache; import org.mockito.Mockito; import java.util.Arrays; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import android.app.AlertDialog; import android.app.MockAlertDialog; import android.content.Context; import android.content.Intent; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; /* * * * Copyright (c) 2013 ShareThis Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * * THE SOFTWARE. * */ package com.sharethis.loopy.test; /** * @author Jason Polites */ public class ShareDialogAdapterTest extends LoopyActivityTestCase { public void testGetView() throws Throwable { final Context context = getContext(); final MockShareClickListener shareDialogListener = Mockito.mock(MockShareClickListener.class); final AlertDialog dlg = Mockito.spy(new MockAlertDialog( context )); final MockShareConfig config = Mockito.mock(MockShareConfig.class); final Intent intent = Mockito.mock(Intent.class); final MockItem item = Mockito.mock(MockItem.class);
final AppDataCache cache = Mockito.mock(AppDataCache.class);
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/ItemTest.java
// Path: sdk/src/com/sharethis/loopy/sdk/Item.java // public class Item { // // String type = "website"; // String url; // String title; // String imageUrl; // String description; // String videoUrl; // Set<String> tags; // // String shortlink; // // /** // * The "og:type" corresponding to the content being shared. // * @return og:type // */ // public String getType() { // return type; // } // // /** // * Optional. // * Corresponds to the og:type meta element. Default is 'website' // * @param type The type of the content being shared (og:type) // * @see <a href="http://ogp.me/#types" target="_blank">http://ogp.me/#types</a> // */ // public void setType(String type) { // this.type = type; // } // // public String getUrl() { // return url; // } // // /** // * Optional. (MUST specify one of url or title!) // * The url of the content being shared. If the content does not have a url, you must at least provide a title. // * @param url The url of the content being shared. // */ // public void setUrl(String url) { // this.url = url; // } // // public String getTitle() { // return title; // } // // /** // * Optional. (MUST specify one of url or title!) // * The title of the content being shared. If the content does not have a url, you must at least provide a title. // * @param title The title of the content being shared. // */ // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // /** // * Optional. Corresponds to og:image // * @param imageUrl An image url corresponding to the content being shared. // */ // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getDescription() { // return description; // } // // /** // * Optional. Corresponds to og:description // * @param description The description of the content being shared. // */ // public void setDescription(String description) { // this.description = description; // } // // public String getVideoUrl() { // return videoUrl; // } // // /** // * Optional. Corresponds to og:video // * @param videoUrl A video url corresponding to the content being shared. // */ // public void setVideoUrl(String videoUrl) { // this.videoUrl = videoUrl; // } // // /** // * @return The custom tags associated with the item // */ // public Set<String> getTags() { // return tags; // } // // /** // * Optional. // * @param tags Any custom tags associated with the item // */ // public void setTags(Set<String> tags) { // this.tags = tags; // } // // public String getShortlink() { // return shortlink; // } // // void setShortlink(String shortlink) { // this.shortlink = shortlink; // } // // public synchronized void addTag(String tag) { // if(tags == null) { // tags = new LinkedHashSet<String>(); // } // tags.add(tag); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Item item = (Item) o; // // if (title != null ? !title.equals(item.title) : item.title != null) return false; // if (url != null ? !url.equals(item.url) : item.url != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = url != null ? url.hashCode() : 0; // result = 31 * result + (title != null ? title.hashCode() : 0); // return result; // } // // @Override // public String toString() { // if(url != null) { // return url; // } // else if(title != null) { // return title; // } // return super.toString(); // } // }
import com.sharethis.loopy.sdk.Item;
package com.sharethis.loopy.test; /** * @author Jason Polites */ public class ItemTest extends LoopyActivityTestCase { public void testEquals() {
// Path: sdk/src/com/sharethis/loopy/sdk/Item.java // public class Item { // // String type = "website"; // String url; // String title; // String imageUrl; // String description; // String videoUrl; // Set<String> tags; // // String shortlink; // // /** // * The "og:type" corresponding to the content being shared. // * @return og:type // */ // public String getType() { // return type; // } // // /** // * Optional. // * Corresponds to the og:type meta element. Default is 'website' // * @param type The type of the content being shared (og:type) // * @see <a href="http://ogp.me/#types" target="_blank">http://ogp.me/#types</a> // */ // public void setType(String type) { // this.type = type; // } // // public String getUrl() { // return url; // } // // /** // * Optional. (MUST specify one of url or title!) // * The url of the content being shared. If the content does not have a url, you must at least provide a title. // * @param url The url of the content being shared. // */ // public void setUrl(String url) { // this.url = url; // } // // public String getTitle() { // return title; // } // // /** // * Optional. (MUST specify one of url or title!) // * The title of the content being shared. If the content does not have a url, you must at least provide a title. // * @param title The title of the content being shared. // */ // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // /** // * Optional. Corresponds to og:image // * @param imageUrl An image url corresponding to the content being shared. // */ // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getDescription() { // return description; // } // // /** // * Optional. Corresponds to og:description // * @param description The description of the content being shared. // */ // public void setDescription(String description) { // this.description = description; // } // // public String getVideoUrl() { // return videoUrl; // } // // /** // * Optional. Corresponds to og:video // * @param videoUrl A video url corresponding to the content being shared. // */ // public void setVideoUrl(String videoUrl) { // this.videoUrl = videoUrl; // } // // /** // * @return The custom tags associated with the item // */ // public Set<String> getTags() { // return tags; // } // // /** // * Optional. // * @param tags Any custom tags associated with the item // */ // public void setTags(Set<String> tags) { // this.tags = tags; // } // // public String getShortlink() { // return shortlink; // } // // void setShortlink(String shortlink) { // this.shortlink = shortlink; // } // // public synchronized void addTag(String tag) { // if(tags == null) { // tags = new LinkedHashSet<String>(); // } // tags.add(tag); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Item item = (Item) o; // // if (title != null ? !title.equals(item.title) : item.title != null) return false; // if (url != null ? !url.equals(item.url) : item.url != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = url != null ? url.hashCode() : 0; // result = 31 * result + (title != null ? title.hashCode() : 0); // return result; // } // // @Override // public String toString() { // if(url != null) { // return url; // } // else if(title != null) { // return title; // } // return super.toString(); // } // } // Path: test/src/com/sharethis/loopy/test/ItemTest.java import com.sharethis.loopy.sdk.Item; package com.sharethis.loopy.test; /** * @author Jason Polites */ public class ItemTest extends LoopyActivityTestCase { public void testEquals() {
Item item0 = new Item();
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/AppDataCacheTest.java
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppUtils.java // public class AppUtils { // // static final AppUtils instance = new AppUtils(); // // AppUtils() {} // // public static AppUtils getInstance() { // return instance; // } // // /** // * Determines inclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ALL the given permissions. // */ // public boolean hasAndPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res != PackageManager.PERMISSION_GRANTED) { // return false; // } // } // return true; // } // // /** // * Determines exclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ANY the given permissions. // */ // public boolean hasOrPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res == PackageManager.PERMISSION_GRANTED) { // return true; // } // } // return false; // } // // /** // * Returns the app info for the apps which support the ACTION_SEND intent with the given types. // * @param context The current context. // * @param contentTypes The content types supported. // * @return A Collection (set) of ResolveInfo objects corresponding to the apps installed on the device that // * support the content type(s). // */ // public Collection<ResolveInfo> getAppsForContentType(Context context, String...contentTypes) { // Set<ResolveInfo> apps = new LinkedHashSet<ResolveInfo>(); // for (String type : contentTypes) { // List<ResolveInfo> appsByType = listAppsForType(context, type); // if(appsByType != null && appsByType.size() > 0) { // apps.addAll(appsByType); // } // } // return apps; // } // // List<ResolveInfo> listAppsForType(Context context, String type) { // Intent intent = getSendIntent(); // intent.setType(type); // // PackageManager p = context.getPackageManager(); // // List<ResolveInfo> appList = p.queryIntentActivities(intent, 0); // // // Sort alphabetically. // Collections.sort(appList, new android.content.pm.ResolveInfo.DisplayNameComparator(p)); // // return appList; // } // // // mockable // Intent getSendIntent() { // return new Intent(Intent.ACTION_SEND); // } // // } // // Path: test/src/com/sharethis/loopy/sdk/util/MockAppDataCache.java // public class MockAppDataCache extends AppDataCache{ // // public MockAppDataCache() {} // // @Override // public String getKey(ResolveInfo item) { // return super.getKey(item); // } // // @Override // public AppUtils getAppUtils() { // return super.getAppUtils(); // } // // public static void setInstance(AppDataCache instance) { // AppDataCache.instance = instance; // } // } // // Path: test/src/com/sharethis/loopy/test/util/Holder.java // public class Holder<T> { // // private T object; // // private List<T> objects = new ArrayList<T>(); // // public Holder() {} // // public Holder(T object) { // super(); // this.object = object; // } // // public T get() { // return object; // } // // public void set(T object) { // this.object = object; // } // // public void add(T object) { // objects.add(object); // } // // public List<T> getObjects() { // return objects; // } // }
import android.content.Context; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; import com.sharethis.loopy.sdk.util.AppUtils; import com.sharethis.loopy.sdk.util.MockAppDataCache; import com.sharethis.loopy.test.util.Holder; import org.mockito.Mockito; import java.util.Arrays; import java.util.List;
package com.sharethis.loopy.test; /** * @author Jason Polites */ public class AppDataCacheTest extends LoopyAndroidTestCase { public void testGetAppLabel() { // Can't mock the ResolveInfo because activityInfo has members not methods. ResolveInfo mockInfo = new ResolveInfo(); ActivityInfo activityInfo = Mockito.mock(ActivityInfo.class); activityInfo.packageName = "foo"; activityInfo.name = "bar"; Mockito.when(activityInfo.loadLabel((PackageManager)Mockito.any())).thenReturn("foobar"); mockInfo.activityInfo = activityInfo;
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppUtils.java // public class AppUtils { // // static final AppUtils instance = new AppUtils(); // // AppUtils() {} // // public static AppUtils getInstance() { // return instance; // } // // /** // * Determines inclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ALL the given permissions. // */ // public boolean hasAndPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res != PackageManager.PERMISSION_GRANTED) { // return false; // } // } // return true; // } // // /** // * Determines exclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ANY the given permissions. // */ // public boolean hasOrPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res == PackageManager.PERMISSION_GRANTED) { // return true; // } // } // return false; // } // // /** // * Returns the app info for the apps which support the ACTION_SEND intent with the given types. // * @param context The current context. // * @param contentTypes The content types supported. // * @return A Collection (set) of ResolveInfo objects corresponding to the apps installed on the device that // * support the content type(s). // */ // public Collection<ResolveInfo> getAppsForContentType(Context context, String...contentTypes) { // Set<ResolveInfo> apps = new LinkedHashSet<ResolveInfo>(); // for (String type : contentTypes) { // List<ResolveInfo> appsByType = listAppsForType(context, type); // if(appsByType != null && appsByType.size() > 0) { // apps.addAll(appsByType); // } // } // return apps; // } // // List<ResolveInfo> listAppsForType(Context context, String type) { // Intent intent = getSendIntent(); // intent.setType(type); // // PackageManager p = context.getPackageManager(); // // List<ResolveInfo> appList = p.queryIntentActivities(intent, 0); // // // Sort alphabetically. // Collections.sort(appList, new android.content.pm.ResolveInfo.DisplayNameComparator(p)); // // return appList; // } // // // mockable // Intent getSendIntent() { // return new Intent(Intent.ACTION_SEND); // } // // } // // Path: test/src/com/sharethis/loopy/sdk/util/MockAppDataCache.java // public class MockAppDataCache extends AppDataCache{ // // public MockAppDataCache() {} // // @Override // public String getKey(ResolveInfo item) { // return super.getKey(item); // } // // @Override // public AppUtils getAppUtils() { // return super.getAppUtils(); // } // // public static void setInstance(AppDataCache instance) { // AppDataCache.instance = instance; // } // } // // Path: test/src/com/sharethis/loopy/test/util/Holder.java // public class Holder<T> { // // private T object; // // private List<T> objects = new ArrayList<T>(); // // public Holder() {} // // public Holder(T object) { // super(); // this.object = object; // } // // public T get() { // return object; // } // // public void set(T object) { // this.object = object; // } // // public void add(T object) { // objects.add(object); // } // // public List<T> getObjects() { // return objects; // } // } // Path: test/src/com/sharethis/loopy/test/AppDataCacheTest.java import android.content.Context; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; import com.sharethis.loopy.sdk.util.AppUtils; import com.sharethis.loopy.sdk.util.MockAppDataCache; import com.sharethis.loopy.test.util.Holder; import org.mockito.Mockito; import java.util.Arrays; import java.util.List; package com.sharethis.loopy.test; /** * @author Jason Polites */ public class AppDataCacheTest extends LoopyAndroidTestCase { public void testGetAppLabel() { // Can't mock the ResolveInfo because activityInfo has members not methods. ResolveInfo mockInfo = new ResolveInfo(); ActivityInfo activityInfo = Mockito.mock(ActivityInfo.class); activityInfo.packageName = "foo"; activityInfo.name = "bar"; Mockito.when(activityInfo.loadLabel((PackageManager)Mockito.any())).thenReturn("foobar"); mockInfo.activityInfo = activityInfo;
MockAppDataCache cache = new MockAppDataCache() ;
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/AppDataCacheTest.java
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppUtils.java // public class AppUtils { // // static final AppUtils instance = new AppUtils(); // // AppUtils() {} // // public static AppUtils getInstance() { // return instance; // } // // /** // * Determines inclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ALL the given permissions. // */ // public boolean hasAndPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res != PackageManager.PERMISSION_GRANTED) { // return false; // } // } // return true; // } // // /** // * Determines exclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ANY the given permissions. // */ // public boolean hasOrPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res == PackageManager.PERMISSION_GRANTED) { // return true; // } // } // return false; // } // // /** // * Returns the app info for the apps which support the ACTION_SEND intent with the given types. // * @param context The current context. // * @param contentTypes The content types supported. // * @return A Collection (set) of ResolveInfo objects corresponding to the apps installed on the device that // * support the content type(s). // */ // public Collection<ResolveInfo> getAppsForContentType(Context context, String...contentTypes) { // Set<ResolveInfo> apps = new LinkedHashSet<ResolveInfo>(); // for (String type : contentTypes) { // List<ResolveInfo> appsByType = listAppsForType(context, type); // if(appsByType != null && appsByType.size() > 0) { // apps.addAll(appsByType); // } // } // return apps; // } // // List<ResolveInfo> listAppsForType(Context context, String type) { // Intent intent = getSendIntent(); // intent.setType(type); // // PackageManager p = context.getPackageManager(); // // List<ResolveInfo> appList = p.queryIntentActivities(intent, 0); // // // Sort alphabetically. // Collections.sort(appList, new android.content.pm.ResolveInfo.DisplayNameComparator(p)); // // return appList; // } // // // mockable // Intent getSendIntent() { // return new Intent(Intent.ACTION_SEND); // } // // } // // Path: test/src/com/sharethis/loopy/sdk/util/MockAppDataCache.java // public class MockAppDataCache extends AppDataCache{ // // public MockAppDataCache() {} // // @Override // public String getKey(ResolveInfo item) { // return super.getKey(item); // } // // @Override // public AppUtils getAppUtils() { // return super.getAppUtils(); // } // // public static void setInstance(AppDataCache instance) { // AppDataCache.instance = instance; // } // } // // Path: test/src/com/sharethis/loopy/test/util/Holder.java // public class Holder<T> { // // private T object; // // private List<T> objects = new ArrayList<T>(); // // public Holder() {} // // public Holder(T object) { // super(); // this.object = object; // } // // public T get() { // return object; // } // // public void set(T object) { // this.object = object; // } // // public void add(T object) { // objects.add(object); // } // // public List<T> getObjects() { // return objects; // } // }
import android.content.Context; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; import com.sharethis.loopy.sdk.util.AppUtils; import com.sharethis.loopy.sdk.util.MockAppDataCache; import com.sharethis.loopy.test.util.Holder; import org.mockito.Mockito; import java.util.Arrays; import java.util.List;
activityInfo.packageName = "foo"; activityInfo.name = "bar"; Mockito.when(activityInfo.loadIcon((PackageManager) Mockito.any())).thenReturn(drawable); mockInfo.activityInfo = activityInfo; MockAppDataCache cache = new MockAppDataCache() ; Drawable cached = cache.getAppIcon(getContext(), mockInfo); assertNotNull(cached); assertSame(drawable, cached); cached = cache.getAppIcon(getContext(), mockInfo); assertNotNull(cached); assertSame(drawable, cached); Mockito.verify(activityInfo, Mockito.times(1)).loadIcon((PackageManager) Mockito.any()); } public void testOnCreate() { ResolveInfo info0 = new ResolveInfo(); ResolveInfo info1 = new ResolveInfo(); final List<ResolveInfo> infos = Arrays.asList(info0, info1);
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppUtils.java // public class AppUtils { // // static final AppUtils instance = new AppUtils(); // // AppUtils() {} // // public static AppUtils getInstance() { // return instance; // } // // /** // * Determines inclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ALL the given permissions. // */ // public boolean hasAndPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res != PackageManager.PERMISSION_GRANTED) { // return false; // } // } // return true; // } // // /** // * Determines exclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ANY the given permissions. // */ // public boolean hasOrPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res == PackageManager.PERMISSION_GRANTED) { // return true; // } // } // return false; // } // // /** // * Returns the app info for the apps which support the ACTION_SEND intent with the given types. // * @param context The current context. // * @param contentTypes The content types supported. // * @return A Collection (set) of ResolveInfo objects corresponding to the apps installed on the device that // * support the content type(s). // */ // public Collection<ResolveInfo> getAppsForContentType(Context context, String...contentTypes) { // Set<ResolveInfo> apps = new LinkedHashSet<ResolveInfo>(); // for (String type : contentTypes) { // List<ResolveInfo> appsByType = listAppsForType(context, type); // if(appsByType != null && appsByType.size() > 0) { // apps.addAll(appsByType); // } // } // return apps; // } // // List<ResolveInfo> listAppsForType(Context context, String type) { // Intent intent = getSendIntent(); // intent.setType(type); // // PackageManager p = context.getPackageManager(); // // List<ResolveInfo> appList = p.queryIntentActivities(intent, 0); // // // Sort alphabetically. // Collections.sort(appList, new android.content.pm.ResolveInfo.DisplayNameComparator(p)); // // return appList; // } // // // mockable // Intent getSendIntent() { // return new Intent(Intent.ACTION_SEND); // } // // } // // Path: test/src/com/sharethis/loopy/sdk/util/MockAppDataCache.java // public class MockAppDataCache extends AppDataCache{ // // public MockAppDataCache() {} // // @Override // public String getKey(ResolveInfo item) { // return super.getKey(item); // } // // @Override // public AppUtils getAppUtils() { // return super.getAppUtils(); // } // // public static void setInstance(AppDataCache instance) { // AppDataCache.instance = instance; // } // } // // Path: test/src/com/sharethis/loopy/test/util/Holder.java // public class Holder<T> { // // private T object; // // private List<T> objects = new ArrayList<T>(); // // public Holder() {} // // public Holder(T object) { // super(); // this.object = object; // } // // public T get() { // return object; // } // // public void set(T object) { // this.object = object; // } // // public void add(T object) { // objects.add(object); // } // // public List<T> getObjects() { // return objects; // } // } // Path: test/src/com/sharethis/loopy/test/AppDataCacheTest.java import android.content.Context; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; import com.sharethis.loopy.sdk.util.AppUtils; import com.sharethis.loopy.sdk.util.MockAppDataCache; import com.sharethis.loopy.test.util.Holder; import org.mockito.Mockito; import java.util.Arrays; import java.util.List; activityInfo.packageName = "foo"; activityInfo.name = "bar"; Mockito.when(activityInfo.loadIcon((PackageManager) Mockito.any())).thenReturn(drawable); mockInfo.activityInfo = activityInfo; MockAppDataCache cache = new MockAppDataCache() ; Drawable cached = cache.getAppIcon(getContext(), mockInfo); assertNotNull(cached); assertSame(drawable, cached); cached = cache.getAppIcon(getContext(), mockInfo); assertNotNull(cached); assertSame(drawable, cached); Mockito.verify(activityInfo, Mockito.times(1)).loadIcon((PackageManager) Mockito.any()); } public void testOnCreate() { ResolveInfo info0 = new ResolveInfo(); ResolveInfo info1 = new ResolveInfo(); final List<ResolveInfo> infos = Arrays.asList(info0, info1);
final Holder<ResolveInfo> iconHolder = new Holder<ResolveInfo>();
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/AppDataCacheTest.java
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppUtils.java // public class AppUtils { // // static final AppUtils instance = new AppUtils(); // // AppUtils() {} // // public static AppUtils getInstance() { // return instance; // } // // /** // * Determines inclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ALL the given permissions. // */ // public boolean hasAndPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res != PackageManager.PERMISSION_GRANTED) { // return false; // } // } // return true; // } // // /** // * Determines exclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ANY the given permissions. // */ // public boolean hasOrPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res == PackageManager.PERMISSION_GRANTED) { // return true; // } // } // return false; // } // // /** // * Returns the app info for the apps which support the ACTION_SEND intent with the given types. // * @param context The current context. // * @param contentTypes The content types supported. // * @return A Collection (set) of ResolveInfo objects corresponding to the apps installed on the device that // * support the content type(s). // */ // public Collection<ResolveInfo> getAppsForContentType(Context context, String...contentTypes) { // Set<ResolveInfo> apps = new LinkedHashSet<ResolveInfo>(); // for (String type : contentTypes) { // List<ResolveInfo> appsByType = listAppsForType(context, type); // if(appsByType != null && appsByType.size() > 0) { // apps.addAll(appsByType); // } // } // return apps; // } // // List<ResolveInfo> listAppsForType(Context context, String type) { // Intent intent = getSendIntent(); // intent.setType(type); // // PackageManager p = context.getPackageManager(); // // List<ResolveInfo> appList = p.queryIntentActivities(intent, 0); // // // Sort alphabetically. // Collections.sort(appList, new android.content.pm.ResolveInfo.DisplayNameComparator(p)); // // return appList; // } // // // mockable // Intent getSendIntent() { // return new Intent(Intent.ACTION_SEND); // } // // } // // Path: test/src/com/sharethis/loopy/sdk/util/MockAppDataCache.java // public class MockAppDataCache extends AppDataCache{ // // public MockAppDataCache() {} // // @Override // public String getKey(ResolveInfo item) { // return super.getKey(item); // } // // @Override // public AppUtils getAppUtils() { // return super.getAppUtils(); // } // // public static void setInstance(AppDataCache instance) { // AppDataCache.instance = instance; // } // } // // Path: test/src/com/sharethis/loopy/test/util/Holder.java // public class Holder<T> { // // private T object; // // private List<T> objects = new ArrayList<T>(); // // public Holder() {} // // public Holder(T object) { // super(); // this.object = object; // } // // public T get() { // return object; // } // // public void set(T object) { // this.object = object; // } // // public void add(T object) { // objects.add(object); // } // // public List<T> getObjects() { // return objects; // } // }
import android.content.Context; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; import com.sharethis.loopy.sdk.util.AppUtils; import com.sharethis.loopy.sdk.util.MockAppDataCache; import com.sharethis.loopy.test.util.Holder; import org.mockito.Mockito; import java.util.Arrays; import java.util.List;
Mockito.when(activityInfo.loadIcon((PackageManager) Mockito.any())).thenReturn(drawable); mockInfo.activityInfo = activityInfo; MockAppDataCache cache = new MockAppDataCache() ; Drawable cached = cache.getAppIcon(getContext(), mockInfo); assertNotNull(cached); assertSame(drawable, cached); cached = cache.getAppIcon(getContext(), mockInfo); assertNotNull(cached); assertSame(drawable, cached); Mockito.verify(activityInfo, Mockito.times(1)).loadIcon((PackageManager) Mockito.any()); } public void testOnCreate() { ResolveInfo info0 = new ResolveInfo(); ResolveInfo info1 = new ResolveInfo(); final List<ResolveInfo> infos = Arrays.asList(info0, info1); final Holder<ResolveInfo> iconHolder = new Holder<ResolveInfo>(); final Holder<ResolveInfo> labelHolder = new Holder<ResolveInfo>(); final Drawable drawable = Mockito.mock(Drawable.class);
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppUtils.java // public class AppUtils { // // static final AppUtils instance = new AppUtils(); // // AppUtils() {} // // public static AppUtils getInstance() { // return instance; // } // // /** // * Determines inclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ALL the given permissions. // */ // public boolean hasAndPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res != PackageManager.PERMISSION_GRANTED) { // return false; // } // } // return true; // } // // /** // * Determines exclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ANY the given permissions. // */ // public boolean hasOrPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res == PackageManager.PERMISSION_GRANTED) { // return true; // } // } // return false; // } // // /** // * Returns the app info for the apps which support the ACTION_SEND intent with the given types. // * @param context The current context. // * @param contentTypes The content types supported. // * @return A Collection (set) of ResolveInfo objects corresponding to the apps installed on the device that // * support the content type(s). // */ // public Collection<ResolveInfo> getAppsForContentType(Context context, String...contentTypes) { // Set<ResolveInfo> apps = new LinkedHashSet<ResolveInfo>(); // for (String type : contentTypes) { // List<ResolveInfo> appsByType = listAppsForType(context, type); // if(appsByType != null && appsByType.size() > 0) { // apps.addAll(appsByType); // } // } // return apps; // } // // List<ResolveInfo> listAppsForType(Context context, String type) { // Intent intent = getSendIntent(); // intent.setType(type); // // PackageManager p = context.getPackageManager(); // // List<ResolveInfo> appList = p.queryIntentActivities(intent, 0); // // // Sort alphabetically. // Collections.sort(appList, new android.content.pm.ResolveInfo.DisplayNameComparator(p)); // // return appList; // } // // // mockable // Intent getSendIntent() { // return new Intent(Intent.ACTION_SEND); // } // // } // // Path: test/src/com/sharethis/loopy/sdk/util/MockAppDataCache.java // public class MockAppDataCache extends AppDataCache{ // // public MockAppDataCache() {} // // @Override // public String getKey(ResolveInfo item) { // return super.getKey(item); // } // // @Override // public AppUtils getAppUtils() { // return super.getAppUtils(); // } // // public static void setInstance(AppDataCache instance) { // AppDataCache.instance = instance; // } // } // // Path: test/src/com/sharethis/loopy/test/util/Holder.java // public class Holder<T> { // // private T object; // // private List<T> objects = new ArrayList<T>(); // // public Holder() {} // // public Holder(T object) { // super(); // this.object = object; // } // // public T get() { // return object; // } // // public void set(T object) { // this.object = object; // } // // public void add(T object) { // objects.add(object); // } // // public List<T> getObjects() { // return objects; // } // } // Path: test/src/com/sharethis/loopy/test/AppDataCacheTest.java import android.content.Context; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; import com.sharethis.loopy.sdk.util.AppUtils; import com.sharethis.loopy.sdk.util.MockAppDataCache; import com.sharethis.loopy.test.util.Holder; import org.mockito.Mockito; import java.util.Arrays; import java.util.List; Mockito.when(activityInfo.loadIcon((PackageManager) Mockito.any())).thenReturn(drawable); mockInfo.activityInfo = activityInfo; MockAppDataCache cache = new MockAppDataCache() ; Drawable cached = cache.getAppIcon(getContext(), mockInfo); assertNotNull(cached); assertSame(drawable, cached); cached = cache.getAppIcon(getContext(), mockInfo); assertNotNull(cached); assertSame(drawable, cached); Mockito.verify(activityInfo, Mockito.times(1)).loadIcon((PackageManager) Mockito.any()); } public void testOnCreate() { ResolveInfo info0 = new ResolveInfo(); ResolveInfo info1 = new ResolveInfo(); final List<ResolveInfo> infos = Arrays.asList(info0, info1); final Holder<ResolveInfo> iconHolder = new Holder<ResolveInfo>(); final Holder<ResolveInfo> labelHolder = new Holder<ResolveInfo>(); final Drawable drawable = Mockito.mock(Drawable.class);
final AppUtils appUtils = Mockito.mock(AppUtils.class);
socialize/loopy-sdk-android
sdk/src/com/sharethis/loopy/sdk/Config.java
// Path: sdk/src/com/sharethis/loopy/sdk/net/HttpClientFactory.java // public class HttpClientFactory { // // public static final int DEFAULT_CONNECTION_TIMEOUT = 1000; // public static final int DEFAULT_READ_TIMEOUT = 1000; // // private HttpParams params; // private ClientConnectionManager connectionManager; // private DefaultHttpClient client; // This should be thread safe // private IdleConnectionMonitorThread monitor; // private boolean initialized = false; // // private int connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; // private int readTimeout = DEFAULT_READ_TIMEOUT; // // public void start(int timeout) { // setConnectionTimeout(timeout); // setReadTimeout(timeout); // init(); // } // // public void stop() { // destroy(); // } // // void init() { // if(!initialized) { // // params = new BasicHttpParams(); // // HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); // HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); // HttpConnectionParams.setSoTimeout(params, readTimeout); // // SchemeRegistry registry = new SchemeRegistry(); // registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); // // connectionManager = new ThreadSafeClientConnManager(params, registry); // // monitor = new IdleConnectionMonitorThread(connectionManager); // monitor.setDaemon(true); // monitor.start(); // } // } // // void destroy() { // if(initialized) { // initialized = false; // if(monitor != null) { // monitor.shutdown(); // } // if(connectionManager != null) { // connectionManager.shutdown(); // } // } // } // // public synchronized HttpClient getClient() { // if(client == null) { // client = new DefaultHttpClient(connectionManager, params); // } // else { // monitor.trigger(); // } // // return client; // } // // public int getConnectionTimeout() { // return connectionTimeout; // } // // public void setConnectionTimeout(int connectionTimeout) { // this.connectionTimeout = connectionTimeout; // } // // public int getReadTimeout() { // return readTimeout; // } // // public void setReadTimeout(int readTimeout) { // this.readTimeout = readTimeout; // } // } // // Path: sdk/src/com/sharethis/loopy/sdk/util/ResourceLocator.java // public class ResourceLocator { // private ClassLoaderProvider classLoaderProvider = new ClassLoaderProvider(); // // public InputStream locateInAssets(Context context, String name) throws IOException { // InputStream in = null; // // try { // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in asset path..."); // } // // in = context.getAssets().open(name); // // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in asset path"); // } // } // catch (IOException ignore) { // // Ignore this, just means no override. // if(Logger.isDebugEnabled()) { // Logger.d("No file found in assets with name [" + // name + // "]."); // } // } // // return in; // } // // public InputStream locateInClassPath(String name) throws IOException { // // InputStream in = null; // // if(classLoaderProvider != null) { // // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in classpath..."); // } // // in = classLoaderProvider.getClassLoader().getResourceAsStream(name); // // if(in != null) { // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in classpath"); // } // } // } // // return in; // } // // public InputStream locate(Context context, String name) throws IOException { // // InputStream in = locateInAssets(context, name); // // if(in == null) { // in = locateInClassPath(name); // } // // if(in == null) { // Logger.w("Could not locate [" + // name + // "] in any location"); // } // // return in; // } // // public ClassLoaderProvider getClassLoaderProvider() { // return classLoaderProvider; // } // // public void setClassLoaderProvider(ClassLoaderProvider classLoaderProvider) { // this.classLoaderProvider = classLoaderProvider; // } // }
import android.content.Context; import com.sharethis.loopy.sdk.net.HttpClientFactory; import com.sharethis.loopy.sdk.util.ResourceLocator; import java.io.IOException; import java.io.InputStream; import java.util.Properties;
package com.sharethis.loopy.sdk; /** * @author Jason Polites */ public class Config { public static final int SESSION_LOAD_TIMEOUT = 2000; public static final int USER_SESSION_TIMEOUT_SECONDS = 60; public static final String DEFAULT_API_URL = "http://loopy.getsocialize.com/v1/"; public static final String DEFAULT_SECURE_URL = "https://loopy.getsocialize.com/v1/"; public static final String LOOPY_PROPERTIES = "loopy.properties"; private String apiUrl = DEFAULT_API_URL; private String secureApiUrl = DEFAULT_SECURE_URL;
// Path: sdk/src/com/sharethis/loopy/sdk/net/HttpClientFactory.java // public class HttpClientFactory { // // public static final int DEFAULT_CONNECTION_TIMEOUT = 1000; // public static final int DEFAULT_READ_TIMEOUT = 1000; // // private HttpParams params; // private ClientConnectionManager connectionManager; // private DefaultHttpClient client; // This should be thread safe // private IdleConnectionMonitorThread monitor; // private boolean initialized = false; // // private int connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; // private int readTimeout = DEFAULT_READ_TIMEOUT; // // public void start(int timeout) { // setConnectionTimeout(timeout); // setReadTimeout(timeout); // init(); // } // // public void stop() { // destroy(); // } // // void init() { // if(!initialized) { // // params = new BasicHttpParams(); // // HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); // HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); // HttpConnectionParams.setSoTimeout(params, readTimeout); // // SchemeRegistry registry = new SchemeRegistry(); // registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); // // connectionManager = new ThreadSafeClientConnManager(params, registry); // // monitor = new IdleConnectionMonitorThread(connectionManager); // monitor.setDaemon(true); // monitor.start(); // } // } // // void destroy() { // if(initialized) { // initialized = false; // if(monitor != null) { // monitor.shutdown(); // } // if(connectionManager != null) { // connectionManager.shutdown(); // } // } // } // // public synchronized HttpClient getClient() { // if(client == null) { // client = new DefaultHttpClient(connectionManager, params); // } // else { // monitor.trigger(); // } // // return client; // } // // public int getConnectionTimeout() { // return connectionTimeout; // } // // public void setConnectionTimeout(int connectionTimeout) { // this.connectionTimeout = connectionTimeout; // } // // public int getReadTimeout() { // return readTimeout; // } // // public void setReadTimeout(int readTimeout) { // this.readTimeout = readTimeout; // } // } // // Path: sdk/src/com/sharethis/loopy/sdk/util/ResourceLocator.java // public class ResourceLocator { // private ClassLoaderProvider classLoaderProvider = new ClassLoaderProvider(); // // public InputStream locateInAssets(Context context, String name) throws IOException { // InputStream in = null; // // try { // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in asset path..."); // } // // in = context.getAssets().open(name); // // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in asset path"); // } // } // catch (IOException ignore) { // // Ignore this, just means no override. // if(Logger.isDebugEnabled()) { // Logger.d("No file found in assets with name [" + // name + // "]."); // } // } // // return in; // } // // public InputStream locateInClassPath(String name) throws IOException { // // InputStream in = null; // // if(classLoaderProvider != null) { // // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in classpath..."); // } // // in = classLoaderProvider.getClassLoader().getResourceAsStream(name); // // if(in != null) { // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in classpath"); // } // } // } // // return in; // } // // public InputStream locate(Context context, String name) throws IOException { // // InputStream in = locateInAssets(context, name); // // if(in == null) { // in = locateInClassPath(name); // } // // if(in == null) { // Logger.w("Could not locate [" + // name + // "] in any location"); // } // // return in; // } // // public ClassLoaderProvider getClassLoaderProvider() { // return classLoaderProvider; // } // // public void setClassLoaderProvider(ClassLoaderProvider classLoaderProvider) { // this.classLoaderProvider = classLoaderProvider; // } // } // Path: sdk/src/com/sharethis/loopy/sdk/Config.java import android.content.Context; import com.sharethis.loopy.sdk.net.HttpClientFactory; import com.sharethis.loopy.sdk.util.ResourceLocator; import java.io.IOException; import java.io.InputStream; import java.util.Properties; package com.sharethis.loopy.sdk; /** * @author Jason Polites */ public class Config { public static final int SESSION_LOAD_TIMEOUT = 2000; public static final int USER_SESSION_TIMEOUT_SECONDS = 60; public static final String DEFAULT_API_URL = "http://loopy.getsocialize.com/v1/"; public static final String DEFAULT_SECURE_URL = "https://loopy.getsocialize.com/v1/"; public static final String LOOPY_PROPERTIES = "loopy.properties"; private String apiUrl = DEFAULT_API_URL; private String secureApiUrl = DEFAULT_SECURE_URL;
private int apiTimeout = HttpClientFactory.DEFAULT_READ_TIMEOUT;
socialize/loopy-sdk-android
sdk/src/com/sharethis/loopy/sdk/Config.java
// Path: sdk/src/com/sharethis/loopy/sdk/net/HttpClientFactory.java // public class HttpClientFactory { // // public static final int DEFAULT_CONNECTION_TIMEOUT = 1000; // public static final int DEFAULT_READ_TIMEOUT = 1000; // // private HttpParams params; // private ClientConnectionManager connectionManager; // private DefaultHttpClient client; // This should be thread safe // private IdleConnectionMonitorThread monitor; // private boolean initialized = false; // // private int connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; // private int readTimeout = DEFAULT_READ_TIMEOUT; // // public void start(int timeout) { // setConnectionTimeout(timeout); // setReadTimeout(timeout); // init(); // } // // public void stop() { // destroy(); // } // // void init() { // if(!initialized) { // // params = new BasicHttpParams(); // // HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); // HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); // HttpConnectionParams.setSoTimeout(params, readTimeout); // // SchemeRegistry registry = new SchemeRegistry(); // registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); // // connectionManager = new ThreadSafeClientConnManager(params, registry); // // monitor = new IdleConnectionMonitorThread(connectionManager); // monitor.setDaemon(true); // monitor.start(); // } // } // // void destroy() { // if(initialized) { // initialized = false; // if(monitor != null) { // monitor.shutdown(); // } // if(connectionManager != null) { // connectionManager.shutdown(); // } // } // } // // public synchronized HttpClient getClient() { // if(client == null) { // client = new DefaultHttpClient(connectionManager, params); // } // else { // monitor.trigger(); // } // // return client; // } // // public int getConnectionTimeout() { // return connectionTimeout; // } // // public void setConnectionTimeout(int connectionTimeout) { // this.connectionTimeout = connectionTimeout; // } // // public int getReadTimeout() { // return readTimeout; // } // // public void setReadTimeout(int readTimeout) { // this.readTimeout = readTimeout; // } // } // // Path: sdk/src/com/sharethis/loopy/sdk/util/ResourceLocator.java // public class ResourceLocator { // private ClassLoaderProvider classLoaderProvider = new ClassLoaderProvider(); // // public InputStream locateInAssets(Context context, String name) throws IOException { // InputStream in = null; // // try { // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in asset path..."); // } // // in = context.getAssets().open(name); // // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in asset path"); // } // } // catch (IOException ignore) { // // Ignore this, just means no override. // if(Logger.isDebugEnabled()) { // Logger.d("No file found in assets with name [" + // name + // "]."); // } // } // // return in; // } // // public InputStream locateInClassPath(String name) throws IOException { // // InputStream in = null; // // if(classLoaderProvider != null) { // // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in classpath..."); // } // // in = classLoaderProvider.getClassLoader().getResourceAsStream(name); // // if(in != null) { // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in classpath"); // } // } // } // // return in; // } // // public InputStream locate(Context context, String name) throws IOException { // // InputStream in = locateInAssets(context, name); // // if(in == null) { // in = locateInClassPath(name); // } // // if(in == null) { // Logger.w("Could not locate [" + // name + // "] in any location"); // } // // return in; // } // // public ClassLoaderProvider getClassLoaderProvider() { // return classLoaderProvider; // } // // public void setClassLoaderProvider(ClassLoaderProvider classLoaderProvider) { // this.classLoaderProvider = classLoaderProvider; // } // }
import android.content.Context; import com.sharethis.loopy.sdk.net.HttpClientFactory; import com.sharethis.loopy.sdk.util.ResourceLocator; import java.io.IOException; import java.io.InputStream; import java.util.Properties;
package com.sharethis.loopy.sdk; /** * @author Jason Polites */ public class Config { public static final int SESSION_LOAD_TIMEOUT = 2000; public static final int USER_SESSION_TIMEOUT_SECONDS = 60; public static final String DEFAULT_API_URL = "http://loopy.getsocialize.com/v1/"; public static final String DEFAULT_SECURE_URL = "https://loopy.getsocialize.com/v1/"; public static final String LOOPY_PROPERTIES = "loopy.properties"; private String apiUrl = DEFAULT_API_URL; private String secureApiUrl = DEFAULT_SECURE_URL; private int apiTimeout = HttpClientFactory.DEFAULT_READ_TIMEOUT; private boolean debug = false; // Time between successive open calls in seconds private int sessionTimeoutSeconds = USER_SESSION_TIMEOUT_SECONDS; boolean initialized = false; public Config load(Context context) { if(!initialized) {
// Path: sdk/src/com/sharethis/loopy/sdk/net/HttpClientFactory.java // public class HttpClientFactory { // // public static final int DEFAULT_CONNECTION_TIMEOUT = 1000; // public static final int DEFAULT_READ_TIMEOUT = 1000; // // private HttpParams params; // private ClientConnectionManager connectionManager; // private DefaultHttpClient client; // This should be thread safe // private IdleConnectionMonitorThread monitor; // private boolean initialized = false; // // private int connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; // private int readTimeout = DEFAULT_READ_TIMEOUT; // // public void start(int timeout) { // setConnectionTimeout(timeout); // setReadTimeout(timeout); // init(); // } // // public void stop() { // destroy(); // } // // void init() { // if(!initialized) { // // params = new BasicHttpParams(); // // HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); // HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); // HttpConnectionParams.setSoTimeout(params, readTimeout); // // SchemeRegistry registry = new SchemeRegistry(); // registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); // // connectionManager = new ThreadSafeClientConnManager(params, registry); // // monitor = new IdleConnectionMonitorThread(connectionManager); // monitor.setDaemon(true); // monitor.start(); // } // } // // void destroy() { // if(initialized) { // initialized = false; // if(monitor != null) { // monitor.shutdown(); // } // if(connectionManager != null) { // connectionManager.shutdown(); // } // } // } // // public synchronized HttpClient getClient() { // if(client == null) { // client = new DefaultHttpClient(connectionManager, params); // } // else { // monitor.trigger(); // } // // return client; // } // // public int getConnectionTimeout() { // return connectionTimeout; // } // // public void setConnectionTimeout(int connectionTimeout) { // this.connectionTimeout = connectionTimeout; // } // // public int getReadTimeout() { // return readTimeout; // } // // public void setReadTimeout(int readTimeout) { // this.readTimeout = readTimeout; // } // } // // Path: sdk/src/com/sharethis/loopy/sdk/util/ResourceLocator.java // public class ResourceLocator { // private ClassLoaderProvider classLoaderProvider = new ClassLoaderProvider(); // // public InputStream locateInAssets(Context context, String name) throws IOException { // InputStream in = null; // // try { // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in asset path..."); // } // // in = context.getAssets().open(name); // // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in asset path"); // } // } // catch (IOException ignore) { // // Ignore this, just means no override. // if(Logger.isDebugEnabled()) { // Logger.d("No file found in assets with name [" + // name + // "]."); // } // } // // return in; // } // // public InputStream locateInClassPath(String name) throws IOException { // // InputStream in = null; // // if(classLoaderProvider != null) { // // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in classpath..."); // } // // in = classLoaderProvider.getClassLoader().getResourceAsStream(name); // // if(in != null) { // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in classpath"); // } // } // } // // return in; // } // // public InputStream locate(Context context, String name) throws IOException { // // InputStream in = locateInAssets(context, name); // // if(in == null) { // in = locateInClassPath(name); // } // // if(in == null) { // Logger.w("Could not locate [" + // name + // "] in any location"); // } // // return in; // } // // public ClassLoaderProvider getClassLoaderProvider() { // return classLoaderProvider; // } // // public void setClassLoaderProvider(ClassLoaderProvider classLoaderProvider) { // this.classLoaderProvider = classLoaderProvider; // } // } // Path: sdk/src/com/sharethis/loopy/sdk/Config.java import android.content.Context; import com.sharethis.loopy.sdk.net.HttpClientFactory; import com.sharethis.loopy.sdk.util.ResourceLocator; import java.io.IOException; import java.io.InputStream; import java.util.Properties; package com.sharethis.loopy.sdk; /** * @author Jason Polites */ public class Config { public static final int SESSION_LOAD_TIMEOUT = 2000; public static final int USER_SESSION_TIMEOUT_SECONDS = 60; public static final String DEFAULT_API_URL = "http://loopy.getsocialize.com/v1/"; public static final String DEFAULT_SECURE_URL = "https://loopy.getsocialize.com/v1/"; public static final String LOOPY_PROPERTIES = "loopy.properties"; private String apiUrl = DEFAULT_API_URL; private String secureApiUrl = DEFAULT_SECURE_URL; private int apiTimeout = HttpClientFactory.DEFAULT_READ_TIMEOUT; private boolean debug = false; // Time between successive open calls in seconds private int sessionTimeoutSeconds = USER_SESSION_TIMEOUT_SECONDS; boolean initialized = false; public Config load(Context context) { if(!initialized) {
ResourceLocator locator = newResourceLocator();
socialize/loopy-sdk-android
sdk/src/com/sharethis/loopy/sdk/Geo.java
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppUtils.java // public class AppUtils { // // static final AppUtils instance = new AppUtils(); // // AppUtils() {} // // public static AppUtils getInstance() { // return instance; // } // // /** // * Determines inclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ALL the given permissions. // */ // public boolean hasAndPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res != PackageManager.PERMISSION_GRANTED) { // return false; // } // } // return true; // } // // /** // * Determines exclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ANY the given permissions. // */ // public boolean hasOrPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res == PackageManager.PERMISSION_GRANTED) { // return true; // } // } // return false; // } // // /** // * Returns the app info for the apps which support the ACTION_SEND intent with the given types. // * @param context The current context. // * @param contentTypes The content types supported. // * @return A Collection (set) of ResolveInfo objects corresponding to the apps installed on the device that // * support the content type(s). // */ // public Collection<ResolveInfo> getAppsForContentType(Context context, String...contentTypes) { // Set<ResolveInfo> apps = new LinkedHashSet<ResolveInfo>(); // for (String type : contentTypes) { // List<ResolveInfo> appsByType = listAppsForType(context, type); // if(appsByType != null && appsByType.size() > 0) { // apps.addAll(appsByType); // } // } // return apps; // } // // List<ResolveInfo> listAppsForType(Context context, String type) { // Intent intent = getSendIntent(); // intent.setType(type); // // PackageManager p = context.getPackageManager(); // // List<ResolveInfo> appList = p.queryIntentActivities(intent, 0); // // // Sort alphabetically. // Collections.sort(appList, new android.content.pm.ResolveInfo.DisplayNameComparator(p)); // // return appList; // } // // // mockable // Intent getSendIntent() { // return new Intent(Intent.ACTION_SEND); // } // // }
import android.content.Context; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import com.sharethis.loopy.sdk.util.AppUtils;
lm.removeUpdates(this); } catch (Throwable e) { Logger.w(e); } } public void onStart(Context context) { try { LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_COARSE); lm.requestLocationUpdates(lm.getBestProvider(criteria, true), 0, 0, this); } catch (Throwable e) { Logger.w(e); } } public double getLat() { return lat; } public double getLon() { return lon; } static boolean hasPermission(Context context) { String permission0 = "android.permission.ACCESS_FINE_LOCATION"; String permission1 = "android.permission.ACCESS_COARSE_LOCATION";
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppUtils.java // public class AppUtils { // // static final AppUtils instance = new AppUtils(); // // AppUtils() {} // // public static AppUtils getInstance() { // return instance; // } // // /** // * Determines inclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ALL the given permissions. // */ // public boolean hasAndPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res != PackageManager.PERMISSION_GRANTED) { // return false; // } // } // return true; // } // // /** // * Determines exclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ANY the given permissions. // */ // public boolean hasOrPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res == PackageManager.PERMISSION_GRANTED) { // return true; // } // } // return false; // } // // /** // * Returns the app info for the apps which support the ACTION_SEND intent with the given types. // * @param context The current context. // * @param contentTypes The content types supported. // * @return A Collection (set) of ResolveInfo objects corresponding to the apps installed on the device that // * support the content type(s). // */ // public Collection<ResolveInfo> getAppsForContentType(Context context, String...contentTypes) { // Set<ResolveInfo> apps = new LinkedHashSet<ResolveInfo>(); // for (String type : contentTypes) { // List<ResolveInfo> appsByType = listAppsForType(context, type); // if(appsByType != null && appsByType.size() > 0) { // apps.addAll(appsByType); // } // } // return apps; // } // // List<ResolveInfo> listAppsForType(Context context, String type) { // Intent intent = getSendIntent(); // intent.setType(type); // // PackageManager p = context.getPackageManager(); // // List<ResolveInfo> appList = p.queryIntentActivities(intent, 0); // // // Sort alphabetically. // Collections.sort(appList, new android.content.pm.ResolveInfo.DisplayNameComparator(p)); // // return appList; // } // // // mockable // Intent getSendIntent() { // return new Intent(Intent.ACTION_SEND); // } // // } // Path: sdk/src/com/sharethis/loopy/sdk/Geo.java import android.content.Context; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import com.sharethis.loopy.sdk.util.AppUtils; lm.removeUpdates(this); } catch (Throwable e) { Logger.w(e); } } public void onStart(Context context) { try { LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_COARSE); lm.requestLocationUpdates(lm.getBestProvider(criteria, true), 0, 0, this); } catch (Throwable e) { Logger.w(e); } } public double getLat() { return lat; } public double getLon() { return lon; } static boolean hasPermission(Context context) { String permission0 = "android.permission.ACCESS_FINE_LOCATION"; String permission1 = "android.permission.ACCESS_COARSE_LOCATION";
return AppUtils.getInstance().hasOrPermission(context, permission0, permission1);
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/ConfigTest.java
// Path: test/src/com/sharethis/loopy/sdk/MockConfig.java // public class MockConfig extends Config { // // @Override // public Properties newProperties() { // return super.newProperties(); // } // // @Override // public String clean(String url) { // return super.clean(url); // } // // @Override // public ResourceLocator newResourceLocator() { // return super.newResourceLocator(); // } // // @Override // public boolean getBooleanProperty(Properties props, String key, boolean defaultValue) { // return super.getBooleanProperty(props, key, defaultValue); // } // // @Override // public int getIntProperty(Properties props, String key, int defaultValue) { // return super.getIntProperty(props, key, defaultValue); // } // // @Override // public String getUrlProperty(Properties props, String key) { // return super.getUrlProperty(props, key); // } // } // // Path: sdk/src/com/sharethis/loopy/sdk/util/ResourceLocator.java // public class ResourceLocator { // private ClassLoaderProvider classLoaderProvider = new ClassLoaderProvider(); // // public InputStream locateInAssets(Context context, String name) throws IOException { // InputStream in = null; // // try { // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in asset path..."); // } // // in = context.getAssets().open(name); // // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in asset path"); // } // } // catch (IOException ignore) { // // Ignore this, just means no override. // if(Logger.isDebugEnabled()) { // Logger.d("No file found in assets with name [" + // name + // "]."); // } // } // // return in; // } // // public InputStream locateInClassPath(String name) throws IOException { // // InputStream in = null; // // if(classLoaderProvider != null) { // // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in classpath..."); // } // // in = classLoaderProvider.getClassLoader().getResourceAsStream(name); // // if(in != null) { // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in classpath"); // } // } // } // // return in; // } // // public InputStream locate(Context context, String name) throws IOException { // // InputStream in = locateInAssets(context, name); // // if(in == null) { // in = locateInClassPath(name); // } // // if(in == null) { // Logger.w("Could not locate [" + // name + // "] in any location"); // } // // return in; // } // // public ClassLoaderProvider getClassLoaderProvider() { // return classLoaderProvider; // } // // public void setClassLoaderProvider(ClassLoaderProvider classLoaderProvider) { // this.classLoaderProvider = classLoaderProvider; // } // }
import java.io.InputStream; import java.util.Properties; import android.content.Context; import com.sharethis.loopy.sdk.MockConfig; import com.sharethis.loopy.sdk.util.ResourceLocator; import org.mockito.Mockito; import java.io.IOException;
/* * * * Copyright (c) 2013 ShareThis Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * * THE SOFTWARE. * */ package com.sharethis.loopy.test; /** * @author Jason Polites */ public class ConfigTest extends LoopyActivityTestCase { public void testConfigLoadWithOverride() throws IOException { final Context context = getContext(); final String apiUrl = "foobar_url/"; final String secureApiUrl = "foobar_secure_url/"; final String apiTimeout = "69"; final String sessionTimeout = "96"; final String debug = "true";
// Path: test/src/com/sharethis/loopy/sdk/MockConfig.java // public class MockConfig extends Config { // // @Override // public Properties newProperties() { // return super.newProperties(); // } // // @Override // public String clean(String url) { // return super.clean(url); // } // // @Override // public ResourceLocator newResourceLocator() { // return super.newResourceLocator(); // } // // @Override // public boolean getBooleanProperty(Properties props, String key, boolean defaultValue) { // return super.getBooleanProperty(props, key, defaultValue); // } // // @Override // public int getIntProperty(Properties props, String key, int defaultValue) { // return super.getIntProperty(props, key, defaultValue); // } // // @Override // public String getUrlProperty(Properties props, String key) { // return super.getUrlProperty(props, key); // } // } // // Path: sdk/src/com/sharethis/loopy/sdk/util/ResourceLocator.java // public class ResourceLocator { // private ClassLoaderProvider classLoaderProvider = new ClassLoaderProvider(); // // public InputStream locateInAssets(Context context, String name) throws IOException { // InputStream in = null; // // try { // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in asset path..."); // } // // in = context.getAssets().open(name); // // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in asset path"); // } // } // catch (IOException ignore) { // // Ignore this, just means no override. // if(Logger.isDebugEnabled()) { // Logger.d("No file found in assets with name [" + // name + // "]."); // } // } // // return in; // } // // public InputStream locateInClassPath(String name) throws IOException { // // InputStream in = null; // // if(classLoaderProvider != null) { // // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in classpath..."); // } // // in = classLoaderProvider.getClassLoader().getResourceAsStream(name); // // if(in != null) { // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in classpath"); // } // } // } // // return in; // } // // public InputStream locate(Context context, String name) throws IOException { // // InputStream in = locateInAssets(context, name); // // if(in == null) { // in = locateInClassPath(name); // } // // if(in == null) { // Logger.w("Could not locate [" + // name + // "] in any location"); // } // // return in; // } // // public ClassLoaderProvider getClassLoaderProvider() { // return classLoaderProvider; // } // // public void setClassLoaderProvider(ClassLoaderProvider classLoaderProvider) { // this.classLoaderProvider = classLoaderProvider; // } // } // Path: test/src/com/sharethis/loopy/test/ConfigTest.java import java.io.InputStream; import java.util.Properties; import android.content.Context; import com.sharethis.loopy.sdk.MockConfig; import com.sharethis.loopy.sdk.util.ResourceLocator; import org.mockito.Mockito; import java.io.IOException; /* * * * Copyright (c) 2013 ShareThis Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * * THE SOFTWARE. * */ package com.sharethis.loopy.test; /** * @author Jason Polites */ public class ConfigTest extends LoopyActivityTestCase { public void testConfigLoadWithOverride() throws IOException { final Context context = getContext(); final String apiUrl = "foobar_url/"; final String secureApiUrl = "foobar_secure_url/"; final String apiTimeout = "69"; final String sessionTimeout = "96"; final String debug = "true";
final ResourceLocator resourceLocator = Mockito.mock(ResourceLocator.class);
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/ConfigTest.java
// Path: test/src/com/sharethis/loopy/sdk/MockConfig.java // public class MockConfig extends Config { // // @Override // public Properties newProperties() { // return super.newProperties(); // } // // @Override // public String clean(String url) { // return super.clean(url); // } // // @Override // public ResourceLocator newResourceLocator() { // return super.newResourceLocator(); // } // // @Override // public boolean getBooleanProperty(Properties props, String key, boolean defaultValue) { // return super.getBooleanProperty(props, key, defaultValue); // } // // @Override // public int getIntProperty(Properties props, String key, int defaultValue) { // return super.getIntProperty(props, key, defaultValue); // } // // @Override // public String getUrlProperty(Properties props, String key) { // return super.getUrlProperty(props, key); // } // } // // Path: sdk/src/com/sharethis/loopy/sdk/util/ResourceLocator.java // public class ResourceLocator { // private ClassLoaderProvider classLoaderProvider = new ClassLoaderProvider(); // // public InputStream locateInAssets(Context context, String name) throws IOException { // InputStream in = null; // // try { // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in asset path..."); // } // // in = context.getAssets().open(name); // // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in asset path"); // } // } // catch (IOException ignore) { // // Ignore this, just means no override. // if(Logger.isDebugEnabled()) { // Logger.d("No file found in assets with name [" + // name + // "]."); // } // } // // return in; // } // // public InputStream locateInClassPath(String name) throws IOException { // // InputStream in = null; // // if(classLoaderProvider != null) { // // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in classpath..."); // } // // in = classLoaderProvider.getClassLoader().getResourceAsStream(name); // // if(in != null) { // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in classpath"); // } // } // } // // return in; // } // // public InputStream locate(Context context, String name) throws IOException { // // InputStream in = locateInAssets(context, name); // // if(in == null) { // in = locateInClassPath(name); // } // // if(in == null) { // Logger.w("Could not locate [" + // name + // "] in any location"); // } // // return in; // } // // public ClassLoaderProvider getClassLoaderProvider() { // return classLoaderProvider; // } // // public void setClassLoaderProvider(ClassLoaderProvider classLoaderProvider) { // this.classLoaderProvider = classLoaderProvider; // } // }
import java.io.InputStream; import java.util.Properties; import android.content.Context; import com.sharethis.loopy.sdk.MockConfig; import com.sharethis.loopy.sdk.util.ResourceLocator; import org.mockito.Mockito; import java.io.IOException;
/* * * * Copyright (c) 2013 ShareThis Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * * THE SOFTWARE. * */ package com.sharethis.loopy.test; /** * @author Jason Polites */ public class ConfigTest extends LoopyActivityTestCase { public void testConfigLoadWithOverride() throws IOException { final Context context = getContext(); final String apiUrl = "foobar_url/"; final String secureApiUrl = "foobar_secure_url/"; final String apiTimeout = "69"; final String sessionTimeout = "96"; final String debug = "true"; final ResourceLocator resourceLocator = Mockito.mock(ResourceLocator.class); final Properties props = Mockito.mock(Properties.class); final Properties overrideProps = Mockito.mock(Properties.class); final InputStream in = Mockito.mock(InputStream.class); final InputStream override = Mockito.mock(InputStream.class); Mockito.when(resourceLocator.locateInClassPath("loopy.properties")).thenReturn(in); Mockito.when(resourceLocator.locateInAssets(context, "loopy.properties")).thenReturn(override); Mockito.when(props.getProperty("api.host")).thenReturn(apiUrl); Mockito.when(props.getProperty("secure.api.host")).thenReturn(secureApiUrl); Mockito.when(props.getProperty("api.timeout")).thenReturn(apiTimeout); Mockito.when(props.getProperty("session.timeout")).thenReturn(sessionTimeout); Mockito.when(props.getProperty("debug")).thenReturn(debug);
// Path: test/src/com/sharethis/loopy/sdk/MockConfig.java // public class MockConfig extends Config { // // @Override // public Properties newProperties() { // return super.newProperties(); // } // // @Override // public String clean(String url) { // return super.clean(url); // } // // @Override // public ResourceLocator newResourceLocator() { // return super.newResourceLocator(); // } // // @Override // public boolean getBooleanProperty(Properties props, String key, boolean defaultValue) { // return super.getBooleanProperty(props, key, defaultValue); // } // // @Override // public int getIntProperty(Properties props, String key, int defaultValue) { // return super.getIntProperty(props, key, defaultValue); // } // // @Override // public String getUrlProperty(Properties props, String key) { // return super.getUrlProperty(props, key); // } // } // // Path: sdk/src/com/sharethis/loopy/sdk/util/ResourceLocator.java // public class ResourceLocator { // private ClassLoaderProvider classLoaderProvider = new ClassLoaderProvider(); // // public InputStream locateInAssets(Context context, String name) throws IOException { // InputStream in = null; // // try { // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in asset path..."); // } // // in = context.getAssets().open(name); // // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in asset path"); // } // } // catch (IOException ignore) { // // Ignore this, just means no override. // if(Logger.isDebugEnabled()) { // Logger.d("No file found in assets with name [" + // name + // "]."); // } // } // // return in; // } // // public InputStream locateInClassPath(String name) throws IOException { // // InputStream in = null; // // if(classLoaderProvider != null) { // // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in classpath..."); // } // // in = classLoaderProvider.getClassLoader().getResourceAsStream(name); // // if(in != null) { // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in classpath"); // } // } // } // // return in; // } // // public InputStream locate(Context context, String name) throws IOException { // // InputStream in = locateInAssets(context, name); // // if(in == null) { // in = locateInClassPath(name); // } // // if(in == null) { // Logger.w("Could not locate [" + // name + // "] in any location"); // } // // return in; // } // // public ClassLoaderProvider getClassLoaderProvider() { // return classLoaderProvider; // } // // public void setClassLoaderProvider(ClassLoaderProvider classLoaderProvider) { // this.classLoaderProvider = classLoaderProvider; // } // } // Path: test/src/com/sharethis/loopy/test/ConfigTest.java import java.io.InputStream; import java.util.Properties; import android.content.Context; import com.sharethis.loopy.sdk.MockConfig; import com.sharethis.loopy.sdk.util.ResourceLocator; import org.mockito.Mockito; import java.io.IOException; /* * * * Copyright (c) 2013 ShareThis Inc. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * * THE SOFTWARE. * */ package com.sharethis.loopy.test; /** * @author Jason Polites */ public class ConfigTest extends LoopyActivityTestCase { public void testConfigLoadWithOverride() throws IOException { final Context context = getContext(); final String apiUrl = "foobar_url/"; final String secureApiUrl = "foobar_secure_url/"; final String apiTimeout = "69"; final String sessionTimeout = "96"; final String debug = "true"; final ResourceLocator resourceLocator = Mockito.mock(ResourceLocator.class); final Properties props = Mockito.mock(Properties.class); final Properties overrideProps = Mockito.mock(Properties.class); final InputStream in = Mockito.mock(InputStream.class); final InputStream override = Mockito.mock(InputStream.class); Mockito.when(resourceLocator.locateInClassPath("loopy.properties")).thenReturn(in); Mockito.when(resourceLocator.locateInAssets(context, "loopy.properties")).thenReturn(override); Mockito.when(props.getProperty("api.host")).thenReturn(apiUrl); Mockito.when(props.getProperty("secure.api.host")).thenReturn(secureApiUrl); Mockito.when(props.getProperty("api.timeout")).thenReturn(apiTimeout); Mockito.when(props.getProperty("session.timeout")).thenReturn(sessionTimeout); Mockito.when(props.getProperty("debug")).thenReturn(debug);
MockConfig config = Mockito.spy(new MockConfig());
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/LoopyStateTest.java
// Path: sdk/src/com/sharethis/loopy/sdk/ApiCallback.java // public abstract class ApiCallback { // // /** // * Called when the API request succeeded. // * This method executes on the main UI thread. // * @param result The result from the API call. // */ // public abstract void onSuccess(JSONObject result); // // /** // * Called when an unrecoverable error occurred during the API call. // * This method executes on the main UI thread. // * @param e The exception thrown within the async task. // */ // public void onError(Throwable e) {} // // /** // * Called within the async task. Implement this if you want additional work in the async task thread. // * This method is NOT called on the main UI thread. // * @param result The result from the API call. // */ // public void onProcess(JSONObject result) {} // // /** // * For internal use only // * @param payload The payload to be sent to the server // */ // public void onBeforePost(Map<String, String> headers, JSONObject payload) {} // } // // Path: test/src/com/sharethis/loopy/sdk/MockLoopyState.java // public class MockLoopyState extends LoopyState { // @Override // public void clear(Context context) { // super.clear(context); // } // }
import android.content.Context; import com.sharethis.loopy.sdk.ApiCallback; import com.sharethis.loopy.sdk.MockLoopyState; import org.json.JSONObject; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit;
package com.sharethis.loopy.test; /** * @author Jason Polites */ public class LoopyStateTest extends LoopyAndroidTestCase { MockLoopyState state = null; @Override public void setUp() throws Exception { state = new MockLoopyState(); super.setUp(); } @Override public void tearDown() throws Exception { state.clear(getLocalContext()); } // Integration test public void testSaveAndLoad() throws InterruptedException { String referrer = "foobar_referrer"; String stdid = "foobar_stdid"; Context context = getLocalContext(); state.clear(context); state.load(context); assertNull(state.getReferrer()); assertNull(state.getSTDID()); state.setReferrer(referrer); state.setStdid(stdid); final CountDownLatch latch = new CountDownLatch(1);
// Path: sdk/src/com/sharethis/loopy/sdk/ApiCallback.java // public abstract class ApiCallback { // // /** // * Called when the API request succeeded. // * This method executes on the main UI thread. // * @param result The result from the API call. // */ // public abstract void onSuccess(JSONObject result); // // /** // * Called when an unrecoverable error occurred during the API call. // * This method executes on the main UI thread. // * @param e The exception thrown within the async task. // */ // public void onError(Throwable e) {} // // /** // * Called within the async task. Implement this if you want additional work in the async task thread. // * This method is NOT called on the main UI thread. // * @param result The result from the API call. // */ // public void onProcess(JSONObject result) {} // // /** // * For internal use only // * @param payload The payload to be sent to the server // */ // public void onBeforePost(Map<String, String> headers, JSONObject payload) {} // } // // Path: test/src/com/sharethis/loopy/sdk/MockLoopyState.java // public class MockLoopyState extends LoopyState { // @Override // public void clear(Context context) { // super.clear(context); // } // } // Path: test/src/com/sharethis/loopy/test/LoopyStateTest.java import android.content.Context; import com.sharethis.loopy.sdk.ApiCallback; import com.sharethis.loopy.sdk.MockLoopyState; import org.json.JSONObject; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; package com.sharethis.loopy.test; /** * @author Jason Polites */ public class LoopyStateTest extends LoopyAndroidTestCase { MockLoopyState state = null; @Override public void setUp() throws Exception { state = new MockLoopyState(); super.setUp(); } @Override public void tearDown() throws Exception { state.clear(getLocalContext()); } // Integration test public void testSaveAndLoad() throws InterruptedException { String referrer = "foobar_referrer"; String stdid = "foobar_stdid"; Context context = getLocalContext(); state.clear(context); state.load(context); assertNull(state.getReferrer()); assertNull(state.getSTDID()); state.setReferrer(referrer); state.setStdid(stdid); final CountDownLatch latch = new CountDownLatch(1);
state.save(context, new ApiCallback() {
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/sdk/MockLoopy.java
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppUtils.java // public class AppUtils { // // static final AppUtils instance = new AppUtils(); // // AppUtils() {} // // public static AppUtils getInstance() { // return instance; // } // // /** // * Determines inclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ALL the given permissions. // */ // public boolean hasAndPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res != PackageManager.PERMISSION_GRANTED) { // return false; // } // } // return true; // } // // /** // * Determines exclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ANY the given permissions. // */ // public boolean hasOrPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res == PackageManager.PERMISSION_GRANTED) { // return true; // } // } // return false; // } // // /** // * Returns the app info for the apps which support the ACTION_SEND intent with the given types. // * @param context The current context. // * @param contentTypes The content types supported. // * @return A Collection (set) of ResolveInfo objects corresponding to the apps installed on the device that // * support the content type(s). // */ // public Collection<ResolveInfo> getAppsForContentType(Context context, String...contentTypes) { // Set<ResolveInfo> apps = new LinkedHashSet<ResolveInfo>(); // for (String type : contentTypes) { // List<ResolveInfo> appsByType = listAppsForType(context, type); // if(appsByType != null && appsByType.size() > 0) { // apps.addAll(appsByType); // } // } // return apps; // } // // List<ResolveInfo> listAppsForType(Context context, String type) { // Intent intent = getSendIntent(); // intent.setType(type); // // PackageManager p = context.getPackageManager(); // // List<ResolveInfo> appList = p.queryIntentActivities(intent, 0); // // // Sort alphabetically. // Collections.sort(appList, new android.content.pm.ResolveInfo.DisplayNameComparator(p)); // // return appList; // } // // // mockable // Intent getSendIntent() { // return new Intent(Intent.ACTION_SEND); // } // // }
import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.content.pm.ResolveInfo; import android.view.LayoutInflater; import com.sharethis.loopy.sdk.util.AppUtils; import java.util.Collection; import java.util.List;
super.shareFromIntent(context, item, intent); } @Override public ApiClient getApiClient() { return super.getApiClient(); } @Override public void doShareDialog(Context context, String title, Item item, Intent shareIntent, ShareDialogListener dialogListener) { super.doShareDialog(context, title, item, shareIntent, dialogListener); } public static void setInstance(Loopy instance) { Loopy.instance = instance; } public static void _reportShareFromIntent(Context context, Item item, Intent intent) { Loopy.reportShareFromIntent(context, item, intent); } public void setConfig(ShareConfig config) { this.config = config; } public void setShareClickListener(ShareClickListener listener) { this.shareClickListener = listener; } @Override
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppUtils.java // public class AppUtils { // // static final AppUtils instance = new AppUtils(); // // AppUtils() {} // // public static AppUtils getInstance() { // return instance; // } // // /** // * Determines inclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ALL the given permissions. // */ // public boolean hasAndPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res != PackageManager.PERMISSION_GRANTED) { // return false; // } // } // return true; // } // // /** // * Determines exclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ANY the given permissions. // */ // public boolean hasOrPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res == PackageManager.PERMISSION_GRANTED) { // return true; // } // } // return false; // } // // /** // * Returns the app info for the apps which support the ACTION_SEND intent with the given types. // * @param context The current context. // * @param contentTypes The content types supported. // * @return A Collection (set) of ResolveInfo objects corresponding to the apps installed on the device that // * support the content type(s). // */ // public Collection<ResolveInfo> getAppsForContentType(Context context, String...contentTypes) { // Set<ResolveInfo> apps = new LinkedHashSet<ResolveInfo>(); // for (String type : contentTypes) { // List<ResolveInfo> appsByType = listAppsForType(context, type); // if(appsByType != null && appsByType.size() > 0) { // apps.addAll(appsByType); // } // } // return apps; // } // // List<ResolveInfo> listAppsForType(Context context, String type) { // Intent intent = getSendIntent(); // intent.setType(type); // // PackageManager p = context.getPackageManager(); // // List<ResolveInfo> appList = p.queryIntentActivities(intent, 0); // // // Sort alphabetically. // Collections.sort(appList, new android.content.pm.ResolveInfo.DisplayNameComparator(p)); // // return appList; // } // // // mockable // Intent getSendIntent() { // return new Intent(Intent.ACTION_SEND); // } // // } // Path: test/src/com/sharethis/loopy/sdk/MockLoopy.java import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.content.pm.ResolveInfo; import android.view.LayoutInflater; import com.sharethis.loopy.sdk.util.AppUtils; import java.util.Collection; import java.util.List; super.shareFromIntent(context, item, intent); } @Override public ApiClient getApiClient() { return super.getApiClient(); } @Override public void doShareDialog(Context context, String title, Item item, Intent shareIntent, ShareDialogListener dialogListener) { super.doShareDialog(context, title, item, shareIntent, dialogListener); } public static void setInstance(Loopy instance) { Loopy.instance = instance; } public static void _reportShareFromIntent(Context context, Item item, Intent intent) { Loopy.reportShareFromIntent(context, item, intent); } public void setConfig(ShareConfig config) { this.config = config; } public void setShareClickListener(ShareClickListener listener) { this.shareClickListener = listener; } @Override
public AppUtils getAppUtils() {
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/sdk/MockShareDialogAdapter.java
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppDataCache.java // public class AppDataCache { // // private final Map<String, Drawable> iconCache = new HashMap<String, Drawable>(); // private final Map<String, String> labelCache = new HashMap<String, String>(); // // static AppDataCache instance = new AppDataCache(); // // AppDataCache() {} // // public static AppDataCache getInstance() { // return instance; // } // // public void onCreate(final Context context) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // Collection<ResolveInfo> appsForContentType = getAppUtils().getAppsForContentType(context, "*/*"); // for (ResolveInfo resolveInfo : appsForContentType) { // getAppIcon(context, resolveInfo); // getAppLabel(context, resolveInfo); // } // return null; // } // }.execute(); // } // // public void onDestroy(Context context) { // iconCache.clear(); // labelCache.clear(); // } // // public synchronized Drawable getAppIcon(Context context, ResolveInfo item) { // String key = getKey(item); // Drawable icon = iconCache.get(key); // if(icon == null) { // icon = item.activityInfo.loadIcon(context.getPackageManager()); // iconCache.put(key, icon); // } // return icon; // } // // /** // * May return null! // * @param packageName The package name. // * @param className The activity class name // * @return The app (activity) label, or null // */ // public String getAppLabel(String packageName, String className) { // return labelCache.get(packageName + "." + className); // } // // public synchronized String getAppLabel(Context context, ResolveInfo item) { // String key = getKey(item); // String label = labelCache.get(key); // if(label == null) { // label = item.activityInfo.loadLabel(context.getPackageManager()).toString(); // labelCache.put(key, label); // } // return label; // } // // String getKey(ResolveInfo item) { // return item.activityInfo.packageName + "." + item.activityInfo.name; // } // // // mockable // AppUtils getAppUtils() { // return AppUtils.getInstance(); // } // // }
import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.pm.ResolveInfo; import android.view.LayoutInflater; import android.widget.ImageView; import android.widget.TextView; import com.sharethis.loopy.sdk.util.AppDataCache; import java.util.List;
public void setShareIntent(Intent shareIntent) { super.setShareIntent(shareIntent); } @Override public void setConfig(ShareConfig config) { super.setConfig(config); } @Override public void setShareDialogListener(ShareDialogListener shareDialogListener) { super.setShareDialogListener(shareDialogListener); } @Override public void setText(Context context, TextView textView, ResolveInfo item) { super.setText(context, textView, item); } @Override public void setImage(Context context, ImageView imageView, ResolveInfo item) { super.setImage(context, imageView, item); } @Override public LayoutInflater getInflater(Context context) { return super.getInflater(context); } @Override
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppDataCache.java // public class AppDataCache { // // private final Map<String, Drawable> iconCache = new HashMap<String, Drawable>(); // private final Map<String, String> labelCache = new HashMap<String, String>(); // // static AppDataCache instance = new AppDataCache(); // // AppDataCache() {} // // public static AppDataCache getInstance() { // return instance; // } // // public void onCreate(final Context context) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // Collection<ResolveInfo> appsForContentType = getAppUtils().getAppsForContentType(context, "*/*"); // for (ResolveInfo resolveInfo : appsForContentType) { // getAppIcon(context, resolveInfo); // getAppLabel(context, resolveInfo); // } // return null; // } // }.execute(); // } // // public void onDestroy(Context context) { // iconCache.clear(); // labelCache.clear(); // } // // public synchronized Drawable getAppIcon(Context context, ResolveInfo item) { // String key = getKey(item); // Drawable icon = iconCache.get(key); // if(icon == null) { // icon = item.activityInfo.loadIcon(context.getPackageManager()); // iconCache.put(key, icon); // } // return icon; // } // // /** // * May return null! // * @param packageName The package name. // * @param className The activity class name // * @return The app (activity) label, or null // */ // public String getAppLabel(String packageName, String className) { // return labelCache.get(packageName + "." + className); // } // // public synchronized String getAppLabel(Context context, ResolveInfo item) { // String key = getKey(item); // String label = labelCache.get(key); // if(label == null) { // label = item.activityInfo.loadLabel(context.getPackageManager()).toString(); // labelCache.put(key, label); // } // return label; // } // // String getKey(ResolveInfo item) { // return item.activityInfo.packageName + "." + item.activityInfo.name; // } // // // mockable // AppUtils getAppUtils() { // return AppUtils.getInstance(); // } // // } // Path: test/src/com/sharethis/loopy/sdk/MockShareDialogAdapter.java import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.pm.ResolveInfo; import android.view.LayoutInflater; import android.widget.ImageView; import android.widget.TextView; import com.sharethis.loopy.sdk.util.AppDataCache; import java.util.List; public void setShareIntent(Intent shareIntent) { super.setShareIntent(shareIntent); } @Override public void setConfig(ShareConfig config) { super.setConfig(config); } @Override public void setShareDialogListener(ShareDialogListener shareDialogListener) { super.setShareDialogListener(shareDialogListener); } @Override public void setText(Context context, TextView textView, ResolveInfo item) { super.setText(context, textView, item); } @Override public void setImage(Context context, ImageView imageView, ResolveInfo item) { super.setImage(context, imageView, item); } @Override public LayoutInflater getInflater(Context context) { return super.getInflater(context); } @Override
public AppDataCache getAppDataCache() {
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/ResourceLocatorTest.java
// Path: sdk/src/com/sharethis/loopy/sdk/util/ClassLoaderProvider.java // public class ClassLoaderProvider { // public ClassLoader getClassLoader() { // return ClassLoaderProvider.class.getClassLoader(); // } // } // // Path: sdk/src/com/sharethis/loopy/sdk/util/ResourceLocator.java // public class ResourceLocator { // private ClassLoaderProvider classLoaderProvider = new ClassLoaderProvider(); // // public InputStream locateInAssets(Context context, String name) throws IOException { // InputStream in = null; // // try { // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in asset path..."); // } // // in = context.getAssets().open(name); // // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in asset path"); // } // } // catch (IOException ignore) { // // Ignore this, just means no override. // if(Logger.isDebugEnabled()) { // Logger.d("No file found in assets with name [" + // name + // "]."); // } // } // // return in; // } // // public InputStream locateInClassPath(String name) throws IOException { // // InputStream in = null; // // if(classLoaderProvider != null) { // // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in classpath..."); // } // // in = classLoaderProvider.getClassLoader().getResourceAsStream(name); // // if(in != null) { // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in classpath"); // } // } // } // // return in; // } // // public InputStream locate(Context context, String name) throws IOException { // // InputStream in = locateInAssets(context, name); // // if(in == null) { // in = locateInClassPath(name); // } // // if(in == null) { // Logger.w("Could not locate [" + // name + // "] in any location"); // } // // return in; // } // // public ClassLoaderProvider getClassLoaderProvider() { // return classLoaderProvider; // } // // public void setClassLoaderProvider(ClassLoaderProvider classLoaderProvider) { // this.classLoaderProvider = classLoaderProvider; // } // }
import com.sharethis.loopy.sdk.util.ClassLoaderProvider; import com.sharethis.loopy.sdk.util.ResourceLocator; import org.mockito.Mockito; import java.io.IOException; import java.io.InputStream;
package com.sharethis.loopy.test; /** * @author Jason Polites */ public class ResourceLocatorTest extends LoopyAndroidTestCase { public void testLocateInAssets() throws IOException { // We can't mock the AssetManager because it's final, // but this test project has assets so we'll just integration test
// Path: sdk/src/com/sharethis/loopy/sdk/util/ClassLoaderProvider.java // public class ClassLoaderProvider { // public ClassLoader getClassLoader() { // return ClassLoaderProvider.class.getClassLoader(); // } // } // // Path: sdk/src/com/sharethis/loopy/sdk/util/ResourceLocator.java // public class ResourceLocator { // private ClassLoaderProvider classLoaderProvider = new ClassLoaderProvider(); // // public InputStream locateInAssets(Context context, String name) throws IOException { // InputStream in = null; // // try { // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in asset path..."); // } // // in = context.getAssets().open(name); // // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in asset path"); // } // } // catch (IOException ignore) { // // Ignore this, just means no override. // if(Logger.isDebugEnabled()) { // Logger.d("No file found in assets with name [" + // name + // "]."); // } // } // // return in; // } // // public InputStream locateInClassPath(String name) throws IOException { // // InputStream in = null; // // if(classLoaderProvider != null) { // // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in classpath..."); // } // // in = classLoaderProvider.getClassLoader().getResourceAsStream(name); // // if(in != null) { // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in classpath"); // } // } // } // // return in; // } // // public InputStream locate(Context context, String name) throws IOException { // // InputStream in = locateInAssets(context, name); // // if(in == null) { // in = locateInClassPath(name); // } // // if(in == null) { // Logger.w("Could not locate [" + // name + // "] in any location"); // } // // return in; // } // // public ClassLoaderProvider getClassLoaderProvider() { // return classLoaderProvider; // } // // public void setClassLoaderProvider(ClassLoaderProvider classLoaderProvider) { // this.classLoaderProvider = classLoaderProvider; // } // } // Path: test/src/com/sharethis/loopy/test/ResourceLocatorTest.java import com.sharethis.loopy.sdk.util.ClassLoaderProvider; import com.sharethis.loopy.sdk.util.ResourceLocator; import org.mockito.Mockito; import java.io.IOException; import java.io.InputStream; package com.sharethis.loopy.test; /** * @author Jason Polites */ public class ResourceLocatorTest extends LoopyAndroidTestCase { public void testLocateInAssets() throws IOException { // We can't mock the AssetManager because it's final, // but this test project has assets so we'll just integration test
ResourceLocator locator = new ResourceLocator();
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/ResourceLocatorTest.java
// Path: sdk/src/com/sharethis/loopy/sdk/util/ClassLoaderProvider.java // public class ClassLoaderProvider { // public ClassLoader getClassLoader() { // return ClassLoaderProvider.class.getClassLoader(); // } // } // // Path: sdk/src/com/sharethis/loopy/sdk/util/ResourceLocator.java // public class ResourceLocator { // private ClassLoaderProvider classLoaderProvider = new ClassLoaderProvider(); // // public InputStream locateInAssets(Context context, String name) throws IOException { // InputStream in = null; // // try { // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in asset path..."); // } // // in = context.getAssets().open(name); // // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in asset path"); // } // } // catch (IOException ignore) { // // Ignore this, just means no override. // if(Logger.isDebugEnabled()) { // Logger.d("No file found in assets with name [" + // name + // "]."); // } // } // // return in; // } // // public InputStream locateInClassPath(String name) throws IOException { // // InputStream in = null; // // if(classLoaderProvider != null) { // // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in classpath..."); // } // // in = classLoaderProvider.getClassLoader().getResourceAsStream(name); // // if(in != null) { // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in classpath"); // } // } // } // // return in; // } // // public InputStream locate(Context context, String name) throws IOException { // // InputStream in = locateInAssets(context, name); // // if(in == null) { // in = locateInClassPath(name); // } // // if(in == null) { // Logger.w("Could not locate [" + // name + // "] in any location"); // } // // return in; // } // // public ClassLoaderProvider getClassLoaderProvider() { // return classLoaderProvider; // } // // public void setClassLoaderProvider(ClassLoaderProvider classLoaderProvider) { // this.classLoaderProvider = classLoaderProvider; // } // }
import com.sharethis.loopy.sdk.util.ClassLoaderProvider; import com.sharethis.loopy.sdk.util.ResourceLocator; import org.mockito.Mockito; import java.io.IOException; import java.io.InputStream;
package com.sharethis.loopy.test; /** * @author Jason Polites */ public class ResourceLocatorTest extends LoopyAndroidTestCase { public void testLocateInAssets() throws IOException { // We can't mock the AssetManager because it's final, // but this test project has assets so we'll just integration test ResourceLocator locator = new ResourceLocator(); InputStream notNull = locator.locateInAssets(getLocalContext(), "loopy.properties"); InputStream isNull = locator.locateInAssets(getLocalContext(), "does.not.exist"); assertNotNull(notNull); assertNull(isNull); } public void testLocateInClassPath() throws IOException { String name = "foobar"; ClassLoader classLoader = Mockito.mock(ClassLoader.class);
// Path: sdk/src/com/sharethis/loopy/sdk/util/ClassLoaderProvider.java // public class ClassLoaderProvider { // public ClassLoader getClassLoader() { // return ClassLoaderProvider.class.getClassLoader(); // } // } // // Path: sdk/src/com/sharethis/loopy/sdk/util/ResourceLocator.java // public class ResourceLocator { // private ClassLoaderProvider classLoaderProvider = new ClassLoaderProvider(); // // public InputStream locateInAssets(Context context, String name) throws IOException { // InputStream in = null; // // try { // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in asset path..."); // } // // in = context.getAssets().open(name); // // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in asset path"); // } // } // catch (IOException ignore) { // // Ignore this, just means no override. // if(Logger.isDebugEnabled()) { // Logger.d("No file found in assets with name [" + // name + // "]."); // } // } // // return in; // } // // public InputStream locateInClassPath(String name) throws IOException { // // InputStream in = null; // // if(classLoaderProvider != null) { // // if(Logger.isDebugEnabled()) { // Logger.d("Looking for " + // name + // " in classpath..."); // } // // in = classLoaderProvider.getClassLoader().getResourceAsStream(name); // // if(in != null) { // if(Logger.isDebugEnabled()) { // Logger.d("Found " + // name + // " in classpath"); // } // } // } // // return in; // } // // public InputStream locate(Context context, String name) throws IOException { // // InputStream in = locateInAssets(context, name); // // if(in == null) { // in = locateInClassPath(name); // } // // if(in == null) { // Logger.w("Could not locate [" + // name + // "] in any location"); // } // // return in; // } // // public ClassLoaderProvider getClassLoaderProvider() { // return classLoaderProvider; // } // // public void setClassLoaderProvider(ClassLoaderProvider classLoaderProvider) { // this.classLoaderProvider = classLoaderProvider; // } // } // Path: test/src/com/sharethis/loopy/test/ResourceLocatorTest.java import com.sharethis.loopy.sdk.util.ClassLoaderProvider; import com.sharethis.loopy.sdk.util.ResourceLocator; import org.mockito.Mockito; import java.io.IOException; import java.io.InputStream; package com.sharethis.loopy.test; /** * @author Jason Polites */ public class ResourceLocatorTest extends LoopyAndroidTestCase { public void testLocateInAssets() throws IOException { // We can't mock the AssetManager because it's final, // but this test project has assets so we'll just integration test ResourceLocator locator = new ResourceLocator(); InputStream notNull = locator.locateInAssets(getLocalContext(), "loopy.properties"); InputStream isNull = locator.locateInAssets(getLocalContext(), "does.not.exist"); assertNotNull(notNull); assertNull(isNull); } public void testLocateInClassPath() throws IOException { String name = "foobar"; ClassLoader classLoader = Mockito.mock(ClassLoader.class);
ClassLoaderProvider classLoaderProvider = Mockito.mock(ClassLoaderProvider.class);
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/AppUtilsTest.java
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppUtils.java // public class AppUtils { // // static final AppUtils instance = new AppUtils(); // // AppUtils() {} // // public static AppUtils getInstance() { // return instance; // } // // /** // * Determines inclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ALL the given permissions. // */ // public boolean hasAndPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res != PackageManager.PERMISSION_GRANTED) { // return false; // } // } // return true; // } // // /** // * Determines exclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ANY the given permissions. // */ // public boolean hasOrPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res == PackageManager.PERMISSION_GRANTED) { // return true; // } // } // return false; // } // // /** // * Returns the app info for the apps which support the ACTION_SEND intent with the given types. // * @param context The current context. // * @param contentTypes The content types supported. // * @return A Collection (set) of ResolveInfo objects corresponding to the apps installed on the device that // * support the content type(s). // */ // public Collection<ResolveInfo> getAppsForContentType(Context context, String...contentTypes) { // Set<ResolveInfo> apps = new LinkedHashSet<ResolveInfo>(); // for (String type : contentTypes) { // List<ResolveInfo> appsByType = listAppsForType(context, type); // if(appsByType != null && appsByType.size() > 0) { // apps.addAll(appsByType); // } // } // return apps; // } // // List<ResolveInfo> listAppsForType(Context context, String type) { // Intent intent = getSendIntent(); // intent.setType(type); // // PackageManager p = context.getPackageManager(); // // List<ResolveInfo> appList = p.queryIntentActivities(intent, 0); // // // Sort alphabetically. // Collections.sort(appList, new android.content.pm.ResolveInfo.DisplayNameComparator(p)); // // return appList; // } // // // mockable // Intent getSendIntent() { // return new Intent(Intent.ACTION_SEND); // } // // } // // Path: test/src/com/sharethis/loopy/sdk/util/MockAppUtils.java // public class MockAppUtils extends AppUtils { // public MockAppUtils() { // super(); // } // // @Override // public List<ResolveInfo> listAppsForType(Context context, String type) { // return super.listAppsForType(context, type); // } // // @Override // public Intent getSendIntent() { // return super.getSendIntent(); // } // }
import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.test.mock.MockContext; import com.sharethis.loopy.sdk.util.AppUtils; import com.sharethis.loopy.sdk.util.MockAppUtils; import org.mockito.Mockito; import java.util.Arrays; import java.util.Collection; import java.util.List;
package com.sharethis.loopy.test; /** * @author Jason Polites */ public class AppUtilsTest extends LoopyAndroidTestCase { public void testHasAndPermission() { Context trueContext = Mockito.mock(MockContext.class); Context falseContext = Mockito.mock(MockContext.class); Mockito.when(trueContext.checkCallingOrSelfPermission(Mockito.anyString())).thenReturn(PackageManager.PERMISSION_GRANTED); Mockito.when(falseContext.checkCallingOrSelfPermission(Mockito.anyString())).thenReturn(PackageManager.PERMISSION_DENIED);
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppUtils.java // public class AppUtils { // // static final AppUtils instance = new AppUtils(); // // AppUtils() {} // // public static AppUtils getInstance() { // return instance; // } // // /** // * Determines inclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ALL the given permissions. // */ // public boolean hasAndPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res != PackageManager.PERMISSION_GRANTED) { // return false; // } // } // return true; // } // // /** // * Determines exclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ANY the given permissions. // */ // public boolean hasOrPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res == PackageManager.PERMISSION_GRANTED) { // return true; // } // } // return false; // } // // /** // * Returns the app info for the apps which support the ACTION_SEND intent with the given types. // * @param context The current context. // * @param contentTypes The content types supported. // * @return A Collection (set) of ResolveInfo objects corresponding to the apps installed on the device that // * support the content type(s). // */ // public Collection<ResolveInfo> getAppsForContentType(Context context, String...contentTypes) { // Set<ResolveInfo> apps = new LinkedHashSet<ResolveInfo>(); // for (String type : contentTypes) { // List<ResolveInfo> appsByType = listAppsForType(context, type); // if(appsByType != null && appsByType.size() > 0) { // apps.addAll(appsByType); // } // } // return apps; // } // // List<ResolveInfo> listAppsForType(Context context, String type) { // Intent intent = getSendIntent(); // intent.setType(type); // // PackageManager p = context.getPackageManager(); // // List<ResolveInfo> appList = p.queryIntentActivities(intent, 0); // // // Sort alphabetically. // Collections.sort(appList, new android.content.pm.ResolveInfo.DisplayNameComparator(p)); // // return appList; // } // // // mockable // Intent getSendIntent() { // return new Intent(Intent.ACTION_SEND); // } // // } // // Path: test/src/com/sharethis/loopy/sdk/util/MockAppUtils.java // public class MockAppUtils extends AppUtils { // public MockAppUtils() { // super(); // } // // @Override // public List<ResolveInfo> listAppsForType(Context context, String type) { // return super.listAppsForType(context, type); // } // // @Override // public Intent getSendIntent() { // return super.getSendIntent(); // } // } // Path: test/src/com/sharethis/loopy/test/AppUtilsTest.java import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.test.mock.MockContext; import com.sharethis.loopy.sdk.util.AppUtils; import com.sharethis.loopy.sdk.util.MockAppUtils; import org.mockito.Mockito; import java.util.Arrays; import java.util.Collection; import java.util.List; package com.sharethis.loopy.test; /** * @author Jason Polites */ public class AppUtilsTest extends LoopyAndroidTestCase { public void testHasAndPermission() { Context trueContext = Mockito.mock(MockContext.class); Context falseContext = Mockito.mock(MockContext.class); Mockito.when(trueContext.checkCallingOrSelfPermission(Mockito.anyString())).thenReturn(PackageManager.PERMISSION_GRANTED); Mockito.when(falseContext.checkCallingOrSelfPermission(Mockito.anyString())).thenReturn(PackageManager.PERMISSION_DENIED);
assertTrue(AppUtils.getInstance().hasAndPermission(trueContext, "foo", "bar"));
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/AppUtilsTest.java
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppUtils.java // public class AppUtils { // // static final AppUtils instance = new AppUtils(); // // AppUtils() {} // // public static AppUtils getInstance() { // return instance; // } // // /** // * Determines inclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ALL the given permissions. // */ // public boolean hasAndPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res != PackageManager.PERMISSION_GRANTED) { // return false; // } // } // return true; // } // // /** // * Determines exclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ANY the given permissions. // */ // public boolean hasOrPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res == PackageManager.PERMISSION_GRANTED) { // return true; // } // } // return false; // } // // /** // * Returns the app info for the apps which support the ACTION_SEND intent with the given types. // * @param context The current context. // * @param contentTypes The content types supported. // * @return A Collection (set) of ResolveInfo objects corresponding to the apps installed on the device that // * support the content type(s). // */ // public Collection<ResolveInfo> getAppsForContentType(Context context, String...contentTypes) { // Set<ResolveInfo> apps = new LinkedHashSet<ResolveInfo>(); // for (String type : contentTypes) { // List<ResolveInfo> appsByType = listAppsForType(context, type); // if(appsByType != null && appsByType.size() > 0) { // apps.addAll(appsByType); // } // } // return apps; // } // // List<ResolveInfo> listAppsForType(Context context, String type) { // Intent intent = getSendIntent(); // intent.setType(type); // // PackageManager p = context.getPackageManager(); // // List<ResolveInfo> appList = p.queryIntentActivities(intent, 0); // // // Sort alphabetically. // Collections.sort(appList, new android.content.pm.ResolveInfo.DisplayNameComparator(p)); // // return appList; // } // // // mockable // Intent getSendIntent() { // return new Intent(Intent.ACTION_SEND); // } // // } // // Path: test/src/com/sharethis/loopy/sdk/util/MockAppUtils.java // public class MockAppUtils extends AppUtils { // public MockAppUtils() { // super(); // } // // @Override // public List<ResolveInfo> listAppsForType(Context context, String type) { // return super.listAppsForType(context, type); // } // // @Override // public Intent getSendIntent() { // return super.getSendIntent(); // } // }
import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.test.mock.MockContext; import com.sharethis.loopy.sdk.util.AppUtils; import com.sharethis.loopy.sdk.util.MockAppUtils; import org.mockito.Mockito; import java.util.Arrays; import java.util.Collection; import java.util.List;
package com.sharethis.loopy.test; /** * @author Jason Polites */ public class AppUtilsTest extends LoopyAndroidTestCase { public void testHasAndPermission() { Context trueContext = Mockito.mock(MockContext.class); Context falseContext = Mockito.mock(MockContext.class); Mockito.when(trueContext.checkCallingOrSelfPermission(Mockito.anyString())).thenReturn(PackageManager.PERMISSION_GRANTED); Mockito.when(falseContext.checkCallingOrSelfPermission(Mockito.anyString())).thenReturn(PackageManager.PERMISSION_DENIED); assertTrue(AppUtils.getInstance().hasAndPermission(trueContext, "foo", "bar")); assertFalse(AppUtils.getInstance().hasAndPermission(falseContext, "foo", "bar")); } public void testHasOrPermission() { Context trueContext = Mockito.mock(MockContext.class); Context falseContext = Mockito.mock(MockContext.class); Mockito.when(trueContext.checkCallingOrSelfPermission("foo")).thenReturn(PackageManager.PERMISSION_GRANTED); Mockito.when(trueContext.checkCallingOrSelfPermission("bar")).thenReturn(PackageManager.PERMISSION_DENIED); Mockito.when(falseContext.checkCallingOrSelfPermission(Mockito.anyString())).thenReturn(PackageManager.PERMISSION_DENIED); assertTrue(AppUtils.getInstance().hasOrPermission(trueContext, "foo", "bar")); assertFalse(AppUtils.getInstance().hasOrPermission(falseContext, "foo", "bar")); } public void testListAppsForType() { final Intent intent = new Intent(); PackageManager pm = Mockito.mock(PackageManager.class); Context context = Mockito.mock(MockContext.class); ResolveInfo foo = Mockito.mock(ResolveInfo.class); ResolveInfo bar = Mockito.mock(ResolveInfo.class); List<ResolveInfo> infos = Arrays.asList(foo, bar); Mockito.when(foo.loadLabel(pm)).thenReturn("foo"); Mockito.when(bar.loadLabel(pm)).thenReturn("bar"); Mockito.when(context.getPackageManager()).thenReturn(pm); Mockito.when(pm.queryIntentActivities(intent, 0)).thenReturn(infos);
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppUtils.java // public class AppUtils { // // static final AppUtils instance = new AppUtils(); // // AppUtils() {} // // public static AppUtils getInstance() { // return instance; // } // // /** // * Determines inclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ALL the given permissions. // */ // public boolean hasAndPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res != PackageManager.PERMISSION_GRANTED) { // return false; // } // } // return true; // } // // /** // * Determines exclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ANY the given permissions. // */ // public boolean hasOrPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res == PackageManager.PERMISSION_GRANTED) { // return true; // } // } // return false; // } // // /** // * Returns the app info for the apps which support the ACTION_SEND intent with the given types. // * @param context The current context. // * @param contentTypes The content types supported. // * @return A Collection (set) of ResolveInfo objects corresponding to the apps installed on the device that // * support the content type(s). // */ // public Collection<ResolveInfo> getAppsForContentType(Context context, String...contentTypes) { // Set<ResolveInfo> apps = new LinkedHashSet<ResolveInfo>(); // for (String type : contentTypes) { // List<ResolveInfo> appsByType = listAppsForType(context, type); // if(appsByType != null && appsByType.size() > 0) { // apps.addAll(appsByType); // } // } // return apps; // } // // List<ResolveInfo> listAppsForType(Context context, String type) { // Intent intent = getSendIntent(); // intent.setType(type); // // PackageManager p = context.getPackageManager(); // // List<ResolveInfo> appList = p.queryIntentActivities(intent, 0); // // // Sort alphabetically. // Collections.sort(appList, new android.content.pm.ResolveInfo.DisplayNameComparator(p)); // // return appList; // } // // // mockable // Intent getSendIntent() { // return new Intent(Intent.ACTION_SEND); // } // // } // // Path: test/src/com/sharethis/loopy/sdk/util/MockAppUtils.java // public class MockAppUtils extends AppUtils { // public MockAppUtils() { // super(); // } // // @Override // public List<ResolveInfo> listAppsForType(Context context, String type) { // return super.listAppsForType(context, type); // } // // @Override // public Intent getSendIntent() { // return super.getSendIntent(); // } // } // Path: test/src/com/sharethis/loopy/test/AppUtilsTest.java import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.test.mock.MockContext; import com.sharethis.loopy.sdk.util.AppUtils; import com.sharethis.loopy.sdk.util.MockAppUtils; import org.mockito.Mockito; import java.util.Arrays; import java.util.Collection; import java.util.List; package com.sharethis.loopy.test; /** * @author Jason Polites */ public class AppUtilsTest extends LoopyAndroidTestCase { public void testHasAndPermission() { Context trueContext = Mockito.mock(MockContext.class); Context falseContext = Mockito.mock(MockContext.class); Mockito.when(trueContext.checkCallingOrSelfPermission(Mockito.anyString())).thenReturn(PackageManager.PERMISSION_GRANTED); Mockito.when(falseContext.checkCallingOrSelfPermission(Mockito.anyString())).thenReturn(PackageManager.PERMISSION_DENIED); assertTrue(AppUtils.getInstance().hasAndPermission(trueContext, "foo", "bar")); assertFalse(AppUtils.getInstance().hasAndPermission(falseContext, "foo", "bar")); } public void testHasOrPermission() { Context trueContext = Mockito.mock(MockContext.class); Context falseContext = Mockito.mock(MockContext.class); Mockito.when(trueContext.checkCallingOrSelfPermission("foo")).thenReturn(PackageManager.PERMISSION_GRANTED); Mockito.when(trueContext.checkCallingOrSelfPermission("bar")).thenReturn(PackageManager.PERMISSION_DENIED); Mockito.when(falseContext.checkCallingOrSelfPermission(Mockito.anyString())).thenReturn(PackageManager.PERMISSION_DENIED); assertTrue(AppUtils.getInstance().hasOrPermission(trueContext, "foo", "bar")); assertFalse(AppUtils.getInstance().hasOrPermission(falseContext, "foo", "bar")); } public void testListAppsForType() { final Intent intent = new Intent(); PackageManager pm = Mockito.mock(PackageManager.class); Context context = Mockito.mock(MockContext.class); ResolveInfo foo = Mockito.mock(ResolveInfo.class); ResolveInfo bar = Mockito.mock(ResolveInfo.class); List<ResolveInfo> infos = Arrays.asList(foo, bar); Mockito.when(foo.loadLabel(pm)).thenReturn("foo"); Mockito.when(bar.loadLabel(pm)).thenReturn("bar"); Mockito.when(context.getPackageManager()).thenReturn(pm); Mockito.when(pm.queryIntentActivities(intent, 0)).thenReturn(infos);
MockAppUtils appUtils = new MockAppUtils() {
socialize/loopy-sdk-android
test/src/com/sharethis/loopy/test/util/TestUtils.java
// Path: sdk/src/com/sharethis/loopy/sdk/util/IOUtils.java // public class IOUtils { // // /** // * Pipes input bytes to output. // * @param in The IN stream // * @param out The OUT stream // * @param bufferSize The buffer size // * @return The number of bytes written. // * @throws IOException // */ // public static long pipe(InputStream in, OutputStream out, int bufferSize) throws IOException { // int read; // long total = 0L; // byte[] buffer = new byte[bufferSize]; // while((read = in.read(buffer)) >= 0) { // total+=read; // out.write(buffer, 0, read); // } // out.flush(); // return total; // } // // public static String read(InputStream in, int bufferSize) throws IOException { // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // pipe(in, bout, bufferSize); // return new String(bout.toByteArray(), "utf-8"); // } // // }
import android.content.Context; import android.graphics.Bitmap; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Handler; import android.test.ActivityTestCase; import android.view.View; import com.sharethis.loopy.sdk.util.IOUtils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static junit.framework.Assert.fail;
package com.sharethis.loopy.test.util; /** * @author Jason Polites */ public class TestUtils { public static InputStream getAssetStream(Context context, String name) throws IOException { return context.getAssets().open(name); } public static String getAssetFile(Context context, String name) { try { InputStream in = context.getAssets().open(name); ByteArrayOutputStream bout = new ByteArrayOutputStream();
// Path: sdk/src/com/sharethis/loopy/sdk/util/IOUtils.java // public class IOUtils { // // /** // * Pipes input bytes to output. // * @param in The IN stream // * @param out The OUT stream // * @param bufferSize The buffer size // * @return The number of bytes written. // * @throws IOException // */ // public static long pipe(InputStream in, OutputStream out, int bufferSize) throws IOException { // int read; // long total = 0L; // byte[] buffer = new byte[bufferSize]; // while((read = in.read(buffer)) >= 0) { // total+=read; // out.write(buffer, 0, read); // } // out.flush(); // return total; // } // // public static String read(InputStream in, int bufferSize) throws IOException { // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // pipe(in, bout, bufferSize); // return new String(bout.toByteArray(), "utf-8"); // } // // } // Path: test/src/com/sharethis/loopy/test/util/TestUtils.java import android.content.Context; import android.graphics.Bitmap; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Handler; import android.test.ActivityTestCase; import android.view.View; import com.sharethis.loopy.sdk.util.IOUtils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static junit.framework.Assert.fail; package com.sharethis.loopy.test.util; /** * @author Jason Polites */ public class TestUtils { public static InputStream getAssetStream(Context context, String name) throws IOException { return context.getAssets().open(name); } public static String getAssetFile(Context context, String name) { try { InputStream in = context.getAssets().open(name); ByteArrayOutputStream bout = new ByteArrayOutputStream();
IOUtils.pipe(in, bout, 2048);
socialize/loopy-sdk-android
sdk/src/com/sharethis/loopy/sdk/ShareDialogAdapter.java
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppDataCache.java // public class AppDataCache { // // private final Map<String, Drawable> iconCache = new HashMap<String, Drawable>(); // private final Map<String, String> labelCache = new HashMap<String, String>(); // // static AppDataCache instance = new AppDataCache(); // // AppDataCache() {} // // public static AppDataCache getInstance() { // return instance; // } // // public void onCreate(final Context context) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // Collection<ResolveInfo> appsForContentType = getAppUtils().getAppsForContentType(context, "*/*"); // for (ResolveInfo resolveInfo : appsForContentType) { // getAppIcon(context, resolveInfo); // getAppLabel(context, resolveInfo); // } // return null; // } // }.execute(); // } // // public void onDestroy(Context context) { // iconCache.clear(); // labelCache.clear(); // } // // public synchronized Drawable getAppIcon(Context context, ResolveInfo item) { // String key = getKey(item); // Drawable icon = iconCache.get(key); // if(icon == null) { // icon = item.activityInfo.loadIcon(context.getPackageManager()); // iconCache.put(key, icon); // } // return icon; // } // // /** // * May return null! // * @param packageName The package name. // * @param className The activity class name // * @return The app (activity) label, or null // */ // public String getAppLabel(String packageName, String className) { // return labelCache.get(packageName + "." + className); // } // // public synchronized String getAppLabel(Context context, ResolveInfo item) { // String key = getKey(item); // String label = labelCache.get(key); // if(label == null) { // label = item.activityInfo.loadLabel(context.getPackageManager()).toString(); // labelCache.put(key, label); // } // return label; // } // // String getKey(ResolveInfo item) { // return item.activityInfo.packageName + "." + item.activityInfo.name; // } // // // mockable // AppUtils getAppUtils() { // return AppUtils.getInstance(); // } // // }
import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.pm.ResolveInfo; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.sharethis.loopy.sdk.util.AppDataCache; import java.util.List;
void setShareItem(Item shareItem) { this.shareItem = shareItem; } void setShareIntent(Intent shareIntent) { this.shareIntent = shareIntent; } void setConfig(ShareConfig config) { this.config = config; } void setShareDialogListener(ShareDialogListener shareDialogListener) { this.shareDialogListener = shareDialogListener; } void setText(Context context, TextView textView, ResolveInfo item) { textView.setText( getAppDataCache().getAppLabel(context, item) ); } void setImage(Context context, ImageView imageView, ResolveInfo item) { imageView.setImageDrawable( getAppDataCache().getAppIcon(context, item) ); } // mockable LayoutInflater getInflater(Context context) { return LayoutInflater.from(context); }
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppDataCache.java // public class AppDataCache { // // private final Map<String, Drawable> iconCache = new HashMap<String, Drawable>(); // private final Map<String, String> labelCache = new HashMap<String, String>(); // // static AppDataCache instance = new AppDataCache(); // // AppDataCache() {} // // public static AppDataCache getInstance() { // return instance; // } // // public void onCreate(final Context context) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // Collection<ResolveInfo> appsForContentType = getAppUtils().getAppsForContentType(context, "*/*"); // for (ResolveInfo resolveInfo : appsForContentType) { // getAppIcon(context, resolveInfo); // getAppLabel(context, resolveInfo); // } // return null; // } // }.execute(); // } // // public void onDestroy(Context context) { // iconCache.clear(); // labelCache.clear(); // } // // public synchronized Drawable getAppIcon(Context context, ResolveInfo item) { // String key = getKey(item); // Drawable icon = iconCache.get(key); // if(icon == null) { // icon = item.activityInfo.loadIcon(context.getPackageManager()); // iconCache.put(key, icon); // } // return icon; // } // // /** // * May return null! // * @param packageName The package name. // * @param className The activity class name // * @return The app (activity) label, or null // */ // public String getAppLabel(String packageName, String className) { // return labelCache.get(packageName + "." + className); // } // // public synchronized String getAppLabel(Context context, ResolveInfo item) { // String key = getKey(item); // String label = labelCache.get(key); // if(label == null) { // label = item.activityInfo.loadLabel(context.getPackageManager()).toString(); // labelCache.put(key, label); // } // return label; // } // // String getKey(ResolveInfo item) { // return item.activityInfo.packageName + "." + item.activityInfo.name; // } // // // mockable // AppUtils getAppUtils() { // return AppUtils.getInstance(); // } // // } // Path: sdk/src/com/sharethis/loopy/sdk/ShareDialogAdapter.java import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.pm.ResolveInfo; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.sharethis.loopy.sdk.util.AppDataCache; import java.util.List; void setShareItem(Item shareItem) { this.shareItem = shareItem; } void setShareIntent(Intent shareIntent) { this.shareIntent = shareIntent; } void setConfig(ShareConfig config) { this.config = config; } void setShareDialogListener(ShareDialogListener shareDialogListener) { this.shareDialogListener = shareDialogListener; } void setText(Context context, TextView textView, ResolveInfo item) { textView.setText( getAppDataCache().getAppLabel(context, item) ); } void setImage(Context context, ImageView imageView, ResolveInfo item) { imageView.setImageDrawable( getAppDataCache().getAppIcon(context, item) ); } // mockable LayoutInflater getInflater(Context context) { return LayoutInflater.from(context); }
AppDataCache getAppDataCache() {
socialize/loopy-sdk-android
sdk/src/com/sharethis/loopy/sdk/ShareCallback.java
// Path: sdk/src/com/sharethis/loopy/sdk/util/JSONUtils.java // public class JSONUtils { // // public static boolean put(JSONObject object, String key, Object value) throws JSONException { // return put(object, key, value, null); // } // // public static boolean put(JSONObject object, String key, Object value, Object defaultValue) throws JSONException { // if(value != null) { // // if(value instanceof Map) { // JSONObject mapObject = new JSONObject(); // Map<?,?> map = (Map<?,?>) value; // for (Object o : map.keySet()) { // put(mapObject, o.toString(), map.get(o)); // } // // object.put(key, mapObject); // } // else if(value instanceof Collection) { // JSONArray arrayObject = new JSONArray(); // Collection<?> collection = (Collection<?>) value; // for (Object o : collection) { // // TODO: This is not very robust. Needs to infer the type // arrayObject.put(o.toString()); // } // object.put(key, arrayObject); // } // else { // object.put(key, value); // } // // return true; // } // else if(defaultValue != null) { // object.put(key, defaultValue); // return true; // } // return false; // } // // public static boolean isNull(JSONObject object, String key) { // return !object.has(key) || object.isNull(key); // } // // public static String getString(JSONObject object, String key) { // if(!isNull(object, key)) { // try { // return object.getString(key); // } catch (JSONException e) { // Logger.e(e); // } // } // return null; // } // }
import android.content.Context; import android.content.Intent; import com.sharethis.loopy.sdk.util.JSONUtils; import org.json.JSONObject;
package com.sharethis.loopy.sdk; /** * Callback used when creating a tracking url. * @author Jason Polites */ public abstract class ShareCallback extends ApiCallback { Item item; @Override public final void onSuccess(JSONObject result) { if(item != null) {
// Path: sdk/src/com/sharethis/loopy/sdk/util/JSONUtils.java // public class JSONUtils { // // public static boolean put(JSONObject object, String key, Object value) throws JSONException { // return put(object, key, value, null); // } // // public static boolean put(JSONObject object, String key, Object value, Object defaultValue) throws JSONException { // if(value != null) { // // if(value instanceof Map) { // JSONObject mapObject = new JSONObject(); // Map<?,?> map = (Map<?,?>) value; // for (Object o : map.keySet()) { // put(mapObject, o.toString(), map.get(o)); // } // // object.put(key, mapObject); // } // else if(value instanceof Collection) { // JSONArray arrayObject = new JSONArray(); // Collection<?> collection = (Collection<?>) value; // for (Object o : collection) { // // TODO: This is not very robust. Needs to infer the type // arrayObject.put(o.toString()); // } // object.put(key, arrayObject); // } // else { // object.put(key, value); // } // // return true; // } // else if(defaultValue != null) { // object.put(key, defaultValue); // return true; // } // return false; // } // // public static boolean isNull(JSONObject object, String key) { // return !object.has(key) || object.isNull(key); // } // // public static String getString(JSONObject object, String key) { // if(!isNull(object, key)) { // try { // return object.getString(key); // } catch (JSONException e) { // Logger.e(e); // } // } // return null; // } // } // Path: sdk/src/com/sharethis/loopy/sdk/ShareCallback.java import android.content.Context; import android.content.Intent; import com.sharethis.loopy.sdk.util.JSONUtils; import org.json.JSONObject; package com.sharethis.loopy.sdk; /** * Callback used when creating a tracking url. * @author Jason Polites */ public abstract class ShareCallback extends ApiCallback { Item item; @Override public final void onSuccess(JSONObject result) { if(item != null) {
item.setShortlink(JSONUtils.getString(result, "shortlink"));
socialize/loopy-sdk-android
sdk/src/com/sharethis/loopy/sdk/Device.java
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppUtils.java // public class AppUtils { // // static final AppUtils instance = new AppUtils(); // // AppUtils() {} // // public static AppUtils getInstance() { // return instance; // } // // /** // * Determines inclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ALL the given permissions. // */ // public boolean hasAndPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res != PackageManager.PERMISSION_GRANTED) { // return false; // } // } // return true; // } // // /** // * Determines exclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ANY the given permissions. // */ // public boolean hasOrPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res == PackageManager.PERMISSION_GRANTED) { // return true; // } // } // return false; // } // // /** // * Returns the app info for the apps which support the ACTION_SEND intent with the given types. // * @param context The current context. // * @param contentTypes The content types supported. // * @return A Collection (set) of ResolveInfo objects corresponding to the apps installed on the device that // * support the content type(s). // */ // public Collection<ResolveInfo> getAppsForContentType(Context context, String...contentTypes) { // Set<ResolveInfo> apps = new LinkedHashSet<ResolveInfo>(); // for (String type : contentTypes) { // List<ResolveInfo> appsByType = listAppsForType(context, type); // if(appsByType != null && appsByType.size() > 0) { // apps.addAll(appsByType); // } // } // return apps; // } // // List<ResolveInfo> listAppsForType(Context context, String type) { // Intent intent = getSendIntent(); // intent.setType(type); // // PackageManager p = context.getPackageManager(); // // List<ResolveInfo> appList = p.queryIntentActivities(intent, 0); // // // Sort alphabetically. // Collections.sort(appList, new android.content.pm.ResolveInfo.DisplayNameComparator(p)); // // return appList; // } // // // mockable // Intent getSendIntent() { // return new Intent(Intent.ACTION_SEND); // } // // } // // Path: sdk/src/com/sharethis/loopy/sdk/util/MD5Util.java // public class MD5Util { // // public static String hash(String s) throws NoSuchAlgorithmException { // MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); // digest.update(s.getBytes()); // byte messageDigest[] = digest.digest(); // StringBuilder hexString = new StringBuilder(); // for (byte aMessageDigest : messageDigest) { // hexString.append(Integer.toHexString(0xFF & aMessageDigest)); // } // return hexString.toString(); // } // }
import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.provider.Settings; import android.telephony.TelephonyManager; import com.sharethis.loopy.sdk.util.AppUtils; import com.sharethis.loopy.sdk.util.MD5Util; import java.security.NoSuchAlgorithmException;
package com.sharethis.loopy.sdk; /** * @author Jason Polites */ public class Device { private String modelName; private String androidVersion; private String androidId; private String md5Id; private String carrier; private boolean initialized = false; private final WifiState wifiState = new WifiState(); Device onCreate(Context context) { modelName = android.os.Build.MODEL; androidVersion = String.valueOf(Build.VERSION.SDK_INT); androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); try {
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppUtils.java // public class AppUtils { // // static final AppUtils instance = new AppUtils(); // // AppUtils() {} // // public static AppUtils getInstance() { // return instance; // } // // /** // * Determines inclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ALL the given permissions. // */ // public boolean hasAndPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res != PackageManager.PERMISSION_GRANTED) { // return false; // } // } // return true; // } // // /** // * Determines exclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ANY the given permissions. // */ // public boolean hasOrPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res == PackageManager.PERMISSION_GRANTED) { // return true; // } // } // return false; // } // // /** // * Returns the app info for the apps which support the ACTION_SEND intent with the given types. // * @param context The current context. // * @param contentTypes The content types supported. // * @return A Collection (set) of ResolveInfo objects corresponding to the apps installed on the device that // * support the content type(s). // */ // public Collection<ResolveInfo> getAppsForContentType(Context context, String...contentTypes) { // Set<ResolveInfo> apps = new LinkedHashSet<ResolveInfo>(); // for (String type : contentTypes) { // List<ResolveInfo> appsByType = listAppsForType(context, type); // if(appsByType != null && appsByType.size() > 0) { // apps.addAll(appsByType); // } // } // return apps; // } // // List<ResolveInfo> listAppsForType(Context context, String type) { // Intent intent = getSendIntent(); // intent.setType(type); // // PackageManager p = context.getPackageManager(); // // List<ResolveInfo> appList = p.queryIntentActivities(intent, 0); // // // Sort alphabetically. // Collections.sort(appList, new android.content.pm.ResolveInfo.DisplayNameComparator(p)); // // return appList; // } // // // mockable // Intent getSendIntent() { // return new Intent(Intent.ACTION_SEND); // } // // } // // Path: sdk/src/com/sharethis/loopy/sdk/util/MD5Util.java // public class MD5Util { // // public static String hash(String s) throws NoSuchAlgorithmException { // MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); // digest.update(s.getBytes()); // byte messageDigest[] = digest.digest(); // StringBuilder hexString = new StringBuilder(); // for (byte aMessageDigest : messageDigest) { // hexString.append(Integer.toHexString(0xFF & aMessageDigest)); // } // return hexString.toString(); // } // } // Path: sdk/src/com/sharethis/loopy/sdk/Device.java import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.provider.Settings; import android.telephony.TelephonyManager; import com.sharethis.loopy.sdk.util.AppUtils; import com.sharethis.loopy.sdk.util.MD5Util; import java.security.NoSuchAlgorithmException; package com.sharethis.loopy.sdk; /** * @author Jason Polites */ public class Device { private String modelName; private String androidVersion; private String androidId; private String md5Id; private String carrier; private boolean initialized = false; private final WifiState wifiState = new WifiState(); Device onCreate(Context context) { modelName = android.os.Build.MODEL; androidVersion = String.valueOf(Build.VERSION.SDK_INT); androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); try {
md5Id = MD5Util.hash(androidId);
socialize/loopy-sdk-android
sdk/src/com/sharethis/loopy/sdk/Device.java
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppUtils.java // public class AppUtils { // // static final AppUtils instance = new AppUtils(); // // AppUtils() {} // // public static AppUtils getInstance() { // return instance; // } // // /** // * Determines inclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ALL the given permissions. // */ // public boolean hasAndPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res != PackageManager.PERMISSION_GRANTED) { // return false; // } // } // return true; // } // // /** // * Determines exclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ANY the given permissions. // */ // public boolean hasOrPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res == PackageManager.PERMISSION_GRANTED) { // return true; // } // } // return false; // } // // /** // * Returns the app info for the apps which support the ACTION_SEND intent with the given types. // * @param context The current context. // * @param contentTypes The content types supported. // * @return A Collection (set) of ResolveInfo objects corresponding to the apps installed on the device that // * support the content type(s). // */ // public Collection<ResolveInfo> getAppsForContentType(Context context, String...contentTypes) { // Set<ResolveInfo> apps = new LinkedHashSet<ResolveInfo>(); // for (String type : contentTypes) { // List<ResolveInfo> appsByType = listAppsForType(context, type); // if(appsByType != null && appsByType.size() > 0) { // apps.addAll(appsByType); // } // } // return apps; // } // // List<ResolveInfo> listAppsForType(Context context, String type) { // Intent intent = getSendIntent(); // intent.setType(type); // // PackageManager p = context.getPackageManager(); // // List<ResolveInfo> appList = p.queryIntentActivities(intent, 0); // // // Sort alphabetically. // Collections.sort(appList, new android.content.pm.ResolveInfo.DisplayNameComparator(p)); // // return appList; // } // // // mockable // Intent getSendIntent() { // return new Intent(Intent.ACTION_SEND); // } // // } // // Path: sdk/src/com/sharethis/loopy/sdk/util/MD5Util.java // public class MD5Util { // // public static String hash(String s) throws NoSuchAlgorithmException { // MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); // digest.update(s.getBytes()); // byte messageDigest[] = digest.digest(); // StringBuilder hexString = new StringBuilder(); // for (byte aMessageDigest : messageDigest) { // hexString.append(Integer.toHexString(0xFF & aMessageDigest)); // } // return hexString.toString(); // } // }
import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.provider.Settings; import android.telephony.TelephonyManager; import com.sharethis.loopy.sdk.util.AppUtils; import com.sharethis.loopy.sdk.util.MD5Util; import java.security.NoSuchAlgorithmException;
public String getAndroidVersion() { return androidVersion; } public String getAndroidId() { return androidId; } public String getModelName() { return modelName; } public boolean isInitialized() { return initialized; } public String getCarrier() { return carrier; } public WifiState getWifiState() { return wifiState; } public String getMd5Id() { return md5Id; } WifiState getWifiState(Context context) {
// Path: sdk/src/com/sharethis/loopy/sdk/util/AppUtils.java // public class AppUtils { // // static final AppUtils instance = new AppUtils(); // // AppUtils() {} // // public static AppUtils getInstance() { // return instance; // } // // /** // * Determines inclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ALL the given permissions. // */ // public boolean hasAndPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res != PackageManager.PERMISSION_GRANTED) { // return false; // } // } // return true; // } // // /** // * Determines exclusive permissions. // * @param context The current context. // * @param permissions The permissions sought. // * @return Returns true iff the app has ANY the given permissions. // */ // public boolean hasOrPermission(Context context, String...permissions) { // for (String permission : permissions) { // int res = context.checkCallingOrSelfPermission(permission); // if(res == PackageManager.PERMISSION_GRANTED) { // return true; // } // } // return false; // } // // /** // * Returns the app info for the apps which support the ACTION_SEND intent with the given types. // * @param context The current context. // * @param contentTypes The content types supported. // * @return A Collection (set) of ResolveInfo objects corresponding to the apps installed on the device that // * support the content type(s). // */ // public Collection<ResolveInfo> getAppsForContentType(Context context, String...contentTypes) { // Set<ResolveInfo> apps = new LinkedHashSet<ResolveInfo>(); // for (String type : contentTypes) { // List<ResolveInfo> appsByType = listAppsForType(context, type); // if(appsByType != null && appsByType.size() > 0) { // apps.addAll(appsByType); // } // } // return apps; // } // // List<ResolveInfo> listAppsForType(Context context, String type) { // Intent intent = getSendIntent(); // intent.setType(type); // // PackageManager p = context.getPackageManager(); // // List<ResolveInfo> appList = p.queryIntentActivities(intent, 0); // // // Sort alphabetically. // Collections.sort(appList, new android.content.pm.ResolveInfo.DisplayNameComparator(p)); // // return appList; // } // // // mockable // Intent getSendIntent() { // return new Intent(Intent.ACTION_SEND); // } // // } // // Path: sdk/src/com/sharethis/loopy/sdk/util/MD5Util.java // public class MD5Util { // // public static String hash(String s) throws NoSuchAlgorithmException { // MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); // digest.update(s.getBytes()); // byte messageDigest[] = digest.digest(); // StringBuilder hexString = new StringBuilder(); // for (byte aMessageDigest : messageDigest) { // hexString.append(Integer.toHexString(0xFF & aMessageDigest)); // } // return hexString.toString(); // } // } // Path: sdk/src/com/sharethis/loopy/sdk/Device.java import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.provider.Settings; import android.telephony.TelephonyManager; import com.sharethis.loopy.sdk.util.AppUtils; import com.sharethis.loopy.sdk.util.MD5Util; import java.security.NoSuchAlgorithmException; public String getAndroidVersion() { return androidVersion; } public String getAndroidId() { return androidId; } public String getModelName() { return modelName; } public boolean isInitialized() { return initialized; } public String getCarrier() { return carrier; } public WifiState getWifiState() { return wifiState; } public String getMd5Id() { return md5Id; } WifiState getWifiState(Context context) {
if(AppUtils.getInstance().hasAndPermission(context, "android.permission.ACCESS_NETWORK_STATE")) {
SpoonLabs/spoon-examples
src/main/java/fr/inria/gforge/spoon/transformation/bound/BoundTest.java
// Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/processing/BoundProcessor.java // public class BoundProcessor extends AbstractAnnotationProcessor<Bound, CtParameter<?>> { // public void process(Bound annotation, CtParameter<?> element) { // final CtMethod parent = element.getParent(CtMethod.class); // // // Build if check for min. // CtIf anIf = getFactory().Core().createIf(); // anIf.setCondition(getFactory().Code().<Boolean>createCodeSnippetExpression(element.getSimpleName() + " < " + annotation.min())); // CtThrow throwStmt = getFactory().Core().createThrow(); // throwStmt.setThrownExpression((CtExpression<? extends Throwable>) getFactory().Core().createCodeSnippetExpression().setValue("new RuntimeException(\"out of min bound (\" + " + element.getSimpleName() + " + \" < " + annotation.min() + "\")")); // anIf.setThenStatement(throwStmt); // parent.getBody().insertBegin(anIf); // anIf.setParent(parent); // // // Build if check for max. // anIf = getFactory().Core().createIf(); // anIf.setCondition(getFactory().Code().<Boolean>createCodeSnippetExpression(element.getSimpleName() + " > " + annotation.max())); // anIf.setThenStatement(getFactory().Code().createCtThrow("new RuntimeException(\"out of max bound (\" + " + element.getSimpleName() + " + \" > " + annotation.max() + "\")")); // parent.getBody().insertBegin(anIf); // anIf.setParent(parent); // } // } // // Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/processing/BoundTemplateProcessor.java // public class BoundTemplateProcessor extends AbstractAnnotationProcessor<Bound, CtParameter<?>> { // // public void process(Bound annotation, CtParameter<?> element) { // // Is to be process? // CtExecutable<?> e = element.getParent(); // if (e.getBody() == null) { // return; // } // // // Use template. // CtClass<?> type = e.getParent(CtClass.class); // Template t = new BoundTemplate(getFactory().Type().createReference(Double.class), element.getSimpleName(), annotation.min(), annotation.max()); // final CtBlock apply = (CtBlock) t.apply(type); // // // Apply transformation. // for (int i = apply.getStatements().size() - 1; i >= 0; i--) { // final CtStatement statement = apply.getStatement(i); // statement.delete(); // e.getBody().insertBegin(statement); // } // } // } // // Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/src/Main.java // public class Main { // // public static void main(String[] args) { // for (int i = 0; i < 10; i++) { // try { // new Main().m(i); // } catch (RuntimeException e) { // System.out.println(e.getMessage()); // } // } // } // // public void m(@Bound(min = 2d, max = 8d) int a) { // System.out.println("Great method!"); // } // // }
import fr.inria.gforge.spoon.transformation.bound.processing.BoundProcessor; import fr.inria.gforge.spoon.transformation.bound.processing.BoundTemplateProcessor; import fr.inria.gforge.spoon.transformation.bound.src.Main; import org.junit.Test; import spoon.Launcher; import spoon.SpoonAPI; import spoon.reflect.code.CtIf; import spoon.reflect.declaration.CtMethod; import spoon.reflect.declaration.CtType; import static org.junit.Assert.assertTrue;
package fr.inria.gforge.spoon.transformation.bound; public class BoundTest { @Test public void testBoundTemplate() throws Exception { SpoonAPI launcher = new Launcher(); launcher.getEnvironment().setNoClasspath(true); launcher.addInputResource("./src/main/java"); launcher.setSourceOutputDirectory("./target/spoon-template");
// Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/processing/BoundProcessor.java // public class BoundProcessor extends AbstractAnnotationProcessor<Bound, CtParameter<?>> { // public void process(Bound annotation, CtParameter<?> element) { // final CtMethod parent = element.getParent(CtMethod.class); // // // Build if check for min. // CtIf anIf = getFactory().Core().createIf(); // anIf.setCondition(getFactory().Code().<Boolean>createCodeSnippetExpression(element.getSimpleName() + " < " + annotation.min())); // CtThrow throwStmt = getFactory().Core().createThrow(); // throwStmt.setThrownExpression((CtExpression<? extends Throwable>) getFactory().Core().createCodeSnippetExpression().setValue("new RuntimeException(\"out of min bound (\" + " + element.getSimpleName() + " + \" < " + annotation.min() + "\")")); // anIf.setThenStatement(throwStmt); // parent.getBody().insertBegin(anIf); // anIf.setParent(parent); // // // Build if check for max. // anIf = getFactory().Core().createIf(); // anIf.setCondition(getFactory().Code().<Boolean>createCodeSnippetExpression(element.getSimpleName() + " > " + annotation.max())); // anIf.setThenStatement(getFactory().Code().createCtThrow("new RuntimeException(\"out of max bound (\" + " + element.getSimpleName() + " + \" > " + annotation.max() + "\")")); // parent.getBody().insertBegin(anIf); // anIf.setParent(parent); // } // } // // Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/processing/BoundTemplateProcessor.java // public class BoundTemplateProcessor extends AbstractAnnotationProcessor<Bound, CtParameter<?>> { // // public void process(Bound annotation, CtParameter<?> element) { // // Is to be process? // CtExecutable<?> e = element.getParent(); // if (e.getBody() == null) { // return; // } // // // Use template. // CtClass<?> type = e.getParent(CtClass.class); // Template t = new BoundTemplate(getFactory().Type().createReference(Double.class), element.getSimpleName(), annotation.min(), annotation.max()); // final CtBlock apply = (CtBlock) t.apply(type); // // // Apply transformation. // for (int i = apply.getStatements().size() - 1; i >= 0; i--) { // final CtStatement statement = apply.getStatement(i); // statement.delete(); // e.getBody().insertBegin(statement); // } // } // } // // Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/src/Main.java // public class Main { // // public static void main(String[] args) { // for (int i = 0; i < 10; i++) { // try { // new Main().m(i); // } catch (RuntimeException e) { // System.out.println(e.getMessage()); // } // } // } // // public void m(@Bound(min = 2d, max = 8d) int a) { // System.out.println("Great method!"); // } // // } // Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/BoundTest.java import fr.inria.gforge.spoon.transformation.bound.processing.BoundProcessor; import fr.inria.gforge.spoon.transformation.bound.processing.BoundTemplateProcessor; import fr.inria.gforge.spoon.transformation.bound.src.Main; import org.junit.Test; import spoon.Launcher; import spoon.SpoonAPI; import spoon.reflect.code.CtIf; import spoon.reflect.declaration.CtMethod; import spoon.reflect.declaration.CtType; import static org.junit.Assert.assertTrue; package fr.inria.gforge.spoon.transformation.bound; public class BoundTest { @Test public void testBoundTemplate() throws Exception { SpoonAPI launcher = new Launcher(); launcher.getEnvironment().setNoClasspath(true); launcher.addInputResource("./src/main/java"); launcher.setSourceOutputDirectory("./target/spoon-template");
launcher.addProcessor(new BoundTemplateProcessor());
SpoonLabs/spoon-examples
src/main/java/fr/inria/gforge/spoon/transformation/bound/BoundTest.java
// Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/processing/BoundProcessor.java // public class BoundProcessor extends AbstractAnnotationProcessor<Bound, CtParameter<?>> { // public void process(Bound annotation, CtParameter<?> element) { // final CtMethod parent = element.getParent(CtMethod.class); // // // Build if check for min. // CtIf anIf = getFactory().Core().createIf(); // anIf.setCondition(getFactory().Code().<Boolean>createCodeSnippetExpression(element.getSimpleName() + " < " + annotation.min())); // CtThrow throwStmt = getFactory().Core().createThrow(); // throwStmt.setThrownExpression((CtExpression<? extends Throwable>) getFactory().Core().createCodeSnippetExpression().setValue("new RuntimeException(\"out of min bound (\" + " + element.getSimpleName() + " + \" < " + annotation.min() + "\")")); // anIf.setThenStatement(throwStmt); // parent.getBody().insertBegin(anIf); // anIf.setParent(parent); // // // Build if check for max. // anIf = getFactory().Core().createIf(); // anIf.setCondition(getFactory().Code().<Boolean>createCodeSnippetExpression(element.getSimpleName() + " > " + annotation.max())); // anIf.setThenStatement(getFactory().Code().createCtThrow("new RuntimeException(\"out of max bound (\" + " + element.getSimpleName() + " + \" > " + annotation.max() + "\")")); // parent.getBody().insertBegin(anIf); // anIf.setParent(parent); // } // } // // Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/processing/BoundTemplateProcessor.java // public class BoundTemplateProcessor extends AbstractAnnotationProcessor<Bound, CtParameter<?>> { // // public void process(Bound annotation, CtParameter<?> element) { // // Is to be process? // CtExecutable<?> e = element.getParent(); // if (e.getBody() == null) { // return; // } // // // Use template. // CtClass<?> type = e.getParent(CtClass.class); // Template t = new BoundTemplate(getFactory().Type().createReference(Double.class), element.getSimpleName(), annotation.min(), annotation.max()); // final CtBlock apply = (CtBlock) t.apply(type); // // // Apply transformation. // for (int i = apply.getStatements().size() - 1; i >= 0; i--) { // final CtStatement statement = apply.getStatement(i); // statement.delete(); // e.getBody().insertBegin(statement); // } // } // } // // Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/src/Main.java // public class Main { // // public static void main(String[] args) { // for (int i = 0; i < 10; i++) { // try { // new Main().m(i); // } catch (RuntimeException e) { // System.out.println(e.getMessage()); // } // } // } // // public void m(@Bound(min = 2d, max = 8d) int a) { // System.out.println("Great method!"); // } // // }
import fr.inria.gforge.spoon.transformation.bound.processing.BoundProcessor; import fr.inria.gforge.spoon.transformation.bound.processing.BoundTemplateProcessor; import fr.inria.gforge.spoon.transformation.bound.src.Main; import org.junit.Test; import spoon.Launcher; import spoon.SpoonAPI; import spoon.reflect.code.CtIf; import spoon.reflect.declaration.CtMethod; import spoon.reflect.declaration.CtType; import static org.junit.Assert.assertTrue;
package fr.inria.gforge.spoon.transformation.bound; public class BoundTest { @Test public void testBoundTemplate() throws Exception { SpoonAPI launcher = new Launcher(); launcher.getEnvironment().setNoClasspath(true); launcher.addInputResource("./src/main/java"); launcher.setSourceOutputDirectory("./target/spoon-template"); launcher.addProcessor(new BoundTemplateProcessor()); launcher.run();
// Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/processing/BoundProcessor.java // public class BoundProcessor extends AbstractAnnotationProcessor<Bound, CtParameter<?>> { // public void process(Bound annotation, CtParameter<?> element) { // final CtMethod parent = element.getParent(CtMethod.class); // // // Build if check for min. // CtIf anIf = getFactory().Core().createIf(); // anIf.setCondition(getFactory().Code().<Boolean>createCodeSnippetExpression(element.getSimpleName() + " < " + annotation.min())); // CtThrow throwStmt = getFactory().Core().createThrow(); // throwStmt.setThrownExpression((CtExpression<? extends Throwable>) getFactory().Core().createCodeSnippetExpression().setValue("new RuntimeException(\"out of min bound (\" + " + element.getSimpleName() + " + \" < " + annotation.min() + "\")")); // anIf.setThenStatement(throwStmt); // parent.getBody().insertBegin(anIf); // anIf.setParent(parent); // // // Build if check for max. // anIf = getFactory().Core().createIf(); // anIf.setCondition(getFactory().Code().<Boolean>createCodeSnippetExpression(element.getSimpleName() + " > " + annotation.max())); // anIf.setThenStatement(getFactory().Code().createCtThrow("new RuntimeException(\"out of max bound (\" + " + element.getSimpleName() + " + \" > " + annotation.max() + "\")")); // parent.getBody().insertBegin(anIf); // anIf.setParent(parent); // } // } // // Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/processing/BoundTemplateProcessor.java // public class BoundTemplateProcessor extends AbstractAnnotationProcessor<Bound, CtParameter<?>> { // // public void process(Bound annotation, CtParameter<?> element) { // // Is to be process? // CtExecutable<?> e = element.getParent(); // if (e.getBody() == null) { // return; // } // // // Use template. // CtClass<?> type = e.getParent(CtClass.class); // Template t = new BoundTemplate(getFactory().Type().createReference(Double.class), element.getSimpleName(), annotation.min(), annotation.max()); // final CtBlock apply = (CtBlock) t.apply(type); // // // Apply transformation. // for (int i = apply.getStatements().size() - 1; i >= 0; i--) { // final CtStatement statement = apply.getStatement(i); // statement.delete(); // e.getBody().insertBegin(statement); // } // } // } // // Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/src/Main.java // public class Main { // // public static void main(String[] args) { // for (int i = 0; i < 10; i++) { // try { // new Main().m(i); // } catch (RuntimeException e) { // System.out.println(e.getMessage()); // } // } // } // // public void m(@Bound(min = 2d, max = 8d) int a) { // System.out.println("Great method!"); // } // // } // Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/BoundTest.java import fr.inria.gforge.spoon.transformation.bound.processing.BoundProcessor; import fr.inria.gforge.spoon.transformation.bound.processing.BoundTemplateProcessor; import fr.inria.gforge.spoon.transformation.bound.src.Main; import org.junit.Test; import spoon.Launcher; import spoon.SpoonAPI; import spoon.reflect.code.CtIf; import spoon.reflect.declaration.CtMethod; import spoon.reflect.declaration.CtType; import static org.junit.Assert.assertTrue; package fr.inria.gforge.spoon.transformation.bound; public class BoundTest { @Test public void testBoundTemplate() throws Exception { SpoonAPI launcher = new Launcher(); launcher.getEnvironment().setNoClasspath(true); launcher.addInputResource("./src/main/java"); launcher.setSourceOutputDirectory("./target/spoon-template"); launcher.addProcessor(new BoundTemplateProcessor()); launcher.run();
final CtType<Main> target = launcher.getFactory().Type().get(Main.class);
SpoonLabs/spoon-examples
src/main/java/fr/inria/gforge/spoon/transformation/bound/BoundTest.java
// Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/processing/BoundProcessor.java // public class BoundProcessor extends AbstractAnnotationProcessor<Bound, CtParameter<?>> { // public void process(Bound annotation, CtParameter<?> element) { // final CtMethod parent = element.getParent(CtMethod.class); // // // Build if check for min. // CtIf anIf = getFactory().Core().createIf(); // anIf.setCondition(getFactory().Code().<Boolean>createCodeSnippetExpression(element.getSimpleName() + " < " + annotation.min())); // CtThrow throwStmt = getFactory().Core().createThrow(); // throwStmt.setThrownExpression((CtExpression<? extends Throwable>) getFactory().Core().createCodeSnippetExpression().setValue("new RuntimeException(\"out of min bound (\" + " + element.getSimpleName() + " + \" < " + annotation.min() + "\")")); // anIf.setThenStatement(throwStmt); // parent.getBody().insertBegin(anIf); // anIf.setParent(parent); // // // Build if check for max. // anIf = getFactory().Core().createIf(); // anIf.setCondition(getFactory().Code().<Boolean>createCodeSnippetExpression(element.getSimpleName() + " > " + annotation.max())); // anIf.setThenStatement(getFactory().Code().createCtThrow("new RuntimeException(\"out of max bound (\" + " + element.getSimpleName() + " + \" > " + annotation.max() + "\")")); // parent.getBody().insertBegin(anIf); // anIf.setParent(parent); // } // } // // Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/processing/BoundTemplateProcessor.java // public class BoundTemplateProcessor extends AbstractAnnotationProcessor<Bound, CtParameter<?>> { // // public void process(Bound annotation, CtParameter<?> element) { // // Is to be process? // CtExecutable<?> e = element.getParent(); // if (e.getBody() == null) { // return; // } // // // Use template. // CtClass<?> type = e.getParent(CtClass.class); // Template t = new BoundTemplate(getFactory().Type().createReference(Double.class), element.getSimpleName(), annotation.min(), annotation.max()); // final CtBlock apply = (CtBlock) t.apply(type); // // // Apply transformation. // for (int i = apply.getStatements().size() - 1; i >= 0; i--) { // final CtStatement statement = apply.getStatement(i); // statement.delete(); // e.getBody().insertBegin(statement); // } // } // } // // Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/src/Main.java // public class Main { // // public static void main(String[] args) { // for (int i = 0; i < 10; i++) { // try { // new Main().m(i); // } catch (RuntimeException e) { // System.out.println(e.getMessage()); // } // } // } // // public void m(@Bound(min = 2d, max = 8d) int a) { // System.out.println("Great method!"); // } // // }
import fr.inria.gforge.spoon.transformation.bound.processing.BoundProcessor; import fr.inria.gforge.spoon.transformation.bound.processing.BoundTemplateProcessor; import fr.inria.gforge.spoon.transformation.bound.src.Main; import org.junit.Test; import spoon.Launcher; import spoon.SpoonAPI; import spoon.reflect.code.CtIf; import spoon.reflect.declaration.CtMethod; import spoon.reflect.declaration.CtType; import static org.junit.Assert.assertTrue;
package fr.inria.gforge.spoon.transformation.bound; public class BoundTest { @Test public void testBoundTemplate() throws Exception { SpoonAPI launcher = new Launcher(); launcher.getEnvironment().setNoClasspath(true); launcher.addInputResource("./src/main/java"); launcher.setSourceOutputDirectory("./target/spoon-template"); launcher.addProcessor(new BoundTemplateProcessor()); launcher.run(); final CtType<Main> target = launcher.getFactory().Type().get(Main.class); final CtMethod<?> m = target.getMethodsByName("m").get(0); assertTrue(m.getBody().getStatements().size() >= 2); assertTrue(m.getBody().getStatement(0) instanceof CtIf); assertTrue(m.getBody().getStatement(1) instanceof CtIf); } @Test public void testBoundProcessor() throws Exception { SpoonAPI launcher = new Launcher(); launcher.getEnvironment().setNoClasspath(true); launcher.addInputResource("./src/main/java"); launcher.setSourceOutputDirectory("./target/spoon-processor");
// Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/processing/BoundProcessor.java // public class BoundProcessor extends AbstractAnnotationProcessor<Bound, CtParameter<?>> { // public void process(Bound annotation, CtParameter<?> element) { // final CtMethod parent = element.getParent(CtMethod.class); // // // Build if check for min. // CtIf anIf = getFactory().Core().createIf(); // anIf.setCondition(getFactory().Code().<Boolean>createCodeSnippetExpression(element.getSimpleName() + " < " + annotation.min())); // CtThrow throwStmt = getFactory().Core().createThrow(); // throwStmt.setThrownExpression((CtExpression<? extends Throwable>) getFactory().Core().createCodeSnippetExpression().setValue("new RuntimeException(\"out of min bound (\" + " + element.getSimpleName() + " + \" < " + annotation.min() + "\")")); // anIf.setThenStatement(throwStmt); // parent.getBody().insertBegin(anIf); // anIf.setParent(parent); // // // Build if check for max. // anIf = getFactory().Core().createIf(); // anIf.setCondition(getFactory().Code().<Boolean>createCodeSnippetExpression(element.getSimpleName() + " > " + annotation.max())); // anIf.setThenStatement(getFactory().Code().createCtThrow("new RuntimeException(\"out of max bound (\" + " + element.getSimpleName() + " + \" > " + annotation.max() + "\")")); // parent.getBody().insertBegin(anIf); // anIf.setParent(parent); // } // } // // Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/processing/BoundTemplateProcessor.java // public class BoundTemplateProcessor extends AbstractAnnotationProcessor<Bound, CtParameter<?>> { // // public void process(Bound annotation, CtParameter<?> element) { // // Is to be process? // CtExecutable<?> e = element.getParent(); // if (e.getBody() == null) { // return; // } // // // Use template. // CtClass<?> type = e.getParent(CtClass.class); // Template t = new BoundTemplate(getFactory().Type().createReference(Double.class), element.getSimpleName(), annotation.min(), annotation.max()); // final CtBlock apply = (CtBlock) t.apply(type); // // // Apply transformation. // for (int i = apply.getStatements().size() - 1; i >= 0; i--) { // final CtStatement statement = apply.getStatement(i); // statement.delete(); // e.getBody().insertBegin(statement); // } // } // } // // Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/src/Main.java // public class Main { // // public static void main(String[] args) { // for (int i = 0; i < 10; i++) { // try { // new Main().m(i); // } catch (RuntimeException e) { // System.out.println(e.getMessage()); // } // } // } // // public void m(@Bound(min = 2d, max = 8d) int a) { // System.out.println("Great method!"); // } // // } // Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/BoundTest.java import fr.inria.gforge.spoon.transformation.bound.processing.BoundProcessor; import fr.inria.gforge.spoon.transformation.bound.processing.BoundTemplateProcessor; import fr.inria.gforge.spoon.transformation.bound.src.Main; import org.junit.Test; import spoon.Launcher; import spoon.SpoonAPI; import spoon.reflect.code.CtIf; import spoon.reflect.declaration.CtMethod; import spoon.reflect.declaration.CtType; import static org.junit.Assert.assertTrue; package fr.inria.gforge.spoon.transformation.bound; public class BoundTest { @Test public void testBoundTemplate() throws Exception { SpoonAPI launcher = new Launcher(); launcher.getEnvironment().setNoClasspath(true); launcher.addInputResource("./src/main/java"); launcher.setSourceOutputDirectory("./target/spoon-template"); launcher.addProcessor(new BoundTemplateProcessor()); launcher.run(); final CtType<Main> target = launcher.getFactory().Type().get(Main.class); final CtMethod<?> m = target.getMethodsByName("m").get(0); assertTrue(m.getBody().getStatements().size() >= 2); assertTrue(m.getBody().getStatement(0) instanceof CtIf); assertTrue(m.getBody().getStatement(1) instanceof CtIf); } @Test public void testBoundProcessor() throws Exception { SpoonAPI launcher = new Launcher(); launcher.getEnvironment().setNoClasspath(true); launcher.addInputResource("./src/main/java"); launcher.setSourceOutputDirectory("./target/spoon-processor");
launcher.addProcessor(new BoundProcessor());
SpoonLabs/spoon-examples
src/test/resources/factory/src/Main.java
// Path: src/test/resources/factory/src/impl1/AImpl1.java // public class AImpl1 implements A { // // public void m1() { // System.out.println("executing AImpl1.m1"); // } // // } // // Path: src/test/resources/factory/src/impl1/BImpl1.java // public class BImpl1 implements B { // // public void m2() { // System.out.println("executing BImpl1.m2"); // } // // } // // Path: src/test/resources/factory/src/impl1/FactoryImpl1.java // public class FactoryImpl1 implements Factory { // // public A createA() { // return new AImpl1(); // } // // public B createB() { // return new BImpl1(); // } // // } // // Path: src/test/resources/factory/src/impl2/FactoryImpl2.java // public class FactoryImpl2 implements Factory { // // public A createA() { // return new AImpl2(); // } // // public B createB() { // return new BImpl2(); // } // // }
import factory.src.impl1.AImpl1; import factory.src.impl1.BImpl1; import factory.src.impl1.FactoryImpl1; import factory.src.impl2.FactoryImpl2;
package factory.src; public class Main { public static void main(String[] args) {
// Path: src/test/resources/factory/src/impl1/AImpl1.java // public class AImpl1 implements A { // // public void m1() { // System.out.println("executing AImpl1.m1"); // } // // } // // Path: src/test/resources/factory/src/impl1/BImpl1.java // public class BImpl1 implements B { // // public void m2() { // System.out.println("executing BImpl1.m2"); // } // // } // // Path: src/test/resources/factory/src/impl1/FactoryImpl1.java // public class FactoryImpl1 implements Factory { // // public A createA() { // return new AImpl1(); // } // // public B createB() { // return new BImpl1(); // } // // } // // Path: src/test/resources/factory/src/impl2/FactoryImpl2.java // public class FactoryImpl2 implements Factory { // // public A createA() { // return new AImpl2(); // } // // public B createB() { // return new BImpl2(); // } // // } // Path: src/test/resources/factory/src/Main.java import factory.src.impl1.AImpl1; import factory.src.impl1.BImpl1; import factory.src.impl1.FactoryImpl1; import factory.src.impl2.FactoryImpl2; package factory.src; public class Main { public static void main(String[] args) {
execute(new FactoryImpl1());
SpoonLabs/spoon-examples
src/test/resources/factory/src/Main.java
// Path: src/test/resources/factory/src/impl1/AImpl1.java // public class AImpl1 implements A { // // public void m1() { // System.out.println("executing AImpl1.m1"); // } // // } // // Path: src/test/resources/factory/src/impl1/BImpl1.java // public class BImpl1 implements B { // // public void m2() { // System.out.println("executing BImpl1.m2"); // } // // } // // Path: src/test/resources/factory/src/impl1/FactoryImpl1.java // public class FactoryImpl1 implements Factory { // // public A createA() { // return new AImpl1(); // } // // public B createB() { // return new BImpl1(); // } // // } // // Path: src/test/resources/factory/src/impl2/FactoryImpl2.java // public class FactoryImpl2 implements Factory { // // public A createA() { // return new AImpl2(); // } // // public B createB() { // return new BImpl2(); // } // // }
import factory.src.impl1.AImpl1; import factory.src.impl1.BImpl1; import factory.src.impl1.FactoryImpl1; import factory.src.impl2.FactoryImpl2;
package factory.src; public class Main { public static void main(String[] args) { execute(new FactoryImpl1());
// Path: src/test/resources/factory/src/impl1/AImpl1.java // public class AImpl1 implements A { // // public void m1() { // System.out.println("executing AImpl1.m1"); // } // // } // // Path: src/test/resources/factory/src/impl1/BImpl1.java // public class BImpl1 implements B { // // public void m2() { // System.out.println("executing BImpl1.m2"); // } // // } // // Path: src/test/resources/factory/src/impl1/FactoryImpl1.java // public class FactoryImpl1 implements Factory { // // public A createA() { // return new AImpl1(); // } // // public B createB() { // return new BImpl1(); // } // // } // // Path: src/test/resources/factory/src/impl2/FactoryImpl2.java // public class FactoryImpl2 implements Factory { // // public A createA() { // return new AImpl2(); // } // // public B createB() { // return new BImpl2(); // } // // } // Path: src/test/resources/factory/src/Main.java import factory.src.impl1.AImpl1; import factory.src.impl1.BImpl1; import factory.src.impl1.FactoryImpl1; import factory.src.impl2.FactoryImpl2; package factory.src; public class Main { public static void main(String[] args) { execute(new FactoryImpl1());
execute(new FactoryImpl2());
SpoonLabs/spoon-examples
src/test/resources/factory/src/Main.java
// Path: src/test/resources/factory/src/impl1/AImpl1.java // public class AImpl1 implements A { // // public void m1() { // System.out.println("executing AImpl1.m1"); // } // // } // // Path: src/test/resources/factory/src/impl1/BImpl1.java // public class BImpl1 implements B { // // public void m2() { // System.out.println("executing BImpl1.m2"); // } // // } // // Path: src/test/resources/factory/src/impl1/FactoryImpl1.java // public class FactoryImpl1 implements Factory { // // public A createA() { // return new AImpl1(); // } // // public B createB() { // return new BImpl1(); // } // // } // // Path: src/test/resources/factory/src/impl2/FactoryImpl2.java // public class FactoryImpl2 implements Factory { // // public A createA() { // return new AImpl2(); // } // // public B createB() { // return new BImpl2(); // } // // }
import factory.src.impl1.AImpl1; import factory.src.impl1.BImpl1; import factory.src.impl1.FactoryImpl1; import factory.src.impl2.FactoryImpl2;
package factory.src; public class Main { public static void main(String[] args) { execute(new FactoryImpl1()); execute(new FactoryImpl2()); } public static void execute(Factory f) { System.out.println("======= running program with factory "+f); A a = f.createA(); a.m1(); B b = f.createB(); b.m2(); // that's a mistake: the factory should be used!
// Path: src/test/resources/factory/src/impl1/AImpl1.java // public class AImpl1 implements A { // // public void m1() { // System.out.println("executing AImpl1.m1"); // } // // } // // Path: src/test/resources/factory/src/impl1/BImpl1.java // public class BImpl1 implements B { // // public void m2() { // System.out.println("executing BImpl1.m2"); // } // // } // // Path: src/test/resources/factory/src/impl1/FactoryImpl1.java // public class FactoryImpl1 implements Factory { // // public A createA() { // return new AImpl1(); // } // // public B createB() { // return new BImpl1(); // } // // } // // Path: src/test/resources/factory/src/impl2/FactoryImpl2.java // public class FactoryImpl2 implements Factory { // // public A createA() { // return new AImpl2(); // } // // public B createB() { // return new BImpl2(); // } // // } // Path: src/test/resources/factory/src/Main.java import factory.src.impl1.AImpl1; import factory.src.impl1.BImpl1; import factory.src.impl1.FactoryImpl1; import factory.src.impl2.FactoryImpl2; package factory.src; public class Main { public static void main(String[] args) { execute(new FactoryImpl1()); execute(new FactoryImpl2()); } public static void execute(Factory f) { System.out.println("======= running program with factory "+f); A a = f.createA(); a.m1(); B b = f.createB(); b.m2(); // that's a mistake: the factory should be used!
new BImpl1().m2();
SpoonLabs/spoon-examples
src/test/resources/factory/src/Main.java
// Path: src/test/resources/factory/src/impl1/AImpl1.java // public class AImpl1 implements A { // // public void m1() { // System.out.println("executing AImpl1.m1"); // } // // } // // Path: src/test/resources/factory/src/impl1/BImpl1.java // public class BImpl1 implements B { // // public void m2() { // System.out.println("executing BImpl1.m2"); // } // // } // // Path: src/test/resources/factory/src/impl1/FactoryImpl1.java // public class FactoryImpl1 implements Factory { // // public A createA() { // return new AImpl1(); // } // // public B createB() { // return new BImpl1(); // } // // } // // Path: src/test/resources/factory/src/impl2/FactoryImpl2.java // public class FactoryImpl2 implements Factory { // // public A createA() { // return new AImpl2(); // } // // public B createB() { // return new BImpl2(); // } // // }
import factory.src.impl1.AImpl1; import factory.src.impl1.BImpl1; import factory.src.impl1.FactoryImpl1; import factory.src.impl2.FactoryImpl2;
package factory.src; public class Main { public static void main(String[] args) { execute(new FactoryImpl1()); execute(new FactoryImpl2()); } public static void execute(Factory f) { System.out.println("======= running program with factory "+f); A a = f.createA(); a.m1(); B b = f.createB(); b.m2(); // that's a mistake: the factory should be used! new BImpl1().m2();
// Path: src/test/resources/factory/src/impl1/AImpl1.java // public class AImpl1 implements A { // // public void m1() { // System.out.println("executing AImpl1.m1"); // } // // } // // Path: src/test/resources/factory/src/impl1/BImpl1.java // public class BImpl1 implements B { // // public void m2() { // System.out.println("executing BImpl1.m2"); // } // // } // // Path: src/test/resources/factory/src/impl1/FactoryImpl1.java // public class FactoryImpl1 implements Factory { // // public A createA() { // return new AImpl1(); // } // // public B createB() { // return new BImpl1(); // } // // } // // Path: src/test/resources/factory/src/impl2/FactoryImpl2.java // public class FactoryImpl2 implements Factory { // // public A createA() { // return new AImpl2(); // } // // public B createB() { // return new BImpl2(); // } // // } // Path: src/test/resources/factory/src/Main.java import factory.src.impl1.AImpl1; import factory.src.impl1.BImpl1; import factory.src.impl1.FactoryImpl1; import factory.src.impl2.FactoryImpl2; package factory.src; public class Main { public static void main(String[] args) { execute(new FactoryImpl1()); execute(new FactoryImpl2()); } public static void execute(Factory f) { System.out.println("======= running program with factory "+f); A a = f.createA(); a.m1(); B b = f.createB(); b.m2(); // that's a mistake: the factory should be used! new BImpl1().m2();
new AImpl1().m1();
SpoonLabs/spoon-examples
src/test/resources/project/src/main/java/ow2con/publicapi/subpack/TypePublic.java
// Path: src/test/resources/project/src/main/java/ow2con/privateapi/PrivateType.java // public class PrivateType { // int i = 0; // // public int getANumber() { // return i+1; // } // } // // Path: src/test/resources/project/src/main/java/ow2con/privateapi/subpack/AnotherType.java // public class AnotherType { // // public String foo() { // return "42"; // } // }
import ow2con.privateapi.PrivateType; import ow2con.privateapi.subpack.AnotherType;
package ow2con.publicapi.subpack; public class TypePublic { private PrivateType getPrivateType() { return new PrivateType(); }
// Path: src/test/resources/project/src/main/java/ow2con/privateapi/PrivateType.java // public class PrivateType { // int i = 0; // // public int getANumber() { // return i+1; // } // } // // Path: src/test/resources/project/src/main/java/ow2con/privateapi/subpack/AnotherType.java // public class AnotherType { // // public String foo() { // return "42"; // } // } // Path: src/test/resources/project/src/main/java/ow2con/publicapi/subpack/TypePublic.java import ow2con.privateapi.PrivateType; import ow2con.privateapi.subpack.AnotherType; package ow2con.publicapi.subpack; public class TypePublic { private PrivateType getPrivateType() { return new PrivateType(); }
public AnotherType getAnotherType() {
SpoonLabs/spoon-examples
src/main/java/fr/inria/gforge/spoon/assertgenerator/workflow/AssertionAdder.java
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Logger.java // public class Logger { // // public static Map<String, Object> observations = new HashMap<>(); // // public static void observe(String name, Object object) { // observations.put(name, object); // } // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static List<CtMethod> getGetters(CtLocalVariable localVariable) { // return ((Set<CtMethod<?>>) localVariable.getType().getDeclaration().getMethods()).stream() // .filter(method -> method.getParameters().isEmpty() && // method.getType() != localVariable.getFactory().Type().VOID_PRIMITIVE && // (method.getSimpleName().startsWith("get") || // method.getSimpleName().startsWith("is")) // ).collect(Collectors.toList()); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static String getKey(CtMethod method) { // return method.getParent(CtClass.class).getSimpleName() + "#" + method.getSimpleName(); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static CtInvocation invok(CtMethod method, CtLocalVariable localVariable) { // final CtExecutableReference reference = method.getReference(); // final CtVariableAccess variableRead = method.getFactory().createVariableRead(localVariable.getReference(), false); // return method.getFactory().createInvocation(variableRead, reference); // }
import fr.inria.gforge.spoon.assertgenerator.Logger; import org.junit.Assert; import spoon.reflect.code.CtExpression; import spoon.reflect.code.CtInvocation; import spoon.reflect.code.CtLocalVariable; import spoon.reflect.code.CtTypeAccess; import spoon.reflect.declaration.CtMethod; import spoon.reflect.factory.Factory; import spoon.reflect.reference.CtExecutableReference; import java.util.List; import static fr.inria.gforge.spoon.assertgenerator.Util.getGetters; import static fr.inria.gforge.spoon.assertgenerator.Util.getKey; import static fr.inria.gforge.spoon.assertgenerator.Util.invok;
package fr.inria.gforge.spoon.assertgenerator.workflow; /** * Created by Benjamin DANGLOT * [email protected] * on 22/06/17 */ public class AssertionAdder { private Factory factory; public AssertionAdder(Factory factory) { this.factory = factory; } @SuppressWarnings("unchecked") public void addAssertion(CtMethod<?> testMethod, List<CtLocalVariable> ctLocalVariables) { ctLocalVariables.forEach(ctLocalVariable -> this.addAssertion(testMethod, ctLocalVariable)); System.out.println(testMethod); } @SuppressWarnings("unchecked") void addAssertion(CtMethod testMethod, CtLocalVariable localVariable) { List<CtMethod> getters =
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Logger.java // public class Logger { // // public static Map<String, Object> observations = new HashMap<>(); // // public static void observe(String name, Object object) { // observations.put(name, object); // } // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static List<CtMethod> getGetters(CtLocalVariable localVariable) { // return ((Set<CtMethod<?>>) localVariable.getType().getDeclaration().getMethods()).stream() // .filter(method -> method.getParameters().isEmpty() && // method.getType() != localVariable.getFactory().Type().VOID_PRIMITIVE && // (method.getSimpleName().startsWith("get") || // method.getSimpleName().startsWith("is")) // ).collect(Collectors.toList()); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static String getKey(CtMethod method) { // return method.getParent(CtClass.class).getSimpleName() + "#" + method.getSimpleName(); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static CtInvocation invok(CtMethod method, CtLocalVariable localVariable) { // final CtExecutableReference reference = method.getReference(); // final CtVariableAccess variableRead = method.getFactory().createVariableRead(localVariable.getReference(), false); // return method.getFactory().createInvocation(variableRead, reference); // } // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/workflow/AssertionAdder.java import fr.inria.gforge.spoon.assertgenerator.Logger; import org.junit.Assert; import spoon.reflect.code.CtExpression; import spoon.reflect.code.CtInvocation; import spoon.reflect.code.CtLocalVariable; import spoon.reflect.code.CtTypeAccess; import spoon.reflect.declaration.CtMethod; import spoon.reflect.factory.Factory; import spoon.reflect.reference.CtExecutableReference; import java.util.List; import static fr.inria.gforge.spoon.assertgenerator.Util.getGetters; import static fr.inria.gforge.spoon.assertgenerator.Util.getKey; import static fr.inria.gforge.spoon.assertgenerator.Util.invok; package fr.inria.gforge.spoon.assertgenerator.workflow; /** * Created by Benjamin DANGLOT * [email protected] * on 22/06/17 */ public class AssertionAdder { private Factory factory; public AssertionAdder(Factory factory) { this.factory = factory; } @SuppressWarnings("unchecked") public void addAssertion(CtMethod<?> testMethod, List<CtLocalVariable> ctLocalVariables) { ctLocalVariables.forEach(ctLocalVariable -> this.addAssertion(testMethod, ctLocalVariable)); System.out.println(testMethod); } @SuppressWarnings("unchecked") void addAssertion(CtMethod testMethod, CtLocalVariable localVariable) { List<CtMethod> getters =
getGetters(localVariable);
SpoonLabs/spoon-examples
src/main/java/fr/inria/gforge/spoon/assertgenerator/workflow/AssertionAdder.java
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Logger.java // public class Logger { // // public static Map<String, Object> observations = new HashMap<>(); // // public static void observe(String name, Object object) { // observations.put(name, object); // } // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static List<CtMethod> getGetters(CtLocalVariable localVariable) { // return ((Set<CtMethod<?>>) localVariable.getType().getDeclaration().getMethods()).stream() // .filter(method -> method.getParameters().isEmpty() && // method.getType() != localVariable.getFactory().Type().VOID_PRIMITIVE && // (method.getSimpleName().startsWith("get") || // method.getSimpleName().startsWith("is")) // ).collect(Collectors.toList()); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static String getKey(CtMethod method) { // return method.getParent(CtClass.class).getSimpleName() + "#" + method.getSimpleName(); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static CtInvocation invok(CtMethod method, CtLocalVariable localVariable) { // final CtExecutableReference reference = method.getReference(); // final CtVariableAccess variableRead = method.getFactory().createVariableRead(localVariable.getReference(), false); // return method.getFactory().createInvocation(variableRead, reference); // }
import fr.inria.gforge.spoon.assertgenerator.Logger; import org.junit.Assert; import spoon.reflect.code.CtExpression; import spoon.reflect.code.CtInvocation; import spoon.reflect.code.CtLocalVariable; import spoon.reflect.code.CtTypeAccess; import spoon.reflect.declaration.CtMethod; import spoon.reflect.factory.Factory; import spoon.reflect.reference.CtExecutableReference; import java.util.List; import static fr.inria.gforge.spoon.assertgenerator.Util.getGetters; import static fr.inria.gforge.spoon.assertgenerator.Util.getKey; import static fr.inria.gforge.spoon.assertgenerator.Util.invok;
package fr.inria.gforge.spoon.assertgenerator.workflow; /** * Created by Benjamin DANGLOT * [email protected] * on 22/06/17 */ public class AssertionAdder { private Factory factory; public AssertionAdder(Factory factory) { this.factory = factory; } @SuppressWarnings("unchecked") public void addAssertion(CtMethod<?> testMethod, List<CtLocalVariable> ctLocalVariables) { ctLocalVariables.forEach(ctLocalVariable -> this.addAssertion(testMethod, ctLocalVariable)); System.out.println(testMethod); } @SuppressWarnings("unchecked") void addAssertion(CtMethod testMethod, CtLocalVariable localVariable) { List<CtMethod> getters = getGetters(localVariable); getters.forEach(getter -> {
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Logger.java // public class Logger { // // public static Map<String, Object> observations = new HashMap<>(); // // public static void observe(String name, Object object) { // observations.put(name, object); // } // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static List<CtMethod> getGetters(CtLocalVariable localVariable) { // return ((Set<CtMethod<?>>) localVariable.getType().getDeclaration().getMethods()).stream() // .filter(method -> method.getParameters().isEmpty() && // method.getType() != localVariable.getFactory().Type().VOID_PRIMITIVE && // (method.getSimpleName().startsWith("get") || // method.getSimpleName().startsWith("is")) // ).collect(Collectors.toList()); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static String getKey(CtMethod method) { // return method.getParent(CtClass.class).getSimpleName() + "#" + method.getSimpleName(); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static CtInvocation invok(CtMethod method, CtLocalVariable localVariable) { // final CtExecutableReference reference = method.getReference(); // final CtVariableAccess variableRead = method.getFactory().createVariableRead(localVariable.getReference(), false); // return method.getFactory().createInvocation(variableRead, reference); // } // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/workflow/AssertionAdder.java import fr.inria.gforge.spoon.assertgenerator.Logger; import org.junit.Assert; import spoon.reflect.code.CtExpression; import spoon.reflect.code.CtInvocation; import spoon.reflect.code.CtLocalVariable; import spoon.reflect.code.CtTypeAccess; import spoon.reflect.declaration.CtMethod; import spoon.reflect.factory.Factory; import spoon.reflect.reference.CtExecutableReference; import java.util.List; import static fr.inria.gforge.spoon.assertgenerator.Util.getGetters; import static fr.inria.gforge.spoon.assertgenerator.Util.getKey; import static fr.inria.gforge.spoon.assertgenerator.Util.invok; package fr.inria.gforge.spoon.assertgenerator.workflow; /** * Created by Benjamin DANGLOT * [email protected] * on 22/06/17 */ public class AssertionAdder { private Factory factory; public AssertionAdder(Factory factory) { this.factory = factory; } @SuppressWarnings("unchecked") public void addAssertion(CtMethod<?> testMethod, List<CtLocalVariable> ctLocalVariables) { ctLocalVariables.forEach(ctLocalVariable -> this.addAssertion(testMethod, ctLocalVariable)); System.out.println(testMethod); } @SuppressWarnings("unchecked") void addAssertion(CtMethod testMethod, CtLocalVariable localVariable) { List<CtMethod> getters = getGetters(localVariable); getters.forEach(getter -> {
String key = getKey(getter);
SpoonLabs/spoon-examples
src/main/java/fr/inria/gforge/spoon/assertgenerator/workflow/AssertionAdder.java
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Logger.java // public class Logger { // // public static Map<String, Object> observations = new HashMap<>(); // // public static void observe(String name, Object object) { // observations.put(name, object); // } // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static List<CtMethod> getGetters(CtLocalVariable localVariable) { // return ((Set<CtMethod<?>>) localVariable.getType().getDeclaration().getMethods()).stream() // .filter(method -> method.getParameters().isEmpty() && // method.getType() != localVariable.getFactory().Type().VOID_PRIMITIVE && // (method.getSimpleName().startsWith("get") || // method.getSimpleName().startsWith("is")) // ).collect(Collectors.toList()); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static String getKey(CtMethod method) { // return method.getParent(CtClass.class).getSimpleName() + "#" + method.getSimpleName(); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static CtInvocation invok(CtMethod method, CtLocalVariable localVariable) { // final CtExecutableReference reference = method.getReference(); // final CtVariableAccess variableRead = method.getFactory().createVariableRead(localVariable.getReference(), false); // return method.getFactory().createInvocation(variableRead, reference); // }
import fr.inria.gforge.spoon.assertgenerator.Logger; import org.junit.Assert; import spoon.reflect.code.CtExpression; import spoon.reflect.code.CtInvocation; import spoon.reflect.code.CtLocalVariable; import spoon.reflect.code.CtTypeAccess; import spoon.reflect.declaration.CtMethod; import spoon.reflect.factory.Factory; import spoon.reflect.reference.CtExecutableReference; import java.util.List; import static fr.inria.gforge.spoon.assertgenerator.Util.getGetters; import static fr.inria.gforge.spoon.assertgenerator.Util.getKey; import static fr.inria.gforge.spoon.assertgenerator.Util.invok;
package fr.inria.gforge.spoon.assertgenerator.workflow; /** * Created by Benjamin DANGLOT * [email protected] * on 22/06/17 */ public class AssertionAdder { private Factory factory; public AssertionAdder(Factory factory) { this.factory = factory; } @SuppressWarnings("unchecked") public void addAssertion(CtMethod<?> testMethod, List<CtLocalVariable> ctLocalVariables) { ctLocalVariables.forEach(ctLocalVariable -> this.addAssertion(testMethod, ctLocalVariable)); System.out.println(testMethod); } @SuppressWarnings("unchecked") void addAssertion(CtMethod testMethod, CtLocalVariable localVariable) { List<CtMethod> getters = getGetters(localVariable); getters.forEach(getter -> { String key = getKey(getter); CtInvocation invocationToGetter =
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Logger.java // public class Logger { // // public static Map<String, Object> observations = new HashMap<>(); // // public static void observe(String name, Object object) { // observations.put(name, object); // } // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static List<CtMethod> getGetters(CtLocalVariable localVariable) { // return ((Set<CtMethod<?>>) localVariable.getType().getDeclaration().getMethods()).stream() // .filter(method -> method.getParameters().isEmpty() && // method.getType() != localVariable.getFactory().Type().VOID_PRIMITIVE && // (method.getSimpleName().startsWith("get") || // method.getSimpleName().startsWith("is")) // ).collect(Collectors.toList()); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static String getKey(CtMethod method) { // return method.getParent(CtClass.class).getSimpleName() + "#" + method.getSimpleName(); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static CtInvocation invok(CtMethod method, CtLocalVariable localVariable) { // final CtExecutableReference reference = method.getReference(); // final CtVariableAccess variableRead = method.getFactory().createVariableRead(localVariable.getReference(), false); // return method.getFactory().createInvocation(variableRead, reference); // } // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/workflow/AssertionAdder.java import fr.inria.gforge.spoon.assertgenerator.Logger; import org.junit.Assert; import spoon.reflect.code.CtExpression; import spoon.reflect.code.CtInvocation; import spoon.reflect.code.CtLocalVariable; import spoon.reflect.code.CtTypeAccess; import spoon.reflect.declaration.CtMethod; import spoon.reflect.factory.Factory; import spoon.reflect.reference.CtExecutableReference; import java.util.List; import static fr.inria.gforge.spoon.assertgenerator.Util.getGetters; import static fr.inria.gforge.spoon.assertgenerator.Util.getKey; import static fr.inria.gforge.spoon.assertgenerator.Util.invok; package fr.inria.gforge.spoon.assertgenerator.workflow; /** * Created by Benjamin DANGLOT * [email protected] * on 22/06/17 */ public class AssertionAdder { private Factory factory; public AssertionAdder(Factory factory) { this.factory = factory; } @SuppressWarnings("unchecked") public void addAssertion(CtMethod<?> testMethod, List<CtLocalVariable> ctLocalVariables) { ctLocalVariables.forEach(ctLocalVariable -> this.addAssertion(testMethod, ctLocalVariable)); System.out.println(testMethod); } @SuppressWarnings("unchecked") void addAssertion(CtMethod testMethod, CtLocalVariable localVariable) { List<CtMethod> getters = getGetters(localVariable); getters.forEach(getter -> { String key = getKey(getter); CtInvocation invocationToGetter =
invok(getter, localVariable);
SpoonLabs/spoon-examples
src/main/java/fr/inria/gforge/spoon/assertgenerator/workflow/AssertionAdder.java
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Logger.java // public class Logger { // // public static Map<String, Object> observations = new HashMap<>(); // // public static void observe(String name, Object object) { // observations.put(name, object); // } // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static List<CtMethod> getGetters(CtLocalVariable localVariable) { // return ((Set<CtMethod<?>>) localVariable.getType().getDeclaration().getMethods()).stream() // .filter(method -> method.getParameters().isEmpty() && // method.getType() != localVariable.getFactory().Type().VOID_PRIMITIVE && // (method.getSimpleName().startsWith("get") || // method.getSimpleName().startsWith("is")) // ).collect(Collectors.toList()); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static String getKey(CtMethod method) { // return method.getParent(CtClass.class).getSimpleName() + "#" + method.getSimpleName(); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static CtInvocation invok(CtMethod method, CtLocalVariable localVariable) { // final CtExecutableReference reference = method.getReference(); // final CtVariableAccess variableRead = method.getFactory().createVariableRead(localVariable.getReference(), false); // return method.getFactory().createInvocation(variableRead, reference); // }
import fr.inria.gforge.spoon.assertgenerator.Logger; import org.junit.Assert; import spoon.reflect.code.CtExpression; import spoon.reflect.code.CtInvocation; import spoon.reflect.code.CtLocalVariable; import spoon.reflect.code.CtTypeAccess; import spoon.reflect.declaration.CtMethod; import spoon.reflect.factory.Factory; import spoon.reflect.reference.CtExecutableReference; import java.util.List; import static fr.inria.gforge.spoon.assertgenerator.Util.getGetters; import static fr.inria.gforge.spoon.assertgenerator.Util.getKey; import static fr.inria.gforge.spoon.assertgenerator.Util.invok;
package fr.inria.gforge.spoon.assertgenerator.workflow; /** * Created by Benjamin DANGLOT * [email protected] * on 22/06/17 */ public class AssertionAdder { private Factory factory; public AssertionAdder(Factory factory) { this.factory = factory; } @SuppressWarnings("unchecked") public void addAssertion(CtMethod<?> testMethod, List<CtLocalVariable> ctLocalVariables) { ctLocalVariables.forEach(ctLocalVariable -> this.addAssertion(testMethod, ctLocalVariable)); System.out.println(testMethod); } @SuppressWarnings("unchecked") void addAssertion(CtMethod testMethod, CtLocalVariable localVariable) { List<CtMethod> getters = getGetters(localVariable); getters.forEach(getter -> { String key = getKey(getter); CtInvocation invocationToGetter = invok(getter, localVariable); CtInvocation invocationToAssert = createAssert("assertEquals",
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Logger.java // public class Logger { // // public static Map<String, Object> observations = new HashMap<>(); // // public static void observe(String name, Object object) { // observations.put(name, object); // } // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static List<CtMethod> getGetters(CtLocalVariable localVariable) { // return ((Set<CtMethod<?>>) localVariable.getType().getDeclaration().getMethods()).stream() // .filter(method -> method.getParameters().isEmpty() && // method.getType() != localVariable.getFactory().Type().VOID_PRIMITIVE && // (method.getSimpleName().startsWith("get") || // method.getSimpleName().startsWith("is")) // ).collect(Collectors.toList()); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static String getKey(CtMethod method) { // return method.getParent(CtClass.class).getSimpleName() + "#" + method.getSimpleName(); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static CtInvocation invok(CtMethod method, CtLocalVariable localVariable) { // final CtExecutableReference reference = method.getReference(); // final CtVariableAccess variableRead = method.getFactory().createVariableRead(localVariable.getReference(), false); // return method.getFactory().createInvocation(variableRead, reference); // } // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/workflow/AssertionAdder.java import fr.inria.gforge.spoon.assertgenerator.Logger; import org.junit.Assert; import spoon.reflect.code.CtExpression; import spoon.reflect.code.CtInvocation; import spoon.reflect.code.CtLocalVariable; import spoon.reflect.code.CtTypeAccess; import spoon.reflect.declaration.CtMethod; import spoon.reflect.factory.Factory; import spoon.reflect.reference.CtExecutableReference; import java.util.List; import static fr.inria.gforge.spoon.assertgenerator.Util.getGetters; import static fr.inria.gforge.spoon.assertgenerator.Util.getKey; import static fr.inria.gforge.spoon.assertgenerator.Util.invok; package fr.inria.gforge.spoon.assertgenerator.workflow; /** * Created by Benjamin DANGLOT * [email protected] * on 22/06/17 */ public class AssertionAdder { private Factory factory; public AssertionAdder(Factory factory) { this.factory = factory; } @SuppressWarnings("unchecked") public void addAssertion(CtMethod<?> testMethod, List<CtLocalVariable> ctLocalVariables) { ctLocalVariables.forEach(ctLocalVariable -> this.addAssertion(testMethod, ctLocalVariable)); System.out.println(testMethod); } @SuppressWarnings("unchecked") void addAssertion(CtMethod testMethod, CtLocalVariable localVariable) { List<CtMethod> getters = getGetters(localVariable); getters.forEach(getter -> { String key = getKey(getter); CtInvocation invocationToGetter = invok(getter, localVariable); CtInvocation invocationToAssert = createAssert("assertEquals",
factory.createLiteral(Logger.observations.get(key)), // expected
SpoonLabs/spoon-examples
src/main/java/fr/inria/gforge/spoon/analysis/CatchProcessorTest.java
// Path: src/main/java/fr/inria/gforge/spoon/analysis/CatchProcessor.java // public class CatchProcessor extends AbstractProcessor<CtCatch> { // public final List<CtCatch> emptyCatchs = new ArrayList<>(); // // @Override // public boolean isToBeProcessed(CtCatch candidate) { // return candidate.getBody().getStatements().isEmpty(); // } // // @Override // public void process(CtCatch element) { // getEnvironment().report(this, Level.WARN, element, "empty catch clause " + element.getPosition().toString()); // emptyCatchs.add(element); // } // }
import fr.inria.gforge.spoon.analysis.CatchProcessor; import org.junit.Test; import spoon.Launcher; import spoon.processing.ProcessingManager; import spoon.reflect.factory.Factory; import spoon.support.QueueProcessingManager; import static org.junit.Assert.assertEquals;
package fr.inria.gforge.spoon.analysis; public class CatchProcessorTest { @Test public void testCatchProcessor() throws Exception { final String[] args = { "-i", "src/test/resources/src/", "-o", "target/spooned/" }; final Launcher launcher = new Launcher(); launcher.setArgs(args); launcher.run(); final Factory factory = launcher.getFactory(); final ProcessingManager processingManager = new QueueProcessingManager(factory);
// Path: src/main/java/fr/inria/gforge/spoon/analysis/CatchProcessor.java // public class CatchProcessor extends AbstractProcessor<CtCatch> { // public final List<CtCatch> emptyCatchs = new ArrayList<>(); // // @Override // public boolean isToBeProcessed(CtCatch candidate) { // return candidate.getBody().getStatements().isEmpty(); // } // // @Override // public void process(CtCatch element) { // getEnvironment().report(this, Level.WARN, element, "empty catch clause " + element.getPosition().toString()); // emptyCatchs.add(element); // } // } // Path: src/main/java/fr/inria/gforge/spoon/analysis/CatchProcessorTest.java import fr.inria.gforge.spoon.analysis.CatchProcessor; import org.junit.Test; import spoon.Launcher; import spoon.processing.ProcessingManager; import spoon.reflect.factory.Factory; import spoon.support.QueueProcessingManager; import static org.junit.Assert.assertEquals; package fr.inria.gforge.spoon.analysis; public class CatchProcessorTest { @Test public void testCatchProcessor() throws Exception { final String[] args = { "-i", "src/test/resources/src/", "-o", "target/spooned/" }; final Launcher launcher = new Launcher(); launcher.setArgs(args); launcher.run(); final Factory factory = launcher.getFactory(); final ProcessingManager processingManager = new QueueProcessingManager(factory);
final CatchProcessor processor = new CatchProcessor();
SpoonLabs/spoon-examples
src/main/java/fr/inria/gforge/spoon/transformation/bound/processing/BoundTemplateProcessor.java
// Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/template/BoundTemplate.java // public class BoundTemplate extends AbstractTemplate<CtStatement> { // // @Parameter // public CtTypeReference<Double> typeReference; // // @Parameter // public String _parameter_; // // @Parameter // public double _minBound_; // // @Parameter // public double _maxBound_; // // @Local // public BoundTemplate(CtTypeReference<Double> typeReference, String parameterName, double minBound, double maxBound) { // this.typeReference = typeReference; // _parameter_ = parameterName; // _maxBound_ = maxBound; // _minBound_ = minBound; // } // // public void test(Double _parameter_) throws Throwable { // if (_parameter_ > _maxBound_) { // throw new RuntimeException("out of max bound (" + _parameter_ + ">" + _maxBound_); // } // if (_parameter_ < _minBound_) { // throw new RuntimeException("out of min bound (" + _parameter_ + "<" + _minBound_); // } // } // // @Override // public CtStatement apply(CtType<?> targetType) { // return Substitution.substituteMethodBody((CtClass) targetType, this, "test", typeReference); // } // }
import fr.inria.gforge.spoon.transformation.bound.annotation.Bound; import fr.inria.gforge.spoon.transformation.bound.template.BoundTemplate; import spoon.processing.AbstractAnnotationProcessor; import spoon.reflect.code.CtBlock; import spoon.reflect.code.CtStatement; import spoon.reflect.declaration.CtClass; import spoon.reflect.declaration.CtExecutable; import spoon.reflect.declaration.CtParameter; import spoon.template.Template;
package fr.inria.gforge.spoon.transformation.bound.processing; public class BoundTemplateProcessor extends AbstractAnnotationProcessor<Bound, CtParameter<?>> { public void process(Bound annotation, CtParameter<?> element) { // Is to be process? CtExecutable<?> e = element.getParent(); if (e.getBody() == null) { return; } // Use template. CtClass<?> type = e.getParent(CtClass.class);
// Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/template/BoundTemplate.java // public class BoundTemplate extends AbstractTemplate<CtStatement> { // // @Parameter // public CtTypeReference<Double> typeReference; // // @Parameter // public String _parameter_; // // @Parameter // public double _minBound_; // // @Parameter // public double _maxBound_; // // @Local // public BoundTemplate(CtTypeReference<Double> typeReference, String parameterName, double minBound, double maxBound) { // this.typeReference = typeReference; // _parameter_ = parameterName; // _maxBound_ = maxBound; // _minBound_ = minBound; // } // // public void test(Double _parameter_) throws Throwable { // if (_parameter_ > _maxBound_) { // throw new RuntimeException("out of max bound (" + _parameter_ + ">" + _maxBound_); // } // if (_parameter_ < _minBound_) { // throw new RuntimeException("out of min bound (" + _parameter_ + "<" + _minBound_); // } // } // // @Override // public CtStatement apply(CtType<?> targetType) { // return Substitution.substituteMethodBody((CtClass) targetType, this, "test", typeReference); // } // } // Path: src/main/java/fr/inria/gforge/spoon/transformation/bound/processing/BoundTemplateProcessor.java import fr.inria.gforge.spoon.transformation.bound.annotation.Bound; import fr.inria.gforge.spoon.transformation.bound.template.BoundTemplate; import spoon.processing.AbstractAnnotationProcessor; import spoon.reflect.code.CtBlock; import spoon.reflect.code.CtStatement; import spoon.reflect.declaration.CtClass; import spoon.reflect.declaration.CtExecutable; import spoon.reflect.declaration.CtParameter; import spoon.template.Template; package fr.inria.gforge.spoon.transformation.bound.processing; public class BoundTemplateProcessor extends AbstractAnnotationProcessor<Bound, CtParameter<?>> { public void process(Bound annotation, CtParameter<?> element) { // Is to be process? CtExecutable<?> e = element.getParent(); if (e.getBody() == null) { return; } // Use template. CtClass<?> type = e.getParent(CtClass.class);
Template t = new BoundTemplate(getFactory().Type().createReference(Double.class), element.getSimpleName(), annotation.min(), annotation.max());
SpoonLabs/spoon-examples
src/test/resources/factory/src/impl1/FactoryImpl1.java
// Path: src/test/resources/factory/src/A.java // public interface A { // void m1(); // } // // Path: src/test/resources/factory/src/B.java // public interface B { // void m2(); // } // // Path: src/test/resources/factory/src/Factory.java // public interface Factory { // // A createA(); // B createB(); // // }
import factory.src.A; import factory.src.B; import factory.src.Factory;
package factory.src.impl1; public class FactoryImpl1 implements Factory { public A createA() { return new AImpl1(); }
// Path: src/test/resources/factory/src/A.java // public interface A { // void m1(); // } // // Path: src/test/resources/factory/src/B.java // public interface B { // void m2(); // } // // Path: src/test/resources/factory/src/Factory.java // public interface Factory { // // A createA(); // B createB(); // // } // Path: src/test/resources/factory/src/impl1/FactoryImpl1.java import factory.src.A; import factory.src.B; import factory.src.Factory; package factory.src.impl1; public class FactoryImpl1 implements Factory { public A createA() { return new AImpl1(); }
public B createB() {
SpoonLabs/spoon-examples
src/main/java/fr/inria/gforge/spoon/transformation/retry/RetryTest.java
// Path: src/main/java/fr/inria/gforge/spoon/transformation/retry/template/RetryTemplate.java // public class RetryTemplate extends BlockTemplate { // public RetryTemplate(CtBlock _original_, int _attempts_, long _delay_, boolean _verbose_) { // this._original_ = _original_; // this._attempts_ = _attempts_; // this._delay_ = _delay_; // this._verbose_ = _verbose_; // } // // @Parameter // CtBlock _original_; // // @Parameter // int _attempts_; // // @Parameter // long _delay_; // // @Parameter // boolean _verbose_; // // @Override // public void block() { // int attempt = 0; // Throwable lastTh = null; // while (attempt++ < _attempts_) { // try { // _original_.S(); // } catch (Throwable ex) { // lastTh = ex; // if (_verbose_) { // ex.printStackTrace(); // } // try { // Thread.sleep(_delay_); // } catch (InterruptedException ex2) { // } // } // } // if (lastTh != null) { // throw new RuntimeException(lastTh); // } // } // } // // Path: src/main/java/fr/inria/gforge/spoon/utils/TestSpooner.java // public class TestSpooner { // final SpoonModelBuilder compiler; // // public TestSpooner() throws Exception { // compiler = new TestSpoonCompiler( // new FactoryImpl(new DefaultCoreFactory(), new StandardEnvironment())); // } // // public TestSpooner addSource(File... files) throws Exception { // for (File file : files) { // compiler.addInputSource(file); // } // return this; // } // // public TestSpooner addTemplate(File... files) throws Exception { // for (File file : files) { // compiler.addTemplateSource(file); // } // return this; // } // // spoon.reflect.factory.Factory getFactory() { // return compiler.getFactory(); // } // // public TestSpooner process(CtElement element, Class<? extends Processor>... processors) throws Exception { // // Build spoon model // compiler.build(); // // ProcessingManager processing = new QueueProcessingManager(compiler.getFactory()); // // for (Class<? extends Processor> processorClz : processors) { // processing.addProcessor(processorClz.getName()); // } // processing.process(element); // // return this; // } // // public TestSpooner process(Class<? extends Processor>... processors) throws Exception { // // Build spoon model // compiler.build(); // // List<Processor<?>> processorsNames = new ArrayList<>(); // for (Class<? extends Processor> processor : processors) { // processorsNames.add(processor.newInstance()); // } // compiler.process(processorsNames); // // return this; // } // // public TestSpooner print(File dest) throws Exception { // dest.mkdirs(); // for (File file : dest.listFiles()) { // file.delete(); // } // // // compiler.getFactory().getEnvironment().setPreserveLineNumbers(true); // compiler.getFactory().getEnvironment().setSourceOutputDirectory(dest); // // compiler.generateProcessedSourceFiles(OutputType.COMPILATION_UNITS); // return this; // } // // public boolean compile() { // File target = compiler.getSourceOutputDirectory(); // final boolean compile = Main.compile(new String[]{"-1.7 " , "-proc:none", target.toString()}, new PrintWriter(System.out), new PrintWriter(System.out),null); // return compile; // } // // public Class getSpoonedClass(String classname) throws ClassNotFoundException { // File target = compiler.getSourceOutputDirectory(); // // ClassLoader classLoader = new SpoonClassLoader(getClass().getClassLoader(), target); // return classLoader.loadClass(classname); // } // // }
import fr.inria.gforge.spoon.transformation.retry.template.RetryTemplate; import fr.inria.gforge.spoon.utils.TestSpooner; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.File; import java.lang.reflect.Field; import java.util.Collection;
package fr.inria.gforge.spoon.transformation.retry; /** * Created by nicolas on 22/01/2015. */ public class RetryTest { TestSpooner spooner; private static final String TEST_CLASS = TestClass.class.getName(); @Before public void setUp() throws Exception { spooner = new TestSpooner() .addSource(new File("src/main/java/" + TEST_CLASS.replaceAll("\\.", "/") + ".java")) .addTemplate(
// Path: src/main/java/fr/inria/gforge/spoon/transformation/retry/template/RetryTemplate.java // public class RetryTemplate extends BlockTemplate { // public RetryTemplate(CtBlock _original_, int _attempts_, long _delay_, boolean _verbose_) { // this._original_ = _original_; // this._attempts_ = _attempts_; // this._delay_ = _delay_; // this._verbose_ = _verbose_; // } // // @Parameter // CtBlock _original_; // // @Parameter // int _attempts_; // // @Parameter // long _delay_; // // @Parameter // boolean _verbose_; // // @Override // public void block() { // int attempt = 0; // Throwable lastTh = null; // while (attempt++ < _attempts_) { // try { // _original_.S(); // } catch (Throwable ex) { // lastTh = ex; // if (_verbose_) { // ex.printStackTrace(); // } // try { // Thread.sleep(_delay_); // } catch (InterruptedException ex2) { // } // } // } // if (lastTh != null) { // throw new RuntimeException(lastTh); // } // } // } // // Path: src/main/java/fr/inria/gforge/spoon/utils/TestSpooner.java // public class TestSpooner { // final SpoonModelBuilder compiler; // // public TestSpooner() throws Exception { // compiler = new TestSpoonCompiler( // new FactoryImpl(new DefaultCoreFactory(), new StandardEnvironment())); // } // // public TestSpooner addSource(File... files) throws Exception { // for (File file : files) { // compiler.addInputSource(file); // } // return this; // } // // public TestSpooner addTemplate(File... files) throws Exception { // for (File file : files) { // compiler.addTemplateSource(file); // } // return this; // } // // spoon.reflect.factory.Factory getFactory() { // return compiler.getFactory(); // } // // public TestSpooner process(CtElement element, Class<? extends Processor>... processors) throws Exception { // // Build spoon model // compiler.build(); // // ProcessingManager processing = new QueueProcessingManager(compiler.getFactory()); // // for (Class<? extends Processor> processorClz : processors) { // processing.addProcessor(processorClz.getName()); // } // processing.process(element); // // return this; // } // // public TestSpooner process(Class<? extends Processor>... processors) throws Exception { // // Build spoon model // compiler.build(); // // List<Processor<?>> processorsNames = new ArrayList<>(); // for (Class<? extends Processor> processor : processors) { // processorsNames.add(processor.newInstance()); // } // compiler.process(processorsNames); // // return this; // } // // public TestSpooner print(File dest) throws Exception { // dest.mkdirs(); // for (File file : dest.listFiles()) { // file.delete(); // } // // // compiler.getFactory().getEnvironment().setPreserveLineNumbers(true); // compiler.getFactory().getEnvironment().setSourceOutputDirectory(dest); // // compiler.generateProcessedSourceFiles(OutputType.COMPILATION_UNITS); // return this; // } // // public boolean compile() { // File target = compiler.getSourceOutputDirectory(); // final boolean compile = Main.compile(new String[]{"-1.7 " , "-proc:none", target.toString()}, new PrintWriter(System.out), new PrintWriter(System.out),null); // return compile; // } // // public Class getSpoonedClass(String classname) throws ClassNotFoundException { // File target = compiler.getSourceOutputDirectory(); // // ClassLoader classLoader = new SpoonClassLoader(getClass().getClassLoader(), target); // return classLoader.loadClass(classname); // } // // } // Path: src/main/java/fr/inria/gforge/spoon/transformation/retry/RetryTest.java import fr.inria.gforge.spoon.transformation.retry.template.RetryTemplate; import fr.inria.gforge.spoon.utils.TestSpooner; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.File; import java.lang.reflect.Field; import java.util.Collection; package fr.inria.gforge.spoon.transformation.retry; /** * Created by nicolas on 22/01/2015. */ public class RetryTest { TestSpooner spooner; private static final String TEST_CLASS = TestClass.class.getName(); @Before public void setUp() throws Exception { spooner = new TestSpooner() .addSource(new File("src/main/java/" + TEST_CLASS.replaceAll("\\.", "/") + ".java")) .addTemplate(
new File("src/main/java/" + RetryTemplate.class.getName().replaceAll("\\.", "/") + ".java"));
SpoonLabs/spoon-examples
src/test/resources/factory/src/impl2/FactoryImpl2.java
// Path: src/test/resources/factory/src/A.java // public interface A { // void m1(); // } // // Path: src/test/resources/factory/src/B.java // public interface B { // void m2(); // } // // Path: src/test/resources/factory/src/Factory.java // public interface Factory { // // A createA(); // B createB(); // // }
import factory.src.A; import factory.src.B; import factory.src.Factory;
package factory.src.impl2; public class FactoryImpl2 implements Factory { public A createA() { return new AImpl2(); }
// Path: src/test/resources/factory/src/A.java // public interface A { // void m1(); // } // // Path: src/test/resources/factory/src/B.java // public interface B { // void m2(); // } // // Path: src/test/resources/factory/src/Factory.java // public interface Factory { // // A createA(); // B createB(); // // } // Path: src/test/resources/factory/src/impl2/FactoryImpl2.java import factory.src.A; import factory.src.B; import factory.src.Factory; package factory.src.impl2; public class FactoryImpl2 implements Factory { public A createA() { return new AImpl2(); }
public B createB() {
SpoonLabs/spoon-examples
src/main/java/fr/inria/gforge/spoon/transformation/retry/RetryProcessor.java
// Path: src/main/java/fr/inria/gforge/spoon/transformation/retry/template/RetryTemplate.java // public class RetryTemplate extends BlockTemplate { // public RetryTemplate(CtBlock _original_, int _attempts_, long _delay_, boolean _verbose_) { // this._original_ = _original_; // this._attempts_ = _attempts_; // this._delay_ = _delay_; // this._verbose_ = _verbose_; // } // // @Parameter // CtBlock _original_; // // @Parameter // int _attempts_; // // @Parameter // long _delay_; // // @Parameter // boolean _verbose_; // // @Override // public void block() { // int attempt = 0; // Throwable lastTh = null; // while (attempt++ < _attempts_) { // try { // _original_.S(); // } catch (Throwable ex) { // lastTh = ex; // if (_verbose_) { // ex.printStackTrace(); // } // try { // Thread.sleep(_delay_); // } catch (InterruptedException ex2) { // } // } // } // if (lastTh != null) { // throw new RuntimeException(lastTh); // } // } // }
import fr.inria.gforge.spoon.transformation.retry.template.RetryTemplate; import spoon.processing.AbstractAnnotationProcessor; import spoon.reflect.code.CtBlock; import spoon.reflect.declaration.CtMethod;
package fr.inria.gforge.spoon.transformation.retry; /** * Created by nicolas on 22/01/2015. */ public class RetryProcessor extends AbstractAnnotationProcessor<RetryOnFailure, CtMethod<?>> { @Override public void process(RetryOnFailure retryOnFailure, CtMethod<?> ctMethod) {
// Path: src/main/java/fr/inria/gforge/spoon/transformation/retry/template/RetryTemplate.java // public class RetryTemplate extends BlockTemplate { // public RetryTemplate(CtBlock _original_, int _attempts_, long _delay_, boolean _verbose_) { // this._original_ = _original_; // this._attempts_ = _attempts_; // this._delay_ = _delay_; // this._verbose_ = _verbose_; // } // // @Parameter // CtBlock _original_; // // @Parameter // int _attempts_; // // @Parameter // long _delay_; // // @Parameter // boolean _verbose_; // // @Override // public void block() { // int attempt = 0; // Throwable lastTh = null; // while (attempt++ < _attempts_) { // try { // _original_.S(); // } catch (Throwable ex) { // lastTh = ex; // if (_verbose_) { // ex.printStackTrace(); // } // try { // Thread.sleep(_delay_); // } catch (InterruptedException ex2) { // } // } // } // if (lastTh != null) { // throw new RuntimeException(lastTh); // } // } // } // Path: src/main/java/fr/inria/gforge/spoon/transformation/retry/RetryProcessor.java import fr.inria.gforge.spoon.transformation.retry.template.RetryTemplate; import spoon.processing.AbstractAnnotationProcessor; import spoon.reflect.code.CtBlock; import spoon.reflect.declaration.CtMethod; package fr.inria.gforge.spoon.transformation.retry; /** * Created by nicolas on 22/01/2015. */ public class RetryProcessor extends AbstractAnnotationProcessor<RetryOnFailure, CtMethod<?>> { @Override public void process(RetryOnFailure retryOnFailure, CtMethod<?> ctMethod) {
RetryTemplate template = new RetryTemplate(
SpoonLabs/spoon-examples
src/test/resources/project/src/main/java/ow2con/publicapi/MyPublicType.java
// Path: src/test/resources/project/src/main/java/ow2con/privateapi/PrivateType.java // public class PrivateType { // int i = 0; // // public int getANumber() { // return i+1; // } // } // // Path: src/test/resources/project/src/main/java/ow2con/publicapi/subpack/TypePublic.java // public class TypePublic { // // private PrivateType getPrivateType() { // return new PrivateType(); // } // // public AnotherType getAnotherType() { // return new AnotherType(); // } // }
import ow2con.privateapi.PrivateType; import ow2con.publicapi.subpack.TypePublic;
package ow2con.publicapi; public class MyPublicType { private PrivateType privateType; public MyPublicType() { this.privateType = new PrivateType(); } public int getANumber() { return privateType.getANumber(); } public PrivateType getPrivateType() { return privateType; }
// Path: src/test/resources/project/src/main/java/ow2con/privateapi/PrivateType.java // public class PrivateType { // int i = 0; // // public int getANumber() { // return i+1; // } // } // // Path: src/test/resources/project/src/main/java/ow2con/publicapi/subpack/TypePublic.java // public class TypePublic { // // private PrivateType getPrivateType() { // return new PrivateType(); // } // // public AnotherType getAnotherType() { // return new AnotherType(); // } // } // Path: src/test/resources/project/src/main/java/ow2con/publicapi/MyPublicType.java import ow2con.privateapi.PrivateType; import ow2con.publicapi.subpack.TypePublic; package ow2con.publicapi; public class MyPublicType { private PrivateType privateType; public MyPublicType() { this.privateType = new PrivateType(); } public int getANumber() { return privateType.getANumber(); } public PrivateType getPrivateType() { return privateType; }
public TypePublic getTypePublic() {
SpoonLabs/spoon-examples
src/main/java/fr/inria/gforge/spoon/assertgenerator/workflow/Collector.java
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Logger.java // public class Logger { // // public static Map<String, Object> observations = new HashMap<>(); // // public static void observe(String name, Object object) { // observations.put(name, object); // } // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/test/TestRunner.java // public class TestRunner { // // private static Function<String[], URL[]> arrayStringToArrayUrl = (arrayStr) -> // Arrays.stream(arrayStr) // .map(File::new) // .map(File::toURI) // .map(uri -> { // try { // return uri.toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // }) // .toArray(URL[]::new); // // //TODO should maybe run the Listener // // public static List<Failure> runTest(String fullQualifiedName, String testCaseName, String[] classpath) throws MalformedURLException, ClassNotFoundException { // ClassLoader classLoader = new URLClassLoader( // arrayStringToArrayUrl.apply(classpath), // ClassLoader.getSystemClassLoader() // ); // Request request = Request.method(classLoader.loadClass(fullQualifiedName), testCaseName); // Runner runner = request.getRunner(); // RunNotifier fNotifier = new RunNotifier(); // final TestListener listener = new TestListener(); // fNotifier.addFirstListener(listener); // fNotifier.fireTestRunStarted(runner.getDescription()); // runner.run(fNotifier); // return listener.getTestFails(); // } // // public static List<Failure> runTest(String fullQualifiedName, String[] classpath) throws MalformedURLException, ClassNotFoundException { // ClassLoader classLoader = new URLClassLoader( // arrayStringToArrayUrl.apply(classpath), // ClassLoader.getSystemClassLoader() // ); // Request request = Request.classes(classLoader.loadClass(fullQualifiedName)); // Runner runner = request.getRunner(); // RunNotifier fNotifier = new RunNotifier(); // final TestListener listener = new TestListener(); // fNotifier.addFirstListener(listener); // fNotifier.fireTestRunStarted(runner.getDescription()); // runner.run(fNotifier); // return listener.getTestFails(); // } // // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static List<CtMethod> getGetters(CtLocalVariable localVariable) { // return ((Set<CtMethod<?>>) localVariable.getType().getDeclaration().getMethods()).stream() // .filter(method -> method.getParameters().isEmpty() && // method.getType() != localVariable.getFactory().Type().VOID_PRIMITIVE && // (method.getSimpleName().startsWith("get") || // method.getSimpleName().startsWith("is")) // ).collect(Collectors.toList()); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static String getKey(CtMethod method) { // return method.getParent(CtClass.class).getSimpleName() + "#" + method.getSimpleName(); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static CtInvocation invok(CtMethod method, CtLocalVariable localVariable) { // final CtExecutableReference reference = method.getReference(); // final CtVariableAccess variableRead = method.getFactory().createVariableRead(localVariable.getReference(), false); // return method.getFactory().createInvocation(variableRead, reference); // }
import fr.inria.gforge.spoon.assertgenerator.Logger; import fr.inria.gforge.spoon.assertgenerator.test.TestRunner; import spoon.Launcher; import spoon.SpoonModelBuilder; import spoon.reflect.code.CtInvocation; import spoon.reflect.code.CtLocalVariable; import spoon.reflect.code.CtTypeAccess; import spoon.reflect.declaration.CtClass; import spoon.reflect.declaration.CtMethod; import spoon.reflect.factory.Factory; import spoon.reflect.reference.CtExecutableReference; import java.util.List; import static fr.inria.gforge.spoon.assertgenerator.Util.getGetters; import static fr.inria.gforge.spoon.assertgenerator.Util.getKey; import static fr.inria.gforge.spoon.assertgenerator.Util.invok; import java.net.MalformedURLException;
package fr.inria.gforge.spoon.assertgenerator.workflow; /** * Created by Benjamin DANGLOT * [email protected] * on 22/06/17 */ public class Collector { private Factory factory; public Collector(Factory factory) { this.factory = factory; } public void collect(Launcher launcher, CtMethod<?> testMethod, List<CtLocalVariable> localVariables) { CtClass testClass = testMethod.getParent(CtClass.class); testClass.removeMethod(testMethod); CtMethod<?> clone = testMethod.clone(); instrument(clone, localVariables); testClass.addMethod(clone); System.out.println(clone); run(launcher, testClass, clone); testClass.removeMethod(clone); testClass.addMethod(testMethod); } public void run(Launcher launcher, CtClass testClass, CtMethod<?> clone) { String fullQualifiedName = testClass.getQualifiedName(); String testMethodName = clone.getSimpleName(); try { final SpoonModelBuilder compiler = launcher.createCompiler(); compiler.compile(SpoonModelBuilder.InputType.CTTYPES);
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Logger.java // public class Logger { // // public static Map<String, Object> observations = new HashMap<>(); // // public static void observe(String name, Object object) { // observations.put(name, object); // } // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/test/TestRunner.java // public class TestRunner { // // private static Function<String[], URL[]> arrayStringToArrayUrl = (arrayStr) -> // Arrays.stream(arrayStr) // .map(File::new) // .map(File::toURI) // .map(uri -> { // try { // return uri.toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // }) // .toArray(URL[]::new); // // //TODO should maybe run the Listener // // public static List<Failure> runTest(String fullQualifiedName, String testCaseName, String[] classpath) throws MalformedURLException, ClassNotFoundException { // ClassLoader classLoader = new URLClassLoader( // arrayStringToArrayUrl.apply(classpath), // ClassLoader.getSystemClassLoader() // ); // Request request = Request.method(classLoader.loadClass(fullQualifiedName), testCaseName); // Runner runner = request.getRunner(); // RunNotifier fNotifier = new RunNotifier(); // final TestListener listener = new TestListener(); // fNotifier.addFirstListener(listener); // fNotifier.fireTestRunStarted(runner.getDescription()); // runner.run(fNotifier); // return listener.getTestFails(); // } // // public static List<Failure> runTest(String fullQualifiedName, String[] classpath) throws MalformedURLException, ClassNotFoundException { // ClassLoader classLoader = new URLClassLoader( // arrayStringToArrayUrl.apply(classpath), // ClassLoader.getSystemClassLoader() // ); // Request request = Request.classes(classLoader.loadClass(fullQualifiedName)); // Runner runner = request.getRunner(); // RunNotifier fNotifier = new RunNotifier(); // final TestListener listener = new TestListener(); // fNotifier.addFirstListener(listener); // fNotifier.fireTestRunStarted(runner.getDescription()); // runner.run(fNotifier); // return listener.getTestFails(); // } // // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static List<CtMethod> getGetters(CtLocalVariable localVariable) { // return ((Set<CtMethod<?>>) localVariable.getType().getDeclaration().getMethods()).stream() // .filter(method -> method.getParameters().isEmpty() && // method.getType() != localVariable.getFactory().Type().VOID_PRIMITIVE && // (method.getSimpleName().startsWith("get") || // method.getSimpleName().startsWith("is")) // ).collect(Collectors.toList()); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static String getKey(CtMethod method) { // return method.getParent(CtClass.class).getSimpleName() + "#" + method.getSimpleName(); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static CtInvocation invok(CtMethod method, CtLocalVariable localVariable) { // final CtExecutableReference reference = method.getReference(); // final CtVariableAccess variableRead = method.getFactory().createVariableRead(localVariable.getReference(), false); // return method.getFactory().createInvocation(variableRead, reference); // } // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/workflow/Collector.java import fr.inria.gforge.spoon.assertgenerator.Logger; import fr.inria.gforge.spoon.assertgenerator.test.TestRunner; import spoon.Launcher; import spoon.SpoonModelBuilder; import spoon.reflect.code.CtInvocation; import spoon.reflect.code.CtLocalVariable; import spoon.reflect.code.CtTypeAccess; import spoon.reflect.declaration.CtClass; import spoon.reflect.declaration.CtMethod; import spoon.reflect.factory.Factory; import spoon.reflect.reference.CtExecutableReference; import java.util.List; import static fr.inria.gforge.spoon.assertgenerator.Util.getGetters; import static fr.inria.gforge.spoon.assertgenerator.Util.getKey; import static fr.inria.gforge.spoon.assertgenerator.Util.invok; import java.net.MalformedURLException; package fr.inria.gforge.spoon.assertgenerator.workflow; /** * Created by Benjamin DANGLOT * [email protected] * on 22/06/17 */ public class Collector { private Factory factory; public Collector(Factory factory) { this.factory = factory; } public void collect(Launcher launcher, CtMethod<?> testMethod, List<CtLocalVariable> localVariables) { CtClass testClass = testMethod.getParent(CtClass.class); testClass.removeMethod(testMethod); CtMethod<?> clone = testMethod.clone(); instrument(clone, localVariables); testClass.addMethod(clone); System.out.println(clone); run(launcher, testClass, clone); testClass.removeMethod(clone); testClass.addMethod(testMethod); } public void run(Launcher launcher, CtClass testClass, CtMethod<?> clone) { String fullQualifiedName = testClass.getQualifiedName(); String testMethodName = clone.getSimpleName(); try { final SpoonModelBuilder compiler = launcher.createCompiler(); compiler.compile(SpoonModelBuilder.InputType.CTTYPES);
TestRunner.runTest(fullQualifiedName, testMethodName, new String[]{"spooned-classes"});
SpoonLabs/spoon-examples
src/main/java/fr/inria/gforge/spoon/assertgenerator/workflow/Collector.java
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Logger.java // public class Logger { // // public static Map<String, Object> observations = new HashMap<>(); // // public static void observe(String name, Object object) { // observations.put(name, object); // } // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/test/TestRunner.java // public class TestRunner { // // private static Function<String[], URL[]> arrayStringToArrayUrl = (arrayStr) -> // Arrays.stream(arrayStr) // .map(File::new) // .map(File::toURI) // .map(uri -> { // try { // return uri.toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // }) // .toArray(URL[]::new); // // //TODO should maybe run the Listener // // public static List<Failure> runTest(String fullQualifiedName, String testCaseName, String[] classpath) throws MalformedURLException, ClassNotFoundException { // ClassLoader classLoader = new URLClassLoader( // arrayStringToArrayUrl.apply(classpath), // ClassLoader.getSystemClassLoader() // ); // Request request = Request.method(classLoader.loadClass(fullQualifiedName), testCaseName); // Runner runner = request.getRunner(); // RunNotifier fNotifier = new RunNotifier(); // final TestListener listener = new TestListener(); // fNotifier.addFirstListener(listener); // fNotifier.fireTestRunStarted(runner.getDescription()); // runner.run(fNotifier); // return listener.getTestFails(); // } // // public static List<Failure> runTest(String fullQualifiedName, String[] classpath) throws MalformedURLException, ClassNotFoundException { // ClassLoader classLoader = new URLClassLoader( // arrayStringToArrayUrl.apply(classpath), // ClassLoader.getSystemClassLoader() // ); // Request request = Request.classes(classLoader.loadClass(fullQualifiedName)); // Runner runner = request.getRunner(); // RunNotifier fNotifier = new RunNotifier(); // final TestListener listener = new TestListener(); // fNotifier.addFirstListener(listener); // fNotifier.fireTestRunStarted(runner.getDescription()); // runner.run(fNotifier); // return listener.getTestFails(); // } // // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static List<CtMethod> getGetters(CtLocalVariable localVariable) { // return ((Set<CtMethod<?>>) localVariable.getType().getDeclaration().getMethods()).stream() // .filter(method -> method.getParameters().isEmpty() && // method.getType() != localVariable.getFactory().Type().VOID_PRIMITIVE && // (method.getSimpleName().startsWith("get") || // method.getSimpleName().startsWith("is")) // ).collect(Collectors.toList()); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static String getKey(CtMethod method) { // return method.getParent(CtClass.class).getSimpleName() + "#" + method.getSimpleName(); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static CtInvocation invok(CtMethod method, CtLocalVariable localVariable) { // final CtExecutableReference reference = method.getReference(); // final CtVariableAccess variableRead = method.getFactory().createVariableRead(localVariable.getReference(), false); // return method.getFactory().createInvocation(variableRead, reference); // }
import fr.inria.gforge.spoon.assertgenerator.Logger; import fr.inria.gforge.spoon.assertgenerator.test.TestRunner; import spoon.Launcher; import spoon.SpoonModelBuilder; import spoon.reflect.code.CtInvocation; import spoon.reflect.code.CtLocalVariable; import spoon.reflect.code.CtTypeAccess; import spoon.reflect.declaration.CtClass; import spoon.reflect.declaration.CtMethod; import spoon.reflect.factory.Factory; import spoon.reflect.reference.CtExecutableReference; import java.util.List; import static fr.inria.gforge.spoon.assertgenerator.Util.getGetters; import static fr.inria.gforge.spoon.assertgenerator.Util.getKey; import static fr.inria.gforge.spoon.assertgenerator.Util.invok; import java.net.MalformedURLException;
public void collect(Launcher launcher, CtMethod<?> testMethod, List<CtLocalVariable> localVariables) { CtClass testClass = testMethod.getParent(CtClass.class); testClass.removeMethod(testMethod); CtMethod<?> clone = testMethod.clone(); instrument(clone, localVariables); testClass.addMethod(clone); System.out.println(clone); run(launcher, testClass, clone); testClass.removeMethod(clone); testClass.addMethod(testMethod); } public void run(Launcher launcher, CtClass testClass, CtMethod<?> clone) { String fullQualifiedName = testClass.getQualifiedName(); String testMethodName = clone.getSimpleName(); try { final SpoonModelBuilder compiler = launcher.createCompiler(); compiler.compile(SpoonModelBuilder.InputType.CTTYPES); TestRunner.runTest(fullQualifiedName, testMethodName, new String[]{"spooned-classes"}); } catch (ClassNotFoundException | MalformedURLException e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") public void instrument(CtMethod<?> testMethod, List<CtLocalVariable> ctLocalVariables) { ctLocalVariables.forEach(ctLocalVariable -> this.instrument(testMethod, ctLocalVariable)); } void instrument(CtMethod testMethod, CtLocalVariable localVariable) {
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Logger.java // public class Logger { // // public static Map<String, Object> observations = new HashMap<>(); // // public static void observe(String name, Object object) { // observations.put(name, object); // } // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/test/TestRunner.java // public class TestRunner { // // private static Function<String[], URL[]> arrayStringToArrayUrl = (arrayStr) -> // Arrays.stream(arrayStr) // .map(File::new) // .map(File::toURI) // .map(uri -> { // try { // return uri.toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // }) // .toArray(URL[]::new); // // //TODO should maybe run the Listener // // public static List<Failure> runTest(String fullQualifiedName, String testCaseName, String[] classpath) throws MalformedURLException, ClassNotFoundException { // ClassLoader classLoader = new URLClassLoader( // arrayStringToArrayUrl.apply(classpath), // ClassLoader.getSystemClassLoader() // ); // Request request = Request.method(classLoader.loadClass(fullQualifiedName), testCaseName); // Runner runner = request.getRunner(); // RunNotifier fNotifier = new RunNotifier(); // final TestListener listener = new TestListener(); // fNotifier.addFirstListener(listener); // fNotifier.fireTestRunStarted(runner.getDescription()); // runner.run(fNotifier); // return listener.getTestFails(); // } // // public static List<Failure> runTest(String fullQualifiedName, String[] classpath) throws MalformedURLException, ClassNotFoundException { // ClassLoader classLoader = new URLClassLoader( // arrayStringToArrayUrl.apply(classpath), // ClassLoader.getSystemClassLoader() // ); // Request request = Request.classes(classLoader.loadClass(fullQualifiedName)); // Runner runner = request.getRunner(); // RunNotifier fNotifier = new RunNotifier(); // final TestListener listener = new TestListener(); // fNotifier.addFirstListener(listener); // fNotifier.fireTestRunStarted(runner.getDescription()); // runner.run(fNotifier); // return listener.getTestFails(); // } // // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static List<CtMethod> getGetters(CtLocalVariable localVariable) { // return ((Set<CtMethod<?>>) localVariable.getType().getDeclaration().getMethods()).stream() // .filter(method -> method.getParameters().isEmpty() && // method.getType() != localVariable.getFactory().Type().VOID_PRIMITIVE && // (method.getSimpleName().startsWith("get") || // method.getSimpleName().startsWith("is")) // ).collect(Collectors.toList()); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static String getKey(CtMethod method) { // return method.getParent(CtClass.class).getSimpleName() + "#" + method.getSimpleName(); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static CtInvocation invok(CtMethod method, CtLocalVariable localVariable) { // final CtExecutableReference reference = method.getReference(); // final CtVariableAccess variableRead = method.getFactory().createVariableRead(localVariable.getReference(), false); // return method.getFactory().createInvocation(variableRead, reference); // } // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/workflow/Collector.java import fr.inria.gforge.spoon.assertgenerator.Logger; import fr.inria.gforge.spoon.assertgenerator.test.TestRunner; import spoon.Launcher; import spoon.SpoonModelBuilder; import spoon.reflect.code.CtInvocation; import spoon.reflect.code.CtLocalVariable; import spoon.reflect.code.CtTypeAccess; import spoon.reflect.declaration.CtClass; import spoon.reflect.declaration.CtMethod; import spoon.reflect.factory.Factory; import spoon.reflect.reference.CtExecutableReference; import java.util.List; import static fr.inria.gforge.spoon.assertgenerator.Util.getGetters; import static fr.inria.gforge.spoon.assertgenerator.Util.getKey; import static fr.inria.gforge.spoon.assertgenerator.Util.invok; import java.net.MalformedURLException; public void collect(Launcher launcher, CtMethod<?> testMethod, List<CtLocalVariable> localVariables) { CtClass testClass = testMethod.getParent(CtClass.class); testClass.removeMethod(testMethod); CtMethod<?> clone = testMethod.clone(); instrument(clone, localVariables); testClass.addMethod(clone); System.out.println(clone); run(launcher, testClass, clone); testClass.removeMethod(clone); testClass.addMethod(testMethod); } public void run(Launcher launcher, CtClass testClass, CtMethod<?> clone) { String fullQualifiedName = testClass.getQualifiedName(); String testMethodName = clone.getSimpleName(); try { final SpoonModelBuilder compiler = launcher.createCompiler(); compiler.compile(SpoonModelBuilder.InputType.CTTYPES); TestRunner.runTest(fullQualifiedName, testMethodName, new String[]{"spooned-classes"}); } catch (ClassNotFoundException | MalformedURLException e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") public void instrument(CtMethod<?> testMethod, List<CtLocalVariable> ctLocalVariables) { ctLocalVariables.forEach(ctLocalVariable -> this.instrument(testMethod, ctLocalVariable)); } void instrument(CtMethod testMethod, CtLocalVariable localVariable) {
List<CtMethod> getters = getGetters(localVariable);
SpoonLabs/spoon-examples
src/main/java/fr/inria/gforge/spoon/assertgenerator/workflow/Collector.java
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Logger.java // public class Logger { // // public static Map<String, Object> observations = new HashMap<>(); // // public static void observe(String name, Object object) { // observations.put(name, object); // } // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/test/TestRunner.java // public class TestRunner { // // private static Function<String[], URL[]> arrayStringToArrayUrl = (arrayStr) -> // Arrays.stream(arrayStr) // .map(File::new) // .map(File::toURI) // .map(uri -> { // try { // return uri.toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // }) // .toArray(URL[]::new); // // //TODO should maybe run the Listener // // public static List<Failure> runTest(String fullQualifiedName, String testCaseName, String[] classpath) throws MalformedURLException, ClassNotFoundException { // ClassLoader classLoader = new URLClassLoader( // arrayStringToArrayUrl.apply(classpath), // ClassLoader.getSystemClassLoader() // ); // Request request = Request.method(classLoader.loadClass(fullQualifiedName), testCaseName); // Runner runner = request.getRunner(); // RunNotifier fNotifier = new RunNotifier(); // final TestListener listener = new TestListener(); // fNotifier.addFirstListener(listener); // fNotifier.fireTestRunStarted(runner.getDescription()); // runner.run(fNotifier); // return listener.getTestFails(); // } // // public static List<Failure> runTest(String fullQualifiedName, String[] classpath) throws MalformedURLException, ClassNotFoundException { // ClassLoader classLoader = new URLClassLoader( // arrayStringToArrayUrl.apply(classpath), // ClassLoader.getSystemClassLoader() // ); // Request request = Request.classes(classLoader.loadClass(fullQualifiedName)); // Runner runner = request.getRunner(); // RunNotifier fNotifier = new RunNotifier(); // final TestListener listener = new TestListener(); // fNotifier.addFirstListener(listener); // fNotifier.fireTestRunStarted(runner.getDescription()); // runner.run(fNotifier); // return listener.getTestFails(); // } // // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static List<CtMethod> getGetters(CtLocalVariable localVariable) { // return ((Set<CtMethod<?>>) localVariable.getType().getDeclaration().getMethods()).stream() // .filter(method -> method.getParameters().isEmpty() && // method.getType() != localVariable.getFactory().Type().VOID_PRIMITIVE && // (method.getSimpleName().startsWith("get") || // method.getSimpleName().startsWith("is")) // ).collect(Collectors.toList()); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static String getKey(CtMethod method) { // return method.getParent(CtClass.class).getSimpleName() + "#" + method.getSimpleName(); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static CtInvocation invok(CtMethod method, CtLocalVariable localVariable) { // final CtExecutableReference reference = method.getReference(); // final CtVariableAccess variableRead = method.getFactory().createVariableRead(localVariable.getReference(), false); // return method.getFactory().createInvocation(variableRead, reference); // }
import fr.inria.gforge.spoon.assertgenerator.Logger; import fr.inria.gforge.spoon.assertgenerator.test.TestRunner; import spoon.Launcher; import spoon.SpoonModelBuilder; import spoon.reflect.code.CtInvocation; import spoon.reflect.code.CtLocalVariable; import spoon.reflect.code.CtTypeAccess; import spoon.reflect.declaration.CtClass; import spoon.reflect.declaration.CtMethod; import spoon.reflect.factory.Factory; import spoon.reflect.reference.CtExecutableReference; import java.util.List; import static fr.inria.gforge.spoon.assertgenerator.Util.getGetters; import static fr.inria.gforge.spoon.assertgenerator.Util.getKey; import static fr.inria.gforge.spoon.assertgenerator.Util.invok; import java.net.MalformedURLException;
CtMethod<?> clone = testMethod.clone(); instrument(clone, localVariables); testClass.addMethod(clone); System.out.println(clone); run(launcher, testClass, clone); testClass.removeMethod(clone); testClass.addMethod(testMethod); } public void run(Launcher launcher, CtClass testClass, CtMethod<?> clone) { String fullQualifiedName = testClass.getQualifiedName(); String testMethodName = clone.getSimpleName(); try { final SpoonModelBuilder compiler = launcher.createCompiler(); compiler.compile(SpoonModelBuilder.InputType.CTTYPES); TestRunner.runTest(fullQualifiedName, testMethodName, new String[]{"spooned-classes"}); } catch (ClassNotFoundException | MalformedURLException e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") public void instrument(CtMethod<?> testMethod, List<CtLocalVariable> ctLocalVariables) { ctLocalVariables.forEach(ctLocalVariable -> this.instrument(testMethod, ctLocalVariable)); } void instrument(CtMethod testMethod, CtLocalVariable localVariable) { List<CtMethod> getters = getGetters(localVariable); getters.forEach(getter -> { CtInvocation invocationToGetter =
// Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Logger.java // public class Logger { // // public static Map<String, Object> observations = new HashMap<>(); // // public static void observe(String name, Object object) { // observations.put(name, object); // } // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/test/TestRunner.java // public class TestRunner { // // private static Function<String[], URL[]> arrayStringToArrayUrl = (arrayStr) -> // Arrays.stream(arrayStr) // .map(File::new) // .map(File::toURI) // .map(uri -> { // try { // return uri.toURL(); // } catch (MalformedURLException e) { // throw new RuntimeException(e); // } // }) // .toArray(URL[]::new); // // //TODO should maybe run the Listener // // public static List<Failure> runTest(String fullQualifiedName, String testCaseName, String[] classpath) throws MalformedURLException, ClassNotFoundException { // ClassLoader classLoader = new URLClassLoader( // arrayStringToArrayUrl.apply(classpath), // ClassLoader.getSystemClassLoader() // ); // Request request = Request.method(classLoader.loadClass(fullQualifiedName), testCaseName); // Runner runner = request.getRunner(); // RunNotifier fNotifier = new RunNotifier(); // final TestListener listener = new TestListener(); // fNotifier.addFirstListener(listener); // fNotifier.fireTestRunStarted(runner.getDescription()); // runner.run(fNotifier); // return listener.getTestFails(); // } // // public static List<Failure> runTest(String fullQualifiedName, String[] classpath) throws MalformedURLException, ClassNotFoundException { // ClassLoader classLoader = new URLClassLoader( // arrayStringToArrayUrl.apply(classpath), // ClassLoader.getSystemClassLoader() // ); // Request request = Request.classes(classLoader.loadClass(fullQualifiedName)); // Runner runner = request.getRunner(); // RunNotifier fNotifier = new RunNotifier(); // final TestListener listener = new TestListener(); // fNotifier.addFirstListener(listener); // fNotifier.fireTestRunStarted(runner.getDescription()); // runner.run(fNotifier); // return listener.getTestFails(); // } // // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static List<CtMethod> getGetters(CtLocalVariable localVariable) { // return ((Set<CtMethod<?>>) localVariable.getType().getDeclaration().getMethods()).stream() // .filter(method -> method.getParameters().isEmpty() && // method.getType() != localVariable.getFactory().Type().VOID_PRIMITIVE && // (method.getSimpleName().startsWith("get") || // method.getSimpleName().startsWith("is")) // ).collect(Collectors.toList()); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static String getKey(CtMethod method) { // return method.getParent(CtClass.class).getSimpleName() + "#" + method.getSimpleName(); // } // // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/Util.java // public static CtInvocation invok(CtMethod method, CtLocalVariable localVariable) { // final CtExecutableReference reference = method.getReference(); // final CtVariableAccess variableRead = method.getFactory().createVariableRead(localVariable.getReference(), false); // return method.getFactory().createInvocation(variableRead, reference); // } // Path: src/main/java/fr/inria/gforge/spoon/assertgenerator/workflow/Collector.java import fr.inria.gforge.spoon.assertgenerator.Logger; import fr.inria.gforge.spoon.assertgenerator.test.TestRunner; import spoon.Launcher; import spoon.SpoonModelBuilder; import spoon.reflect.code.CtInvocation; import spoon.reflect.code.CtLocalVariable; import spoon.reflect.code.CtTypeAccess; import spoon.reflect.declaration.CtClass; import spoon.reflect.declaration.CtMethod; import spoon.reflect.factory.Factory; import spoon.reflect.reference.CtExecutableReference; import java.util.List; import static fr.inria.gforge.spoon.assertgenerator.Util.getGetters; import static fr.inria.gforge.spoon.assertgenerator.Util.getKey; import static fr.inria.gforge.spoon.assertgenerator.Util.invok; import java.net.MalformedURLException; CtMethod<?> clone = testMethod.clone(); instrument(clone, localVariables); testClass.addMethod(clone); System.out.println(clone); run(launcher, testClass, clone); testClass.removeMethod(clone); testClass.addMethod(testMethod); } public void run(Launcher launcher, CtClass testClass, CtMethod<?> clone) { String fullQualifiedName = testClass.getQualifiedName(); String testMethodName = clone.getSimpleName(); try { final SpoonModelBuilder compiler = launcher.createCompiler(); compiler.compile(SpoonModelBuilder.InputType.CTTYPES); TestRunner.runTest(fullQualifiedName, testMethodName, new String[]{"spooned-classes"}); } catch (ClassNotFoundException | MalformedURLException e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") public void instrument(CtMethod<?> testMethod, List<CtLocalVariable> ctLocalVariables) { ctLocalVariables.forEach(ctLocalVariable -> this.instrument(testMethod, ctLocalVariable)); } void instrument(CtMethod testMethod, CtLocalVariable localVariable) { List<CtMethod> getters = getGetters(localVariable); getters.forEach(getter -> { CtInvocation invocationToGetter =
invok(getter, localVariable);