Where can I find the source code for ActivityTestRule? - android-testing

Where can I find the source code for ActivityTestRule?

You can find it at
https://android.googlesource.com/platform/frameworks/testing/+/android-support-test/rules/src/main/java/android/support/test/rule/ActivityTestRule.java
You have to use branch android-support-test instead of master on platform/frameworks/testing project in AOSP.

You can add ActivityTestRule in code, import library and CTRL+Left Click to decompile.
If you can't import this class, you need to add it to dependencies in your build.gradle
androidTestCompile 'com.android.support.test:rules:0.3'
EDIT:
My result of decompiling:
package android.support.test.rule;
import android.app.Activity;
import android.app.Instrumentation;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.test.InstrumentationRegistry;
import android.support.test.annotation.Beta;
import android.support.test.internal.util.Checks;
import android.support.test.rule.UiThreadTestRule;
import android.util.Log;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
#Beta
public class ActivityTestRule<T extends Activity> extends UiThreadTestRule {
private static final String TAG = "ActivityInstrumentationRule";
private final Class<T> mActivityClass;
private Instrumentation mInstrumentation;
private boolean mInitialTouchMode;
private boolean mLaunchActivity;
private T mActivity;
public ActivityTestRule(Class<T> activityClass) {
this(activityClass, false);
}
public ActivityTestRule(Class<T> activityClass, boolean initialTouchMode) {
this(activityClass, initialTouchMode, true);
}
public ActivityTestRule(Class<T> activityClass, boolean initialTouchMode, boolean launchActivity) {
this.mInitialTouchMode = false;
this.mLaunchActivity = false;
this.mActivityClass = activityClass;
this.mInitialTouchMode = initialTouchMode;
this.mLaunchActivity = launchActivity;
this.mInstrumentation = InstrumentationRegistry.getInstrumentation();
}
protected Intent getActivityIntent() {
return new Intent("android.intent.action.MAIN");
}
protected void beforeActivityLaunched() {
}
protected void afterActivityLaunched() {
}
protected void afterActivityFinished() {
}
public T getActivity() {
if(this.mActivity == null) {
Log.w("ActivityInstrumentationRule", "Activity wasn\'t created yet");
}
return this.mActivity;
}
public Statement apply(Statement base, Description description) {
return new ActivityTestRule.ActivityStatement(super.apply(base, description));
}
public T launchActivity(#Nullable Intent startIntent) {
this.mInstrumentation.setInTouchMode(this.mInitialTouchMode);
String targetPackage = this.mInstrumentation.getTargetContext().getPackageName();
if(null == startIntent) {
startIntent = this.getActivityIntent();
if(null == startIntent) {
Log.w("ActivityInstrumentationRule", "getActivityIntent() returned null using default: Intent(Intent.ACTION_MAIN)");
startIntent = new Intent("android.intent.action.MAIN");
}
}
startIntent.setClassName(targetPackage, this.mActivityClass.getName());
startIntent.addFlags(268435456);
Log.d("ActivityInstrumentationRule", String.format("Launching activity %s", new Object[]{this.mActivityClass.getName()}));
this.beforeActivityLaunched();
this.mActivity = (Activity)this.mActivityClass.cast(this.mInstrumentation.startActivitySync(startIntent));
this.mInstrumentation.waitForIdleSync();
this.afterActivityLaunched();
return this.mActivity;
}
void setInstrumentation(Instrumentation instrumentation) {
this.mInstrumentation = (Instrumentation)Checks.checkNotNull(instrumentation, "instrumentation cannot be null!");
}
void finishActivity() {
if(this.mActivity != null) {
this.mActivity.finish();
this.mActivity = null;
}
}
private class ActivityStatement extends Statement {
private final Statement mBase;
public ActivityStatement(Statement base) {
this.mBase = base;
}
public void evaluate() throws Throwable {
try {
if(ActivityTestRule.this.mLaunchActivity) {
ActivityTestRule.this.mActivity = ActivityTestRule.this.launchActivity(ActivityTestRule.this.getActivityIntent());
}
this.mBase.evaluate();
} finally {
ActivityTestRule.this.finishActivity();
ActivityTestRule.this.afterActivityFinished();
}
}
}
}

Related

Grails 2.5.4: Get all logged in users with HttpSessionListener

I'm trying to get all the current user sessions using the app-info plugin but it doesn't compile in Grails 2.5.4. Is there another way to get this information? I'm new to Grails.
This link has some information including a reference to the app-info plugin but it's old and I wasn't able to get anything to compile.
UPDATE
I've added this custom class in src\groovy\UserSessions:
package usersessions
import javax.servlet.http.HttpSessionEvent
import javax.servlet.http.HttpSessionListener
//import org.apache.shiro.subject.PrincipalCollection
//import org.apache.shiro.subject.SimplePrincipalCollection;
//import org.apache.shiro.subject.support.DefaultSubjectContext
class MyHttpSessionListener implements HttpSessionListener {
private static List activeUsers = Collections.synchronizedList(new ArrayList());
#Override
public void sessionCreated(HttpSessionEvent event) { }
#Override
public void sessionDestroyed(HttpSessionEvent event) {
String userName = getCurrentUserName(event)
if (userName == null) {
return
}
MyHttpSessionListener.userLoggedOut(userName)
}
public static void userLoggedIn(String userName) {
if (!activeUsers.contains(userName)) {
activeUsers.add(userName)
}
}
public static void userLoggedOut(String userName) {
activeUsers.remove(userName)
}
public static List getCurrentUserNames() {
return Collections.unmodifiableList(activeUsers);
}
/*
private String getCurrentUserName(HttpSessionEvent event) {
PrincipalCollection currentUser = (PrincipalCollection) event.getSession().getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
if (currentUser == null) {
return null
}
return (String) currentUser.getPrimaryPrincipal();
}
*/
}
Added this to /scripts/_Events.groovy
import groovy.xml.StreamingMarkupBuilder
eventWebXmlEnd = {String tmpfile ->
def root = new XmlSlurper().parse(webXmlFile)
root.appendNode {
'listener' {
'listener-class' (
'usersessions.MyHttpSessionListener'
)
}
}
webXmlFile.text = new StreamingMarkupBuilder().bind {
mkp.declareNamespace(
"": "http://java.sun.com/xml/ns/javaee")
mkp.yield(root)
}
}
Added this to resources.groovy
myHttpSessionListener(usersessions.MyHttpSessionListener)
/* shiroAuthenticator(ModularRealmAuthenticator) {
authenticationStrategy = ref("shiroAuthenticationStrategy")
authenticationListeners = [ ref("authListener") ]
}
*/
Added this to my controller:
package usersessions
class NewController extends MyHttpSessionListener {
def index() {
myHttpSessionListener.userLoggedIn("user1")
render "Users "+ getCurrentUserNames()
}
}
It compiles and the app runs but I don't see how to get sessions in the listener? The controller gives an error when I load it:
No such property: myHttpSessionListener for class: usersessions.NewController
UPDATE 2
I changed the controller to use this code to test creating a sessions and it works:
def index() {
String randomString = org.apache.commons.lang.RandomStringUtils.random(3, true, true)
userLoggedIn(randomString)
render "Users "+ getCurrentUserNames()
}

Class not found exception on com.itextpdf.text.pdf.parser.RenderListener

I am trying to parse PDF files in Mapreduce using custom input format class as below:
import java.io.IOException;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
public class PdfFileInputFormat extends FileInputFormat<LongWritable, Text> {
#Override
public RecordReader<LongWritable, Text> createRecordReader(InputSplit split,
TaskAttemptContext context) throws IOException, InterruptedException {
System.out.println("Entered PdfFileInputFormat class");
return new PdfRecordReader();
}
#Override
protected boolean isSplitable(JobContext context, Path file) {
return false;
}
}
and my pdf reader class is:
package com.pdf.prac;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
import com.itextpdf.text.pdf.parser.TextExtractionStrategy;
import com.itextpdf.text.pdf.parser.RenderListener;
public class PdfRecordReader extends RecordReader<LongWritable, Text> {
private int flag = 0;
private LongWritable key = null;
private Text value = null;
private PdfReader reader;
private PdfReaderContentParser parser;
private TextExtractionStrategy strategy;
private FSDataInputStream fileIn;
private List<String> records = new ArrayList<String>();
public void initialize(InputSplit genericSplit, TaskAttemptContext context)
throws IOException {
System.out.println("Executing initialize........");
FileSplit split = (FileSplit) genericSplit;
Configuration conf = context.getConfiguration();
final Path file = split.getPath();
FileSystem fs = file.getFileSystem(conf);
this.fileIn = fs.open(split.getPath());
this.reader = new PdfReader(fileIn);
this.parser = new PdfReaderContentParser(reader);
readRecords();
}
public synchronized boolean nextKeyValue() throws IOException {
System.out.println("Executing nextKey........Total Records : " + records.size() + "; Flag : " + (flag++));
int index = 0;
if (key == null) {
key = new LongWritable(index);
} else {
index = (int) key.get();
key.set(++index);
}
if (value == null) {
value = new Text(records.get(index));
} else {
value.set(records.get(index));
}
if (flag == records.size()) {
return false;
} else {
return true;
}
}
#Override
public LongWritable getCurrentKey() {
return key;
}
#Override
public Text getCurrentValue() {
return value;
}
/**
* Get the progress within the split
*/
public float getProgress() {
return 0;
}
public synchronized void close() throws IOException {
if (fileIn != null) {
fileIn.close();
}
}
private void readRecords() throws IOException {
if (reader != null) {
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
strategy = parser.processContent(i, new SimpleTextExtractionStrategy());
if (strategy != null) {
/* String[] content = (strategy.getResultantText()).split("\n");
for (String str : content) {
records.add(str);
}*/
StringTokenizer tokens = new StringTokenizer(strategy.getResultantText(), "\n");
while (tokens.hasMoreTokens()) {
records.add(tokens.nextToken());
}
}
}
reader.close();
}
return;
}
}
But this is giving a class not found exception on com.itextpdf.text.pdf.parser.RenderListener at the runtime on hadoop environment. Appreciate any help on this. All the jar files are correctly added on build path and there are no multiple jars as well.

JavaFx2.x : extends Path

The code below perform a freehand draw, my problem is that this class compile under Linux but I get error in WindowsXP.
Here is the code
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.input.ContextMenuEvent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Path;
import javafx.scene.shape.PathElement;
public class Freehand {
private Group group ;
private FreeHandDrawPath freehandDraw;
public Freehand(ObservableList<PathElement> _initFreehand) {
this.freehandDraw = new FreeHandDrawPath(_initFreehand);
this.group = new Group();
group.getChildren().add(freehandDraw);
group.addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
#Override
public void handle(final KeyEvent keyEvent) {
if (keyEvent.getCode() == KeyCode.DELETE ) {
group.getChildren().removeAll(freehandDraw);
}
}
});
}
class FreeHandDrawPath extends Path {
double x, y;
final ContextMenu contextMenu = new ContextMenu();
final MenuItem itemDelete = new MenuItem("Delete");
FreeHandDrawPath (ObservableList<PathElement> _initFreehand) {
super(_initFreehand);
setStroke(Color.BLACK);
itemDelete.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
group.getChildren().removeAll(freehandDraw);
//System.out.println("Delete");
}
});
contextMenu.getItems().addAll(itemDelete);
this.addEventHandler(MouseEvent.MOUSE_ENTERED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
// just to show that the line is selected
x = event.getX();
y = event.getY();
setStroke(Color.RED);
setStrokeWidth(getStrokeWidth()+4);
group.requestFocus();
event.consume();
}
});
this.addEventHandler(MouseEvent.MOUSE_EXITED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
setStroke(Color.BLACK);
setStrokeWidth(getStrokeWidth()-4);
event.consume();
}
});
this.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (event.isSecondaryButtonDown()){
setOnContextMenuRequested(
new EventHandler<ContextMenuEvent>() {
#Override
public void handle(ContextMenuEvent event) {
//contextMenu.show(l, Side.RIGHT, 0, 0);
contextMenu.show((Path) event.getSource(), event.getScreenX() + 1, event.getScreenY());
//System.out.println("Hello World!");
}
});
}
event.consume();
}
});
}
}
public Node view() {
return group ;
}
}
Why do I get such error?
Thanks.

How Can i show urls clicked by user in Primefaces+JSF2

I am using JSF2 with Prime faces. I will want to show all the previous links or Urls clicked by user in every page.How can i do this?
Here's a good link for you: How can I get the request URL from a Java Filter?
What I would do is use something like that example and do a set of three URLs.
//Using linked example
public class MyFilter implements Filter {
public void init(FilterConfig config) throws ServletException { }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
chain.doFilter(request, response);
String url = ((HttpServletRequest) request).getPathTranslated();
UrlBean urlBean = (UrlBean) FacesContext.getCurrentInstance()getApplication().getValueBinding("#{urlBean}");
urlBean.storeUrl(url);
}
public void destroy() { }
}
This is totally untested, but the idea should work. You would just need to implement some logic (probably a stack) for your component so it stores what you need. (Obviously you might end up at the same URL multiple times). I should note the UrlBean is just an abstract idea, you would have to implement it
Hi I have created this Singleton class to put the Url Browsed by a User.
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class UrlHistory {
#SuppressWarnings("rawtypes")
private static Map<String, List> store = new HashMap<String, List>();
private static UrlHistoryBean instance = null;
public static UrlHistoryBean getInstance() {
if (instance == null) {
instance = new UrlHistoryBean();
}
return instance;
}
LinkedList<UrlData> urlList = new LinkedList<UrlHistoryBean.UrlData>();
public void addUrl(String sessionId, String urlString, int urlId) {
UrlData data = new UrlData();
data.setUrlName(urlString);
data.setUrlId(companyId);
if (urlList.isEmpty()) {
urlList.add(data);
} else {
boolean isEqual = false;
for (UrlData urlDataObj : urlList) {
if (urlDataObj.equals(data))
isEqual = true;
}
if(!isEqual)
urlList.addFirst(data);
}
store.put(sessionId, urlList);
}
#SuppressWarnings("rawtypes")
public static Map<String, List> getStore() {
return store;
}
#SuppressWarnings("rawtypes")
public static void setStore(Map<String, List> store) {
UrlHistoryBean.store = store;
}
public class UrlData {
String urlName;
int urlId;
public String getUrlName() {
return UrlName;
}
public void setUrlName(String UrlName) {
this.UrlName = UrlName;
}
public int getUrlId() {
return urlId;
}
public void setUrlId(int urlId) {
this.urlId = urlId;
}
public boolean equals(UrlData rData) {
boolean bEqual = false;
if (this.getUrlId() > 0 && rData.getUrlId() > 0 && this.getUrlId() == rData.getUrlId()) {
bEqual = true;
}
return bEqual;
}
}
}

Cannot find database list pressing back button in blackberry

In screen1 i have 2 buttons a and b.i have given field change listener for both such that each pushes corresponding screen .When i press button 'a' it pushes say screen2 where i have used a keywordFilter to search words from sqlite database and is listed.These all are perfect when i run the application ,but when i press the back(or previous key) and then press the button 'a' from screen1 again i dont find any results from database.same thing happens to button b also .What cud b the pblm pls help.
Thank u so much in advance
Below is the class called after button 'a' is clicked
import net.rim.device.api.ui.*;
import net.rim.device.api.io.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.system.*;
import java.util.*;
import net.rim.device.api.database.Database;
import net.rim.device.api.database.DatabaseFactory;
import net.rim.device.api.database.Row;
import net.rim.device.api.database.Statement;
public final class KeywordFilter
{
private KeywordFilterField _keywordFilterField;
private WordList _wordList;
private Vector _words;
public KeywordFilter()
{
_words = getDataFromDatabase();
if(_words != null)
{
_wordList = new WordList(_words);
_keywordFilterField = new KeywordFilterField();
_keywordFilterField.setSourceList(_wordList, _wordList);
CustomKeywordField customSearchField = new CustomKeywordField();
_keywordFilterField.setKeywordField(customSearchField);
KeywordFilterScreen screen = new KeywordFilterScreen(this);
screen.setTitle(_keywordFilterField.getKeywordField());
screen.add(_keywordFilterField);
UiApplication ui = UiApplication.getUiApplication();
ui.pushScreen(screen);
}
else
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert("Error reading data file.");
System.exit(0);
}
});
}
}
KeywordFilterField getKeywordFilterField()
{
return _keywordFilterField;
}
private Vector getDataFromDatabase()
{
Vector words = new Vector();
Database d;
for(;;)
{
try
{
URI myURI=URI.create("file:///SDCard/Databases/MyTestDatabase.db");
d=DatabaseFactory.open(myURI);
Statement st=d.createStatement("SELECT eng,mal FROM Malayalam m,English e where e.Ecode=m.Mcode");
st.prepare();
net.rim.device.api.database.Cursor c=st.getCursor();
Row r;
while(c.next())
{
r=c.getRow();
String w=r.getString(0);
String meaning=r.getString(1);
words.addElement(new Word(w,meaning));
}}
catch ( Exception e )
{
System.out.println( e.getMessage() );
e.printStackTrace();
}
return words;
}
}
void addElementToList(Word w)
{
_wordList.addElement(w);
_keywordFilterField.updateList();
}
final static class CustomKeywordField extends BasicEditField
{
CustomKeywordField()
{
super(USE_ALL_WIDTH|NON_FOCUSABLE|NO_LEARNING|NO_NEWLINE);
setLabel("Search: ");
}
protected boolean keyChar(char ch, int status, int time)
{
switch(ch)
{
case Characters.ESCAPE:
if(super.getTextLength() > 0)
{
setText("");
return true;
}
}
return super.keyChar(ch, status, time);
}
protected void paint(Graphics graphics)
{
super.paint(graphics);
getFocusRect(new XYRect());
drawFocus(graphics, true);
}
}
}
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.system.*;
final class KeywordFilterScreen extends MainScreen
{
private KeywordFilter _app;
private KeywordFilterField _keywordFilterField;
public KeywordFilterScreen(KeywordFilter app)
{
_app = app;
_keywordFilterField = _app.getKeywordFilterField();
}
protected boolean keyChar(char key, int status, int time)
{
if (key == Characters.ENTER)
{
displayInfoScreen();
return true;
}
return super.keyChar(key, status, time);
}
public boolean invokeAction(int action)
{
switch(action)
{
case ACTION_INVOKE:
displayInfoScreen();
return true;
}
return super.invokeAction(action);
}
private void displayInfoScreen()
{
Word w = (Word)_keywordFilterField.getSelectedElement();
if(w != null)
{
InfoScreen infoScreen = new InfoScreen(w);
UiApplication ui = UiApplication.getUiApplication();
ui.pushScreen(infoScreen);
ui.popScreen(this);
}
}
private final static class InfoScreen extends MainScreen
{
InfoScreen(Word w)
{
setTitle(w.toString());
BasicEditField popField = new BasicEditField(":",w.getMeaning(),20,Field.NON_FOCUSABLE);
add(popField);
}
}
}
public class Word
{
private String _word;
private String _meaning;
public Word(String word, String meaning)
{
_word = word;
_meaning = meaning;
}
String getMeaning()
{
return _meaning;
}
public String toString()
{
return _word;
}
}
import net.rim.device.api.ui.component .*;
import net.rim.device.api.collection.util.*;
import net.rim.device.api.util.*;
import java.util.*;
public class WordList extends SortedReadableList implements KeywordProvider
{
public WordList(Vector words)
{
super(new WordListComparator());
loadFrom(words.elements());
}
void addElement(Object element)
{
doAdd(element);
}
public String[] getKeywords( Object element )
{
if(element instanceof Word )
{
return StringUtilities.stringToWords(element.toString());
}
return null;
}
final static class WordListComparator implements Comparator
{
public int compare(Object o1, Object o2)
{
if (o1 == null || o2 == null)
throw new IllegalArgumentException("Cannot compare null words");
return o1.toString().compareTo(o2.toString());
}
}
}
add st.close(); and d.close() after accessing db in private Vector getDataFromDatabase() method just before closing the try block

Resources