Ajax request fails in JBOSS EAP 7.1 in Java EAR application - ajax

I've EAR applications which run fine in JBOSS EAP 6.3. When I run this application in EAP 7, then ajax call response is empty after few call. Mainly jsp page calls servlet using ajax. I use common code snippet for AJAX call. I can get response properly first 3/4 times. After that it is not working. The whole thing is working fine in EAP 6.3.
The ajax code snippet is as follows:
try{
objXMLHTTP = new XMLHttpRequest();
}catch(e){
try {
objXMLHTTP = new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch(e){
try {
objXMLHTTP = new ActiveXObject("MSXML2.XMLHTTP");
}
catch(e) {
try {
objXMLHTTP = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
alert("XMLHTTP Not Supported On Your Browser");
return;
}
}
}
}
var urlstr = "" ;
var key = "";
var j = 0;
//dataStore is an array of key/value pair.
for(key in dataStore){
if(j == 0) {
urlstr += key + "=" + dataStore[key];
j = 1;
} else {
urlstr += "&" + key + "=" + dataStore[key];
}
}
var _dateTime = new Date().getTime();
urlstr += "&CALLTIME=" + _dateTime + "-";
var requNumber = "?requNumber=" + _dateTime;
// http request has been changed as Parameterised
var _AsyncRequest = true;
try{
if(_httpMode == "undefined")
_httpMode = "0";
}catch(e){
_httpMode = "0";
}
if((_httpMode != "undefined") && (_httpMode != null) && (_httpMode == "1"))
{
_AsyncRequest = false;
}
if(!document.all)
{
_AsyncRequest = false;
}
if(urlstr.length<=1000) {
objXMLHTTP.open("POST","XMLDHTTPServlet" + requNumber + "&" + urlstr,false);
} else {
objXMLHTTP.open("POST","XMLDHTTPServlet" + requNumber,false);
}
urlstr = URLEncode(urlstr);
objXMLHTTP.setRequestHeader("content-type", "application/x-www-form-urlencoded") ;
//The following is not working after few calls
if(urlstr.length<=1000) {
objXMLHTTP.send("");
} else {
objXMLHTTP.send(urlstr);
}
rtnXML = objXMLHTTP.responseText;
if (objXMLHTTP.statusText == "OK" )
// This condition fails after successive requests
{
//Code
}
Following is in JSP page to call the AJAX. Most importantly, when I put the character **|**, then response in empty and objXMLHTTP.statusText shows Bad Request in EAP 7. But EAP 6, it is working fine.
var objXMLApplet = new xmlHTTPValidator();
objXMLApplet.clearMap();
objXMLApplet.setValue("Package", "panaceaFLweb.getMenuInfo.ReadInfo");
objXMLApplet.setValue("ValidateToken","true");
objXMLApplet.setValue("Method", "chkEODStatus");
objXMLApplet.setValue("BRNCH_CODE",BranCode);
objXMLApplet.setValue("CURR_BUSS_DATE",CBD);
objXMLApplet.setValue("DataTypes","S|S");
objXMLApplet.sendAndReceive();

It is because character | present in URL post request and didn't encode the string which length is less than 1000. Just use
urlstr = URLEncode(urlstr);
before if/else condition of connection open.
Code snippet are as follows:
urlstr = URLEncode(urlstr);
if(urlstr.length<=1000) {
objXMLHTTP.open("POST","XMLDHTTPServlet" + requNumber + "&" + urlstr,false);
} else {
objXMLHTTP.open("POST","XMLDHTTPServlet" + requNumber,false);
}
objXMLHTTP.setRequestHeader("content-type", "application/x-www-form-urlencoded") ;
if(urlstr.length<=1000) {
objXMLHTTP.send("");
} else {
objXMLHTTP.send(urlstr);
}
rtnXML = objXMLHTTP.responseText;
And URLEncode function definition are as follows:
function URLEncode(urlstr ){
var SAFECHARS = "0123456789" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "-_.!~*'()=?&";
var HEX = "0123456789ABCDEF";
var plaintext = urlstr;
var encoded = "";
for (var i = 0; i < plaintext.length; i++ ) {
var ch = plaintext.charAt(i);
if (ch == " "){
encoded += "+";
}else if (SAFECHARS.indexOf(ch) != -1) {
encoded += ch;
}else {
var charCode = ch.charCodeAt(0);
if (charCode > 255) {
encoded += "+";
}else {
encoded += "%";
encoded += HEX.charAt((charCode >> 4) & 0xF);
encoded += HEX.charAt(charCode & 0xF);
}
}
}
return encoded;
}

Related

TOTP Problem - Microsoft Authenticator is not matching the code generated on server

I am getting a not verified using the TOTP method I have found on the following link.
OTP code generation and validation with otp.net
!My! code is below.
The _2FAValue line at the top is embedded into the QR barcode that Microsoft Authenticator attaches too.
The _Check... Function is the server ajax call to the server which implements OTP.Net library exposing TOTP calculation.
MakeTOTPSecret creates an SHA1 version of a Guid which is applied to the User profile and stored in _gTOTPSecret. NB: This IS populated in the places it is used.
I think I must have missed something obvious to get a result, here.
loSetup2FAData._s2FAValue = $#"otpauth://totp/{loUser.UserName}?secret={loUser.MakeTOTPSecret()}&digits=6&issuer={Booking.Library.Classes.Constants._sCompanyName}&period=60&algorithm=SHA1";
[AllowAnonymous]
public JsonResult _CheckTOTPCodeOnServer([FromBody] Booking.Site.Models.Shared.CheckTotpData loCheckTotpData)
{
string lsMessage = "<ul>";
try
{
string lsEmail = this.Request.HttpContext.Session.GetString("Buku_sEmail");
Booking.Data.DB.Extensions.IdentityExtend.User loUser = this._oDbContext.Users.Where(U => U.UserName.ToLower() == lsEmail.ToLower() || U.Email == lsEmail).FirstOrDefault();
if (loUser != null && loUser.Load(this._oDbContext) && loUser._gTOTPSecret != Guid.Empty)
{
OtpNet.Totp loTotp = new Totp(Booking.Library.Classes.Utility.StringToBytes(loUser.MakeTOTPSecret()), 60, OtpHashMode.Sha1, 6);
loTotp.ComputeTotp(DateTime.Now);
long lnTimeStepMatched = 0;
bool lbVerify = loTotp.VerifyTotp(loCheckTotpData._nTotp.ToString("000000"), out lnTimeStepMatched, new VerificationWindow(2, 2));
if (lbVerify)
{
lsMessage += "<li>Successfully validated Totp code</li>";
lsMessage += "<li>Save is now activated</li>";
return this.Json(new { bResult = true, sMessage = lsMessage + "</ul>" });
}
}
}
catch (Exception loException)
{
lsMessage += "<li>" + Booking.Library.Classes.Utility.MakeExceptionMessage(true, loException, "\r\n", "_CheckTOTPCodeOnServer") + "</li>";
}
lsMessage += "<li>Unsuccessfully validated Totp code</li>";
return this.Json(new { bResult = false, sMessage = lsMessage + "</ul>" });
}
public string MakeTOTPSecret()
{
string lsReturn = String.Empty;
try
{
using (SHA1Managed loSha1 = new SHA1Managed())
{
var loHash = loSha1.ComputeHash(Encoding.UTF8.GetBytes(this._gTOTPSecret.ToString()));
var loSb = new StringBuilder(loHash.Length * 2);
foreach (byte b in loHash)
{
loSb.Append(b.ToString("X2"));
}
lsReturn = loSb.ToString();
}
}
catch (Exception loException)
{
Booking.Library.Classes.Utility.MakeExceptionMessage(true, loException, "\r\n", "Identity.MakeSHA1Secret");
}
return lsReturn;
}

how to restrict double extension while uploading file to server

fileName = inputParam.file_name.split('.')[0].toLowerCase().replace(/ /g, '') + '' + Date.now() + "." + (fileData.file.name.split('.')[1] || inputParam.file_name.split('.')[1])
filePath = filePath + fileName
This is the condition I am using.
For example it should only restrict a.jpeg.jpg or a.php.jpeg. and allow extension like a.a.jpeg or bird.tree.jpeg
var _validFilejpeg = [".jpeg", ".jpg", ".bmp", ".png",".pdf", ".txt"];
var invalid = [".php",".php5", ".pht", ".phtml", ".shtml", ".asa", ".cer", ".asax", ".swf",".xap"];
function validateForSize(oInput, minSize, maxSizejpeg) {
//if there is a need of specifying any other type, just add that particular type in var _validFilejpeg
if (oInput.type == "file") {
var sFileName = oInput.value;
var file = sFileName.match(/\d/g);
var fileExt = sFileName.substr(sFileName.length-4);
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFilejpeg.length; j++) {
var sCurExtension = _validFilejpeg[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length)
.toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if(fileExt = 'invalid'){
alert("Your document does not have a proper file extension.")
blnValid = false;
}
if(fileExt = 'file'){
alert("Your document does not have a proper file extension.")
blnValid = false;
}
if (!blnValid) {
alert("Sorry, this file is invalid, allowed extension is: " + _validFilejpeg.join(", "));
oInput.value = "";
return false;
}
}
}
fileSizeValidatejpeg(oInput, minSize, maxSizejpeg);
}
function fileSizeValidatejpeg(fdata, minSize, maxSizejpeg) {
if (fdata.files && fdata.files[0]) {
var fsize = fdata.files[0].size /1024; //The files property of an input element returns a FileList. fdata is an input element,fdata.files[0] returns a File object at the index 0.
//alert(fsize)
if (fsize > maxSizejpeg || fsize < minSize) {
alert('This file size is: ' + fsize.toFixed(2) +
"KB. Files should be in " + (minSize) + " to " + (maxSizejpeg) + " KB ");
fdata.value = ""; //so that the file name is not displayed on the side of the choose file button
return false;
} else {
console.log("");
}
}
}
<input type="file" onchange="validateForSize(this,20,5000);" >
You can simply do this
if (fileName.split('.').length > 2) {
throw new Error('Double extension file detected')
}

Catch incoming emails and send them to a web service (rather than just to a mail server)

I would like to catch incoming emails and send them a web service (rather than just to a mail server).
--
After some searching I found a way of getting new emails via polling - see below: This may be of some help to others. Is there a way to receive messages by SMTP? Perhaps by ISAPI ???
using Limilabs.Mail;
using Limilabs.Client.IMAP;
public ActionResult checkIMAPmail()
{
string rval = "not a sausage";
using (Imap imap = new Imap())
{
imap.Connect(<mail server>);
imap.Login(<username>, <password>);
imap.SelectInbox();
List<long> uids = imap.Search(Flag.Unseen);
foreach (long uid in uids)
{
byte[] ourBytes = imap.GetMessageByUID(uid);
IMail email = new MailBuilder().CreateFromEml(ourBytes);
rval = email.Subject + " [" + email.From + "][" + email.Text + "]";
}
imap.Close();
}
return Content(rval, "text/html");
}
See also http://stackoverflow.com/questions/670183/accessing-imap-in-c-sharp
for other IMAP packages, although note the change to using byte[], above.
Given that Limilabs.Mail is a paid service, I finally used MailKit:
using MailKit;
public int checkIMAPmail()
{
int numEmails = 0;
try {
using (var client = new MailKit.Net.Imap.ImapClient())
{
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect(ourSmtpClient);
// disable the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
client.Authenticate(ourSmtpAdminUser, ourSmtpAdminUserPwd);
// The Inbox folder is always available on all IMAP servers...
var inboxFolder = client.Inbox;
var savedFolder = client.GetFolder("saved");
inboxFolder.Open(FolderAccess.ReadWrite);
for (int ii = 0; ii < inboxFolder.Count; ii++)
{
var query = MailKit.Search.SearchQuery.NotSeen;
foreach (var uid in inboxFolder.Search(query))
{
var thisMsg = inboxFolder.GetMessage(uid);
string thisDate = notNullString(thisMsg.Date);
string thisSubject = notNullString( thisMsg.Subject);
string thisBody = notNullString(thisMsg.GetTextBody(0)); // plain text
string thisFromName = "";
string thisFromEmail = "";
if ( thisMsg.From != null)
{
// just get the first
foreach( var mb in thisMsg.From.Mailboxes)
{
thisFromName = notNullString( mb.Name);
thisFromEmail = notNullString( mb.Address);
break;
}
}
numEmails += 1;
// move email to saved
inboxFolder.MoveTo(uid, savedFolder);
}
}
client.Disconnect(true);
}
}
catch (Exception exc)
{
log2file("checkIMAPmail Error: " + exc.ToString());
}
return numEmails;
}

AD with LDAP connection error

Im trying to use a .net application but the application cant find the server in my local network.
Im using LdapExploreTool 2 with the following settings:
the base DN is "DC=exago,DC=local", the Ip address "192.168.1.250" and the server name "exago.local"
The connection is successful and this is the result:
Inputing the values:
Examining the code, i get the exception when "Bind to the native AdsObject to force authentication":
"The specified domain either does not exist or could not be contacted."
public bool IsAuthenticated(string domain, string ldapPath, string username, string pwd, string userToValidate)
{
string domainAndUsername = domain + #"\" + username;
if (string.IsNullOrEmpty(ldapPath))
SetLdapPath(domain);
else
_path = ldapPath;
App.Services.Log.LogUtils.WriteLog(Log.LogLevel.INFO, "IsAuthenticated_DirectoryEntry:" + _path + "," + domainAndUsername + "," + pwd);
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);
//check if domain is valid
int domainId = AppDomains.GetDomainIdByName(domain);
if (domainId == int.MinValue)
{
return false;
}
AppDomains d = AppDomains.GetRecord(domainId);
List<AppDomainQueries> lQueries = new List<AppDomainQueries>(AppDomainQueries.GetArray());
lQueries = lQueries.FindAll(delegate(AppDomainQueries dq) { return dq.DomainId == domainId && dq.Status == 'A'; });
string queryString = string.Empty;
try
{
// Bind to the native AdsObject to force authentication.
Object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
string ldapAndQuerie = string.Empty;
//base account search
queryString = "(SAMAccountName=" + userToValidate + ")";
if (username != userToValidate)
{
if (lQueries.Count == 1)
ldapAndQuerie = lQueries.FirstOrDefault().QueryString;
if ((ldapAndQuerie != string.Empty) && (ldapAndQuerie != "*") && (ldapAndQuerie != "(objectClass = user)"))
queryString = "(&(SAMAccountName=" + userToValidate + ")" + ldapAndQuerie + ")";
}
search.Filter = queryString;
App.Services.Log.LogUtils.WriteLog(Log.LogLevel.INFO, "LDAP=" + queryString);
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (null == result)
{
return false;
}
// Update the new path to the user in the directory
_path = result.Path;
_filterAttribute = (String)result.Properties["cn"][0];
}
catch (Exception ex)
{
App.Services.Log.LogUtils.WriteLog(Log.LogLevel.ERROR, "App.Services.Core.LdapAuthentication.IsAuthenticated() Exception - (LDAP=" + queryString + ")" + ex.Message, ex);
return false;
}
return true;
}
How can i establish a connection?
The problem was the LDAP connection string,
it seems that it missed the actual location(IP + port) in the network.
LDAP://192.168.1.250:389/DC=exago,DC=local

j2me midlet chinese character display message garbled

My J2ME midlet could retrieves message in Chinese character from a PHP server but it's garbled. The server basically returns the response string and by detecting the first 2 characters. AA = good, anything else indicates error of which the message is to be passed to the calling function for display
InputStream is = null;
StringBuffer sb = null;
String str = "";
HttpConnection http = null;
DataOutputStream dos = null;
try
{
URL = login.getURL();
URL += ctlFunction + "/" + uriStr;
URL = EncodeURL(URL);
//System.out.println(URL);
if(!ctlFunction.equals("login"))
{
msg += "&user=" + login.getUsername();
msg += "&token=" + login.getToken();
}
msg += "&lang=" + System.getProperty("microedition.locale");
// establish the connection
http = (HttpConnection) Connector.open(URL);
http.setRequestMethod(HttpConnection.POST);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setRequestProperty("Content-length", ""+EncodeURL(msg).getBytes().length);
dos = http.openDataOutputStream();
byte[] request_body = EncodeURL(msg).getBytes();
for (int i = 0; i < request_body.length; i++)
{
dos.writeByte(request_body[i]);
}
// server response
if (http.getResponseCode() == HttpConnection.HTTP_OK)
{
is = http.openDataInputStream();
int length = (int) http.getLength();
if (length != -1)
{
// Read data in one chunk
byte serverData[] = new byte[length];
is.read(serverData);
str = new String(serverData);
}
else // Length not available...
{
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = is.read()) != -1)
bStrm.write(ch);
str = new String(bStrm.toByteArray());
bStrm.close();
}
}
else
{
networkError();
}
}
catch (Exception e)
{
System.err.println("Error3: " + e.toString());
networkError(e.toString());
}
finally
{
if (is != null)
is.close();
if (!str.equals(""))
post = str;
else
networkError();
if (http != null)
http.close();
}
if (post != null)
{
String fate = post.substring(0, 2);
if(fate.equals("AA"))
{
if(ctlFunction.equals("login"))
{
String rawPost = post.substring(2);
Vector v = new Vector();
int index = 0;
//find the first occurrence of the SPLITTER
int endIndex = rawPost.indexOf(SPLITTER, index);
String item = "";
//extract the items until the end of the last SPLITTER found in the rawPost string
while(endIndex != -1)
{
item = rawPost.substring(index, endIndex);
index = endIndex + 1;
endIndex = rawPost.indexOf(SPLITTER, index);
v.addElement(item);
}
//extract the rest of the rawPost (the text item)
item = rawPost.substring(index);
v.addElement(item);
String[] ret = new String[v.size()];
v.copyInto(ret);
login.setToken(ret[0]);
login.setToday(ret[1]);
login.setNextDrawDay(ret[2]);
}
midlet.returnResults(post.substring(2), getCurrentDisplay(), ctlFunction);
}
else
{
String errmessage = post.substring(2);
System.out.println(post);
midlet.showInfo(post, getCurrentDisplay());
}
}
else
{
networkError();
}
On the PHP server, I have set the header to UTF-8 encoding
<?php header("Content-Type:text/plain; charset=utf-8"); ?>
What could possibly be wrong?
I found that this user has the same problem and it's been answered
Reading UTF8 strings from a server through http using MIDP. Kudos to the answer.
I basically edited my MIDP code from
// is = http.openDataInputStream();
// int length = (int) http.getLength();
// if (length != -1)
// {
// // Read data in one chunk
// byte serverData[] = new byte[length];
// is.read(serverData);
// str = new String(serverData);
// }
// else // Length not available...
// {
// ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
// int ch;
// while ((ch = is.read()) != -1)
// bStrm.write(ch);
//
// str = new String(bStrm.toByteArray());
// bStrm.close();
// }
to
Reader r = new InputStreamReader(http.openInputStream(), "UTF-8");
int ch;
while((ch = r.read()) != -1)
str = str + (char)ch;
just wondering though why does reading bytes messes up the UTF-8 characters?

Resources