I am currently using Apache Commons Net to develop my own NNTP reader. Using the tutorial available I was able to use some of their code to allow me to get articles back.
The Code I am using from NNTP Section -
System.out.println("Retrieving articles between [" + lowArticleNumber + "] and [" + highArticleNumber + "]");
Iterable<Article> articles = client.iterateArticleInfo(lowArticleNumber, highArticleNumber);
System.out.println("Building message thread tree...");
Threader threader = new Threader();
Article root = (Article)threader.thread(articles);
Article.printThread(root, 0);
I need to take the articles and turn them into a List type so I can send them to AWT using something like this -
List x = (List) b.GetGroupList(dog);
f.add(CreateList(x));
My Entire code Base for this section is -
public void GetThreadList(String Search) throws SocketException, IOException {
String hostname = USE_NET_HOST;
String newsgroup = Search;
NNTPClient client = new NNTPClient();
client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
client.connect(hostname);
client.authenticate(USER_NAME, PASS_WORD);
if(!client.authenticate(USER_NAME, PASS_WORD)) {
System.out.println("Authentication failed for user " + USER_NAME + "!");
System.exit(1);
}
String fmt[] = client.listOverviewFmt();
if (fmt != null) {
System.out.println("LIST OVERVIEW.FMT:");
for(String s : fmt) {
System.out.println(s);
}
} else {
System.out.println("Failed to get OVERVIEW.FMT");
}
NewsgroupInfo group = new NewsgroupInfo();
client.selectNewsgroup(newsgroup, group);
long lowArticleNumber = group.getFirstArticleLong();
long highArticleNumber = lowArticleNumber + 5000;
System.out.println("Retrieving articles between [" + lowArticleNumber + "] and [" + highArticleNumber + "]");
Iterable<Article> articles = client.iterateArticleInfo(lowArticleNumber, highArticleNumber);
System.out.println("Building message thread tree...");
Threader threader = new Threader();
Article root = (Article)threader.thread(articles);
Article.printThread(root, 0);
try {
if (client.isConnected()) {
client.disconnect();
}
}
catch (IOException e) {
System.err.println("Error disconnecting from server.");
e.printStackTrace();
}
}
and -
public void CreateFrame() throws SocketException, IOException {
// Make a new program view
Frame f = new Frame("NNTP Reader");
// Pick my layout
f.setLayout(new GridLayout());
// Set the size
f.setSize(H_SIZE, V_SIZE);
// Make it resizable
f.setResizable(true);
//Create the menubar
f.setMenuBar(CreateMenu());
// Create the lists
UseNetController b = new UseNetController(NEWS_SERVER_CREDS);
String dog = "*";
List x = (List) b.GetGroupList(dog);
f.add(CreateList(x));
//f.add(CreateList(y));
// Add Listeners
f = CreateListeners(f);
// Show the program
f.setVisible(true);
}
I just want to take my list of returned news articles and send them to the display in AWT. Can any one explain to me how to turn those Articles into a list?
Welcome to the DIY newsreader club. I'm not sure if you are trying to get a list of newsgroups on the server, or articles.You have already have your Articles in an Iterable Collection. Iterate through it appending what you want in the list from each article. You probably aren't going to want to display the whole article body in a list view. More likely the message id, subject, author or date (or combination as a string). For example for a List of just subjects:
...
Iterable<Article> articles = client.iterateArticleInfo(lowArticleNumber, highArticleNumber);
Iterator<Article> it = articles.iterator();
while(it.hasNext()) {
Article thisone = it.next();
MyList.add(thisone.getSubject());
//MyList should have been declared up there somewhere ^^^ and
//your GetThreadList method must include List in the declaration
}
return MyList;
...
My strategy has been to retrieve the articles via an iterator in to an SQLite database with the body, subject, references etc. stored in fields. Then you can create a list sorted just how you want, with a link by primary key to retrieve what you need for individual articles as you display them. Another strategy would be an array of message_ids or article numbers and fetch each one individually from the news server as required. Have fun - particularly when you are coding for Android and want to display a list of threaded messages in the correct sequence with suitable indents and markers ;). In fact, you can learn a lot by looking at the open source Groundhog newsreader project (to which I am eternally grateful).
http://bazaar.launchpad.net/~juanjux/groundhog/trunk/files/head:/GroundhogReader/src/com/almarsoft/GroundhogReader
Related
I'm trying to develop a small Application for a Zebra handheld rfid reader and can't find a way to access the MemoryBank of the tag. My reader configuration is as follows:
private void ConfigureReader() {
if (reader.isConnected()) {
TriggerInfo triggerInfo = new TriggerInfo();
triggerInfo.StartTrigger.setTriggerType(START_TRIGGER_TYPE.START_TRIGGER_TYPE_IMMEDIATE);
triggerInfo.StopTrigger.setTriggerType(STOP_TRIGGER_TYPE.STOP_TRIGGER_TYPE_IMMEDIATE);
try {
// receive events from reader
if (eventHandler == null){
eventHandler = new EventHandler();
}
reader.Events.addEventsListener(eventHandler);
// HH event
reader.Events.setHandheldEvent(true);
// tag event with tag data
reader.Events.setTagReadEvent(true);
reader.Events.setAttachTagDataWithReadEvent(true);
// set trigger mode as rfid so scanner beam will not come
reader.Config.setTriggerMode(ENUM_TRIGGER_MODE.RFID_MODE, true);
// set start and stop triggers
reader.Config.setStartTrigger(triggerInfo.StartTrigger);
reader.Config.setStopTrigger(triggerInfo.StopTrigger);
} catch (InvalidUsageException e) {
e.printStackTrace();
} catch (OperationFailureException e) {
e.printStackTrace();
}
}
}
And the eventReadNotify looks like this:
public void eventReadNotify(RfidReadEvents e) {
// Recommended to use new method getReadTagsEx for better performance in case of large tag population
TagData[] myTags = reader.Actions.getReadTags(100);
if (myTags != null) {
for (int index = 0; index < myTags.length; index++) {
Log.d(TAG, "Tag ID " + myTags[index].getTagID());
ACCESS_OPERATION_CODE aoc = myTags[index].getOpCode();
ACCESS_OPERATION_STATUS aos = myTags[index].getOpStatus();
if (aoc == ACCESS_OPERATION_CODE.ACCESS_OPERATION_READ && aos == ACCESS_OPERATION_STATUS.ACCESS_SUCCESS) {
if (myTags[index].getMemoryBankData().length() > 0) {
Log.d(TAG, " Mem Bank Data " + myTags[index].getMemoryBankData());
}
}
}
}
}
When I'm scanning a tag I get the correct TagID but both myTags[index].getOpCode() and myTags[index].getOpStatus() return null values.
I appreciate every suggestion that might lead to a successful scan.
Thanks.
I managed to find a solution for my problem. To perform any Read or Write task with Zebra Handheld Scanners the following two conditions must be satisfied. Look here for reference: How to write to RFID tag using RFIDLibrary by Zebra?
// make sure Inventory is stopped
reader.Actions.Inventory.stop();
// make sure DPO is disabled
reader.Config.setDPOState(DYNAMIC_POWER_OPTIMIZATION.DISABLE);
You have to stop the inventory and make sure to disable dpo in order to get data other than the TagID from a Tag. Unfortunately this isn't mentioned in the docu for Reading RFID Tags.
For example, I want to read Age Ranges, Genders, Operating Systems, etc, which are supported in google adwords. I want to read the above said targeting options using either AWQL or Selector?
I am able to read those targeting options using ConstantDataService.
AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();
ConstantDataServiceInterface constantDataService =
adWordsServices.get(this.session, ConstantDataServiceInterface.class);
AgeRange []ageRanges = constantDataService.getAgeRangeCriterion();
for(AgeRange a : ageRanges) {
System.out.println(a.getId() + " :: " + a.getAgeRangeType() + " :: " + a.getCriterionType() + " :: " + a.getType());
}
But I am unable to apply filters. I saw that I can apply filters if I use AWQL or Selector? I tried the following
AdGroupCriterionServiceInterface adGroupCriterionService =
adWordsServices.get(session, AdGroupCriterionServiceInterface.class);
// Create selector.
SelectorBuilder builder = new SelectorBuilder();
Selector selector = builder
.fields("Id", "AgeRangeType")
.build();
int PAGE_SIZE = 100;
ServiceQuery serviceQuery = new ServiceQuery.Builder().fields(AdGroupCriterionField.Id, AdGroupCriterionField.AgeRangeType).limit(0, PAGE_SIZE).build();
// Set selector paging = the most important change is to set numberResults to 0.
AdGroupCriterionPage page = null;
do {
serviceQuery.nextPage(page);
page = adGroupCriterionService.query(serviceQuery.toString());
if (page.getEntries() != null) {
for (AdGroupCriterion criterion : page.getEntries()) {
System.out.printf("Campaign with name '%s' and ID %d was found.%n", criterion.getAdGroupCriterionType(),
criterion.getCriterion());
}
} else {
System.out.println("No criterion were found.");
}
} while(serviceQuery.hasNext(page));
but not working as expected.
Can someone tell me how to read targeting options using AWQL or Selector?
I am really new to SOAP web services and to Netsuite ERP and I am trying to generate a report in my company where I need to obtain all the Clients and their Invoices using the data available in Netsuite ERP. I followed the Java and Axis tutorial they offer with their sample app for the ERP and I successfully created a Java project in Eclipse that consumes the WSDL for netsuite 2015-2 and compiles the needed classes to run the sample app. So, I followed an example found in their CRM exapmle app to obtain a Client's information but the only problem is that their example method needs you to introduce the Client's ID. Here is the sample code:
public int getCustomerList() throws RemoteException,
ExceededUsageLimitFault, UnexpectedErrorFault, InvalidSessionFault,
ExceededRecordCountFault, UnsupportedEncodingException {
// This operation requires a valid session
this.login(true);
// Prompt for list of internalIds and put in an array
_console
.write("\ninternalIds for records to retrieved (separated by commas): ");
String reqKeys = _console.readLn();
String[] internalIds = reqKeys.split(",");
return getCustomerList(internalIds, false);
}
private int getCustomerList(String[] internalIds, boolean isExternal)
throws RemoteException, ExceededUsageLimitFault,
UnexpectedErrorFault, InvalidSessionFault, ExceededRecordCountFault {
// Build an array of RecordRef objects and invoke the getList()
// operation to retrieve these records
RecordRef[] recordRefs = new RecordRef[internalIds.length];
for (int i = 0; i < internalIds.length; i++) {
RecordRef recordRef = new RecordRef();
recordRef.setInternalId(internalIds[i]);
recordRefs[i] = recordRef;
recordRefs[i].setType(RecordType.customer);
}
// Invoke getList() operation
ReadResponseList getResponseList = _port.getList(recordRefs);
// Process response from get() operation
if (!isExternal)
_console.info("\nRecords returned from getList() operation: \n");
int numRecords = 0;
ReadResponse[] getResponses = getResponseList.getReadResponse();
for (int i = 0; i < getResponses.length; i++) {
_console.info("\n Record[" + i + "]: ");
if (!getResponses[i].getStatus().isIsSuccess()) {
_console.errorForRecord(getStatusDetails(getResponses[i]
.getStatus()));
} else {
numRecords++;
Customer customer = (Customer) getResponses[i].getRecord();
_console.info(" internalId="
+ customer.getInternalId()
+ "\n entityId="
+ customer.getEntityId()
+ (customer.getCompanyName() == null ? ""
: ("\n companyName=" + customer
.getCompanyName()))
+ (customer.getEntityStatus() == null ? ""
: ("\n status=" + customer.getEntityStatus().getName()))
+ (customer.getEmail() == null ? ""
: ("\n email=" + customer.getEmail()))
+ (customer.getPhone() == null ? ""
: ("\n phone=" + customer.getPhone()))
+ "\n isInactive="
+ customer.getIsInactive()
+ (customer.getDateCreated() != null ? ""
: ("\n dateCreated=" + customer
.getDateCreated().toString())));
}
}
return numRecords;
}
So as you can see, this method needs the internal ID of each Customer which I find not useful as I have a many Customers and I don't want to pass each Customer's ID. I read their API docs (which I find hard to navigate and kind of useless) and I found a web service called getAll() that gives all the records given a getAllRecord object which requires a getAllRecordType object. However, the getAllRecordType object does not support Customer entities, so I can't obtain all the customers on the ERP this way.
Is there an easy way to obtain all the Customers in my Netsuite ERP (maybe using other thing rather than the SOAP Web Services they offer? I am desperate about this situation as understanding how Netsuite's Web Services API has been really troublesome.
Thanks!
You would normally use a search to select a list of customers. On a large account you would not normally get all customers on any regular basis. If you are trying to get the invoices you might just find it more practical to get those with a search.
You wrote "in your company". Are you trying to write an application of some sort? If this is an internal project (and even if it's not) you'll probably find using SuiteScripts much more efficient in terms of your time and frustration level.
I made it using the following code on my getCustomerList method:
CustomerSearch customerSrch = new CustomerSearch();
SearchResult searchResult = _port.search(customerSrch);
System.out.println(searchResult.getTotalRecords());
RecordList rl = searchResult.getRecordList();
for (int i = 0; i <searchResult.getTotalRecords()-1; i++) {
Record r = rl.getRecord(i);
System.out.println("Customer # " + i);
Customer testcust = (Customer)r;
System.out.println("First Name: " + testcust.getFirstName());
}
I'm learning to work with google alerts API.
I want to create an alerts from java code, and when I have alerts put them to my DB
My way:
I'm able to create an new google alert , that would send alerts to my gmail.
Read all the mails with java from my mail.
I parse them and put to my DB.
Is there a better way to do that ?
I saw that google can give me an XML rss , it would be much easier to parse , but I wasn't able to get the rss with java.
Thanks for any help.
Maybe it would be helpful :
Java code to create google alert:
public static void addAlertToUser(String userMail , String password , String query)
{
GAService service;
try {
service = new GAService(userMail, password);
service.doLogin();
Alert alert = new Alert();
alert.setSearchQuery(query);
alert.setHowOften(HowOften.AS_IT_HAPPENS);
//alert.setLanguage(Region.Israel);
//alert.setLanguage(Language.Hebrew);
alert.setHowMany(HowMany.ONLY_THE_BEST_RESULTS);
service.createAlert(alert);
} catch (Exception e) {
e.printStackTrace();
}
}
Code to read the alert from the Gmail:
public static void readGoogleAlretsEmail()
{
Hashtable<String , Alert[]> allAlerts = checkMail("myGmail#gmail.com", "12q3wa4esz");
for(String key : allAlerts.keySet())
{
System.out.println("Key : " + key + "\n");
Alert[] alerts = allAlerts.get(key);
for (int i = 0; i < alerts.length; i++)
{
Alert currentAlret = (Alert)alerts[i];
System.out.println(i + ". " + alerts[i]);
TextAnalysisResults results = TextAnalysis.getResults(currentAlret.title,currentAlret.content);
}
}
}
I want to delete documents for which a specific property has been set in the current version. If this property has been set all versions of that document need to be removed.
My current implementation which searches for IsCurrentVersion = TRUE and foo = 'bar' has the problem that only the current version gets removed and not the older ones. So I assume that I need to delete the complete VersionSeries ?
Till now I use
doc.delete();
doc.save(RefreshMode.NO_REFRESH);
for each document I find. How can I retrieve all documents from the series and have them deleted too ? And is it more efficient if I add this to a batch ?
You should call the
delete()
method for the VersionSeries (http://www-304.ibm.com/support/knowledgecenter/SSNW2F_5.2.0/com.ibm.p8.ce.dev.java.doc/com/filenet/api/core/VersionSeries.html) instance,
VersionSeries vs = doc.getVersionSeries();
vs.delete();
vs.save(Refresh.NO_REFRESH);
Quote from docs
Caution: The delete and moveContent methods impact all document versions in the version series. That is, all document versions are deleted, and the content of all document versions are moved.
Method for deleting all the versions of a document from FileNet
public void deleteDocumentFromCE(String filenetDocGUID) throws Exception
{
System.out.println("In deleteDocumentFromCE() method");
System.out.println("Input Parameter filenetDocGUID is : " + filenetDocGUID);
Document document = null;
UserContext uc = null;
ObjectStore os = null;
Subject subject = null;
VersionSeries vs = null;
try
{
if (filenetDocGUID != null)
{
getCESession(); //This method will get the CE session and set it in ceSessionData private class variable
os = ceSessionData.getObjectStore();
System.out.println("ObjectStore fetched from CESession static reference is : " + os.get_Name());
subject = ceSessionData.getSubject();
System.out.println("Subject fetched from CESession static reference.");
uc = UserContext.get();
uc.pushSubject(subject);
if (os != null)
{
document = Factory.Document.fetchInstance(os, filenetDocGUID, null);
vs = document.get_VersionSeries();
vs.delete();
vs.save(RefreshMode.NO_REFRESH);
System.out.println("All Document Versions deleted : " + filenetDocGUID);
}
else
{
System.out.println("Error :: Object Store is not available.");
}
}
}
catch (Exception e)
{
System.out.println("Exception in deleteDocumentFromCE() Method : "+ e.getMessage());
//pass the error to the calling method
throw new Exception("System Error occurred while deleting the document in CE.. "+e.getMessage());
}
finally
{
if (uc != null)
uc.popSubject();
}
System.out.println("End of deleteDocumentFromCE() method");
}