XPages: How to acces an application scope bean from a session scope bean - jsf

I need a value from my application scope managed bean in my session scope managed bean. Not sure how to get this done. Saw a poste here: https://guedebyte.wordpress.com/2012/05/19/accessing-beans-from-java-code-in-xpages-learned-by-reading-the-sourcecode-of-the-extensionlibrary/ But I get a bunch of errors... I also found this: JSF 2.0 Accessing Application Scope bean from another Bean so IM thinking maybe I need to redefine my application bean??? Totally clueless...
How can I make that happen?
Here is the application scope bean's code:
public class AppConfig implements Serializable {
private static final long serialVersionUID = 2768250939591274442L;
public AppConfig() {
initDefaults();
initFromConfigDoc();
}
// Control the number of entries displayed in the widgets
private int nbWidgetFavorites = 0;
private int nbWidgetMostPopular = 0;
private int nbWidgetToolbox = 0;
// Control the number of entries to display in the What's new view
private int nbWhatsNew = 0;
private String showDetailsWhatsNew = "no";
//controls various search options
private int nbSearchResults = 0;
private int nbMaxSearchResults = 0;
//the home page to use for each language
private String homePageUNID_FR = "";
private String homePageUNID_EN = "";
//application email address to use (webmaster)
// DEV ADDRESS
private String appEmailAddress = "DEVTEAMTEST/DEV#DEVELOPMENTCORP";
// UAT ADDRESS
// PROD ADDRESS
//path to the stats DB
private String statsDB = "";
//application message, if needed
private String systemMessageFR = "";
private String systemMessageEN = "";
//default lang (defined here as session bean will read from the App bean first to
// see if there's a value stored there)
private String defaultLang = "";
//default prov
private String defaultProv = "";
// show Province drop down?
private String showProv = "no";
//various text for "share this link" emails
private String senderEmail = "";
private String senderName = "";
private String appURL = "";
private String emailText = "";
private String clickLinkText = "";
private String emailFooter = "";
private String messageIntro = "";
private String allowRatingModification = "";
/*****************************************************************************/
private void initDefaults() {
// Control the number of entries displayed in the widgets
nbWidgetFavorites = 10;
nbWidgetMostPopular = 10;
nbWidgetToolbox = 10;
nbWhatsNew = 15;
showDetailsWhatsNew = "no";
nbSearchResults = 25;
nbMaxSearchResults = 100;
homePageUNID_FR = "";
homePageUNID_EN = "";
appEmailAddress = "DEVTEAMTEST/DEV#DEVELOPMENTCORP";
statsDB = "belair\\xBiblioStats.nsf";
systemMessageFR = "";
systemMessageEN = "";
defaultLang = "FR";
defaultProv = "QC";
showProv = "no";
allowRatingModification = "1";
}
/*****************************************************************************/
public boolean persistToConfigDoc() {
//write content of sessionScope vars to config doc
try {
Database db = ExtLibUtil.getCurrentSession().getCurrentDatabase();
View view = db.getView("AppConfig");
Document doc = view.getFirstDocument();
if(doc == null) {
doc = db.createDocument();
doc.replaceItemValue("form", "AppConfig");
}
doc.replaceItemValue("nbWidgetFavorites", this.nbWidgetFavorites);
doc.replaceItemValue("nbWidgetMostPopular", this.nbWidgetMostPopular);
doc.replaceItemValue("nbWidgetToolbox", this.nbWidgetToolbox);
doc.replaceItemValue("nbWidgetToolbox", this.nbWidgetToolbox);
doc.replaceItemValue("nbWhatsNew", this.nbWhatsNew);
doc.replaceItemValue("showDetailsWhatsNew", this.showDetailsWhatsNew);
doc.replaceItemValue("nbSearchResults", this.nbSearchResults);
doc.replaceItemValue("nbMaxSearchResults", this.nbMaxSearchResults);
doc.replaceItemValue("homePageUNID_FR", this.homePageUNID_FR);
doc.replaceItemValue("homePageUNID_EN", this.homePageUNID_EN);
doc.replaceItemValue("appEmailAddress", this.appEmailAddress);
doc.replaceItemValue("statsDB", this.statsDB);
doc.replaceItemValue("systemMessageFR", this.systemMessageFR);
doc.replaceItemValue("systemMessageEN", this.systemMessageEN);
doc.replaceItemValue("defaultLang", this.defaultLang);
doc.replaceItemValue("defaultProv", this.defaultProv);
doc.replaceItemValue("showProv", this.showProv);
doc.replaceItemValue("senderEmail", this.senderEmail);
doc.replaceItemValue("senderName", this.senderName);
doc.replaceItemValue("appURL", this.appURL);
doc.replaceItemValue("emailText", this.emailText);
doc.replaceItemValue("clickLinkText", this.clickLinkText);
doc.replaceItemValue("emailFooter", this.emailFooter);
doc.replaceItemValue("messageIntro", this.messageIntro);
doc.replaceItemValue("allowRatingModification", this.allowRatingModification);
doc.save();
return true;
} catch (NotesException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
/*****************************************************************************/
public void initFromConfigDoc() {
try {
Database db = ExtLibUtil.getCurrentSession().getCurrentDatabase();
View view = db.getView("AppConfig");
Document doc = view.getFirstDocument();
if(doc != null) {
//load default values
if(doc.hasItem("nbWidgetFavorites")) {
int tmp = doc.getItemValueInteger("nbWidgetFavorites");
if(tmp > 0) {
this.nbWidgetFavorites = tmp;
}
}
if(doc.hasItem("nbWidgetMostPopular")) {
int tmp = doc.getItemValueInteger("nbWidgetMostPopular");
if(tmp > 0) {
this.nbWidgetMostPopular = tmp;
}
}
if(doc.hasItem("nbWidgetToolbox")) {
int tmp = doc.getItemValueInteger("nbWidgetToolbox");
if(tmp > 0) {
this.nbWidgetToolbox = tmp;
}
}
if(doc.hasItem("nbWhatsNew")) {
int tmp = doc.getItemValueInteger("nbWhatsNew");
if(tmp > 0) {
this.nbWhatsNew = tmp;
}
}
if(doc.hasItem("showDetailsWhatsNew")) {
String tmp = doc.getItemValueString("showDetailsWhatsNew");
this.showDetailsWhatsNew = tmp;
}
if(doc.hasItem("nbSearchResults")) {
int tmp = doc.getItemValueInteger("nbSearchResults");
if(tmp > 0) {
this.nbSearchResults = tmp;
}
}
if(doc.hasItem("nbMaxSearchResults")) {
int tmp = doc.getItemValueInteger("nbMaxSearchResults");
if(tmp > 0) {
this.nbMaxSearchResults = tmp;
}
}
if(doc.hasItem("homePageUNID_FR")) {
String tmp = doc.getItemValueString("homePageUNID_FR");
if(!"".equals(tmp)) {
this.homePageUNID_FR = tmp;
}
}
if(doc.hasItem("homePageUNID_EN")) {
String tmp = doc.getItemValueString("homePageUNID_EN");
if(!"".equals(tmp)) {
this.homePageUNID_EN = tmp;
}
}
if(doc.hasItem("appEmailAddress")) {
String tmp = doc.getItemValueString("appEmailAddress");
if(!"".equals(tmp)) {
this.appEmailAddress = tmp;
}
}
if(doc.hasItem("statsDB")) {
String tmp = doc.getItemValueString("statsDB");
if(!"".equals(tmp)) {
this.statsDB = tmp;
}
}
if(doc.hasItem("systemMessageFR")) {
String tmp = doc.getItemValueString("systemMessageFR");
if(!"".equals(tmp)) {
this.systemMessageFR = tmp;
}
}
if(doc.hasItem("systemMessageEN")) {
String tmp = doc.getItemValueString("systemMessageEN");
if(!"".equals(tmp)) {
this.systemMessageEN = tmp;
}
}
if(doc.hasItem("defaultLang")) {
String tmp = doc.getItemValueString("defaultLang");
if(!"".equals(tmp)) {
this.defaultLang = tmp;
}
}
if(doc.hasItem("defaultProv")) {
String tmp = doc.getItemValueString("defaultProv");
if(!"".equals(tmp)) {
this.defaultProv = tmp;
}
}
if(doc.hasItem("showProv")) {
String tmp = doc.getItemValueString("showProv");
if(!"".equals(tmp)) {
this.showProv = tmp;
}
}
if(doc.hasItem("senderEmail")) {
String tmp = doc.getItemValueString("senderEmail");
if(!"".equals(tmp)) {
this.senderEmail = tmp;
}
}
if(doc.hasItem("senderName")) {
String tmp = doc.getItemValueString("senderName");
if(!"".equals(tmp)) {
this.senderName = tmp;
}
}
if(doc.hasItem("appURL")) {
String tmp = doc.getItemValueString("appURL");
if(!"".equals(tmp)) {
this.appURL = tmp;
}
}
if(doc.hasItem("emailText")) {
String tmp = doc.getItemValueString("emailText");
if(!"".equals(tmp)) {
this.emailText = tmp;
}
}
if(doc.hasItem("clickLinkText")) {
String tmp = doc.getItemValueString("clickLinkText");
if(!"".equals(tmp)) {
this.clickLinkText = tmp;
}
}
if(doc.hasItem("emailFooter")) {
String tmp = doc.getItemValueString("emailFooter");
if(!"".equals(tmp)) {
this.emailFooter = tmp;
}
}
if(doc.hasItem("messageIntro")) {
String tmp = doc.getItemValueString("messageIntro");
if(!"".equals(tmp)) {
this.messageIntro = tmp;
}
}
//allowRatingModification
if(doc.hasItem("allowRatingModification")) {
String tmp = doc.getItemValueString("allowRatingModification");
if(!"".equals(tmp)) {
this.allowRatingModification = tmp;
}
}
}
} catch (NotesException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*****************************************************************************/
public int getNbWidgetFavorites() {
return nbWidgetFavorites;
}
public void setNbWidgetFavorites(int nbWidgetFavorites) {
this.nbWidgetFavorites = nbWidgetFavorites;
}
public int getNbWidgetMostPopular() {
return nbWidgetMostPopular;
}
public void setNbWidgetMostPopular(int nbWidgetMostPopular) {
this.nbWidgetMostPopular = nbWidgetMostPopular;
}
public int getNbWidgetToolbox() {
return nbWidgetToolbox;
}
public void setNbWidgetToolbox(int nbWidgetToolbox) {
this.nbWidgetToolbox = nbWidgetToolbox;
}
public void setNbWhatsNew(int nbWhatsNew) {
this.nbWhatsNew = nbWhatsNew;
}
public int getNbWhatsNew() {
return nbWhatsNew;
}
public void setShowDetailsWhatsNew(String showDetailsWhatsNew) {
this.showDetailsWhatsNew = showDetailsWhatsNew;
}
public String getShowDetailsWhatsNew() {
return showDetailsWhatsNew;
}
public int getNbSearchResults() {
return nbSearchResults;
}
public void setNbSearchResults(int nbSearchResults) {
this.nbSearchResults = nbSearchResults;
}
public int getNbMaxSearchResults() {
return nbMaxSearchResults;
}
public void setNbMaxSearchResults(int nbMaxSearchResults) {
this.nbMaxSearchResults = nbMaxSearchResults;
}
public String getHomePageUNID_FR() {
return homePageUNID_FR;
}
public void setHomePageUNID_FR(String homePageUNID_FR) {
this.homePageUNID_FR = homePageUNID_FR;
}
public String getHomePageUNID_EN() {
return homePageUNID_EN;
}
public void setHomePageUNID_EN(String homePageUNID_EN) {
this.homePageUNID_EN = homePageUNID_EN;
}
public String getAppEmailAddress() {
return appEmailAddress;
}
public void setAppEmailAddress(String appEmailAddress) {
this.appEmailAddress = appEmailAddress;
}
public String getSystemMessageFR() {
return systemMessageFR;
}
public void setSystemMessageFR(String systemMessageFR) {
this.systemMessageFR = systemMessageFR;
}
public String getSystemMessageEN() {
return systemMessageEN;
}
public void setSystemMessageEN(String systemMessageEN) {
this.systemMessageEN = systemMessageEN;
}
public void setStatsDB(String statsDB) {
this.statsDB = statsDB;
}
public String getStatsDB() {
return statsDB;
}
public void setDefaultLang(String defaultLang) {
this.defaultLang = defaultLang;
}
public String getDefaultProv() {
return defaultProv;
}
public void setDefaultProv(String defaultPRov) {
this.defaultProv = defaultPRov;
}
public void setShowProv(String showProv) {
this.showProv = showProv;
}
public String getShowProv() {
return showProv;
}
public String getDefaultLang() {
return defaultLang;
}
public String getMessageIntro() {
return messageIntro;
}
public void setMessageIntro(String messageIntro) {
this.messageIntro = messageIntro;
}
public String getSenderEmail() {
return senderEmail;
}
public void setSenderEmail(String senderEmail) {
this.senderEmail = senderEmail;
}
public String getSenderName() {
return senderName;
}
public void setSenderName(String senderName) {
this.senderName = senderName;
}
public String getAppURL() {
return appURL;
}
public void setAppURL(String appURL) {
this.appURL = appURL;
}
public String getEmailText() {
return emailText;
}
public void setEmailText(String emailText) {
this.emailText = emailText;
}
public String getClickLinkText() {
return clickLinkText;
}
public void setClickLinkText(String clickLinkText) {
this.clickLinkText = clickLinkText;
}
public String getEmailFooter() {
return emailFooter;
}
public void setEmailFooter(String emailFooter) {
this.emailFooter = emailFooter;
}
//allowRatingModification
public String getAllowRatingModification() {
return allowRatingModification;
}
public void setAllowRatingModification(String allowRatingModification) {
this.allowRatingModification = allowRatingModification;
}
}

The VariableResolver goes through all implicit variables (e.g. session, database) as well as scoped variables (e.g. applicationScope.myVar). Your bean is also accessed from SSJS via the VariableResolver.
So you can use:
ExtLibUtil.resolveVariable(FacesContext.getCurrentInstance(), "myAppScopeBean");

This is not a direct answer to your question...
An alternative would be to set the value you want in applicationScope and then access it this way from your bean. To access the entire bean directly is a different answer.
You use this code get a handle to your applicationScope.
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
Map<String, Object> applicationScope = externalContext.getApplicationMap();
Then to use this you have code like this:
String agentLogDB = (String) applicationScope.get("LOGDB");

Related

Hazelcast Predicate SQL into map

I'm trying to build a method that deletes entries with attributes that are not null, but I keep failing in predicates and I don't know how to implement properly the predicate because hazelcast doesn't take "NOT NULL" or "IS NULL" as a where clause Any idea how can I find into the map the values I need to search to delete them?
the method
public int removeEntry(String CacheName, String claveReq, int id_interno_pe, String cod_nrbe_en, int num_sec_ac) {
int counter = 0;
IMap<String, ResponseSerializablePlus> map = clientInstance.getMap(CacheName);
// Predicate claveReqQuery = Predicates.equal("claveReq", claveReq);
// Predicate idInternoQuery = Predicates.equal("id_interno_pe", id_interno_pe);
// Predicate codNrbeQuery = Predicates.equal("cod_nrbe_en", cod_nrbe_en);
// Predicate numSecQuery = Predicates.equal("num_sec_ac", num_sec_ac);
// Predicate query = Predicates.and(idInternoQuery,codNrbeQuery,numSecQuery);
Predicate query = Predicates.sql("id_interno_pe IS NOT NULL");
if (!map.isEmpty()) {
for (ResponseSerializablePlus entry : map.values(query)) {
System.out.println("Entry "+entry.toString()+" Found");
map.delete(entry);
counter++;
}
System.out.println("Map Size ->"+map.size());
System.out.println("Deleted entries -> "+counter);
return counter;
}else {
System.out.println("No matches");
return 0;
}
}
the main class ResponseSerializablePlus
public class ResponseSerializablePlus implements IdentifiedDataSerializable{
private int id_interno_pe;
private String cod_nrbe_en;
private int num_sec_ac;
private int statusCode;
private HashMap<String,List<String>> headers;
private byte[] content;
public ResponseSerializablePlus(int id_interno_pe, String cod_nrbe_en, int num_sec_ac, int statusCode,
HashMap<String, List<String>> headers, byte[] content) {
this.id_interno_pe = id_interno_pe;
this.cod_nrbe_en = cod_nrbe_en;
this.num_sec_ac = num_sec_ac;
this.statusCode = statusCode;
this.headers = headers;
this.content = content;
}
public ResponseSerializablePlus() {
}
public void writeData(ObjectDataOutput out) throws IOException {
out.writeInt(id_interno_pe);
out.writeString(cod_nrbe_en);
out.writeInt(num_sec_ac);
out.writeInt(statusCode);
out.writeObject(headers);
out.writeByteArray(content);
}
public void readData(ObjectDataInput in) throws IOException {
this.id_interno_pe = in.readInt();
this.cod_nrbe_en = in.readString();
this.num_sec_ac = in.readInt();
this.statusCode = in.readInt();
this.headers = in.readObject();
this.content = in.readByteArray();
}
public int getFactoryId() {
return ResponseSerializablePlusFactory.FACTORY_ID;
}
public int getClassId() {
return ResponseSerializablePlusFactory.RESPONSE_SERIALIZABLE_PLUS_CLASS;
}
#Override
public String toString() {
return "ResponseSerializablePlus [id_interno_pe=" + id_interno_pe + ", cod_nrbe_en=" + cod_nrbe_en
+ ", num_sec_ac=" + num_sec_ac + ", statusCode=" + statusCode + ", headers=" + headers + ", content="
+ Arrays.toString(content) + "]";
}
}
It's indeed not supported, and it's document, along with the alternative option. Have a look here: https://github.com/hazelcast/hazelcast/blob/3cb8ce1fc3bb848aced6c87a30bf7b31aec16cf7/hazelcast/src/main/java/com/hazelcast/query/Predicates.java#L492-L497

Get posted file over HTTP Listener in c#

I have make a simple http server using c#. And I know how to get posted data and output them. Here is my c# code
public static void start(){
HttpListener listener = new HttpListener();
listener.Prefixes.Add(new Uri("http://localhost:8080").ToString());
istener.Start();
while(true){
HttpListenerContext con = listener.GetContext();
showPostedData(con.Request);
con.Response.StatusCode = (int)HttpStatusCode.NotFound;
string data = "Uploaded successful";
byte[] output = Encoding.ASCII.GetBytes(data);
con.Response.ContentType = "text/html";
con.Response.ContentLength64 = output.Length;
con.Response.OutputStream.Write(output , 0, output.Length );
}
}
public static void showPostedData(HttpListenerRequest request){
if (!request.HasEntityBody)
{
return;
}
System.IO.Stream body = request.InputStream;
System.Text.Encoding encoding = request.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
string text;
if (request.ContentType != null)
{
text = reader.ReadToEnd();
}
Console.WriteLine( text );
}
My client html form has input box named file: <input type="file" name"file">
In the console output is like that :
file='Path of Choosed file not a file'
So How i get POSTED files and copy them to upload directory..?
Sorry for my english and thanks in advance...
public static void start(){
HttpListener listener = new HttpListener();
listener.Prefixes.Add(new Uri("http://localhost:80").ToString());
istener.Start();
while(true){
HttpListenerContext con = listener.GetContext();
var values = new HttpNameValueCollection(ref con);
try
{
Console.WriteLine(values.Files["file"].FileName);
File.WriteAllText(values.Files["file"].FileName, values.Files["file"].FileData, Encoding.Default);
}
catch (Exception tr)
{
}
}
}
class HTTPFormData
{
public class File
{
private string _fileName;
public string FileName { get { return _fileName ?? (_fileName = ""); } set { _fileName = value; } }
private string _fileData;
public string FileData { get { return _fileData ?? (_fileName = ""); } set { _fileData = value; } }
private string _contentType;
public string ContentType { get { return _contentType ?? (_contentType = ""); } set { _contentType = value; } }
}
private NameValueCollection _post;
private Dictionary<string, File> _files;
private readonly HttpListenerContext _ctx;
public NameValueCollection Post { get { return _post ?? (_post = new NameValueCollection()); } set { _post = value; } }
public NameValueCollection Get { get { return _ctx.Request.QueryString; } }
public Dictionary<string, File> Files { get { return _files ?? (_files = new Dictionary<string, File>()); } set { _files = value; } }
private void PopulatePostMultiPart(string post_string)
{
var boundary_index = _ctx.Request.ContentType.IndexOf("boundary=") + 9;
var boundary = _ctx.Request.ContentType.Substring(boundary_index, _ctx.Request.ContentType.Length - boundary_index);
var upper_bound = post_string.Length - 4;
if (post_string.Substring(2, boundary.Length) != boundary)
throw (new InvalidDataException());
var current_string = new StringBuilder();
for (var x = 4 + boundary.Length; x < upper_bound; ++x)
{
if (post_string.Substring(x, boundary.Length) == boundary)
{
x += boundary.Length + 1;
var post_variable_string = current_string.Remove(current_string.Length - 4, 4).ToString();
var end_of_header = post_variable_string.IndexOf("\r\n\r\n");
if (end_of_header == -1) throw (new InvalidDataException());
var filename_index = post_variable_string.IndexOf("filename=\"", 0, end_of_header);
var filename_starts = filename_index + 10;
var content_type_starts = post_variable_string.IndexOf("Content-Type: ", 0, end_of_header) + 14;
var name_starts = post_variable_string.IndexOf("name=\"") + 6;
var data_starts = end_of_header + 4;
if (filename_index != -1)
{
var filename = post_variable_string.Substring(filename_starts, post_variable_string.IndexOf("\"", filename_starts) - filename_starts);
var content_type = post_variable_string.Substring(content_type_starts, post_variable_string.IndexOf("\r\n", content_type_starts) - content_type_starts);
var file_data = post_variable_string.Substring(data_starts, post_variable_string.Length - data_starts);
var name = post_variable_string.Substring(name_starts, post_variable_string.IndexOf("\"", name_starts) - name_starts);
Files.Add(name, new File() { FileName = filename, ContentType = content_type, FileData = file_data });
}
else
{
var name = post_variable_string.Substring(name_starts, post_variable_string.IndexOf("\"", name_starts) - name_starts);
var value = post_variable_string.Substring(data_starts, post_variable_string.Length - data_starts);
Post.Add(name, value);
}
current_string.Clear();
continue;
}
current_string.Append(post_string[x]);
}
}
private void PopulatePost()
{
if (_ctx.Request.HttpMethod != "POST" || _ctx.Request.ContentType == null) return;
var post_string = new StreamReader(_ctx.Request.InputStream, _ctx.Request.ContentEncoding).ReadToEnd();
if (_ctx.Request.ContentType.StartsWith("multipart/form-data"))
PopulatePostMultiPart(post_string);
}
public HTTPFormData(ref HttpListenerContext ctx)
{
_ctx = ctx;
PopulatePost();
}
}

how to generate sequence number using c# in window application

private string GenerateID()
{
}
private void auto()
{
AdmissionNo.Text = "A-" + GenerateID();
}
with prefix of A like below
A-0001
A-0002 and so on .
You can use below code.
private string GenerateId()
{
int lastAddedId = 8; // get this value from database
string demo = Convert.ToString(lastAddedId + 1).PadLeft(4, '0');
return demo;
// it will return 0009
}
private void Auto()
{
AdmissionNo.Text = "A-" + GenerateId();
// here it will set the text as "A-0009"
}
Look at this
public class Program
{
private static int _globalSequence;
static void Main(string[] args)
{
_globalSequence = 0;
for (int i = 0; i < 10; i++)
{
Randomize(i);
Console.WriteLine("----------------------------------------->");
}
Console.ReadLine();
}
static void Randomize(int seed)
{
Random r = new Random();
if (_globalSequence == 0) _globalSequence = r.Next();
Console.WriteLine("Random: {0}", _globalSequence);
int localSequence = Interlocked.Increment(ref _globalSequence);
Console.WriteLine("Increment: {0}, Output: {1}", _globalSequence, localSequence);
}
}
Whether it is an windows application or not is IMHO not relevant. I'd rather care about thread safety. Hence, I would use something like this:
public sealed class Sequence
{
private int value = 0;
public Sequence(string prefix)
{
this.Prefix = prefix;
}
public string Prefix { get; }
public int GetNextValue()
{
return System.Threading.Interlocked.Increment(ref this.value);
}
public string GetNextNumber()
{
return $"{this.Prefix}{this.GetNextValue():0000}";
}
}
This could easily be enhanced to use the a digit count. So the "0000" part could be dynamically specified as well.

Blackberry - How if addElement() doesn't work?

I am a newbie of Blackberry developing application. I try to store all xml parsing data to an object, and set them to a vector.
public class XmlParser extends MainScreen {
Database d;
private HttpConnection hcon = null;
private Vector binN;
public Vector getBinN() {
return binN;
}
public void setBinN(Vector bin) {
this.binN = bin;
}
LabelField from;
LabelField ttl;
LabelField desc;
LabelField date;
public XmlParser() {
LabelField title = new LabelField("Headline News" ,LabelField.HCENTER|LabelField.USE_ALL_WIDTH);
setTitle(title);
try {
URI myURI = URI.create("file:///SDCard/Database/WebFeed.db");
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement("SELECT feed_url, feed_name FROM WebFeed");
st.prepare();
Cursor c = st.getCursor();
while (c.next()) {
Row r = c.getRow();
hcon = (HttpConnection)Connector.open(r.getString(0));
hcon.setRequestMethod(HttpConnection.GET);
hcon.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
hcon.setRequestProperty("Content-Length", "0");
hcon.setRequestProperty("Connection", "close");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.isValidating();
Document document = builder.parse(hcon.openInputStream());
Element rootElement = document.getDocumentElement();
rootElement.normalize();
NodeList list = document.getElementsByTagName("item");
int i=0;
while (i<10){
Node item = list.item(i);
if(item.getNodeType() != Node.TEXT_NODE) {
NodeList itemChilds = item.getChildNodes();
int j=0;
while (j<10){
Node detailNode = itemChilds.item(j);
if(detailNode.getNodeType() != Node.TEXT_NODE) {
if(detailNode.getNodeName().equalsIgnoreCase("title")) {
ttl = new LabelField(getNodeValue(detailNode)) {
public void paint(Graphics g) {
g.setColor(Color.BLUE);
super.paint(g);
}
};
from = new LabelField(r.getString(1), LabelField.FIELD_RIGHT|LabelField.USE_ALL_WIDTH);
ttl.setFont(Font.getDefault().derive(Font.BOLD));
from.setFont(Font.getDefault().derive(Font.BOLD));
add (from);
add (ttl);
} else if(detailNode.getNodeName().equalsIgnoreCase("description")) {
desc = new LabelField(getNodeValue(detailNode), 0, 70, USE_ALL_WIDTH);
add(desc);
} else if(detailNode.getNodeName().equalsIgnoreCase("dc:date")) {
date = new LabelField(getNodeValue(detailNode), 11, 5, USE_ALL_WIDTH) {
public void paint(Graphics g) {
g.setColor(Color.ORANGE);
super.paint(g);
}
};
add(date);
add(new SeparatorField());
} else if(detailNode.getNodeName().equalsIgnoreCase("pubDate")) {
date = new LabelField(getNodeValue(detailNode), 0, 22, USE_ALL_WIDTH) {
public void paint(Graphics g) {
g.setColor(Color.ORANGE);
super.paint(g);
}
};
add(date);
add(new SeparatorField());
} else {
System.out.println("not the node");
}
} else {
System.out.println("not text node");
}
j++;
}
}
i++;
BinNews bin = new BinNews();
bin.setProv(from.getText());
bin.setTitle(ttl.getText());
bin.setDesc(desc.getText());
bin.setDate(date.getText());
binN.addElement(bin);
}
setBinN(binN);
}
//setBinN(binN);
st.close();
d.close();
} catch (Exception e) {
add (new LabelField(e.toString(),LabelField.HCENTER|LabelField.USE_ALL_WIDTH));
System.out.println(e.toString());
}
}
public String getNodeValue(Node node) {
NodeList nodeList = node.getChildNodes();
Node childNode = nodeList.item(0);
return childNode.getNodeValue();
}
}
I try to store all data from an object called BinNews, to a vector called binN. But when I do debugging, I found that BinN has null value, because "binN.addElement(bin)" doesn't work.
Please advise.
First, you don't actually call setBinN until after the while(i < 10) loop completes. So when you say binN.addElement(bin) then binN will be null.
However your setBinN(binN) call doesn't make sense because you're passing in binN and then setting it to itself which isn't going to do anything.
What you can do is have binN = new Vector(); at the top of the constructor and then it won't be null later on. I don't think the setBinN call will be necessary later on if you're adding the BinNews objects straight to binN.

How to sort search dictionary result based on frequency in j2me

This is my dictionary format:
word Frequency
Gone 60
Goes 10
Go 30
So far the system returns words eg starting with 'g' as go30, goes10, gone60 as a list.
(alphabetically). I want to increase the accuracy of the system so that the search result is based on frequency. Words with high frequencies appear first. kindly help.
Here is the Text midlet class that reads the dictionary line by line.
public class Text extends MIDlet {
// Fields
private static final String[] DEFAULT_KEY_CODES = {
// 1
".,?!'\"1-()#/:_",
// 2
"ABC2",
// 3
"DEF3",
// 4
"GHI4",
// 5
"JKL5",
// 6
"MNO6",
// 7
"PQRS7",
// 8
"TUV8",
// 9
"WXYZ9",
};
//Initializing inner Classes
public ComposeText() {
cmdHandler = new CommandHandler();
lineVector = new Vector();
}
//Calling All InitMethods, setting Theme, Show MainForm
public void startApp() {
Display.init(this);
setTheme();
initCmd();
initMainGui();
mainFrm.show();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
//Initializing all the Commands
public void initCmd() {
exitCmd = new Command("Exit");
selectCmd = new Command("Ok");
cancelCmd = new Command("Cancel");
predCmd = new Command("Prediction");
sendCmd = new Command("Send");
tfPredArea = new TextField();
//check dictionary
try {
readFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
//Initiating MainScreen
public void initMainGui() {
mainFrm = new Form("Compose Text");
mainFrm.setLayout(new BorderLayout());
mainFrm.setLayout(new CoordinateLayout(150, 150));
mainFrm.addCommand(exitCmd);
mainFrm.addCommand(predCmd);
mainFrm.addCommand(sendCmd);
mainFrm.addCommandListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == predCmd){
initPredGui();
} else if(ae.getSource() == exitCmd){
destroyApp(true);
notifyDestroyed();
}
}
});
// To : 07xxxxxxxxxx
Dimension d1 = new Dimension(130, 20);
lbTo = new Label("To:");
lbTo.setX(10);
lbTo.setY(10);
tfTo = new TextField();
tfTo.setReplaceMenu(false);
tfTo.setConstraint(TextField.NUMERIC);
tfTo.setInputModeOrder(new String[]{"123"});
tfTo.setMaxSize(13);
tfTo.setX(40);
tfTo.setY(10);
tfTo.setPreferredSize(d1);
//Message : Compose Text
Dimension d2 = new Dimension(135, 135);
lbSms = new Label("Message:");
lbSms.setX(5);
lbSms.setY(40);
tfSms = new TextField();
tfSms.setReplaceMenu(false);
tfSms.setX(40);
tfSms.setY(40);
tfSms.setPreferredSize(d2);
//add stuff
mainFrm.addComponent(lbTo);
mainFrm.addComponent(lbSms);
mainFrm.addComponent(tfTo);
mainFrm.addComponent(tfSms);
}
//Initiating FilterSelection Screen
public void initPredGui() {
predForm = new Form("Prediction on");
predForm.setLayout(new CoordinateLayout(150, 150));
predForm.addCommand(cancelCmd);
predForm.addCommand(selectCmd);
//textfied in prediction form
final Dimension d5 = new Dimension(200, 200);
tfPredArea = new TextField();
tfPredArea.setReplaceMenu(false);
tfPredArea.setX(10);
tfPredArea.setY(10);
tfPredArea.setPreferredSize(d5);
predForm.addComponent(tfPredArea);
final ListModel underlyingModel = new DefaultListModel(lineVector);
// final ListModel underlyingModel = new
DefaultListModel(tree.getAllPrefixMatches(avail));
// this is a list model that can narrow down the underlying model
final SortListModel proxyModel = new SortListModel(underlyingModel);
final List suggestion = new List(proxyModel);
tfPredArea.addDataChangeListener(new DataChangedListener() {
public void dataChanged(int type, int index) {
int len = 0;
int i = 0;
String input = tfPredArea.getText();
len = tfPredArea.getText().length();
//ensure start search character is set for each word
if (!(len == 0)) {
for (i = 0; i < len; i++) {
if (input.charAt(i) == ' ') {
k = i;
}
}
String currentInput = input.substring(k + 1, len);
proxyModel.filter(currentInput);
}
}
});
Dimension d3 = new Dimension(110, 120);
suggestion.setX(80);
suggestion.setY(80);
suggestion.setPreferredSize(d3);
predForm.addComponent(suggestion);
suggestion.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String string = suggestion.getSelectedItem().toString();
if (tfPredArea.getText().charAt(0) == 0) {
tfPredArea.setText(string);
}
else if (tfPredArea.getText().length() == 0) {
tfPredArea.setText(string);
} else {
tfPredArea.setText(tfPredArea.getText() + string);
}
}
});
predForm.addCommandListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == addCmd) {
newDictionaryFrm.show();
} else {
mainFrm.show();
}
}
});
predForm.show();
}
//Setting Theme for All Forms
public void setTheme() {
try {
Resources r = Resources.open("/theme.res");
UIManager.getInstance().setThemeProps(r.getTheme(
r.getThemeResourceNames()[0]));
} catch (java.io.IOException e) {
System.err.println("Couldn't load the theme");
}
}
//Inner class CommandHandler
public class CommandHandler implements ActionListener {
public void actionPerformed(ActionEvent ae) {
//cancelCommand from predictionForm
if (ae.getSource() == cancelCmd) {
if (edit) {
mainFrm.show();
// clearFields();
} else if (ae.getSource() == selectCmd){
tfPredList.addDataChangeListener(model);
predForm.show();
}
else{}
}
}
}
// method that reads dictionary line by line
public void readFile() throws IOException {
tree = new Trie();
InputStreamReader reader = new InputStreamReader(
getClass().getResourceAsStream("/Maa Corpus.txt-01-ngrams-Alpha.txt"));
String line = null;
// Read a single line from the file. null represents the EOF.
while ((line = readLine(reader)) != null) {
// Append to a vector to be used as a list
lineVector.addElement(line);
}
}
public String readLine(InputStreamReader reader) throws IOException {
// Test whether the end of file has been reached. If so, return null.
int readChar = reader.read();
if (readChar == -1) {
return null;
}
StringBuffer string = new StringBuffer("");
// Read until end of file or new line
while (readChar != -1 && readChar != '\n') {
// Append the read character to the string.
// This is part of the newline character
if (readChar != '\r') {
string.append((char) readChar);
}
// Read the next character
readChar = reader.read();
}
return string.toString();
}
}
}
The SortListModel Class has a filter method that gets prefix from the textfield datachangeLister
class SortListModel implements ListModel, DataChangedListener {
private ListModel underlying;
private Vector filter;
private Vector listeners = new Vector();
public SortListModel(ListModel underlying) {
this.underlying = underlying;
underlying.addDataChangedListener(this);
}
private int getFilterOffset(int index) {
if(filter == null) {
return index;
}
if(filter.size() > index) {
return ((Integer)filter.elementAt(index)).intValue();
}
return -1;
}
private int getUnderlyingOffset(int index) {
if(filter == null) {
return index;
}
return filter.indexOf(new Integer(index));
}
public void filter(String str) {
filter = new Vector();
str = str.toUpperCase();
for(int iter = 0 ; iter < underlying.getSize() ; iter++) {
String element = (String)underlying.getItemAt(iter);
if(element.toUpperCase().startsWith(str)) // suggest only if smthing
{
filter.addElement(new Integer(iter));
}
}
dataChanged(DataChangedListener.CHANGED, -1);
}
public Object getItemAt(int index) {
return underlying.getItemAt(getFilterOffset(index));
}
public int getSize() {
if(filter == null) {
return underlying.getSize();
}
return filter.size();
}
public int getSelectedIndex() {
return Math.max(0, getUnderlyingOffset(underlying.getSelectedIndex()));
}
public void setSelectedIndex(int index) {
underlying.setSelectedIndex(getFilterOffset(index));
}
public void addDataChangedListener(DataChangedListener l) {
listeners.addElement(l);
}
public void removeDataChangedListener(DataChangedListener l) {
listeners.removeElement(l);
}
public void addSelectionListener(SelectionListener l) {
underlying.addSelectionListener(l);
}
public void removeSelectionListener(SelectionListener l) {
underlying.removeSelectionListener(l);
}
public void addItem(Object item) {
underlying.addItem(item);
}
public void removeItem(int index) {
underlying.removeItem(index);
}
public void dataChanged(int type, int index) {
if(index > -1) {
index = getUnderlyingOffset(index);
if(index < 0) {
return;
}
}
for(int iter = 0 ; iter < listeners.size() ; iter++) {
((DataChangedListener)listeners.elementAt(iter)).dataChanged(type, index);
}
}
}

Resources