J2ME Login and Search Record Store - search

I'm new to J2ME and I'm taking a class where we use it. I created a simple travel reservation MIDlet using choice groups text fields etc. I then added a Record Store to capture this information. I now have a user login that only requires a user name, but i don't know how to verify that the user name is in the Record Store, so instead I accept any one as long as the Textfield for the user name is not empty. My first question is how would I verify that the user exist, I already can create an account. The second question is how can I search a record store not by id but say using a string within a certain range for each row of the Record store.
Here is my code so far:
$import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.util.Date;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.*;
/**
* #author XayBlu
*/
public class tripMe extends MIDlet implements CommandListener {
Form startForm, airForm, trainForm, cruiseForm, autoForm, Ext, Pass,home,login, create;
Command Exit, Trip, Cinfo, AutC,AiC,CrC, info,Tme,trainC, logC,signC, createC, prev, newTrip, Home;
ChoiceGroup trans,hCAP, passCNT,airT,airC,AuC,AuT,CrL,CcabT,Tseat,TOP;
Display Xdisplay;
TextField Eneed, uName, uName2;
Alert Final, FinalT, Sucess, nope;
DateField dDate, rDate;
Date d,r;
Image [] image;
String details =" ",tt="", Trav, Rdate, Ddate, extraA, Pcount,specialA, TT,AIR2, AIR,AUTO,AUTO2,CRUISE,CRUISE2,TRAIN,TRAIN2, USERS="USERS";
String op[] = {"Air","Auto","Cruise","Train"}; //Array Items for Choice Groups
String ep[] = {"Wheel Chair","Baby Seat","Extended Seatbelt","Extra Pillows","Oxygen Tank","GPS"};
String count[] = {"1","2","3","4","5","6","7","8"};
String AL []= {"American Airlines","Delta","US Airways","South West Airlines","United Airlines"};
String Rental [] = {"Alamo","Avis","Budget","Enteprise","Dollar","Hertz"};
String CL [] = {"Carnival","Norwegian","Royal Caribbean","Celebrity X","MSC"};
String CT [] = {"Compact","Standard","Full","SUV","Luxury","Sports"};
String Cabin [] = {"Suite","Ocean Balcony","Standard","Economy"};
String tCAB[] = {"Standard Seat","Sleeper Cart"};
String Toptions[] ={"Extra Luggage room","Salad Buffet","Wifi Access","Extra Blanket"};
RecordStore usr,itt;
RecordEnumeration recEnum = null;
RecordFilter filter = null;
int Umax=5;
int tran1 =6;
String last;
Byte [] data = new Byte[Umax];
/* NEW COMMANDS FOR FLEXIBLE USER INPUT TO RECORD STORES */
public void writeRecord(String str){ // User to insert user input to record stores
byte[] rec = str.getBytes();
try{
usr.addRecord(rec, 0, rec.length);
}catch (Exception e){}
}
public void writeInfo(String str){ // User to insert user input to record stores
byte[] rec = str.getBytes();
try{
usr.addRecord(rec, tran1, rec.length);
}catch (Exception e){}
}
public void updateRecord(String str){
try{
usr.setRecord(1, str.getBytes(), 0, str.length());
}catch (Exception e){}
}
public void deleteRecord(){
try{
usr.deleteRecord(1);
}catch (Exception e){}
}
public void closeRecord(){
try{
usr.closeRecordStore();
}catch (Exception e){}
}
public void deleteRecStore(){
if (RecordStore.listRecordStores() != null){
try{
RecordStore.deleteRecordStore(USERS);
}catch (Exception e){}
}
}
public void openRecStore()
{
try
{
// The second parameter indicates that the record store
// should be created if it does not exist
usr = RecordStore.openRecordStore(USERS, true );
}
catch (Exception e)
{
System.out.print("Could not open record store");
}
}
public void readRecords()
{
try
{
// Intentionally make this too small to test code below
byte[] recData = new byte[5];
int len;
for (int i = 1; i <= usr.getNumRecords(); i++)
{
if (usr.getRecordSize(i) > recData.length)
recData = new byte[usr.getRecordSize(i)];
len = usr.getRecord(i, recData, 0);
home.append(new String(recData,0,len));
// System.out.println("Record #" + i + ": " + new String(recData, 0, len));
// System.out.println("------------------------------");
}
}
catch (Exception e)
{
nope = new Alert("Sorry no match!",null,null,AlertType.INFO);
nope.setTimeout(Alert.FOREVER); //Append string for FinalT Alert
Xdisplay.setCurrent(nope, login);
}
}
}
class Filter implements RecordFilter {
private String search = null;
private ByteArrayInputStream inputstream = null;
private DataInputStream datainputstream = null;
public Filter(String search) {
this.search = search.toLowerCase();
}
public void filterClose() {
try {
if (inputstream != null) {
inputstream.close();
}
if (datainputstream != null) {
datainputstream.close();
}
} catch (Exception error) {
}
}
}
public tripMe (){
try{ //Initializing individual images for Choice Group Icons
Image car = Image.createImage("/car2.png");
Image plane = Image.createImage("/plane2.png");
Image train = Image.createImage("/train2.png");
Image cruise = Image.createImage("/cruise2.png");
image = new Image[] {plane,car,cruise,train}; //Initializing Image array for ChoiceGroup
}
catch (java.io.IOException err) {System.out.print("Could not load pics"); } //Throws exception if pic cannot be found
startForm = new Form("Get Away Today"); //Initialization of forms
Pass = new Form ("Passenger Information");
airForm = new Form("Low Prices!");
autoForm = new Form("Find the best car for you");
Ext = new Form("Itinerary Details");
Ext.setTicker(new Ticker("Enjoy Your Vacation"));
cruiseForm = new Form("Sail Away Today");
trainForm = new Form("Chuuu- Chuuu");
login = new Form("Sign up Today");
home = new Form("Welcome Back");
create = new Form("Create an account");
trans = new ChoiceGroup("Select travel type",ChoiceGroup.EXCLUSIVE,op,image); //Transport tation choice group initialized with corresponding string and image array
Exit = new Command("Exit", Command.EXIT,1);//Adding necessary commands
Trip = new Command("Go", Command.SCREEN,2);//Adding go command which allows you to select travel type
signC = new Command("Sign up",Command.SCREEN,2);
logC = new Command("Log in",Command.SCREEN,2);
createC = new Command("OK",Command.SCREEN,2);
prev = new Command("History",Command.SCREEN,2);
newTrip = new Command("Reservations",Command.SCREEN,2);
Home = new Command("Log out",Command.SCREEN,1);
hCAP = new ChoiceGroup("Extra Assistance", ChoiceGroup.MULTIPLE,ep,null);//Passenger Info items
passCNT = new ChoiceGroup("Number of Passengers:",ChoiceGroup.POPUP,count,null);
rDate = new DateField("Return Date",DateField.DATE_TIME);//Could not get the DateField to return string date value
dDate = new DateField("Departure Date",DateField.DATE_TIME);
Eneed = new TextField("Special Needs","",50,TextField.ANY);
uName = new TextField("User Name","",5,TextField.ANY);
uName2 = new TextField("User Name","",5,TextField.ANY);
info = new Command("Next",Command.SCREEN,2);
AiC = new Command("Complete",Command.SCREEN,2);//Air travel option items
airT = new ChoiceGroup("Choose Airline", ChoiceGroup.POPUP,AL,null);//Airline selection
airC = new ChoiceGroup("Select Class",ChoiceGroup.EXCLUSIVE);//Economy or first cass?
airC.append("First Class", null);//Adding elements to Choice Group
airC.append("Economy", null);
AuC = new ChoiceGroup("Choose rental company", ChoiceGroup.POPUP,Rental,null);//Auto travel option items
AuT = new ChoiceGroup("Select Vehicle Type", ChoiceGroup.EXCLUSIVE, CT,null);//Choicegroup for Vehicle type
AutC = new Command("Drive away", Command.SCREEN,2);//Adding drive away command to form
CrL = new ChoiceGroup("Select Cruise Line Comp.", ChoiceGroup.POPUP,CL,null);//Cruise option Items, Cruise line choicegroup
CcabT = new ChoiceGroup("Select Cabin Type", ChoiceGroup.EXCLUSIVE,Cabin,null);//Cabin type choice group
CrC = new Command("Cruise", Command.SCREEN,2);//Cruise form command being added
trainC = new Command("Track!", Command.SCREEN,2);//Train option items, Train form command
Tseat = new ChoiceGroup("Seat Type", ChoiceGroup.EXCLUSIVE,tCAB,null);//Choicegroup for train seat type
TOP = new ChoiceGroup("Extra Options", ChoiceGroup.POPUP,Toptions,null);//Train extra options choice group
/* Appending Items to necessary Forms*/
create.append(uName2);
create.addCommand(createC);
create.setCommandListener(this);
home.addCommand(prev);
home.addCommand(newTrip);
home.setCommandListener(this);
login.append(uName);
login.addCommand(logC);
login.addCommand(signC);
login.setCommandListener(this);
startForm.append(trans);
startForm.addCommand(Exit);
startForm.addCommand(Trip);
startForm.setCommandListener(this);
Pass.append(dDate);
Pass.append(rDate);
Pass.append(hCAP);
Pass.append(passCNT);
Pass.append(Eneed);
Pass.addCommand(info);
Pass.setCommandListener(this);
airForm.append(airT);
airForm.append(airC);
airForm.addCommand(AiC);
airForm.setCommandListener(this);
autoForm.addCommand(AutC);
autoForm.append(AuC);
autoForm.append(AuT);
autoForm.setCommandListener(this);
cruiseForm.addCommand(CrC);
cruiseForm.append(CrL);
cruiseForm.append(CcabT);
cruiseForm.setCommandListener(this);
trainForm.addCommand(trainC);
trainForm.append(Tseat);
trainForm.append(TOP);
trainForm.setCommandListener(this);
Ext.addCommand(Exit);
Ext.addCommand(Home);
Ext.setCommandListener(this);
}
public void startApp() {
Xdisplay= Display.getDisplay(this);
Xdisplay.setCurrent(login);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
public void commandAction(Command c, Displayable displayable){
try {
usr = RecordStore.openRecordStore(USERS, false);
} catch (Exception e) {
Sucess = new Alert("Error","Could not open Record Strore",null,AlertType.INFO);
Sucess.setTimeout(Alert.FOREVER); //Append string for FinalT Alert
Xdisplay.setCurrent(Sucess, login);
}
if(c==signC)
{
Xdisplay.setCurrent(create);
}
else if(c == newTrip)
{
Xdisplay.setCurrent(startForm);
}
else if(c == prev)
{
try {
String record = "";
for (int i = 1; i < usr.getNextRecordID(); i++) {
record = new String(usr.getRecord(i));
}
home.append(record);
} catch (Exception e) {
home.append("Could not retrieve data");
try {
usr.closeRecordStore();
RecordStore.deleteRecordStore(USERS);
} catch (Exception x) {
}
}
try {
usr.closeRecordStore();
} catch (Exception e) {
}
}
else if(c==createC)
{
try {
usr = RecordStore.openRecordStore(USERS, true);
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
if(!"".equals(uName2.getString()))
{
writeRecord(uName2.getString());
}
Sucess = new Alert("Welcome to the mile high club","Hello:"+uName2.getString(),null,AlertType.INFO);
Sucess.setTimeout(Alert.FOREVER); //Append string for FinalT Alert
Xdisplay.setCurrent(Sucess, login);
}
else if (c == logC)
{
if(!"".equals(uName.getString()))
{
String name = uName.getString();
byte[] data = name.getBytes();
Xdisplay.setCurrent(home);
}
else
{
Sucess = new Alert("Please enter user name!","Invalid user name",null,AlertType.INFO);
Sucess.setTimeout(Alert.FOREVER); //Append string for FinalT Alert
Xdisplay.setCurrent(Sucess, login);
}
}
else if(c==Trip)
{
tt +="Travel Mode: "+ trans.getString(trans.getSelectedIndex())+"\n";
if(trans.isSelected(0))
{
TT="A"; //Sets the type of travel based on choicegroup user selection
Xdisplay.setCurrent(Pass);
}
else if(trans.isSelected(1))
{
TT="B";
Xdisplay.setCurrent(Pass);
}
else if(trans.isSelected(2))
{
TT="C";
Xdisplay.setCurrent(Pass);
}
else if(trans.isSelected(3))
{
TT="D";
Xdisplay.setCurrent(Pass);
}
}
else if (c == info)
{
for(int i = 0; i < hCAP.size(); i++) //Checks to see what items are selected in a ChoiceGrou
{
if(hCAP.isSelected(i))
{
details += hCAP.getString(i)+","; //If item is selected then it is appended to the string details
}
}
Rdate = rDate.getDate().toString();
Ddate = dDate.getDate().toString();
tt+= "Departure Date: "+ Ddate.substring(0, 10)+"\n";
tt+= "Return Date: "+ Rdate.substring(0, 10)+"\n";
Pcount = passCNT.getString(passCNT.getSelectedIndex()); //Gets passenger count from choicegroup of integers
specialA = Eneed.getString();
Final = new Alert("Your travel details: \n","Requested Devices:"+details+"\nPassenger Count: "+Pcount+
"\nSpecific Request: "+specialA,null,AlertType.INFO); //Appends string for alert
Final.setTimeout(Alert.FOREVER);
if("A".equals(TT)){ //Directs user to form based on travel type choice
Xdisplay.setCurrent(Final,airForm);
}
else if("B".equals(TT)){//Directs user to form based on travel type choice
Xdisplay.setCurrent(Final, autoForm);
}
else if ("C".equals(TT)){//Directs user to form based on travel type choice
Xdisplay.setCurrent(Final, cruiseForm);
}
else if ("D".equals(TT)){//Directs user to form based on travel type choice
Xdisplay.setCurrent(Final, trainForm);
}
}
else if(c==AiC)
{
AIR = airT.getString(airT.getSelectedIndex());//Retrieves selected item from choicegroup
tt+="Company: "+AIR+"\n";
AIR2 = airC.getString(airC.getSelectedIndex());//Retrieves selected item from choicegroup
FinalT = new Alert("Flight Details: \n","Airline Company:"+AIR+"\nSeat Class: "+AIR2,null,AlertType.INFO);
FinalT.setTimeout(Alert.FOREVER); //Append string for FinalT Alert
Trav ="Customer Details \nRequested Devices:\n"+details+"\n# of Passengers:\n "+Pcount+"\nSpecific customer request:\n "+specialA+
"\nDeparture Date: "+Ddate+"\nReturn Date: "+Rdate;
Ext.append(Trav);
extraA ="Carrier Details\n"+"Airline Carrier: "+AIR+"\nSeat Type: "+AIR2; //Append string for final display of info to user
Ext.append(extraA);
try {
usr = RecordStore.openRecordStore(USERS, true);
} catch (RecordStoreException ex) {
}
writeRecord("\n"+tt);
Xdisplay.setCurrent(FinalT,Ext);
}
else if (c == AutC)
{
AUTO = AuC.getString(AuC.getSelectedIndex());//Retrieves selected item from choicegroup
tt += "Company: "+AUTO+"\n";
AUTO2 = AuT.getString(AuT.getSelectedIndex());//Retrieves selected item from choicegroup
FinalT = new Alert("Auto Details: \n","Car Rental Company:"+AUTO+"\nVehicle Class: "+AUTO2,null,AlertType.INFO);
FinalT.setTimeout(Alert.FOREVER);
Trav ="Customer Details \nRequested Devices:\n"+details+"\n# of Passengers:\n "+Pcount+"\nSpecific customer request:\n "+specialA+
"\nDeparture Date: "+Ddate+"\nReturn Date: "+Rdate;
Ext.append(Trav);
extraA ="Carrier Details\n"+"Rental Company: "+AUTO+"\nVehicle Class: "+AUTO2; //Append string for final display of info to user
Ext.append(extraA);
try {
usr = RecordStore.openRecordStore(USERS, true);
} catch (RecordStoreException ex) {
}
writeRecord("\n"+tt);
Xdisplay.setCurrent(FinalT, Ext);
}
else if (c == CrC)
{
CRUISE = CrL.getString(CrL.getSelectedIndex());
tt += "Company: "+CRUISE+"\n";
CRUISE2 = CcabT.getString(CcabT.getSelectedIndex());
FinalT = new Alert("Cruise Details: \n","Cruise Line Company:"+CRUISE+"\nCabin Type:"+CRUISE2,null,AlertType.INFO);
FinalT.setTimeout(Alert.FOREVER);
Trav ="Customer Details \nRequested Devices:\n"+details+"\n# of Passengers:\n "+Pcount+"\nSpecific customer request:\n "+specialA+
"\nDeparture Date: "+Ddate+"\nReturn Date: "+Rdate;
Ext.append(Trav);
extraA ="Carrier Details\n"+"Cruise Line Company: "+CRUISE+"\nCabin Type: "+CRUISE2; //Append string for final display of info to user
Ext.append(extraA);
try {
usr = RecordStore.openRecordStore(USERS, true);
} catch (RecordStoreException ex) {
}
writeRecord("\n"+tt);
Xdisplay.setCurrent(FinalT, Ext);
}
else if (c == trainC)
{
TRAIN = Tseat.getString(Tseat.getSelectedIndex());
TRAIN2 = TOP.getString(TOP.getSelectedIndex());
FinalT = new Alert("Train Details: \n","Train Seat Type:"+TRAIN+"\nExtra Amenities:"+TRAIN2,null,AlertType.INFO);
FinalT.setTimeout(Alert.FOREVER);
Trav ="Customer Details \nRequested Devices:\n"+details+"\n# of Passengers:\n "+Pcount+"\nSpecific customer request:\n "+specialA+
"\nDeparture Date: "+Ddate+"\nReturn Date: "+Rdate;
Ext.append(Trav);
extraA ="Carrier Details\n"+"Train Seat Type: "+TRAIN+"\nExtra Amenities: "+TRAIN2; //Append string for final display of info to user
Ext.append(extraA);
try {
usr = RecordStore.openRecordStore(USERS, true);
} catch (RecordStoreException ex) {
}
writeRecord("\n"+tt);
Xdisplay.setCurrent(FinalT, Ext);
}
else if(c == Home)
{
home.deleteAll();
Xdisplay.setCurrent(login);
}
else if(c==Exit)
{
destroyApp(false);
notifyDestroyed();
}
}
}

Related

Sending notification to requester when PO is created in Acumatica

I need to be able to send an email to the original requester when a PO is created from a Requisition in Acumatica 6.1.
Per Acumatica, the Notification screen cannot handle this functionality, so I have this code to extend the POOrder Entry graph, which sends an email to the Customer's contact email from the Requisition when a PO is created (along with the RQRequisitionEntryExt trigger):
public class POOrderEntryExt : PXGraphExtension<POOrderEntry>
{
private bool sendEmailNotification = false;
public bool SendEmailNotification
{
get
{
return sendEmailNotification;
}
set
{
sendEmailNotification = value;
}
}
[PXOverride]
public void Persist(Action del)
{
using (var ts = new PXTransactionScope())
{
if (del != null)
{
del();
}
if (SendEmailNotification)
{
bool sent = false;
string sError = "Failed to send E-mail.";
try
{
Notification rowNotification = PXSelect<Notification,
Where<Notification.name, Equal<Required<Notification.name>>>>
.Select(Base, "PurchaseOrderNotification");
if (rowNotification == null)
throw new PXException("Notification Template was not found.");
var order = Base.Document.Current;
var requisition = (RQRequisition)PXSelect<RQRequisition,
Where<RQRequisition.reqNbr, Equal<Current<POOrder.rQReqNbr>>>>
.SelectSingleBound(Base, new object[] { order });
if (requisition.CustomerID != null)
{
var customer = (BAccountR)PXSelectorAttribute.Select<RQRequisition.customerID>(
Base.Caches[typeof(RQRequisition)], requisition);
if (customer != null)
{
var defCustContact = (Contact)PXSelectorAttribute.Select<BAccountR.defContactID>(
Base.Caches[typeof(BAccountR)], customer);
if (String.IsNullOrEmpty(defCustContact.EMail))
throw new PXException("E-mail is not specified for Customer Contact.");
var sender = TemplateNotificationGenerator.Create(order,
rowNotification.NotificationID.Value);
sender.RefNoteID = order.NoteID;
sender.MailAccountId = rowNotification.NFrom.HasValue ?
rowNotification.NFrom.Value :
PX.Data.EP.MailAccountManager.DefaultMailAccountID;
sender.To = defCustContact.EMail;
sent |= sender.Send().Any();
}
}
}
catch (Exception Err)
{
sent = false;
sError = Err.Message;
}
if (!sent)
throw new PXException(sError);
}
ts.Complete();
}
}
}
And this to modify RQRequisitionEntry:
public class RQRequisitionEntryExt : PXGraphExtension<RQRequisitionEntry>
{
public PXAction<RQRequisition> createPOOrder;
[PXButton(ImageKey = PX.Web.UI.Sprite.Main.DataEntry)]
[PXUIField(DisplayName = Messages.CreateOrders)]
public IEnumerable CreatePOOrder(PXAdapter adapter)
{
PXGraph.InstanceCreated.AddHandler<POOrderEntry>((graph) =>
{
graph.GetExtension<POOrderEntryExt>().SendEmailNotification = true;
});
return Base.createPOOrder.Press(adapter);
}
}
In order to send an email to the Requester's (Employee) contact email from the Request, I modified the POOrderEntryExt to pull the information from the Request object and the Employee's Contact email (I left the RQRequisitionEntryExt the same and in place):
public class POOrderEntryExt : PXGraphExtension<POOrderEntry>
{
private bool sendEmailNotification = false;
public bool SendEmailNotification
{
get
{
return sendEmailNotification;
}
set
{
sendEmailNotification = value;
}
}
[PXOverride]
public void Persist(Action del)
{
using (var ts = new PXTransactionScope())
{
if (del != null)
{
del();
}
if (SendEmailNotification)
{
bool sent = false;
string sError = "Failed to send E-mail.";
try
{
Notification rowNotification = PXSelect<Notification,
Where<Notification.name, Equal<Required<Notification.name>>>>
.Select(Base, "PurchaseOrderNotification");
if (rowNotification == null)
throw new PXException("Notification Template was not found.");
var order = Base.Document.Current;
var requisition = (RQRequisition)PXSelect<RQRequisition,
Where<RQRequisition.reqNbr, Equal<Current<POOrder.rQReqNbr>>>>
.SelectSingleBound(Base, new object[] { order });
var request = (RQRequest)PXSelectJoin<RQRequest,
InnerJoin<RQRequisitionContent,
On<RQRequisitionContent.orderNbr, Equal<RQRequest.orderNbr>>>,
Where<RQRequisitionContent.reqNbr, Equal<POOrder.rQReqNbr>>>
.SelectSingleBound(Base, new object[] { order });
if (request.EmployeeID != null)
{
var employee = (BAccountR)PXSelectorAttribute.Select<RQRequest.employeeID>(
Base.Caches[typeof(RQRequest)], request);
if (employee != null)
{
var defEmpContact = (Contact)PXSelectorAttribute.Select<BAccountR.defContactID>(
Base.Caches[typeof(BAccountR)], employee);
if (String.IsNullOrEmpty(defEmpContact.EMail))
throw new PXException("E-mail is not specified for Employee Contact.");
var sender = TemplateNotificationGenerator.Create(order,
rowNotification.NotificationID.Value);
sender.RefNoteID = order.NoteID;
sender.MailAccountId = rowNotification.NFrom.HasValue ?
rowNotification.NFrom.Value :
PX.Data.EP.MailAccountManager.DefaultMailAccountID;
sender.To = defEmpContact.EMail;
sent |= sender.Send().Any();
}
else
throw new PXException("Customer not found.");
}
else
throw new PXException("Request not found.");
}
catch (Exception Err)
{
sent = false;
sError = Err.Message;
}
if (!sent)
throw new PXException(sError);
}
ts.Complete();
}
}
}
I can get the original code to send an email in my development environment, but my modified code only returns the outer "Failed to send E-mail" error.
Can anyone help point me in the right direction to get my modifications to work?
Because in Acumatica there is one-to-many relationship between RQRequisition and RQRequest, I believe the better approach is to loop through all requests linked to the current requisition and compose a list of requester's emails. After that we can go ahead and send emails to all requesters as part of the Create Orders operation:
public class POOrderEntryExt : PXGraphExtension<POOrderEntry>
{
private bool sendEmailNotification = false;
public bool SendEmailNotification
{
get
{
return sendEmailNotification;
}
set
{
sendEmailNotification = value;
}
}
[PXOverride]
public void Persist(Action del)
{
using (var ts = new PXTransactionScope())
{
if (del != null)
{
del();
}
if (SendEmailNotification)
{
bool sent = false;
string sError = "Failed to send E-mail.";
try
{
Notification rowNotification = PXSelect<Notification,
Where<Notification.name, Equal<Required<Notification.name>>>>
.Select(Base, "PONotification");
if (rowNotification == null)
throw new PXException("Notification Template was not found.");
var order = Base.Document.Current;
var emails = new List<string>();
var requests = PXSelectJoinGroupBy<RQRequest,
InnerJoin<RQRequisitionContent,
On<RQRequest.orderNbr,
Equal<RQRequisitionContent.orderNbr>>>,
Where<RQRequisitionContent.reqNbr,
Equal<Required<RQRequisition.reqNbr>>>,
Aggregate<GroupBy<RQRequest.orderNbr>>>
.Select(Base, order.RQReqNbr);
foreach (RQRequest request in requests)
{
if (request.EmployeeID != null)
{
var requestCache = Base.Caches[typeof(RQRequest)];
requestCache.Current = request;
var emplOrCust = (BAccountR)PXSelectorAttribute
.Select<RQRequest.employeeID>(requestCache, request);
if (emplOrCust != null)
{
var defEmpContact = (Contact)PXSelectorAttribute
.Select<BAccountR.defContactID>(
Base.Caches[typeof(BAccountR)], emplOrCust);
if (!String.IsNullOrEmpty(defEmpContact.EMail) &&
!emails.Contains(defEmpContact.EMail))
{
emails.Add(defEmpContact.EMail);
}
}
}
}
foreach (string email in emails)
{
var sender = TemplateNotificationGenerator.Create(order,
rowNotification.NotificationID.Value);
sender.RefNoteID = order.NoteID;
sender.MailAccountId = rowNotification.NFrom.HasValue ?
rowNotification.NFrom.Value :
PX.Data.EP.MailAccountManager.DefaultMailAccountID;
sender.To = email;
sent |= sender.Send().Any();
}
}
catch (Exception Err)
{
sent = false;
sError = Err.Message;
}
if (!sent)
throw new PXException(sError);
}
ts.Complete();
}
}
}

Application in JaveME using RMS

I'm trying write application in Jave ME with RMS. Application stores information about courier's customer.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.DataInputStream;
public class ClientsApp extends MIDlet implements CommandListener {
// controls
private Display screen = null;
private List menu = null;
private Form addClientForm = null;
private Form showClientForm = null;
private RecordStore clients;
private ByteArrayOutputStream stream = null;
private DataOutputStream out = null;
private byte[] dates;
TextField name = null;
TextField surname = null;
TextField email = null;
TextField phone = null;
DateField date = null;
TextField price = null;
TextField description = null;
// comands
private final Command backCommand;
private final Command mainMenuCommand;
private final Command exitCommand;
private final Command addClientCommand;
public ClientsApp() {
// initializating controls and comands
menu = new List("Lista klientów", Choice.IMPLICIT);
backCommand = new Command("Cofnij", Command.BACK, 0);
mainMenuCommand = new Command("Main", Command.SCREEN, 1);
exitCommand = new Command("Koniec", Command.EXIT, 2);
addClientCommand = new Command("Zapisz", Command.OK, 3);
stream = new ByteArrayOutputStream();
out = new DataOutputStream(stream);
menu.append("Dodaj klienta", null);
menu.append("Przegladaj klientow", null);
menu.append("Usun klienta", null);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
screen = Display.getDisplay(this);
screen.setCurrent(menu);
try {
clients = RecordStore.openRecordStore("clients", false, RecordStore.AUTHMODE_PRIVATE, false);
}
catch(RecordStoreException exc) {
}
menu.addCommand(exitCommand);
menu.setCommandListener(this);
}
public void commandAction(Command cmd, Displayable dsp) {
if(cmd.getCommandType() == Command.EXIT) {
try{
destroyApp(false);
notifyDestroyed();
}
catch(Exception exc) {
exc.printStackTrace();
}
}
else if(cmd.getCommandType() == Command.BACK) {
screen.setCurrent(menu);
}
else if(cmd.getCommandType() == Command.OK) {
try {
out.writeUTF(name.getString());
out.writeUTF(surname.getString());
out.writeUTF(email.getString());
out.writeUTF(phone.getString());
out.writeUTF(date.getDate().toString());
out.writeUTF(price.getString());
out.writeUTF(description.getString());
dates = stream.toByteArray();
clients.addRecord(dates, 0, dates.length);
stream.close();
out.close();
clients.closeRecordStore();
}
catch(Exception exc) {
}
}
else {
List option = (List) screen.getCurrent();
switch(option.getSelectedIndex()) {
case 0 : {
addClients();
break;
}
case 1 : {
showClients();
break;
}
case 2 : {
deleteClients();
break;
}
}
}
}
protected void addClients() {
addClientForm = new Form("Dodaj klienta");
name = new TextField("Imię klienta", "", 10, TextField.ANY);
surname = new TextField("Nazwisko klienta", "", 15, TextField.ANY);
email = new TextField("Email klienta", "", 20, TextField.EMAILADDR);
phone = new TextField("Numer telefonu", "", 12, TextField.PHONENUMBER);
date = new DateField("Data dostarczenia", DateField.DATE);
price = new TextField("Do zapłaty", "", 6, TextField.NUMERIC);
description = new TextField("Uwagi", "", 50, TextField.ANY);
addClientForm.append(name);
addClientForm.append(surname);
addClientForm.append(email);
addClientForm.append(phone);
addClientForm.append(date);
addClientForm.append(price);
addClientForm.append(description);
screen.setCurrent(addClientForm);
addClientForm.addCommand(backCommand);
addClientForm.addCommand(addClientCommand);
addClientForm.setCommandListener(this);
}
protected void showClients() {
TextBox info = new TextBox("Klienci", null, 100, 0);
RecordEnumeration iterator = null;
String str = null;
byte[] temp = null;
try {
iterator = clients.enumerateRecords(null, null, false);
while(iterator.hasNextElement()) {
temp = iterator.nextRecord();
}
for(int i = 0; i < temp.length; i++) {
str += (char) temp[i];
}
System.out.println(str);
clients.closeRecordStore();
}
catch(Exception exc) {
}
info.setString(str);
screen.setCurrent(info);
}
}
Write/read information from RecordStore don't work. I don't have any exception throw. Could somebody help me?
PS Sorry for my bad language.
Are you sure you do not get any exception? Catch blocks are empty...
I see several issues:
Shouldn't you open the record store with createIfNecessary (2nd parameter) set to true?
In ShowClients method, you should use DataInputStream to read items from the record (the byte array 'temp'), the loop over temp is strange. And a check for null 'temp' to avoid NPE when the store is empty is missing too.
On OK command, and also in ShowClients, the store is closed, so next time it will fail with RecordStoreNotOpenException I guess.
I would also consider flushing 'out' stream before calling stream.toByteArray(), although in this case (DataOutputStrea/ByteArrayOutputStream) it is nothing but a good practice..

Blackberry - How to consume wcf rest services

Recently i have started working on consuming wcf rest webservices in blackberry.
I have used the below two codes:
1.
URLEncodedPostData postData = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, false);
// passing q’s value and ie’s value
postData.append("UserName", "hsharma#seasiaconsulting.com");
postData.append("Password", "mind#123");
HttpPosst hh=new HttpPosst();
add(new LabelField("1"));
String res=hh.GetResponse("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration",postData);
add(new LabelField("2"));
add(new LabelField(res));
public String GetResponse(String url, URLEncodedPostData data)
{
this._postData = data;
this._url = url;
ConnectionFactory conFactory = new ConnectionFactory();
ConnectionDescriptor conDesc = null;
try
{
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
connectionString = ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// logMessage("Carrier coverage.");
// String carrierUid = getCarrierBIBSUid();
// Has carrier coverage, but not BIBS. So use the carrier's TCP
// network
// logMessage("No Uid");
connectionString = ";deviceside=true";
}
// Check for an MDS connection instead (BlackBerry Enterprise
// Server)
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
// logMessage("MDS coverage found");
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid bugging the
// user
// unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE)
{
// logMessage("There is no available connection.");
}
// In theory, all bases are covered so this shouldn't be reachable.
else {
// logMessage("no other options found, assuming device.");
// connectionString = ";deviceside=true";
}
conDesc = conFactory.getConnection(url + connectionString);
}
catch (Exception e)
{
System.out.println(e.toString() + ":" + e.getMessage());
}
String response = ""; // this variable used for the server response
// if we can get the connection descriptor from ConnectionFactory
if (null != conDesc)
{
try
{
HttpConnection connection = (HttpConnection) conDesc.getConnection();
// set the header property
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("Content-Length",Integer.toString(data.size()));
// body content of
// post data
connection.setRequestProperty("Connection", "close");
// close
// the
// connection
// after
// success
// sending
// request
// and
// receiving
// response
// from
// the
// server
connection.setRequestProperty("Content-Type","application/json");
// we set the
// content of
// this request
// as
// application/x-www-form-urlencoded,
// because the
// post data is
// encoded as
// form-urlencoded(if
// you print the
// post data
// string, it
// will be like
// this ->
// q=remoQte&ie=UTF-8).
// now it is time to write the post data into OutputStream
OutputStream out = connection.openOutputStream();
out.write(data.getBytes());
out.flush();
out.close();
int responseCode = connection.getResponseCode();
// when this
// code is
// called,
// the post
// data
// request
// will be
// send to
// server,
// and after
// that we
// can read
// the
// response
// from the
// server if
// the
// response
// code is
// 200 (HTTP
// OK).
if (responseCode == HttpConnection.HTTP_OK)
{
// read the response from the server, if the response is
// ascii character, you can use this following code,
// otherwise, you must use array of byte instead of String
InputStream in = connection.openInputStream();
StringBuffer buf = new StringBuffer();
int read = -1;
while ((read = in.read()) != -1)
buf.append((char) read);
response = buf.toString();
}
// don’t forget to close the connection
connection.close();
}
catch (Exception e)
{
System.out.println(e.toString() + ":" + e.getMessage());
}
}
return response;
}
public boolean checkResponse(String res)
{
if(!res.equals(""))
{
if(res.charAt(0)=='{')
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
but with this code i am unable to obtain response as what the above wcf web service return
which is({"UserRegistrationResult":[{"OutputCode":"2","OutputDescription":"UserName Already Exists."}]})
Can anybody help me regarding its parsing in blackberry client end.
2.And the another code which i used is:
public class KSoapDemo extends MainScreen
{
private EditField userNametxt;
private PasswordEditField passwordTxt;
private ButtonField loginBtn;
String Username;
String Password;
public KSoapDemo()
{
userNametxt = new EditField("User Name : ", "hsharma#seasiaconsulting.com");
passwordTxt = new PasswordEditField("Password : ", "mind#123");
loginBtn = new ButtonField("Login");
add(userNametxt);
add(passwordTxt);
add(loginBtn);
loginBtn.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
//Dialog.alert("Hi Satyaseshu..!");
login();
}
});
}
private void login()
{
if (userNametxt.getTextLength() == 0 || passwordTxt.getTextLength() == 0)
{
//Dialog.alert("You must enter a username and password", );
}
else
{
String username = userNametxt.getText();
String password = passwordTxt.getText();
System.out.println("UserName... " + username);
System.out.println("Password... " + password);
boolean value = loginPArse1(username, password);
add(new LabelField("value... " + value));
}
}
public boolean onClose()
{
Dialog.alert("ADIOOO!!");
System.exit(0);
return true;
}
public boolean loginPArse1(String username, String password)
{
username=this.Username;
password=this.Password;
boolean ans = false;
String result = null;
SoapObject request = new SoapObject("http://dotnetstg.seasiaconsulting.com/","UserRegistration");
//request.addProperty("PowerValue","1000");
//request.addProperty("fromPowerUnit","kilowatts");
//request.addProperty("toPowerUnit","megawatts");
request.addProperty("userName",Username);
request.addProperty("Password", Password);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = request;
envelope.dotNet = true;
add(new LabelField("value... " + "1"));
HttpTransport ht = new HttpTransport("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration"+ConnectionInfo.getInstance().getConnectionParameters());
ht.debug = true;
add(new LabelField("value... " + "2"));
//System.out.println("connectionType is: " + connectionType);
try {
ht.call("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration", envelope);
SoapObject body = (SoapObject) envelope.bodyIn;
add(new LabelField("soap....="+body.toString()));
add(new LabelField("property count....="+body.getPropertyCount()));
// add(new LabelField("Result....="+body.getProperty("HelloWorldResult")));
//result = body.getProperty("Params").toString();
// add(new LabelField("value... " + "4"));
ans=true;
}
catch (XmlPullParserException ex) {
add(new LabelField("ex1 "+ex.toString()) );
ex.printStackTrace();
} catch (IOException ex) {
add(new LabelField("ex1 "+ex.toString()) );
ex.printStackTrace();
} catch (Exception ex) {
add(new LabelField("ex1 "+ex.toString()) );
ex.printStackTrace();
}
return ans;
}
and in return i am obtain response as net.rim.device.cldc.io.dns.DNS Exception:DNS Error
Please help me in this regard
Thanks And Regards
Pinkesh Gupta
Please have the answer for my own question helps in parsing wcf rest services developed in .net and parsed at blackberry end.
This 2 classess definitely helps in achieving the above code parsing.
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
public class ConnectionThread extends Thread
{
private boolean start = false;
private boolean stop = false;
private String url;
private String data;
public boolean sendResult = false;
public boolean sending = false;
private String requestMode = HttpConnection.POST;
public String responseContent;
int ch;
public void run()
{
while (true)
{
if (start == false && stop == false)
{
try
{
sleep(200);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
else if (stop)
{
return;
}
else if (start)
{
http();
}
}
}
private void getResponseContent( HttpConnection conn ) throws IOException
{
InputStream is = null;
is = conn.openInputStream();
// Get the length and process the data
int len = (int) conn.getLength();
if ( len > 0 )
{
int actual = 0;
int bytesread = 0;
byte[] data = new byte[len];
while ( ( bytesread != len ) && ( actual != -1 ) )
{
actual = is.read( data, bytesread, len - bytesread );
bytesread += actual;
}
responseContent = new String (data);
}
else
{
// int ch;
while ( ( ch = is.read() ) != -1 )
{
}
}
}
private void http()
{
System.out.println( url );
HttpConnection conn = null;
OutputStream out = null;
int responseCode;
try
{
conn = (HttpConnection) Connector.open(url);
conn.setRequestMethod(requestMode);
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Length",Integer.toString(data.length()));
conn.setRequestProperty("Connection", "close");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("SOAPAction","http://dotnetstg.seasiaconsulting.com/");
out = conn.openOutputStream();
out.write(data.getBytes());
out.flush();
responseCode = conn.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK)
{
sendResult = false;
responseContent = null;
}
else
{
sendResult = true;
getResponseContent( conn );
}
start = false;
sending = false;
}
catch (IOException e)
{
start = false;
sendResult = false;
sending = false;
}
}
public void get(String url)
{
this.url = url;
this.data = "";
requestMode = HttpConnection.GET;
sendResult = false;
sending = true;
start = true;
}
public void post(String url, String data)
{
this.url = url;
this.data = data;
requestMode = HttpConnection.POST;
sendResult = false;
sending = true;
start = true;
}
public void stop()
{
stop = true;
}
}
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.component.AutoTextEditField;
import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.DateField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.component.Status;
import net.rim.device.api.ui.container.MainScreen;
import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;
import org.xml.sax.SAXException;
import net.rim.device.api.xml.parsers.SAXParser;
import net.rim.device.api.xml.jaxp.SAXParserImpl;
import org.xml.sax.helpers.DefaultHandler;
import java.io.ByteArrayInputStream;
import com.sts.example.ConnectionThread;
import com.sts.example.ResponseHandler;
public class DemoScreen extends MainScreen
{
private ConnectionThread connThread;
private BasicEditField response = new BasicEditField("Response: ", "");
private BasicEditField xmlResponse = new BasicEditField("xml: ", "");
private ButtonField sendButton = new ButtonField("Response");
public DemoScreen(ConnectionThread connThread)
{
this.connThread = connThread;
FieldListener sendListener = new FieldListener();
sendButton.setChangeListener(sendListener);
response.setEditable( false );
xmlResponse.setEditable( false );
add(sendButton);
add(response);
add(new SeparatorField());
add(xmlResponse);
}
public boolean onClose()
{
connThread.stop();
close();
return true;
}
private String getFieldData()
{
//{"UserName":"hsharma#seasiaconsulting.com","Password":"mind#123"}
StringBuffer sb = new StringBuffer();
sb.append("{\"UserNamepinkesh.g#cisinlabs.com\",\"Password\":\"pinkesh1985\"}");
return sb.toString();
}
class FieldListener implements FieldChangeListener
{
public void fieldChanged(Field field, int context)
{
StringBuffer sb = new StringBuffer("Sending...");
connThread.post("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration"+ConnectionInfo.getInstance().getConnectionParameters(), getFieldData());
while (connThread.sending)
{
try
{
Status.show( sb.append(".").toString() );
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
if (connThread.sendResult)
{
Status.show("Transmission Successfull");
xmlResponse.setText( connThread.responseContent );
try {
JSONObject jsonResponse = new JSONObject(connThread.responseContent);
JSONArray jsonArray = jsonResponse.getJSONArray("UserRegistrationResult");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject result = (JSONObject)jsonArray.get(i);
add(new LabelField("OutputCode"+result.getString("OutputCode")));
add(new LabelField("OutputDescription"+result.getString("OutputDescription")));
}
}
catch (JSONException e)
{
add(new LabelField(e.getMessage().toString()));
e.printStackTrace();
}
}
else
{
Status.show("Transmission Failed");
}
}
}
}

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.

Not able to get DirContext ctx using Spring Ldap

Hi i am using Spring ldap , after execution below program It display I am here only and after that nothing is happening, program is in continue execution mode.
public class SimpleLDAPClient {
public static void main(String[] args) {
Hashtable env = new Hashtable();
System.out.println("I am here");
String principal = "uid="+"a502455"+", ou=People, o=ao, dc=com";
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "MYURL");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, principal);
env.put(Context.SECURITY_CREDENTIALS,"PASSWORD");
DirContext ctx = null;
NamingEnumeration results = null;
try {
ctx = new InitialDirContext(env);
System.out.println(" Context" + ctx);
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
results = ctx.search("", "(objectclass=aoPerson)", controls);
while (results.hasMore()) {
SearchResult searchResult = (SearchResult) results.next();
Attributes attributes = searchResult.getAttributes();
Attribute attr = attributes.get("cn");
String cn = (String) attr.get();
System.out.println(" Person Common Name = " + cn);
}
} catch (NamingException e) {
throw new RuntimeException(e);
} finally {
if (results != null) {
try {
results.close();
} catch (Exception e) {
}
}
if (ctx != null) {
try {
ctx.close();
} catch (Exception e) {
}
}
}
}
}
Try fixing the below lines, i removed "ao" and it works fine.
results = ctx.search("", "(objectclass=Person)", controls);
You need to give search base as well
env.put(Context.PROVIDER_URL, "ldap://xx:389/DC=test,DC=enterprise,DC=xx,DC=com");
Refer this link as well http://www.adamretter.org.uk/blog/entries/LDAPTest.java

Resources