I'm starting working with Twitter4J and I would like to figure out what each method does.
I'm implementing UserStreamListener which has a lot of methods what don't have JavaDoc,, as:
public void onException(Exception ex) {
public void onBlock(User arg0, User arg1)
public void onDeletionNotice(long arg0, long arg1)
public void onDirectMessage(DirectMessage arg0)
...
So, I don't know when they are exactly executed and what the params mean. I downloaded the code of Twitter4J and I have seen a class where you can see how the library is generating the events, but when I try to link that information with Twitter, I don't find more information.
I found this web https://dev.twitter.com/docs/platform-objects/tweets , but it isn't this information.
public final class JSONObjectType {
public enum Type {
SENDER,
STATUS,
DIRECT_MESSAGE,
DELETE,
LIMIT,
STALL_WARNING,
SCRUB_GEO,
FRIENDS,
FAVORITE,
UNFAVORITE,
FOLLOW,
UNFOLLOW,
USER_LIST_MEMBER_ADDED,
USER_LIST_MEMBER_DELETED,
USER_LIST_SUBSCRIBED,
USER_LIST_UNSUBSCRIBED,
USER_LIST_CREATED,
USER_LIST_UPDATED,
USER_LIST_DESTROYED,
USER_UPDATE,
BLOCK,
UNBLOCK,
DISCONNECTION,
UNKNOWN
}
private static final Logger logger = Logger.getLogger(JSONObjectType.class);
/**
* Determine the respective object type for a given JSONObject. This
* method inspects the object to figure out what type of object it
* represents. This is useful when processing JSON events of mixed type
* from a stream, in which case you may need to know what type of object
* to construct, or how to handle the event properly.
*
* #param json the JSONObject whose type should be determined
* #return the determined JSONObjectType, or null if not recognized
*/
public static Type determine(JSONObject json) {
// This code originally lived in AbstractStreamImplementation.
// I've moved it in here to expose it as a public encapsulation of
// the object type determination logic.
if (!json.isNull("sender")) {
return Type.SENDER;
} else if (!json.isNull("text")) {
return Type.STATUS;
} else if (!json.isNull("direct_message")) {
return Type.DIRECT_MESSAGE;
} else if (!json.isNull("delete")) {
return Type.DELETE;
} else if (!json.isNull("limit")) {
return Type.LIMIT;
} else if (!json.isNull("warning")) {
return Type.STALL_WARNING;
} else if (!json.isNull("scrub_geo")) {
return Type.SCRUB_GEO;
} else if (!json.isNull("friends")) {
return Type.FRIENDS;
} else if (!json.isNull("event")) {
String event;
try {
event = json.getString("event");
if ("favorite".equals(event)) {
return Type.FAVORITE;
} else if ("unfavorite".equals(event)) {
return Type.UNFAVORITE;
} else if ("follow".equals(event)) {
return Type.FOLLOW;
} else if ("unfollow".equals(event)) {
return Type.UNFOLLOW;
} else if (event.startsWith("list")) {
if ("list_member_added".equals(event)) {
return Type.USER_LIST_MEMBER_ADDED;
} else if ("list_member_removed".equals(event)) {
return Type.USER_LIST_MEMBER_DELETED;
} else if ("list_user_subscribed".equals(event)) {
return Type.USER_LIST_SUBSCRIBED;
} else if ("list_user_unsubscribed".equals(event)) {
return Type.USER_LIST_UNSUBSCRIBED;
} else if ("list_created".equals(event)) {
return Type.USER_LIST_CREATED;
} else if ("list_updated".equals(event)) {
return Type.USER_LIST_UPDATED;
} else if ("list_destroyed".equals(event)) {
return Type.USER_LIST_DESTROYED;
}
} else if ("user_update".equals(event)) {
return Type.USER_UPDATE;
} else if ("block".equals(event)) {
return Type.BLOCK;
} else if ("unblock".equals(event)) {
return Type.UNBLOCK;
}
} catch (JSONException jsone) {
try {
logger.warn("Failed to get event element: ", json.toString(2));
} catch (JSONException ignore) {
}
}
} else if (!json.isNull("disconnect")) {
return Type.DISCONNECTION;
}
return Type.UNKNOWN;
}
}
For example, if the JSON is coming "event" and "block", the method onBlock will be executed. But, where is the information about all the possible fields in a Tweet???
You may find the information you need in Twitter's Streaming message types documentation, specifically, take a look at the Events section which describes the message format:
{
"target": TARGET_USER,
"source": SOURCE_USER,
"event":"EVENT_NAME",
"target_object": TARGET_OBJECT,
"created_at": "Sat Sep 4 16:10:54 +0000 2010"
}
Additionally, this documentation for UserStreamListener will help with the argument names of the methods, for example the onBlock method:
onBlock(User source, User blockedUser)
Related
I am trying to make a way to read a file with data saved in a specific format, parse it to JSON then convert it to an object so that I can use dot notation.
The problem here is using dot notation as it just returns null
CoreData.dart
import 'dart:convert';
import 'dart:io';
import 'dart:async';
import 'package:path_provider/path_provider.dart';
#proxy
class CoreObject {
Map _data;
CoreObject([String source]) {
Map json = (source == null) ? new Map() : JSON.decode(source);
_data = new Map.from(json);
json.forEach((k, v) {
print(k);
_data[k] = v;
});
}
static encode(List<CoreObject> list) {
String result = "";
for (CoreObject item in list) {
result += "${item.toString()};";
}
return result;
}
#override toString() {
print(this._data);
return JSON.encode(this._data);
}
#override
noSuchMethod(Invocation invocation) {
var name = invocation.memberName.toString().replaceFirst('Symbol(\"', "");
print("_data.keys ${_data.keys}");
print("_data.values ${_data.values}");
if (invocation.isGetter) {
print("name ${name.replaceAll("\")", "")}");
var ret = _data[name.replaceAll("\")", "")];
print("ret $ret");
print(ret.toString());
return ret;
}
if (invocation.isSetter) {
_data[name.replaceAll("=\")", "")] = invocation.positionalArguments.first;
} else {
super.noSuchMethod(invocation);
}
}
}
class Person extends CoreObject {
Person([source]): super(source);
#override noSuchMethod(Invocation invocation) {
super.noSuchMethod(invocation);
}
}
class CoreContainer {
String _object;
var returnNew;
var path;
_map(String source) {
var result = [];
for (var line in source.split(";")) {
// print("line $line");
if (line != "") result.add(returnNew(line));
}
print("result $result");
return result;
}
encode(List<CoreObject> list) {
// print("list $list");
String result = "";
list.forEach((CoreObject item) {
// print("item ${item.toString()}");
result += "${item};";
});
// print("result $result");
return result;
}
CoreContainer(this._object, this.returnNew);
Future<File> _getFile() async {
String dir = path ?? (await getApplicationDocumentsDirectory()).path;
this.path = dir;
return new File('$dir/$_object.txt');
}
Future<List<CoreObject>> getAll() async {
return _getFile().then((File file) {
String contents = file.readAsStringSync();
print("contents $contents");
return this._map(contents);
})
.catchError((Error error) {
print('error: $error');
_getFile().then((File file) {
file.writeAsStringSync("");
});
return [];
});
}
save(List<CoreObject> data) async {
_getFile().then((file) {
try {
file.writeAsStringSync(this.encode(data));
}
catch (error) {
print("error: $error");
}
}).catchError((Error error) {
print("error: $error");
});
}
clear() async {
return _getFile().then((file) {
file.writeAsStringSync("");
}).catchError((Error error) {
print("error: $error");
});
}
Future<List<CoreObject>> get(query) async {
return this.getAll().then((List data) {
data.retainWhere(query);
return data;
}).catchError((error) {
print("error: $error");
});
}
Future<List<CoreObject>> remove(query) async {
return this.getAll().then((List data) {
// print(data);
data.removeWhere(query);
save(data);
return data;
}).catchError((error) {
print("error: $error");
});
}
Future<List<CoreObject>> add(obj) async {
return this.getAll().then((data) {
data.add(obj);
return save(data).then(() {
return data;
})
.catchError((Error error) {
throw error;
});
}).catchError((Error error) {
print("error: $error");
});
}
}
Using it:
CoreContainer corePerson = new CoreContainer("Person", (source) => new Person(source));
corePerson.getAll().then((List<CoreObject> array) {
var tempItems = [];
var i = 0;
print("array $array");
while (i < array.length) {
Person person = array[i];
print(person); //{"name":"<whatever 'i' is>"}
print(person.name); //null
tempItems.add(new ListTile(
title: new Text("$i"),
subtitle: new Text("${person.name}"),
));
i++;
}
print(tempItems.length);
count = tempItems.length;
setState(() {
items = tempItems;
});
}).catchError((Error error) {
print("error: $error, ${error.stackTrace}");
});
Code is hard to read because of a lot of print debugging.
But I suppose you need a way to convert JSON data into a Dart class.
You should use library like jaguar_serializer that do the job for you.
https://pub.dartlang.org/packages/jaguar_serializer
Dart doesn't use dot notation like dynamic languages (Python, JavaScript). In Python and JavaScript, for example, every single object is actually internally a HashMap, and . is actually a hash lookup of the property name:
a.bar // Loosely the same as a.lookup('bar')
The Python/JS VM though can "see" that a.bar is used like a property on a class-like object a, and optimize it to use a true property/field access - this is part of the "optimization" phase of a JIT (just-in-time compiler).
It is features like this that make it almost impossible to ahead-of-time compile either Python or JS - they require runtime profile information to generate fast code. Dart (and specifically Dart 2.0) is implementing a sound type system where a.bar, when a is known, is always a property accessor, not a hash lookup.
That means at runtime you can't take an arbitrary hash map and force it to act like an object, which is why your code seems awkward. I'd recommend using code generation if you need a typed object with . notation, or settling for a HashMap [] if you do not.
Check also mapping json into class objects answers for example of clean basic way of json -> dart class mapping.
i'm relative new to this, so i want to implement dependency injection using typescript (is the first time I use this pattern), I'm more that using language programming like java or c# for OOP, so there is more easy to apply this pattern,
I found an example on internet and I can use it without problems on eclipse and visual studio, but when i use it on typescript the IDE raise an error like this:
Supplied parameters do not match any signature of call target
and is just at the end of implement it when this error appears
my base class:
class Motor {
Acelerar(): void {
}
GetRevoluciones(): number {
let currentRPM: number = 0;
return currentRPM;
}
}
export {Motor};
my class that uses motor
import { Motor } from "./1";
class Vehiculo {
private m: Motor;
public Vehiculo(motorVehiculo: Motor) {
this.m = motorVehiculo;
}
public GetRevolucionesMotor(): number {
if (this.m != null) {
return this.m.GetRevoluciones();
}
else {
return -1;
}
}
}
export { Vehiculo };
my interface and the type of motor
interface IMotor {
Acelerar(): void;
GetRevoluciones(): number;
}
class MotorGasoline implements IMotor {
private DoAdmission() { }
private DoCompression() { }
private DoExplosion() { }
private DoEscape() { }
Acelerar() {
this.DoAdmission();
this.DoCompression();
this.DoExplosion();
this.DoEscape();
}
GetRevoluciones() {
let currentRPM: number = 0;
return currentRPM;
}
}
class MotorDiesel implements IMotor {
Acelerar() {
this.DoAdmission();
this.DoCompression();
this.DoCombustion();
this.DoEscape();
}
GetRevoluciones() {
let currentRPM: number = 0;
return currentRPM;
}
DoAdmission() { }
DoCompression() { }
DoCombustion() { }
DoEscape() { }
}
and here is where the error appears:
import { Vehiculo } from "./2";
enum TypeMotor {
MOTOR_GASOLINE = 0,
MOTOR_DIESEL = 1
}
class VehiculoFactory {
public static VehiculoCreate(tipo: TypeMotor) {
let v: Vehiculo = null;
switch (tipo) {
case TypeMotor.MOTOR_DIESEL:
v = new Vehiculo(new MotorDiesel()); break;
case TypeMotor.MOTOR_GASOLINE:
v = new Vehiculo(new MotorGasoline()); break;
default: break;
}
return v;
}
}
I don't wanna use any library or module like SIMPLE-DIJS or D4js or any other for the moment, I just wanna know how to implement without them
You have this error because you don't specify a constructor on the Vehiculo type.
To declare a constructor you should use use the constructor keyword and not the name of the class.
class Vehiculo {
private m: Motor;
constructor(motorVehiculo: Motor) {
this.m = motorVehiculo;
}
public GetRevolucionesMotor(): number {
if (this.m != null) {
return this.m.GetRevoluciones();
}
else {
return -1;
}
}
}
I need to catch data from < itunes:sumary > tag but my handler is getting only the end of tag's content (last three words for example). I don't know what to do because other tags are being handled as expected, getting all content.*
I've seen that some tags are ignored by parser, but I don't think it's happening with because as I said it gets the content but only the end of that.
The source XML is hosted in -> http://djpaulonla.podomatic.com/archive/rss2.xml
Please, could someone help me???
The code is the following:
public class PodOMaticCustomHandler extends CustomHandler {
public PodOMaticCustomHandler(int quantityToFetch, String startTagValue,
String endTagValue) {
super(quantityToFetch, startTagValue, endTagValue);
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
this.value = new String(ch, start, length);
}
#Override
public void endDocument() throws SAXException {
super.endDocument();
this.endDoc = true;
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
if (this.podcast != null) {
if (qName.equalsIgnoreCase("title")) {
podcast.setTitle(this.value);
} else if (qName.equalsIgnoreCase("pubDate")) {
podcast.setPubDate(this.value);
} else if (qName.equalsIgnoreCase("description")) {
podcast.setContent(this.value);
} else if (qName.equalsIgnoreCase("guid")) {
this.podcast.setLink(value);
}
}
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if (this.startTagValue == null) {
this.startTagValueFound = true;
} else if (qName.equalsIgnoreCase("guid")
&& this.value.equalsIgnoreCase(this.startTagValue)) {
this.startTagValueFound = true;
}
if (this.endTagValue != null) {
if (qName.equalsIgnoreCase("guid")
&& this.value.equalsIgnoreCase(this.endTagValue)) {
this.endDoc = true;
}
}
if (!this.endDoc) {
if (this.quantityToFetch != this.podcasts.size()) {
if (this.startTagValueFound == true) {
if (qName.equalsIgnoreCase("item")) {
this.podcast = new Podcast();
} else if (qName.equalsIgnoreCase("enclosure")) {
this.podcast.setMedia(attributes.getValue("url"));
this.podcasts.add(podcast);
}
}
} else {
this.podcast = null;
}
}else{
this.podcast = null;
}
}
}
You can't rely on the characters method being called once with the entire element text, it may be called multiple times, each time with only part of the text.
Add a debug log statement to the characters method showing what you're setting value to and you will see that values is getting set with the first part of the string and then getting overwritten with the last part.
The answer is to buffer the text passed in from the characters calls in a CharArrayWriter or StringBuilder. Then you have to clear the buffer when the end of the element is found.
Here's what the Java tutorial on SAX has to say about the characters method:
Parsers are not required to return any particular number of characters at one time. A parser can return anything from a single character at a time up to several thousand and still be a standard-conforming implementation. So if your application needs to process the characters it sees, it is wise to have the characters() method accumulate the characters in a java.lang.StringBuffer and operate on them only when you are sure that all of them have been found.
In Dart, how would I best code the equivalent of an (immutable/value/non-object) out or reference parameter?
For example in C#-ish I might code:
function void example()
{
int result = 0;
if (tryFindResult(anObject, ref result))
processResult(result);
else
processForNoResult();
}
function bool tryFindResult(Object obj, ref int result)
{
if (obj.Contains("what I'm looking for"))
{
result = aValue;
return true;
}
return false;
}
This is not possible in Dart. Support for struct value types, ref or val keywords were discussed on the Dart mailing list just like week. Here is a link to the discussion where you should let your desire be known:
https://groups.google.com/a/dartlang.org/d/topic/misc/iP5TiJMW1F8/discussion
The Dart-way would be:
void example() {
List result = tryFindResult(anObject);
if (result[0]) {
processResult(result[1]);
} else {
processForNoResult();
}
}
List tryFindResult(Object obj) {
if (obj.contains("What I'm looking for")) {
return [true, aValue];
}
return [false, null];
}
you can also use a tuple package like tuple-2.0.0
add tuple: ^2.0.0
to your pubspec.yaml
then any function can return many typed objects like this:
import 'package:tuple/tuple.dart';
Tuple3<int, String, bool?>? returnMany() {
return ok ? Tuple3(5, "OK", null) : null;
}
var str = returnMany().item2;
In your case:
void example() {
var result = tryFindResult(anObject);
if (result.item1) {
processResult(result.item2!);
} else {
processForNoResult();
}
}
Tuple2<bool, int?> tryFindResult(Object obj) {
if (obj.contains("What I'm looking for")) {
return Tuple2(true, aValue);
}
return Tuple2(false, null);
}
you can throw an exception too when no result.
void example() {
var result = tryFindResult(anObject);
try {
processResult(result);
} on NullException catch(e){
processForNoResult();
}
}
int tryFindResult(Object obj) { // throws NullException
if (obj.contains("What I'm looking for")) {
return aValue;
}
throw NullException();
}
I want to perform validations for my editfields.so I am writing the validations on ButtonField.setChangeListener method. If editField is empty and when clicking on the button i have to show that the field is empty. To show the message i tried by using both status.show() and dialog.alert() methods. But both are generating a NullPointerException. What is the problem? Can anyone help to solve this problem or are there any other solutions to this problem?
I have written my code like this:
btnencrypt = new ButtonField("Encrypt");
btnencrypt.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
//getphonenos();
System.out.println("savedPhone no are in compose encrypt:"+savedphoneno);
encryptClicked= true;
if (savedphoneno.equals("")) { **Getting the exception here....**
Dialog.alert("Please select valid contact");
} else {
if (!(savedphoneno.equals(""))) {
if (edmsg.getText().toString().trim().equals("")) {
Dialog.alert("Please enter message");
}else {
int index = savedphoneno.indexOf(",");
if (index < 0) {
encryptBTNClicked = true;
try {
base64msgString = encrypt(savedphoneno);
} catch (CryptoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
edencryptmsg.setText(base64msgString);
} else {
//encryptTV.setText("");
edencryptmsg
.setText("Sending data to multiple receipients,"
+ "can't show the encrypted msg,as it varies");
//edencryptmsg.setTextColor(Color.MAGENTA);
}
btnencrypt.setEnabled(false);
btnclear.setEnabled(false);
}
}
}
}
});
I have a useful method that I put into my StringUtils class that checks if a string is valid.
/**
* Tests if a string is a non-null, non-empty string. This can be called to
* determine if the string should be displayed, or not.
*
* #param text
* String to test.
* #return
* If <code>text</code> is <code>null</code>, returns
* <code>false</code>. <br>
* If <code>text</code> is an empty string (""), returns
* <code>false</code>. <br>
* Else returns <code>true</code>.
*/
public static boolean isNonBlankString(String text)
{
// null text -> false
if (text == null)
return false;
// empty text -> false
if ("".equals(text))
return false;
return true;
}
This will help you with Rupak's answer.