got the following error after upgrading Acumatica from 2020r2 to 2022r2
After my research found out UpdateServiceOrderHeader() was removed from CRExtensionHelper.cs
now its SM_CRCaseMaint.cs and SM_SOOrderEntry.cs.
I implemented the following changes but got the following error;
full code:
public PXAction<CRCase> CreateServiceOrders;
[PXButton]
[PXUIField(DisplayName = "Create Service Orders", Visible = true, MapEnableRights = PXCacheRights.Select, MapViewRights = PXCacheRights.Select)]
public virtual void createServiceOrders()
{
CRCase crCaseRow = Base.Case.Current;
FSxCRCase fsxCRCaseRow = Base.Case.Cache.GetExtension<FSxCRCase>(crCaseRow);
if (crCaseRow.CustomerID == null && crCaseRow.ContactID == null)
{
throw new PXException("You can not create proceed." + Environment.NewLine + "The Business Account and Contact are NULL.");
}
if (crCaseRow.CustomerID == null)
{
throw new PXException("You can not create proceed." + Environment.NewLine + "The Business Account is NULL.");
}
if (crCaseRow.ContactID == null)
{
throw new PXException("You can not create proceed." + Environment.NewLine + "The ContactID is NULL.");
}
if (CreateServiceOrderFilter.AskExt() == WebDialogResult.OK)
{
fsxCRCaseRow.SDEnabled = true;
fsxCRCaseRow.BranchLocationID = CreateServiceOrderFilter.Current.BranchLocationID;
fsxCRCaseRow.SrvOrdType = CreateServiceOrderFilter.Current.SrvOrdType;
fsxCRCaseRow.AssignedEmpID = CreateServiceOrderFilter.Current.AssignedEmpID;
fsxCRCaseRow.ProblemID = CreateServiceOrderFilter.Current.ProblemID;
PXLongOperation.StartOperation(Base, delegate ()
{
CreateServiceOrderDocument(Base, crCaseRow, CreateServiceOrderFilter.Current);
});
}
}
private void CreateServiceOrderDocument(CRCaseMaint graphCRCaseMaint, CRCase crCaseRow, FSCreateServiceOrderOnCaseFilter fsCreateServiceOrderOnCaseFilterRow)
{
if (graphCRCaseMaint == null || crCaseRow == null || fsCreateServiceOrderOnCaseFilterRow == null)
{
return;
}
ServiceOrderEntry graphServiceOrderEntry = PXGraph.CreateInstance<ServiceOrderEntry>();
FSServiceOrder newServiceOrderRow = CRExtensionHelper.InitNewServiceOrder(CreateServiceOrderFilter.Current.SrvOrdType, ID.SourceType_ServiceOrder.CASE);
graphServiceOrderEntry.ServiceOrderRecords.Current = graphServiceOrderEntry.ServiceOrderRecords.Insert(newServiceOrderRow);
//CRExtensionHelper.UpdateServiceOrderHeader(
// graphServiceOrderEntry,
// Base.Case.Cache,
// crCaseRow,
// fsCreateServiceOrderOnCaseFilterRow,
// graphServiceOrderEntry.ServiceOrderRecords.Current,
// true);
SM_CRCaseMaint.UpdateServiceOrderHeader(
graphServiceOrderEntry,
Base.Case.Cache,
crCaseRow,
fsCreateServiceOrderOnCaseFilterRow,
graphServiceOrderEntry.ServiceOrderRecords.Current,
true);
//graphServiceOrderEntry.ServiceOrderRecords.Current.SourceID = crCaseRow.CaseCD;
graphServiceOrderEntry.ServiceOrderRecords.Current.SourceRefNbr = crCaseRow.CaseCD;
if (!Base.IsContractBasedAPI)
{
throw new PXRedirectRequiredException(graphServiceOrderEntry, null);
}
}
}
#endregion
}
Error CS0120 means that you need to instantiate the object before calling UpdateServiceOrderHeader(). I would try searching the source code for other instances of this function being called and replicate the setup.
When creating a user like so:
using var trans = Db.BeginTransaction();
AuthRepository.CreateUserAuth(newUser, request.Password);
AuthRepository.AssignRoles(created, new List<string> { request.role });
//.. do other stuff
throw new Exception("other code may throw this");
trans.Commit();
The Auth repo has it's own connection so it's not part of the transaction. This means, if my code bails out, I end up with an unwanted user.
Is there any way to use a transaction with AuthRepository or is only way to manually write to user and role tables? I couldn't find an example of creating the password hash in docs when manually saving, is there any example?
You can't use the existing Auth Repository APIs within a transaction because each uses its own DB connection.
If you want you can take the implementation of those OrmLite Auth Respository APIs in OrmLiteAuthRepository.cs and move them into your method so they're all using the same DB Connection + Transaction.
Also note that to use Transactions in OrmLite you should use OpenTransaction() instead, e.g:
using (var dbTrans = db.OpenTransaction())
{
}
Adding class I used here in case it helps anyone as needed a little refactoring:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using OutReachPete.ServiceModel.User;
using ServiceStack;
using ServiceStack.Auth;
using ServiceStack.OrmLite;
namespace OutReachPete.ServiceInterface.User
{
public class UserHelper
{
public static bool ForceCaseInsensitiveUserNameSearch { get; set; } = true;
public static bool UseDistinctRoleTables { get; set; } = true;
public static UserAuthCustom CreateUserAuth(UserAuthCustom newUser, string password, IDbConnection db)
{
newUser.ValidateNewUser(password);
AssertNoExistingUser(db, newUser);
newUser.PopulatePasswordHashes(password);
newUser.CreatedDate = DateTime.UtcNow;
newUser.ModifiedDate = newUser.CreatedDate;
db.Save(newUser);
newUser = db.SingleById<UserAuthCustom>(newUser.Id);
return newUser;
}
public static void AssertNoExistingUser(IDbConnection db, IUserAuth newUser,
IUserAuth exceptForExistingUser = null)
{
if (newUser.UserName != null)
{
var existingUser = GetUserAuthByUserName(db, newUser.UserName);
if (existingUser != null
&& (exceptForExistingUser == null || existingUser.Id != exceptForExistingUser.Id))
throw new ArgumentException(string.Format(ErrorMessages.UserAlreadyExistsTemplate1,
newUser.UserName.SafeInput()));
}
if (newUser.Email != null)
{
var existingUser = GetUserAuthByUserName(db, newUser.Email);
if (existingUser != null
&& (exceptForExistingUser == null || existingUser.Id != exceptForExistingUser.Id))
throw new ArgumentException(string.Format(ErrorMessages.EmailAlreadyExistsTemplate1,
newUser.Email.SafeInput()));
}
}
public static UserAuthCustom GetUserAuthByUserName(IDbConnection db, string userNameOrEmail)
{
var isEmail = userNameOrEmail.Contains("#");
var lowerUserName = userNameOrEmail.ToLower();
UserAuthCustom userAuth = null;
// Usernames/Emails are saved in Lower Case so we can do an exact search using lowerUserName
if (HostContext.GetPlugin<AuthFeature>()?.SaveUserNamesInLowerCase == true)
{
return isEmail
? db.Select<UserAuthCustom>(q => q.Email == lowerUserName).FirstOrDefault()
: db.Select<UserAuthCustom>(q => q.UserName == lowerUserName).FirstOrDefault();
}
// Try an exact search using index first
userAuth = isEmail
? db.Select<UserAuthCustom>(q => q.Email == userNameOrEmail).FirstOrDefault()
: db.Select<UserAuthCustom>(q => q.UserName == userNameOrEmail).FirstOrDefault();
if (userAuth != null)
return userAuth;
// Fallback to a non-index search if no exact match is found
if (ForceCaseInsensitiveUserNameSearch)
{
userAuth = isEmail
? db.Select<UserAuthCustom>(q => q.Email.ToLower() == lowerUserName).FirstOrDefault()
: db.Select<UserAuthCustom>(q => q.UserName.ToLower() == lowerUserName).FirstOrDefault();
}
return userAuth;
}
public static void AssignRoles(IAuthRepository userAuthRepo, IUserAuth userAuth, IDbConnection db,
ICollection<string> roles = null, ICollection<string> permissions = null)
{
if (userAuthRepo is IManageRoles managesRoles)
{
AssignRoles(userAuth.Id.ToString(), db, roles, permissions);
}
else
{
AssignRolesInternal(userAuth, roles, permissions);
SaveUserAuth(userAuth, db);
}
}
public static IUserAuth GetUserAuth(string userAuthId, IDbConnection db)
{
if (string.IsNullOrEmpty(userAuthId))
throw new ArgumentNullException(nameof(userAuthId));
return db.SingleById<UserAuthCustom>(int.Parse(userAuthId));
}
public static void AssignRoles(string userAuthId, IDbConnection db, ICollection<string> roles = null, ICollection<string> permissions = null)
{
var userAuth = GetUserAuth(userAuthId, db);
if (!UseDistinctRoleTables)
{
if (!roles.IsEmpty())
{
foreach (var missingRole in roles.Where(x => userAuth.Roles == null || !userAuth.Roles.Contains(x)))
{
if (userAuth.Roles == null)
userAuth.Roles = new List<string>();
userAuth.Roles.Add(missingRole);
}
}
if (!permissions.IsEmpty())
{
foreach (var missingPermission in permissions.Where(x => userAuth.Permissions == null || !userAuth.Permissions.Contains(x)))
{
if (userAuth.Permissions == null)
userAuth.Permissions = new List<string>();
userAuth.Permissions.Add(missingPermission);
}
}
SaveUserAuth(userAuth, db);
}
else
{
var now = DateTime.UtcNow;
var userRoles = db.Select<UserAuthRole>(q => q.UserAuthId == userAuth.Id);
if (!roles.IsEmpty())
{
var roleSet = userRoles.Where(x => x.Role != null).Select(x => x.Role).ToHashSet();
foreach (var role in roles)
{
if (!roleSet.Contains(role))
{
db.Insert(new UserAuthRole
{
UserAuthId = userAuth.Id,
Role = role,
CreatedDate = now,
ModifiedDate = now,
});
}
}
}
if (!permissions.IsEmpty())
{
var permissionSet = userRoles.Where(x => x.Permission != null).Select(x => x.Permission).ToHashSet();
foreach (var permission in permissions)
{
if (!permissionSet.Contains(permission))
{
db.Insert(new UserAuthRole
{
UserAuthId = userAuth.Id,
Permission = permission,
CreatedDate = now,
ModifiedDate = now,
});
}
}
}
}
}
private static void AssignRolesInternal(IUserAuth userAuth, ICollection<string> roles, ICollection<string> permissions)
{
if (!roles.IsEmpty())
{
foreach (var missingRole in roles.Where(x => userAuth.Roles == null || !userAuth.Roles.Contains(x)))
{
if (userAuth.Roles == null)
userAuth.Roles = new List<string>();
userAuth.Roles.Add(missingRole);
}
}
if (!permissions.IsEmpty())
{
foreach (var missingPermission in permissions.Where(x =>
userAuth.Permissions == null || !userAuth.Permissions.Contains(x)))
{
if (userAuth.Permissions == null)
userAuth.Permissions = new List<string>();
userAuth.Permissions.Add(missingPermission);
}
}
}
public static void SaveUserAuth(IUserAuth userAuth, IDbConnection db)
{
if (userAuth == null)
throw new ArgumentNullException(nameof(userAuth));
userAuth.ModifiedDate = DateTime.UtcNow;
if (userAuth.CreatedDate == default(DateTime))
userAuth.CreatedDate = userAuth.ModifiedDate;
db.Save((UserAuthCustom)userAuth);
}
}
}
Then just call it like:
var created = UserHelper.CreateUserAuth(newUser, request.Password, Db);
UserHelper.AssignRoles(AuthRepository, created, Db, new List<string> { request.CreateUserType.ToString() });
It will only use the connection passed. Just change UserAuthCustom to whatever you user class is.
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");
}
}
}
}
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();
}
}
}
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