p:commandButton execution order of events - javascript

I am using PrimeFaces 6.0 components:
<p:commandButton type="submit" value="Create Customer"
icon="ui-icon-check"
actionListener="#{newCustomerBean.saveNewCustomer}"
update = "#form"
oncomplete="ajaxUploadFile();"/>
<p:inputText id="saveCustomerId" value ="#{newCustomerBean.savedKundeId}"/>
and I want to execute the following sequence of actions with them:
1.) Execute the actionListener method on the backing bean to save a customer;
2.) Update the form field saveCustomerId with the id of the customer that is saved on step (1). The actionListener method generates a customer Id after the successful save and stores is as a bean property;
3.) Execute the Java Script method ajaxUploadFile()
According to the link
Execution order of events when pressing PrimeFaces p:commandButton
this sequence shall be as I have imagined.
However, in reality, the method
ajaxUploadFile()
is called BEFORE the input field with id saveCustomerId is updated.
Could you help me get the right sequence?
Here is the backing bean:
#ManagedBean
#ViewScoped
public class NewCustomerBean implements Serializable {
public enum KundeTyp {
TYP_NATPERS("Nat. Person"), TYP_FIRMA("Firma");
private String value;
private KundeTyp(String value) {
this.value = value;
}
#Override
public String toString() {
return value;
}
}
private KundeTyp custmerType;
private Map<String, KundeTyp> custmerTypes;
private long savedKundeId;
#Inject
private KundeDBService kundeService;
private String vorname;
private String addresse;
private String steuerNummer;
private String kundeTyp = Integer.MIN_VALUE + "";
#PostConstruct
public void init() {
custmerTypes = new HashMap<String, KundeTyp>();
custmerTypes.put(KundeTyp.TYP_NATPERS.value, KundeTyp.TYP_NATPERS);
custmerTypes.put(KundeTyp.TYP_FIRMA.value, KundeTyp.TYP_FIRMA);
}
public KundeTyp getCustmerType() {
return custmerType;
}
public void setCustmerType(KundeTyp custmerType) {
this.custmerType = custmerType;
}
public Map<String, KundeTyp> getCustmerTypes() {
return custmerTypes;
}
public void setCustmerTypes(Map<String, KundeTyp> custmerTypes) {
this.custmerTypes = custmerTypes;
}
public String getVorname() {
return vorname;
}
public void setVorname(String vorname) {
this.vorname = vorname;
}
public String getAddresse() {
return addresse;
}
public void setAddresse(String addresse) {
this.addresse = addresse;
}
public String getSteuerNummer() {
return steuerNummer;
}
public void setSteuerNummer(String steuerNummer) {
this.steuerNummer = steuerNummer;
}
public String getKundeTyp() {
return kundeTyp;
}
public void setKundeTyp(String kundenTyp) {
this.kundeTyp = kundenTyp;
}
public String saveNewCustomer(ActionEvent e) {
Kunde neuerKunde = null;
switch (this.custmerType) {
case TYP_NATPERS: {
neuerKunde = new NatuerlichePerson();
break;
}
case TYP_FIRMA: {
neuerKunde = new Firma();
((Firma) neuerKunde).setSteuerNummer("123456");
break;
}
}
neuerKunde.setVorname(vorname);
neuerKunde.setAdresse(this.addresse);
try {
savedKundeId = kundeService.saveKunde(neuerKunde);
} catch (ServiceException se) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error",
"Unable to save the new customer: " + se.getMessage()));
}
return null;
}
public long getSavedKundeId() {
return savedKundeId;
}
public void setSavedKundeId(long savedKundeId) {
this.savedKundeId = savedKundeId;
}
}

I would propose a work-around here, since I was not able to find a solution.
Instead of updating the customerId on the front-end, we put it as a session attribute in the HttpSession.
Then, in the UploadServlet, which handles the file upload, we read this attribute and save the image under this customerId.

Related

How to pass data from database popup list to javascript interface android and add this value on html webview

popupdialog.java
public void showCustomRegionPopup() {
.
.
.
listRegion.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String region = (String) listRegion.getItemAtPosition(position);
SQLiteDatabase database = context.pdfDatabaseManager.getReadableDatabase();
final Cursor c = database.rawQuery("Select * From " + PDFDatabaseManager.DATABASE_REGION_TABLE + " WHERE "+ PDFDatabaseManager.KEY_REGION +"='"+region+"'", null);
String code = "";
while (c.moveToNext()) code = c.getString(1);
c.close();
context.setCodeAndRegion(code,region);
a.dismiss();
}
});
androidaction.java
#JavascriptInterface
public void showCustomRegionPopup(){
context.popupDialog.showCustomRegionPopup();
}
I want to take database region value from popupdialog.java and pass data to androidaction.java and run this code to put them on html...
webview.post(new Runnable() {
#Override
public void run() {
webview.evaluateJavascript("javascript:showCustomRegionPopup('".concat(region).concat("');"), null);
}
});
}

How fix to SMS Retriever API

I wrote code for example "SMS Retreiver API" https://developers.google.com/identity/sms-retriever/request
but I don`t result which I wont
This code past to MainActivity.
SmsRetrieverClient client = SmsRetriever.getClient(this);
Task<Void> task = client.startSmsRetriever();
task.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
});
task.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
This code past to MySMSBroadcastReceiver.
public class MySMSBroadcastReceiver extends BroadcastReceiver {
String message;
Status status;
private static MessageListener mListener;
#Override
public void onReceive(Context context, Intent intent) {
if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction())) {
Bundle extras = intent.getExtras();
status = (Status) extras.get(SmsRetriever.EXTRA_STATUS);
switch(status.getStatusCode()) {
case CommonStatusCodes.SUCCESS:
// Get SMS message contents
message = (String) extras.get(SmsRetriever.EXTRA_SMS_MESSAGE);
// Extract one-time code from the message and complete verification
// by sending the code back to your server.
break;
case CommonStatusCodes.TIMEOUT:
// Waiting for SMS timed out (5 minutes)
// Handle the error ...
break;
}
mListener.MySMSBroadcastReceiver(message);
}
}
public static void bindListener(MessageListener listener){
mListener = listener;
}
}
In my Manifest
<receiver android:name="ru.project.MBank.MySMSBroadcastReceiver" android:exported="true">
<intent-filter>
<action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED"/>
</intent-filter>
</receiver>
But result get nothing.
Help what do I do wrong?
I had same problem. First you need to generate a unique key (App Signature) that will identify message and your device. Once you generate key, your broadcaster will be able to detect message.
public class AppSignature extends ContextWrapper {
public static final String TAG = AppSignature.class.getSimpleName();
private static final String HASH_TYPE = "SHA-256";
public static final int NUM_HASHED_BYTES = 9;
public static final int NUM_BASE64_CHAR = 11;
public AppSignature(Context context) {
super(context);
}
/**
* Get all the app signatures for the current package
* #return
*/
public ArrayList<String> getAppSignatures() {
ArrayList<String> appCodes = new ArrayList<>();
try {
// Get all package signatures for the current package
String packageName = getPackageName();
PackageManager packageManager = getPackageManager();
Signature[] signatures = packageManager.getPackageInfo(packageName,
PackageManager.GET_SIGNATURES).signatures;
// For each signature create a compatible hash
for (Signature signature : signatures) {
String hash = hash(packageName, signature.toCharsString());
if (hash != null) {
appCodes.add(String.format("%s", hash));
}
}
} catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "Unable to find package to obtain hash.", e);
}
return appCodes;
}
private static String hash(String packageName, String signature) {
String appInfo = packageName + " " + signature;
try {
MessageDigest messageDigest = MessageDigest.getInstance(HASH_TYPE);
messageDigest.update(appInfo.getBytes(StandardCharsets.UTF_8));
byte[] hashSignature = messageDigest.digest();
// truncated into NUM_HASHED_BYTES
hashSignature = Arrays.copyOfRange(hashSignature, 0, NUM_HASHED_BYTES);
// encode into Base64
String base64Hash = Base64.encodeToString(hashSignature, Base64.NO_PADDING | Base64.NO_WRAP);
base64Hash = base64Hash.substring(0, NUM_BASE64_CHAR);
return base64Hash;
} catch (NoSuchAlgorithmException e) {
}
return null;
}
}
After this initiate this class in your firs activity.
Hope this will help you.

Added columns to SQLiteDatabase, can no longer read from it

My SQLiteDatabase was working fine with just 3 entries, the UUID, Title and Date, but ever since I added some more columns I am getting this error.
Not sure what it can be, I have read that 0,-1 means that the column cannot be read, but I have made sure to spell all my column names correctly.
CrimeCursorWrapper.java
public List<Crime> getCrimes() {
List<Crime> crimes = new ArrayList<>();
CrimeCursorWrapper cursor = queryCrimes(null, null);
try {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
crimes.add(cursor.getCrime());
cursor.moveToNext();
}
} finally{
cursor.close();
}
return crimes;
}
CrimeLab.java:
public Crime getCrime(UUID id) {
CrimeCursorWrapper cursor = queryCrimes(
CrimeTable.Cols.UUID + " = ?",
new String[] { id.toString() }
);
try {
if (cursor.getCount() == 0) {
return null;
}
cursor.moveToFirst();
return cursor.getCrime();
} finally {
cursor.close();
}
}
private static ContentValues getContentValues(Crime crime) {
ContentValues values = new ContentValues();
values.put(CrimeTable.Cols.UUID, crime.getId().toString());
values.put(CrimeTable.Cols.TITLE, crime.getTitle());
values.put(CrimeTable.Cols.DATE, crime.getDate().getTime());
values.put(CrimeTable.Cols.ACTTYPE, crime.getActType().toString());
values.put(CrimeTable.Cols.PLACE, crime.getPlace().toString());
values.put(CrimeTable.Cols.DURATION, crime.getDuration().toString());
values.put(CrimeTable.Cols.COMMENT, crime.getComment().toString());
return values;
}
private CrimeCursorWrapper queryCrimes(String whereClause, String[] whereArgs) {
Cursor cursor = mDatabase.query(
CrimeTable.NAME,
null, // Columns - null selects all columns
whereClause,
whereArgs,
null, // groupBy
null, // having
null // orderBy
);
return new CrimeCursorWrapper(cursor);
}
CrimeCursorWrapper.java:
public class CrimeCursorWrapper extends CursorWrapper{
public CrimeCursorWrapper(Cursor cursor) {
super(cursor);
}
public Crime getCrime() {
String uuidString = getString(getColumnIndex(CrimeTable.Cols.UUID));
String title = getString(getColumnIndex(CrimeTable.Cols.TITLE));
long date = getLong(getColumnIndex(CrimeTable.Cols.DATE));
String actType = getString(getColumnIndex(CrimeTable.Cols.ACTTYPE));
String place = getString(getColumnIndex(CrimeTable.Cols.PLACE));
String duration = getString(getColumnIndex(CrimeTable.Cols.DURATION));
String comment = getString(getColumnIndex(CrimeTable.Cols.COMMENT));
Crime crime = new Crime(UUID.fromString(uuidString));
crime.setTitle(title);
crime.setDate(new Date(date));
crime.setActType(actType);
crime.setPlace(place);
crime.setDuration(duration);
crime.setComment(comment);
return crime;
}
}
Crime.java:
public class Crime {
private UUID mId;
private String mTitle;
private Date mDate;
private String mActType;
private String mPlace;
private String mDuration;
private String mComment;
public Crime() {
this(UUID.randomUUID());
}
public Crime(UUID id) {
mId = id;
mDate = new Date();
}
public UUID getId() {
return mId;
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
public Date getDate() {
return mDate;
}
public void setDate(Date date) {
mDate = date;
}
public String getPhotoFilename() {
return "IMG_" + getId().toString() + ".jpg";
}
public String getActType() {
return mActType;
}
public void setActType(String actType) {
mActType = actType;
}
public String getPlace() {
return mPlace;
}
public void setPlace(String place) {
mPlace = place;
}
public String getDuration() {
return mDuration;
}
public void setDuration(String duration) {
mDuration = duration;
}
public String getComment() {
return mComment;
}
public void setComment(String comment) {
mComment = comment;
}
}
It "CAN" be the reason: If you use your physical mobile device for debugging, after you change your database tables inside the code, delete your application's data from the mobile device and reinstall your apk (or press debug or run buttons). Database files are not updating automatically by Android Studio.
Did you change version of your database after adding more columns? It is mandatory.

Display message in a toastr after controller method finish

i have controller method that upload image file, not using jQuery AJAX, from <input> type "file", the method returns:
Return Redirect(Request.UrlReferrer.PathAndQuery)
Because i want to stay in the same view after the submit click.
I want to show after the success image upload, toastr.success.
How i can do it?
In your http post action method, after successful upload, set an entry to TempData dictionary and read it in the next view which is loaded by the Redirect method and display the toastr message.
TempData["Msg"] = "Uploaded successfully";
return Redirect(Request.UrlReferrer.PathAndQuery);
in your view
<script>
$(function(){
var msg = "#(TempData["Msg"] as string)";
if (msg !== "") {
toastr.success(msg);
}
});
</script>
There is another way.
Create a Toastr model that includes Message, Title, Type, SessionID and Date.
public class Toastr
{
public string Title { get; set; }
public string Message { get; set; }
public ToastrType Type { get; set; }
public string SessionId { get; set; }
public DateTime Date { get; set; }
public Toastr(string message, string title = "Information" , ToastrType type = ToastrType.Info)
{
this.Message = message;
this.Title = title;
this.Type = type;
this.Date = DateTime.Now;
}
}
public enum ToastrType
{
Info = 0,
Success = 1,
Warning = 2,
Error = 3
}
Create a Service or Manager where you define your basic functions (add, remove toasts)
private static List<Toastr> _toasts = new List<Toastr>();
private static string GetSession()
{
return HttpContext.Current.Session.SessionID;
}
public static void AddToUserQueue(Toastr toastr)
{
toastr.SessionId = GetSession();
_toasts.Add(toastr);
}
public static void AddToUserQueue(string message, string title, ToastrType type)
{
var toast = new Toastr(message, title, type);
toast.SessionId = GetSession();
AddToUserQueue(toast);
}
public static bool HasQueue()
{
return _toasts.Any(t => t.SessionId == GetSession());
}
public static void RemoveUserQueue()
{
_toasts.RemoveAll(t => t.SessionId == GetSession());
}
public static void ClearAll()
{
_toasts.Clear();
}
public static List<Toastr> GetUserQueue()
{
if (HasQueue())
return _toasts.Where(t => t.SessionId == GetSession())
.OrderByDescending(x=>x.Date)
.ToList();
return null;
}
public static List<Toastr> GetAndRemoveUserQueue()
{
var list = GetUserQueue();
RemoveUserQueue();
return list;
}
In your layout / page make use of the functions by creating some helpers.
#helper ProcessToasts()
{
List<Toastr> toasts = ToastrManager.GetAndRemoveUserQueue();
if (toasts != null && toasts.Count > 0)
{
foreach (var item in toasts)
{
#ShowToastr(item);
}
}
}
#helper ShowToastr(Toastr item)
{
switch (item.Type)
{
case ToastrType.Info:
#ToastrInfo(item.Message, item.Title)
break;
case ToastrType.Success:
#ToastrSuccess(item.Message, item.Title)
break;
case ToastrType.Warning:
#ToastrWarning(item.Message, item.Title)
break;
case ToastrType.Error:
#ToastrError(item.Message, item.Title);
break;
}
}
#helper ToastrInfo(string message, string title)
{
<script>
toastr.info("#message","#title")
</script>
}
#helper ToastrSuccess(string message, string title)
{
<script>
toastr.success("#message","#title")
</script>
}
#helper ToastrWarning(string message, string title)
{
<script>
toastr.warning("#message","#title")
</script>
}
#helper ToastrError(string message, string title)
{
<script>
toastr.error("#message","#title")
</script>
}
Since the helpers are below closing HTML tag, you need just to add the #ProcessToasts() right before the body closing tag.

How to extract text from a WebPage

First off, yes, I have done research on this question. And yes, I have found an answer here. But the whole process still isn't working for me. All I need to do is grab text off of a webpage like Google, and create a string from the text it grabs. Here is my code with the aforementioned tutorials code in it:
public class Searching_Animation_Screen extends ActionBarActivity {
TextView loading_txt;
Animation blink;
public String pre_split;
public String[] split_string;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_searchinganimationscreen);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
int width = getWindowManager().getDefaultDisplay().getWidth();
loading_txt = (TextView)findViewById(R.id.loading);
text =(TextView)findViewById(R.id.textView);
Typeface pacifico_typeface = Typeface.createFromAsset(getAssets(), "fonts/pacifico.ttf");
loading_txt.setTypeface(pacifico_typeface);
loading_txt.setTextSize(width / 20);
blink = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.blink);
loading_txt.setAnimation(blink);
Begin();
}
private void Begin() {
Intent SEARCH_INTENT = getIntent();
pre_split=SEARCH_INTENT.getStringExtra("Search_Text");
split_string = pre_split.split(" ");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_searchinganimationscreen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
String google_url ="https://www.google.com/#safe=active&q=";
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
text.setText(Html.fromHtml(result));
//throw into summarizer
}
public void readWebpage(View view) {
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] {"www.google.com"});
}
}
}
Android studio is saying that readWebpage is never used, along with the actual DownloadWebPageTask class. Any ideas? I would like this class to run immediately on Create. Thanks!
#Ethan, sure, I hope this is what you want, just adding the readWebpage method in the onCreate method, but I modified it and removed the View object since it is not being used,
public class Searching_Animation_Screen extends ActionBarActivity {
TextView loading_txt;
Animation blink;
public String pre_split;
public String[] split_string;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_searchinganimationscreen);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
int width = getWindowManager().getDefaultDisplay().getWidth();
loading_txt = (TextView)findViewById(R.id.loading);
text =(TextView)findViewById(R.id.textView);
Typeface pacifico_typeface = Typeface.createFromAsset(getAssets(), "fonts/pacifico.ttf");
loading_txt.setTypeface(pacifico_typeface);
loading_txt.setTextSize(width / 20);
blink = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.blink);
loading_txt.setAnimation(blink);
Begin();
//* call webpage here,
//* note, i removed passing the view object since it is not being used
readWebpage()
}
//* (modify) by remvoving it from the code below
//* and removing the view object since it is not being used
public void readWebpage() {
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] {"http://www.google.com"});
}
private void Begin() {
Intent SEARCH_INTENT = getIntent();
pre_split=SEARCH_INTENT.getStringExtra("Search_Text");
split_string = pre_split.split(" ");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_searchinganimationscreen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
String google_url ="https://www.google.com/#safe=active&q=";
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
text.setText(Html.fromHtml(result));
//throw into summarizer
}
}
}

Categories