I am trying to consume Liferay's User entity to add users by writing code. The password is not encrypting, so log in is failing. The code is pasting below.
int countOfUsr = UserLocalServiceUtil.getUsersCount();
User user = UserLocalServiceUtil.createUser(countOfUsr + 1);
Date date = new Date();
user.setCompanyId(countOfUsr + 1);
user.setCreateDate(date);
user.setModifiedDate(date);
user.setDefaultUser(false);
user.setContactId(countOfUsr + 1);
user.setPasswordEncrypted(true);
user.setAgreedToTermsOfUse(true);
user.setPassword("123");
user.setPasswordReset(false);
user.setPasswordModifiedDate(date);
user.setReminderQueryQuestion("what-is-your-father's-middle-name");
user.setReminderQueryAnswer("daddad");
user.setGraceLoginCount(0);
user.setScreenName("shibu");
user.setFirstName("SHIBU");
user.setEmailAddress("shibu#liferay.com");
user.setFacebookId(0);
user.setOpenId("");
user.setPortraitId(0);
user.setLanguageId("en_US");
user.setTimeZoneId("GMT");
UserLocalServiceUtil.addUser(user);
How to modify the code to save the user properly?
What to do for pssword encryption?
How to give value for user.setDigest(arg)?
Specify the encryption algorithm to encrypt passwords in portal-ext.properties file.
For eg.,
passwords.encryption.algorithm=SHA //Check out different algorithms in portal.properties
I think you should use UserLocalServiceUtil.addUser(whole bunch of arguments) instead of UserLocalServiceUtil.addUser(User).
It will do what you want : create your user and encrypt the password.
The method signature is :
public User addUser(
long creatorUserId, long companyId, boolean autoPassword,
String password1, String password2, boolean autoScreenName,
String screenName, String emailAddress, long facebookId,
String openId, Locale locale, String firstName, String middleName,
String lastName, int prefixId, int suffixId, boolean male,
int birthdayMonth, int birthdayDay, int birthdayYear,
String jobTitle, long[] groupIds, long[] organizationIds,
long[] roleIds, long[] userGroupIds, boolean sendEmail,
ServiceContext serviceContext)
throws PortalException, SystemException
Beware : if your password do not validate the password policie, it will throw a UserPasswordException
Related
This the code. I have mentioned where the query stops. There is no error in the console too. What could be the problem. I am using postgres database. getting data from jsp servlet and passing to dao through servlet as string. But as my db has different format i want to convert the variables to their respective types. But i first want to check whether insert query works with dummy data. It seems that every thing is working fine but code flow stops where mentioned and there is no data inserted in my db also.
public void doInsert(Connection conn, String i, String nam,String indate, String amont, String tx, String tot,String closd, String shipvia, String not) throws Exception {
ResultSet rs = null;
ResultSet rs1 = null;
Statement st=null;
Statement st1=null;
// TODO Auto-generated method stub
try{
/* String in=indate;
String reverse = new StringBuffer(in).reverse().toString();
System.out.println(reverse);
System.out.println(reverse);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd");
String dateInString = indate;
Date date = sdf.parse(dateInString);
System.out.println(date);*/
/*String it=i;
String n=nam;
String in=indate;
String a=amont;
String t=tx;
String tota=tot;
String closed=closd;
String ship_via=shipvia;
String note=not;
to_date("+date+",'YYYY-MM-DD')*/
System.out.println("came above sql");
/*to_date("+date+",'YYYY-MM-DD')*/
String sql="insert into invheader(id,invdate,client_id,amount,tax,total,closed,ship_via,note) values(100001,to_date('1963-09-01', 'YYYY-MM-DD'),100001,100.00,20.00,120.00,TRUE,'tnt','note 1')";
//"insert into invheader(id,invdate,client_id,amount,tax,total,closed,ship_via,note) values('',to_date('1963-09-01', 'YYYY-MM-DD'),"+i+","+amont+","+tx+","+tot+","+closd+","+shipvia+","+not+")";
System.out.println("after 1st query");
String sql1="insert into clients(client_id,name) values("+i+","+nam+")";
System.out.println("after 2nd query");
st =conn.createStatement();
st1 =conn.createStatement();
//Statement stmt1 = conn.createStatement();//connection to statement
System.out.println("above execute"); //<======= code stops here
rs=st.executeQuery(sql);
System.out.println("above execute1");
rs1=st1.executeQuery(sql1);
System.out.println("inserted dao");
}catch(Exception e){
e.printStackTrace();
throw e;
}
// TODO Auto-generated method stub
}
Please help me. what could be the reason?
I am using this code:
SqlParameter pNombreUsuario = new SqlParameter("NombreUsuario", paramNombreUsuario);
object[] parametros = new object[] { pNombreUsuario };
string passwordDB = dbContext.Database.SqlQuery<string>("select password from Personal where NombreUsuario = #NombreUsuario", parametros)
.SingleOrDefault<string>();
but the query that is sent to the database is:
select password from Personal where NombreUsuario = #NombreUsuario
Why the parameter with the username name is not used?
Thanks.
The docs indicate that you should send an array of object values rather than SqlParameter objects.
E.g.
string passwordDB = dbContext.Database
.SqlQuery<string>("select password from Personal where NombreUsuario = #p0", paramNombreUsuario)
.SingleOrDefault<string>();
Does that work for you?
Edit: I misread the docs. Try this:
string passwordDB = dbContext.Database
.SqlQuery<string>(
"select password from Personal where NombreUsuario = #NombreUsuario",
new SqlParameter("NombreUsuario", paramNombreUsuario))
.SingleOrDefault<string>();
I created code to create a SQLite database based on the article here.
The most pertinent code is:
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Platypus.db";
private static final String TABLE_VENDORS = "vendors";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_VENDORID = "vendorId";
public static final String COLUMN_COMPANYNAME = "companyName";
public SQLiteHandlerVendors(Context context, String vendor,
SQLiteDatabase.CursorFactory factory, int company) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_VENDORS_TABLE = "CREATE TABLE " +
TABLE_VENDORS + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_VENDORID
+ " TEXT," + COLUMN_COMPANYNAME + " TEXT" + ")";
db.execSQL(CREATE_VENDORS_TABLE);
}
public void addVendor(Vendor vendor) {
ContentValues values = new ContentValues();
values.put(COLUMN_VENDORID, vendor.getVendorId());
values.put(COLUMN_COMPANYNAME, vendor.getCompanyName());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_VENDORS, null, values);
db.close();
}
Yet, although the insertions of data seem to be working -- the calls to addVendor() run without any exception being thrown with the following code:
protected void onPostExecute(String result) {
try {
JSONArray jsonArr = new JSONArray(result);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
String vendorId = jsonObj.getString("vendorId");
String companyName = jsonObj.getString("companyName");
Log.i("vendorId", vendorId);
Log.i("companyName", companyName);
// Prepare for writing to db
Vendor vend = new Vendor();
vend.setVendorId(vendorId);
vend.setCompanyName(companyName);
SQLiteHandlerVendors sqliteHandler = new SQLiteHandlerVendors(MainActivity.this, null, null, 1);
sqliteHandler.addVendor(vend);
}
} catch (JSONException j) {
System.out.println(j.getMessage());
Log.i("jsonEx", j.getMessage());
}
Log.i("GetVendorsTask.FromOnPostExecute", result);
}
I cannot locate the Platypus.db file that should have been created.
This article says, "If your application creates a database, this database is by default saved in the directory DATA/data/APP_NAME/databases/FILENAME."
A global search for "Platypus.DB" on my hard drive turns up nothing. Is the database created not being persisted, or is there some other reason why I'm not finding it?
I tried to find it by adding this code:
Log.i("Data Dir", Environment.getDataDirectory().toString());
...and when LogCat gives me is:
04-07 12:36:47.133 1089-1089/platypus.app I/Data Dirīš /data
There is no "data" folder in C:\Users\clay\AndroidStudioProjects\Platypus, nor is there one in the root of my hard drive (*C:*).
Can the data dir/file only be viewed in some virtual space, in a file system for the emulator or so? If so, how can I actually access the emulator's file system to view this data?
UPDATE
Okay, I opened up this view, and navigated to data/data/hhs (the app's name is really "hhs" not "platypus"):
...but still do not see HHS.DB (I see no "databases" folder below all that)...
UPDATE 2
If I select the "<=" button ("Pull a file from the device") with the file with the size of 16384 highlighted, it does open the "Get Device File" dialog with a filename of "HHS.DB" (just what I was hoping to find).
But, why is its path "data\data\hhs\unnamed folder\unnamed file" instead of "data\data\hhs\databases\HHS.DB"?
The other file (size 8720) is HHS.db-journal
UPDATE 3
After saving those files to my hard drive and downloading SQLite Data Browser, I'm able to verify that the records actually were written to the table:
SQLite Data Browser is a great tool for just such a need!
UPDATE 4
I don't know what changed/how it changed, but it's now working as it should:
There is no "data" folder in
C:\Users\clay\AndroidStudioProjects\Platypus, nor is there one in the
root of my hard drive (C:).
Yes that is corect.
Can the data dir/file only be viewed in some virtual space, in a file
system for the emulator or so? If so, how can I actually access the
emulator's file system to view this data?
Using Eclipse you can pull the db from your emulator
Goto windows open perspective. Goto DDMS
Then goto file explorer-> data->data->see your package name-> databases->Platypus.DB"
/data/data/[packagename]/databases/
You select the db and there is a option to pull the db and then you can use a sqlite browser to view the data
I have to created a dynamic URLcontaining the user id and email parameters, which will direct to sign up form in my GWT application. I want to set and get the parameters in the query string. I have referred tp http://code.google.com/p/gwt-examples/source/browse/trunk/System/src/com/gawkat/gwt/system/client/global/QueryString.java?r=1241 but here QueryStringData is inaccessible to my project.Please tell me how I can do it? Any alternative could also help me.
#Stein, but there is (a query parameter tokenizer in GWT): e.g. Window.Location.getParameter("debug") will return the string value of the parameter debug.
Don't think there's a simple tokenized query string parser in GWT. But you can get the raw query string by using:
String queryString = Window.Location.getQueryString();
Parse it any way you like. I use it like this to set debug flags etc.:
boolean debugMode = Window.Location.getQueryString().indexOf("debug=true") >= 0;
Note that changing values in the query part of the url (between the ? and the #) will reload the page. While changing the "hash part" of the url (anything after the #) will not reload the page. Which is why the com.google.gwt.user.client.History uses the hash part.
If you want really want to parse the history token (hash part) to encode parameters, here's the code for that:
private static Map<String, String> buildHashParameterMap() {
final String historyToken = History.getToken();
Map<String, String> paramMap = new HashMap<String, String>();
if (historyToken != null && historyToken.length() > 1) {
for (String kvPair : historyToken.split("&")) {
String[] kv = kvPair.split("=", 2);
if (kv.length > 1) {
paramMap.put(kv[0], URL.decodeQueryString(kv[1]));
} else {
paramMap.put(kv[0], "");
}
}
}
return paramMap;
}
There is in-built support for getting all of the parameters.
Simply call:
Map<String, List<String>> parameterMap = Window.Location.getParameterMap();
I have my passwords encoded in MD5 in C# and inserted in my DB.
MD5 MD5Hasher = MD5.Create();
byte[] PasswordHash = MD5Hasher.ComputeHash(Encoding.Unicode.GetBytes(PasswordText.Value));
PasswordHash is inserted as is and look like 0x09C09E5B52580E477514FA.......... for example.
In the blackberry app, I get the password, want to encode it to pass it to a web service that will compare both hashed password. The problem is my result is different from the MD5 I create in my Blackberry app.
password = Crypto.encodeStringMD5(password);
Then below my function:
public static String encodeStringMD5(String s) throws Exception {
byte[] bytes = s.getBytes();
MD5Digest digest = new MD5Digest();
digest.update(bytes, 0, bytes.length);
int length = digest.getDigestLength();
byte[] md5 = new byte[length];
digest.getDigest(md5, 0, true);
return convertToHex(md5);
}
private static String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while(two_halfs++ < 1);
}
return buf.toString();
}
So it returns something like this: 07054da3aea1cc98377fe0..........
Any idea how I can get the same hashed password that I create with my C# function in the Blackberry?
Thank you!
The getBytes() method of java String returns a different encoding than the Encoding.Unicode in .NET. You need to specify unambiguous encoding algorithms. Use UTF-8 for both platforms and you should be ok. You can also try providing a charset name to the getBytes method on the Java side; try getBytes("UTF-16")
GregS answered your question directly; but as an aside I would recommend against having the client create the MD5 sum. If the server manages creating the MD5sum, you can further ensure that the password can't be reverse engineered (eg rainbow table) by adding a "salt" value to the password before encoding it on the server. If you do that on the client, you must expose the salt to the client which is less secure.
Do you check the format? Many languages create the same hashes but in different formats.
For example:
5f45r5ssfds544g56fd4gfd56g4f6dgf
vs.
5f-45-r5-ss-fd-s5-44-g5-6f-d4-gf-d5-6g-4f-6d-gf
Try checking for both formats when converting to a string.