Refer classes by their metadata tag - dart

Is it possible to find(probably with the mirror API) all classes(in my project) with some metadata annotation?
Example:
import 'baz.dart'; //more tagged classes
#Tag(#foo)
class A{
}
#Tag(#foo)
class B{
}
void main() {
List<ClassMirror> li = getClassMirrorsByTag(#foo);
}

I have found the answer:
getClassMirrorsByTag.dart
library impl;
#MirrorsUsed(metaTargets: Tag)
import 'dart:mirrors';
class Tag {
final Symbol name;
const Tag(this.name);
}
List<ClassMirror> getClassMirrorsByTag(Symbol name) {
List<ClassMirror> res = new List<ClassMirror>();
MirrorSystem ms = currentMirrorSystem();
ms.libraries.forEach((u, lm) {
lm.declarations.forEach((s, dm) {
dm.metadata.forEach((im) {
if ((im.reflectee is Tag) && im.reflectee.name == name) {
res.add(dm);
}
});
});
});
return res;
}
extra.dart
library extra;
import 'getClassMirrorsByTag.dart';
#Tag(#foo)
class C {}
main.dart
library main;
import 'getClassMirrorsByTag.dart';
import 'extra.dart';
#Tag(#foo)
class A{}
#Tag(#baz)
class B{}
void main() {
print(getClassMirrorsByTag(#foo));
}
output:
[ClassMirror on 'A', ClassMirror on 'C']

Related

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.

Where can I find the source code for ActivityTestRule?

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();
}
}
}
}

How do I add a valid default constructor to a dart polymer class?

The following code defines the Polymer element
What do I need as a valid default constructor for this class?
My question is what is needed for a proper constructor
import 'package:polymer/polymer.dart';
import 'lib/NPIDefs.dart';
import 'dart:html';
/**
* A Polymer click counter element.
*/
#CustomTag('detail-panel')
class NPIDetailPanel extends PolymerElement {
#published #observable NPIRecord record;
#observable String detailPanelICON = "unfold-less";
NPIDetailPanel.created() : super.created() {
}
setValue(NPIRecord npiRec) {
record = npiRec;
}
void dremoveDetailPanel() {
Element e;
e = shadowRoot.querySelector('#dpanel');
if(e != null) {
e.remove();
}
}
The code below gets a The class 'NPIDetailPanel' does not have a default constructor error
Please show how to do a default constructor
in the definition of the class
void addDetailPanel(Event e) {
NPIDetailPanel e1;
e1 = new NPIDetailPanel();
}
/* How do I add a proper default constructor? */
You can create a new instance of a Polymer element using new Element.tag('some-tag');
Just add a factory constructor that contains this to your Polymer element class.
#CustomTag('detail-panel')
class NPIDetailPanel extends PolymerElement {
factory NPIDetailPanel NPIDetailPanel() => new Element.tag('detail-panel'); // <== added
#published #observable NPIRecord record;
#observable String detailPanelICON = "unfold-less";
NPIDetailPanel.created() : super.created() {
}
setValue(NPIRecord npiRec) {
record = npiRec;
}
void dremoveDetailPanel() {
Element e;
e = shadowRoot.querySelector('#dpanel');
if(e != null) {
e.remove();
}
}
}
see also Instantiating polymer element via dart code

custom annotation / Metadata in dart lang

Can any one explain me the use of annotations in Dart?
In the documentations, I found this example:
library todo;
class todo {
final String who;
final String what;
const todo(this.who, this.what);
}
followed by
import 'todo.dart';
#todo('seth', 'make this do something')
void doSomething() {
print('do something');
}
so, what shall I write in the main() to get the doSomething() function executed?
thanks
Something like
import 'dart:mirrors';
import 'do_something.dart';
import 'todo.dart';
void main() {
currentMirrorSystem().libraries.forEach((uri, lib) {
//print('lib: ${uri}');
lib.declarations.forEach((s, decl) {
//print('decl: ${s}');
decl.metadata.where((m) => m.reflectee is Todo).forEach((m) {
var anno = m.reflectee as Todo;
if(decl is MethodMirror) {
print('Todo(${anno.who}, ${anno.what})');
((decl as MethodMirror).owner as LibraryMirror).invoke(s, []);
};
});
});
});
}

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