Liferay - Select item filled with json responseData - javascript

It's my first post on stackoverflow so I hope I won't make too many mistakes.
I've a problem with filling Java List and sending it to aui:select as options. My goal is to fill aui:select dynamically whenever one of their options is changed. For example: if you change first select item (county), second and third items (community and city respectively) are emptied and then filled with data dependent on selected county.
I've come to a conclusion that whenever there's a "mvcPath" parameter in Query String Parameters this code basically copies code from the whole page. This code works well whenever there's no "mvcPath" though. Sadly, I need this parameter to change pages (from search results to selected result details).
Image showing badly filled select item
Image showing correctly filled select item
Java code:
#Override
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
throws IOException, PortletException {
String communityName = "";
long communityId = 0;
String cityName = "";
long cityId = 0;
String countySelected = ParamUtil.getString(resourceRequest, "countySelected");
long countySelectedId = ParamUtil.getLong(resourceRequest, "countyDictionaryId");
String communitySelected = ParamUtil.getString(resourceRequest, "communitySelected");
long communitySelectedId = ParamUtil.getLong(resourceRequest, "communityDictionaryId");
JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
if (countySelected.equalsIgnoreCase("countySelected") && countySelectedId != 0) {
System.out.println("County id: " + countySelectedId);
try {
int communitiesCount = CommunityDictionaryLocalServiceUtil.getCommunityDictionariesCount();
List<CommunityDictionary> communities = CommunityDictionaryLocalServiceUtil.getCommunityDictionaries(0,
communitiesCount);
for (CommunityDictionary community : communities) {
if (community.getCountyDictionaryId() == countySelectedId) {
communityName = community.getCommunityName();
communityId = community.getCommunityDictionaryId();
JSONObject communityObject = JSONFactoryUtil.createJSONObject();
communityObject.put("communityName", communityName);
communityObject.put("communityDictionaryId", communityId);
jsonArray.put(communityObject);
System.out.print(jsonArray.toString());
}
}
} catch (SystemException e) {
e.printStackTrace();
}
} else if (countySelected.equalsIgnoreCase("countySelected") && countySelectedId == 0) {
System.out.println("No county chosen.");
try {
int communitiesCount = CommunityDictionaryLocalServiceUtil.getCommunityDictionariesCount();
List<CommunityDictionary> communities = CommunityDictionaryLocalServiceUtil.getCommunityDictionaries(0,
communitiesCount);
for (CommunityDictionary community : communities) {
communityName = community.getCommunityName();
communityId = community.getCommunityDictionaryId();
JSONObject communityObject = JSONFactoryUtil.createJSONObject();
communityObject.put("communityName", communityName);
communityObject.put("communityDictionaryId", communityId);
jsonArray.put(communityObject);
}
} catch (SystemException e) {
e.printStackTrace();
}
}
if (communitySelected.equalsIgnoreCase("communitySelected") && communitySelectedId != 0) {
System.out.println("Community id: " + communitySelectedId);
try {
int citiesCount = CityDictionaryLocalServiceUtil.getCityDictionariesCount();
List<CityDictionary> cities = CityDictionaryLocalServiceUtil.getCityDictionaries(0, citiesCount);
for (CityDictionary city : cities) {
if (city.getCommunityDictionaryId() == communitySelectedId) {
cityName = city.getCityName();
cityId = city.getCityDictionaryId();
JSONObject cityObject = JSONFactoryUtil.createJSONObject();
cityObject.put("cityName", cityName);
cityObject.put("cityDictionaryId", cityId);
jsonArray.put(cityObject);
System.out.print(jsonArray.toString());
}
}
} catch (SystemException e) {
e.printStackTrace();
}
} else if (communitySelected.equalsIgnoreCase("communitySelected") && communitySelectedId == 0) {
System.out.println("No community chosen.");
try {
int citiesCount = CityDictionaryLocalServiceUtil.getCityDictionariesCount();
List<CityDictionary> cities = CityDictionaryLocalServiceUtil.getCityDictionaries(0, citiesCount);
for (CityDictionary city : cities) {
cityName = city.getCityName();
cityId = city.getCityDictionaryId();
JSONObject cityObject = JSONFactoryUtil.createJSONObject();
cityObject.put("cityName", cityName);
cityObject.put("cityDictionaryId", cityId);
jsonArray.put(cityObject);
}
} catch (SystemException e) {
e.printStackTrace();
}
}
PrintWriter writer = resourceResponse.getWriter();
writer.write(jsonArray.toString());
writer.flush();
super.serveResource(resourceRequest, resourceResponse);
}
Script:
<aui:script>
AUI().use('aui-base', 'aui-io-request', 'aui-node',
function(A) {A.one("#<portlet:namespace />countySelect").on('change', function() {
A.io.request('<%= selectionChangedURL %>',
{
method : 'POST',
data : {
"<portlet:namespace />countyDictionaryId" : A.one("#<portlet:namespace />countySelect").val(),
'<portlet:namespace />countySelected' : 'countySelected'
},
dataType : 'json',
on : {
success : function() {
var communitiesList = this.get('responseData');
A.one('#<portlet:namespace />communitySelect').empty();
A.one('#<portlet:namespace />citySelect').empty();
A.one('#<portlet:namespace />communitySelect').prepend("<option value='0'> </option>");
for (var i in communitiesList) {
console.info(communitiesList[i]);
A.one('#<portlet:namespace />communitySelect').append("<option value='" + communitiesList[i].communityDictionaryId + "'>" + communitiesList[i].communityName + "</option>");
}
}
}
});
});
A.one("#<portlet:namespace />communitySelect").on('change', function() {
A.io.request('<%= selectionChangedURL %>',
{
method : 'POST',
data : {
"<portlet:namespace />communityDictionaryId" : A.one("#<portlet:namespace />communitySelect").val(),
'<portlet:namespace />communitySelected' : 'communitySelected'
},
dataType : 'json',
on : {
success : function() {
var citiesList = this.get('responseData');
A.one('#<portlet:namespace />citySelect').empty();
A.one('#<portlet:namespace />citySelect').prepend("<option value='0'> </option>");
for (var i in citiesList) {
console.info(citiesList[i]);
A.one('#<portlet:namespace />citySelect').append("<option value='" + citiesList[i].cityDictionaryId + "'>" + citiesList[i].cityName + "</option>");
}
}
}
});
});
});

After some changes in server-side code I managed to fix this issue. I'm not really sure how did as small changes as those helped but I'm happy to close this thread.
This is the server-side code:
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
throws IOException, PortletException {
String communityName = "";
long communityId = 0;
String cityName = "";
long cityId = 0;
String countySelected = ParamUtil.getString(resourceRequest, "countySelected");
long countySelectedId = ParamUtil.getLong(resourceRequest, "countyDictionaryId");
String communitySelected = ParamUtil.getString(resourceRequest, "communitySelected");
long communitySelectedId = ParamUtil.getLong(resourceRequest, "communityDictionaryId");
JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
if (countySelected.equalsIgnoreCase("countySelected")) {
try {
int communitiesCount = CommunityDictionaryLocalServiceUtil.getCommunityDictionariesCount();
List<CommunityDictionary> communities = CommunityDictionaryLocalServiceUtil.getCommunityDictionaries(0,
communitiesCount);
if (countySelectedId == 0) {
for (CommunityDictionary community : communities) {
communityName = community.getCommunityName();
communityId = community.getCommunityDictionaryId();
JSONObject communityObject = JSONFactoryUtil.createJSONObject();
communityObject.put("communityName", communityName);
communityObject.put("communityDictionaryId", communityId);
jsonArray.put(communityObject);
}
} else {
for (CommunityDictionary community : communities) {
if (community.getCountyDictionaryId() == countySelectedId) {
communityName = community.getCommunityName();
communityId = community.getCommunityDictionaryId();
JSONObject communityObject = JSONFactoryUtil.createJSONObject();
communityObject.put("communityName", communityName);
communityObject.put("communityDictionaryId", communityId);
jsonArray.put(communityObject);
}
}
}
} catch (SystemException e) {
e.printStackTrace();
}
}
if (communitySelected.equalsIgnoreCase("communitySelected")) {
try {
int citiesCount = CityDictionaryLocalServiceUtil.getCityDictionariesCount();
List<CityDictionary> cities = CityDictionaryLocalServiceUtil.getCityDictionaries(0, citiesCount);
if (communitySelectedId == 0) {
for (CityDictionary city : cities) {
cityName = city.getCityName();
cityId = city.getCityDictionaryId();
JSONObject cityObject = JSONFactoryUtil.createJSONObject();
cityObject.put("cityName", cityName);
cityObject.put("cityDictionaryId", cityId);
jsonArray.put(cityObject);
}
} else {
for (CityDictionary city : cities) {
if (city.getCommunityDictionaryId() == communitySelectedId) {
cityName = city.getCityName();
cityId = city.getCityDictionaryId();
JSONObject cityObject = JSONFactoryUtil.createJSONObject();
cityObject.put("cityName", cityName);
cityObject.put("cityDictionaryId", cityId);
jsonArray.put(cityObject);
}
}
}
} catch (SystemException e) {
e.printStackTrace();
}
}
PrintWriter writer = new PrintWriter(resourceResponse.getPortletOutputStream());
writer.write(jsonArray.toString());
writer.flush();
super.serveResource(resourceRequest, resourceResponse);
}

Related

Issue with JSON in UWP WebView using C# to JavaScript not being read properly

This is rather perplexing. I'm converting an HTML5 game to UWP by using a WebView to host the game content and would like to back up from localStorage in the WebView and create a duplicate in the localStorage for the app as a whole (that is, from browser storage to package storage). This is of course an intended safety net in case the player craps out on hardware (as I obviously want the data to back up to the player's cloud storage) however something's not quite right. Specifically, the backups are written properly but when they're read back from the host app into the HTML5 portion using Javascript methods connected to the host through a WinRT component they're not having an effect on the localStorage in the WebView (which in turn makes it look like there's no save data, so the continue option is disabled).
Here's a code sample for what I'm doing:
var i;
for (i = -1; i <= 200; i++) {
var data = window.UWPConnect.getSaveFile(i);
var key = 'File'+i;
if (i === -1) key = 'Config';
if (i === 0) key = 'Global';
localStorage.setItem(key, data);
}
This first portion reads my WinRT component to load save data from the disk.
public void doSave(int key, string data) {
/*StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile saveWrite = await folder.CreateFileAsync("saveData" + key + ".json", CreationCollisionOption.ReplaceExisting);
try { await saveWrite.DeleteAsync(); } catch { }
String[] lines = { data };
await FileIO.WriteLinesAsync(saveWrite, lines);*/
if (key == -1) { System.IO.File.WriteAllText(ApplicationData.Current.LocalFolder.Path + "\\config.json", data); }
else if (key == 0) { System.IO.File.WriteAllText(ApplicationData.Current.LocalFolder.Path + "\\global.json", data); }
else
{
System.IO.File.WriteAllText(ApplicationData.Current.LocalFolder.Path + "\\saveData" + key + ".json", data);
}
}
public void doStartup()
{
StorageFolder folder = ApplicationData.Current.LocalFolder;
for (int i = -1; i <= 200; i++)
{
try {
if (i == -1)
{
saveData[i] = System.IO.File.ReadAllText(ApplicationData.Current.LocalFolder.Path + "\\config.json");
} else if (i == 0)
{
saveData[i] = System.IO.File.ReadAllText(ApplicationData.Current.LocalFolder.Path + "\\global.json");
}
else
{
saveData[i] = System.IO.File.ReadAllText(ApplicationData.Current.LocalFolder.Path + "\\saveData" + i + ".json");
}
Debug.WriteLine(saveData[i]);
}
catch {}
/*Debug.WriteLine(File.Exists(SaveFile));
if (File.Exists(SaveFile)) {
try { saveData[i] = File.ReadAllText(SaveFile);
Debug.WriteLine(saveData[i]); }
catch { }
}*/
}
}
public string getSaveFile(int savefileId)
{
string data;
try
{
data = saveData[savefileId];
if (data == null) data = "";
Debug.WriteLine(data);
}
catch { data = ""; }
return data;
}
And this second portion handles the saving and loading from disk (which is taken from the WinRT component).
I think I figured it out. In the data reader where it loads and saves I had to use a different set of instructions on the WinRT side, so here's the new code structure:
public void doSave(int key, string data) {
if (key == -1) { System.IO.File.WriteAllText(ApplicationData.Current.LocalFolder.Path + "\\config.json", data); }
else if (key == 0) { System.IO.File.WriteAllText(ApplicationData.Current.LocalFolder.Path + "\\global.json", data); }
else
{
System.IO.File.WriteAllText(ApplicationData.Current.LocalFolder.Path + "\\file" + key + ".json", data);
}
}
public void doBackup(int key, string data) {
System.IO.File.WriteAllText(ApplicationData.Current.LocalFolder.Path + "\\backup" + key + ".json", data);
}
public void doStartup()
{
for (int i = 0; i <= 200; i++)
{
if (i == -1)
{
if (System.IO.File.Exists(ApplicationData.Current.LocalFolder.Path + "\\config.json"))
{
saveData[i] = System.IO.File.ReadAllText(ApplicationData.Current.RoamingFolder.Path + "\\config.json");
}
}
else if (i == 0)
{
if (System.IO.File.Exists(ApplicationData.Current.LocalFolder.Path + "\\global.json"))
{
saveData[i] = System.IO.File.ReadAllText(ApplicationData.Current.LocalFolder.Path + "\\global.json");
}
}
else
{
if (System.IO.File.Exists(ApplicationData.Current.LocalFolder.Path + "\\file" + i + ".json"))
{
saveData[i] = System.IO.File.ReadAllText(ApplicationData.Current.LocalFolder.Path + "\\file" + i + ".json");
}
if (System.IO.File.Exists(ApplicationData.Current.LocalFolder.Path + "\\backup" + i + ".json"))
{
backup[i] = System.IO.File.ReadAllText(ApplicationData.Current.LocalFolder.Path + "\\backup" + i + ".json");
}
}
}
}
public string getSaveFile(int savefileId)
{
string data;
try
{
data = saveData[savefileId];
if (data == null) data = "";
Debug.WriteLine(data);
}
catch { data = ""; }
return data;
}
public string getBackup(int savefileId)
{
string data;
try
{
data = backup[savefileId];
if (data == null) data = "";
Debug.WriteLine(data);
}
catch { data = ""; }
return data;
}
public string getConfig()
{
string data;
try
{
data = System.IO.File.ReadAllText(ApplicationData.Current.LocalFolder.Path + "\\config.json");
if (data == null) data = "";
Debug.WriteLine(data);
}
catch { data = ""; }
return data;
}

javascript function pass object with null values

I am doing master/detail using this article as a guide, my case is a little different as I have five different details for single master table and each one with totally different details/columns. I want my users to enter all rows in selected detail table and pass these rows with the master to the controller, but passed parameter is always null. I searched a lot without success.
Solution in this post did not work for me and a couple of others in different forums.
Here is my code:
//JobOrderMaster Action:
[HttpPost]
public ActionResult JobOrderMaster(WorkOrder objJobOrder, string btnPrevious, string btnNext)
{
ViewBag.Project_Id = new SelectList(db.Projects, "Project_Id", "Project_Name_e");
if (btnNext != null)
{
if (ModelState.IsValid)
{
workOrderId = Guid.NewGuid();
JobOrderViewModel objWorkOrder = GetJobOrder();
objWorkOrder.WorkOrder_Id = workOrderId;
objWorkOrder.Start_Date = objJobOrder.Start_Date;
objWorkOrder.End_Date = objJobOrder.End_Date;
objWorkOrder.Project_Id = objJobOrder.Project_Id;
objWorkOrder.Subject = objJobOrder.Subject;
objWorkOrder.WorkOrder_Date = DateTime.Now;
objWorkOrder.Created_Date = DateTime.UtcNow;
objWorkOrder.WorkOrder_Type = objJobOrder.WorkOrder_Type;
objWorkOrder.Created_By = User.Identity.GetUserName();
objWorkOrder.Descriptions = objJobOrder.Descriptions;
ViewBag.WorkOrderId = objWorkOrder;
switch ((int)objJobOrder.WorkOrder_Type)
{
case 1: return View("JobOrderDetails");
case 2: return View("InHouseMaintenance");
case 3: return View("CustomerSideMaintenance");
case 4: return View("SiteSurvey");
case 5: return View("Installation");
default: return View("JobOrderDetails");
}
}
}
return View();
}
//JobOrderDetails Action:
//string expenseMaster;
[HttpPost]
public ActionResult JobOrderDetails(WorkOrderDetail[] objWorkOrderDetail)
{
WorkOrder objWorkOrder = new WorkOrder();
WorkOrderDetail details = new WorkOrderDetail();
JobOrderViewModel objJobOrder = GetJobOrder();
if (objJobOrder.WorkOrder_Id != null)
{
objWorkOrder.WorkOrder_Id = objJobOrder.WorkOrder_Id;
objWorkOrder.Start_Date = objJobOrder.Start_Date;
objWorkOrder.End_Date = objJobOrder.End_Date;
objWorkOrder.Project_Id = objJobOrder.Project_Id;
objWorkOrder.Subject = objJobOrder.Subject;
objWorkOrder.Descriptions = objJobOrder.Descriptions;
objWorkOrder.Type_Id = objJobOrder.Type_Id;
objWorkOrder.WorkOrder_Type = objJobOrder.WorkOrder_Type;
objWorkOrder.WorkOrder_Status = objJobOrder.WorkOrder_Status;
objWorkOrder.WorkOrder_Priority = objJobOrder.WorkOrder_Priority;
objWorkOrder.WorkOrder_Date = DateTime.Now;
objWorkOrder.Created_Date = DateTime.UtcNow;
objWorkOrder.Created_By = User.Identity.GetUserName();
db.WorkOrders.Add(objWorkOrder);
}
int detailId = 1;
//if (btnNext != null)
//{
if (ModelState.IsValid)
{
foreach (var item in objWorkOrderDetail)
{
details.WorkOrder_Id = objWorkOrder.WorkOrder_Id;
details.Category_Id = item.Category_Id;
details.Detail_Id = detailId;
details.Qty = item.Qty;
db.WorkOrderDetails.Add(details);
detailId++;
}
try
{
db.SaveChanges();
RemoveJobOrder();
return View("Index");
}
catch (DbUpdateException ex)
{
string message = "";
UpdateException updateException = (UpdateException)ex.InnerException;
SqlException sqlException = (SqlException)updateException.InnerException;
foreach (SqlError error in sqlException.Errors)
{
message = string.Format("{0} Error '{1}' occurred in {2} at {3}\n\n\r\n",
message
, error.Number
, error.Message
, error.LineNumber);
}
ViewBag.errorMessage = message;
clsGeneralMethods.ErrorLog(message);
return View("Error");
}
catch (DbEntityValidationException ex)
{
string message = "";
foreach (DbEntityValidationResult item in ex.EntityValidationErrors)
{
//Get entry
DbEntityEntry entry = item.Entry;
string entityTypeName = entry.Entity.GetType().Name;
//Display or log error messages
foreach (DbValidationError subItem in item.ValidationErrors)
{
message = string.Format("{0}Error '{1}' occurred in {2} at {3}\n\n\r\n",
message
, subItem.ErrorMessage
, entityTypeName
, subItem.PropertyName);
}
}
ViewBag.errorMessage = message;
clsGeneralMethods.ErrorLog(message);
return View("Error");
}
}
//}
return View();
}
//My javascript functions
function btnFinish(details) {
//alert(JSON.stringify(details));
return $.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '#Url.Action("JobOrderDetails")',
data: JSON.stringify({ objWorkOrderDetail: details }),
success: function (result) {
//location.reload();
},
error: function (err) {
if (err != null) {
alert('Error: ' + err.Message);
}
}
});
}
$("#btnFinish").click(function (e) {
e.preventDefault();
var claimArr = [];
claimArr.length = 0;
$.each($("#detailsTable tbody tr"), function () {
claimArr.push({
categoryId: $(this).find('td:eq(0)').html(),
descriptions: $(this).find('td:eq(1)').html(),
quantity: $(this).find('td:eq(2)').html()
});
});
var data = JSON.stringify(claimArr);
//alert(data);
$.when(btnFinish(data)).then(function (response) {
window.location.href = "../JobOrder/Index";
//console.log(response);
}).fail(function (err) {
console.log(err.Message);
window.location.href = "../JobOrder/Index";
});
});
});
action screenshot shows null values
alert msg shows object received ok in js function
The problem is that You don't have the same names of properties in JSON (JavaScript side) and your class WorkOrderDetails in C#:
WorkOrderDetails
JSON
Category_Id
categoryId
Descriptions
descriptions
Qty
quantity
Make the same names in two of these types and it should be ok.
For example:
WorkOrderDetails
JSON
categoryId
categoryId
descriptions
descriptions
quantity
quantity

autocomplete to avoid tab operation for textbox

I am using Autocomlete to show the list of location which come from database. User get the list as expected. but instate selecting from list user just click on the tab button and control going to next button. I want to avoid TAB operation here.Any suggestion how i will do that .
Here is my function :
$(document).ready(function () {
src = 'LocationHandler.ashx';
$('#txtLocationName').autocomplete({
source: function (request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term: request.term,
type: $("#ddlDivision1").val()
},
success: function (data) {
Object.keys = Object.keys || function (o, k, r) { r = []; for (k in o) r.hasOwnProperty.call(o, k) && r.push(k); return r }
if (Object.keys(data).length == 0) {
$('#txtLocationName').val('');
alert('Location must be selected from the options.');
}
response(data);
}
});
},
min_length: 3,
delay: 300
});
});
My Handler class looks like
public class LocationHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string term = context.Request["term"] ?? "";
string type = context.Request["type"] ?? "";
// type = "FM";
List<string> listLocationNames = new List<string>();
string cs = ConfigurationManager.ConnectionStrings["EGLFormsDB"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spIARLocationNames", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#term",
Value = term
});
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#locType",
Value = type
});
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
listLocationNames.Add(rdr["Name"].ToString());
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
context.Response.Write(js.Serialize(listLocationNames));
}
public bool IsReusable
{
get
{
return false;
}
}
}
this is how i solve this.
$("#txtLocationName").keydown(function (evt) {
var keyCode = evt.keyCode || evt.which;
if (keyCode == 9) {
//evt.preventDefault();
//alert("TAB not allowed111111. Please select business unit number or name from Search box. ");
var textloc = $("#txtLocationName").val();
var specialChars = "{"
if (textloc.indexOf("{") >= 0) {
//no need to do anything
}
else {
evt.preventDefault();
alert("TAB not allowed. Please select business unit number or name from Search box. ");
}
}
if (evt.key === "Tab")
{
var textloc = $("#txtLocationName").val();
var specialChars = "{"
if (textloc.indexOf("{") >= 0) {
//no need to do anything
}
else {
evt.preventDefault();
alert("TAB not allowed. Please select business unit number or name from Search box. ");
}
}
});

Replace Java Applet with GWT

Hi I have the following class which would like to replace with stjs, but it seems it does not work for me, as stjs does not cover all applet libraries, any though if this is can be done thru stjs or any other technology? Thanks in advance
package org.stjs.examples.hello;
import java.applet.Applet;
import java.awt.Button;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.Rectangle;
import java.awt.TextArea;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.text.BreakIterator;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
import java.util.StringTokenizer;
public class DataCache
extends Applet
implements ActionListener
{
private static final String APPLET_VERSION = "1.6.0";
private static final int MSG_WIN_HEIGHT = 179;
private static final int MSG_WIN_WIDTH = 288;
private static final String MSG_WIN_ETITLE = "Error Message";
private static final String MSG_WIN_MTITLE = "Information Message";
public String m_error = "";
public String m_message = "";
public String m_currCacheString = "";
public StringBuffer m_currXMLCache = null;
public Hashtable m_currHashCache = null;
private String m_commandKey;
private Hashtable m_XMLCache = new Hashtable();
private Hashtable m_hashCache = new Hashtable();
private String m_key = "";
private String m_keyList = "";
private String m_file = "";
private String m_dataDir = "";
private String m_autoLoad = "TRUE";
private String m_servletURL = "";
private String m_debugApplet = "";
private Frame m_msgWindow;
private TextArea m_msgText;
private Button m_msgButton;
private FontMetrics m_msgMetrics;
private int m_msgTextHeight;
public void destroy()
{
this.m_msgWindow.dispose();
}
public void init()
{
createErrorWindow();
alertStatus("applet version: 1.6.0", 'D');
this.m_debugApplet = getAppParam("debugApplet");
this.m_autoLoad = getAppParam("autoLoad");
this.m_commandKey = getAppParam("commandKey");
String ls = getAppParam("loadStatic");
String dataDir = getAppParam("dataDir");
this.m_servletURL = getAppParam("servletURL");
URL url = getCodeBase();
int port = url.getPort();
if (this.m_debugApplet.equals("TRUE")) {
System.out.println("url: " + this.m_servletURL);
} else if (port != -1) {
this.m_servletURL = ("http://" + url.getHost() + ":" + port + this.m_servletURL);
} else {
this.m_servletURL = ("http://" + url.getHost() + this.m_servletURL);
}
setDataDir(dataDir);
if (!this.m_autoLoad.toUpperCase().equals("FALSE")) {
if ((ls.equals("")) || (ls.toUpperCase().equals("FALSE")))
{
alertStatus("loading non-static...", 'D');
loadAllData(false);
}
else if (ls.toUpperCase().equals("TRUE"))
{
alertStatus("loading static...", 'D');
openAllData(false);
}
}
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if (s.equals("OK")) {
this.m_msgWindow.hide();
}
}
private void createErrorWindow()
{
this.m_msgWindow = new Frame("New Title");
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3 = new Panel();
p1.setLayout(new GridLayout(2, 1));
this.m_msgText = new TextArea("New Message", 3, 40, 1);
this.m_msgText.setEditable(false);
this.m_msgText.setFont(new Font("Dialog", 0, 8));
this.m_msgMetrics = this.m_msgText.getFontMetrics(this.m_msgText.getFont());
p2.add(this.m_msgText);
p1.add(p2);
this.m_msgButton = new Button(" OK ");
this.m_msgButton.addActionListener(this);
this.m_msgButton.setActionCommand("OK");
p3.add(this.m_msgButton);
p1.add(p3);
this.m_msgWindow.add(p1);
this.m_msgWindow.pack();
Toolkit t = this.m_msgWindow.getToolkit();
this.m_msgTextHeight = this.m_msgMetrics.getHeight();
this.m_msgWindow.setBounds(new Rectangle(
t.getScreenSize().width / 2 - 144,
t.getScreenSize().height / 2 - 89,
288,
179));
}
public void setDataDir(String s)
{
try
{
if ((s != null) && (s.length() > 0))
{
if (s.charAt(s.length() - 1) != '\\') {
s = s + "\\";
}
this.m_dataDir = s;
}
}
catch (Exception e)
{
e.printStackTrace();
alertStatus(e.getMessage(), 'E');
alertStatus(s, 'E');
}
}
private String getAppParam(String s)
{
String param = getParameter(s);
if (param == null) {
return "";
}
return param;
}
private String alertStatus(String source, Exception e, char status)
{
e.printStackTrace(System.out);
return alertStatus(source + " -- " + e.getMessage(), status);
}
private String alertStatus(String s, char status)
{
switch (status)
{
case 'E':
this.m_error = s;
System.out.println(s);
showStatus(s);
this.m_msgWindow.setTitle("Error Message");
setWrapText(s);
this.m_msgButton.setEnabled(true);
this.m_msgWindow.show();
return s;
case 'M':
this.m_message = s;
System.out.println(s);
showStatus(s);
this.m_msgWindow.setTitle("Information Message");
setWrapText(s);
this.m_msgButton.setEnabled(true);
this.m_msgWindow.show();
return s;
case 'S':
this.m_message = s;
System.out.println(s);
showStatus(s);
this.m_msgWindow.setTitle("Information Message");
setWrapText(s);
this.m_msgButton.setEnabled(false);
this.m_msgWindow.show();
return s;
case 'D':
System.out.println(s);
return s;
}
return "";
}
private void setWrapText(String s)
{
BreakIterator boundary = BreakIterator.getWordInstance(Locale.US);
String line = "";
int maxWidth = this.m_msgText.getSize().width;
this.m_msgText.setText("");
boundary.setText(s);
int start = boundary.first();
int end = boundary.next();
while (end != -1)
{
String tmp = s.substring(start, end);
if (this.m_msgMetrics.stringWidth(line + tmp) > maxWidth)
{
this.m_msgText.append(line + "\n");
line = tmp;
}
else
{
line = line + tmp;
}
start = end;
end = boundary.next();
if (end == -1) {
this.m_msgText.append(line);
}
}
this.m_msgText.append(s.substring(start));
}
private void makeDirectories(String dir)
{
String fdir = dir;
AccessController.doPrivileged(new PrivilegedAction()
{
private final String val$fdir="";
public Object run()
{
String subdir = "";
int i = this.val$fdir.indexOf('\\');
while (i != -1)
{
subdir = this.val$fdir.substring(0, i);
File f = new File(subdir);
if (!f.isDirectory()) {
f.mkdir();
}
i = this.val$fdir.indexOf('\\', i + 1);
}
return null;
}
});
}
private boolean verifyDataFile(String s)
{
String fs = s;
Boolean retVal =
(Boolean)AccessController.doPrivileged(new PrivilegedAction()
{
private final String val$fs="";
public Object run()
{
File f = new File(this.val$fs);
if (!f.isFile()) {
return new Boolean(false);
}
return new Boolean(true);
}
});
return retVal.booleanValue();
}
private String verifyDataFilesInternal()
{
try
{
AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
File dir = new File(DataCache.this.m_dataDir);
if (!dir.isDirectory()) {
dir.mkdirs();
}
return dir;
}
});
StringTokenizer st = new StringTokenizer(this.m_commandKey, ";");
while (st.hasMoreElements())
{
String key = (String)st.nextElement();
if (!verifyDataFile(this.m_dataDir + key + ".data")) {
return "Data cache file " + this.m_dataDir + key + ".data could not be found.";
}
if (!verifyDataFile(this.m_dataDir + key + ".hash")) {
return "Data cache file " + this.m_dataDir + key + ".hash could not be found.";
}
}
return "";
}
catch (Exception e)
{
e.printStackTrace();
return e.getMessage();
}
}
private String loadAllDataInternal()
{
String status = "";
String key = "";
StringBuffer data = new StringBuffer("");
Hashtable hash = null;
alertStatus("loading data internal", 'D');
URLConnection connection;
ObjectInputStream in;
try
{
if (this.m_servletURL.equals("")) {
return alertStatus("Servlet URL not specified!", 'E');
}
try
{
URL inURL = new URL(this.m_servletURL);
connection = inURL.openConnection();
}
catch (Exception e)
{
e.printStackTrace();
return alertStatus("Error opening server connection: " + e.getMessage(), 'E');
}
try
{
// URLConnection connection;
URL inURL;
in = new ObjectInputStream(connection.getInputStream());
}
catch (Exception e)
{
e.printStackTrace();
return alertStatus("Error opening input stream: " + e.getMessage(), 'E');
}
int count;
try
{
count = Integer.parseInt((String)in.readObject());
}
catch (Exception e)
{
e.printStackTrace();
return alertStatus("Error getting object count: " + e.getMessage(), 'E');
}
this.m_XMLCache = new Hashtable(count, 1.0F);
this.m_hashCache = new Hashtable(count, 1.0F);
for (int i = 0; i < count; i++)
{
key = "";
data = new StringBuffer("");
status = (String)in.readObject();
alertStatus("read status", 'D');
key = (String)in.readObject();
alertStatus("read key", 'D');
data = (StringBuffer)in.readObject();
alertStatus("read data", 'D');
hash = (Hashtable)in.readObject();
alertStatus("read cache", 'D');
if (status.equals("connection closed")) {
return alertStatus("Error communicating with servlet: Connection is closed. Please re-login.", 'E');
}
if (status.equals("execution error")) {
return alertStatus("Error in servlet: Error during execution of query. Please notify Data Management.", 'E');
}
if (data == null) {
return alertStatus("Error communicating with servlet: There was a data transmission error. Please notify Data Management.", 'E');
}
alertStatus("got cache: " + key, 'D');
this.m_XMLCache.put(key, data);
this.m_hashCache.put(key, hash);
}
alertStatus("closing stream", 'D');
in.close();
return "";
}
catch (Exception e)
{
e.printStackTrace();
return "Error in loadAllDataInternal: " + e.getMessage();
}
}
private String openAllDataInternal(String path)
{
ObjectInputStream in = null;
String file = "";
StringBuffer data = new StringBuffer("");
Hashtable hash = null;
String status = "";
try
{
status = verifyDataFilesInternal();
if (!status.equals("")) {
return status;
}
StringTokenizer st = new StringTokenizer(this.m_commandKey, ";");
int len = st.countTokens();
this.m_XMLCache = new Hashtable(len, 1.0F);
this.m_hashCache = new Hashtable(len, 1.0F);
while (st.hasMoreElements())
{
String key = (String)st.nextElement();
file = path + key + ".data";
in = new ObjectInputStream(new FileInputStream(file));
data = (StringBuffer)in.readObject();
in.close();
file = path + key + ".hash";
in = new ObjectInputStream(new FileInputStream(file));
hash = (Hashtable)in.readObject();
in.close();
this.m_XMLCache.put(key, data);
this.m_hashCache.put(key, hash);
}
return "";
}
catch (Exception e)
{
e.printStackTrace();
return "Error in openAllDataInternal: " + e.getMessage();
}
}
private String saveAllDataInternal(String s)
{
Enumeration keys = null;
String file = "";
StringBuffer data = new StringBuffer("");
Hashtable hash = null;
ObjectOutputStream out = null;
if (s.equals("")) {
return alertStatus("Data file path is '': " + s, 'E');
}
try
{
keys = this.m_XMLCache.keys();
makeDirectories(s);
while (keys.hasMoreElements())
{
this.m_key = ((String)keys.nextElement());
file = s + this.m_key;
data = (StringBuffer)this.m_XMLCache.get(this.m_key);
hash = (Hashtable)this.m_hashCache.get(this.m_key);
out = new ObjectOutputStream(new FileOutputStream(file + ".data"));
out.writeObject(data);
out.close();
out = new ObjectOutputStream(new FileOutputStream(file + ".hash"));
out.writeObject(hash);
out.close();
}
return "";
}
catch (Exception e)
{
e.printStackTrace();
return "Error in saveAllDataInternal: " + e.getMessage();
}
}
public String loadAllData(boolean verbose)
{
String s =
(String)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return DataCache.this.loadAllDataInternal();
}
});
if (verbose) {
if (s.equals("")) {
alertStatus("Loaded all data!", 'M');
} else {
alertStatus(s, 'E');
}
}
return s;
}
public String saveAllData(boolean verbose, String path)
{
String fpath = path;
String s =
(String)AccessController.doPrivileged(new PrivilegedAction()
{
private final String val$fpath="";
public Object run()
{
return DataCache.this.saveAllDataInternal(this.val$fpath);
}
});
if (verbose) {
if (s.equals("")) {
alertStatus("Saved all data files!", 'M');
} else {
alertStatus(s, 'E');
}
}
return s;
}
public String saveAllData(boolean verbose)
{
String s =
(String)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return DataCache.this.saveAllDataInternal(DataCache.this.m_dataDir);
}
});
if (verbose) {
if (s.equals("")) {
alertStatus("Saved all data files!", 'M');
} else {
alertStatus(s, 'E');
}
}
return s;
}
public String openAllData(boolean verbose)
{
String s =
(String)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return DataCache.this.openAllDataInternal(DataCache.this.m_dataDir);
}
});
if ((s.equals("")) && (verbose)) {
alertStatus("Opened all data files!", 'M');
}
return s;
}
public String verifyAllDataFiles(boolean verbose)
{
String s = verifyDataFilesInternal();
if ((s.equals("")) && (verbose)) {
alertStatus("Verified all data files!", 'M');
}
return s;
}
public void setCache(String key, boolean verbose)
{
this.m_currXMLCache = ((StringBuffer)this.m_XMLCache.get(key));
this.m_currHashCache = ((Hashtable)this.m_hashCache.get(key));
this.m_currCacheString = key;
if (((this.m_currXMLCache == null) || (this.m_currHashCache == null)) &&
(verbose)) {
alertStatus("Requested cache (" + this.m_currCacheString + ") is null!", 'E');
}
}
public String getXML(String key)
{
this.m_currXMLCache = ((StringBuffer)this.m_XMLCache.get(key));
this.m_currHashCache = ((Hashtable)this.m_hashCache.get(key));
this.m_currCacheString = key;
return getXML();
}
public String getXML()
{
if (this.m_currXMLCache == null)
{
alertStatus("Current cache (" + this.m_currCacheString + ") is null!", 'E');
return "";
}
return this.m_currXMLCache.toString();
}
public String lookupCacheValue(String code)
{
String[] values = (String[])this.m_currHashCache.get(code);
return values[1];
}
private void printData(String[][] data)
{
alertStatus("printing data", 'D');
for (int i = 0; i < data[0].length; i++) {
System.out.println("key: " + data[0][i] + "\tvalue: " + data[1][i]);
}
}
}

Creating cookies in javascript and use it into mvc 4 action result

I have make cookies in java script page but when used in the Controller page it shows null and i Check in the browser cookies is also created so please help me for this ......
<script>
#Html.Raw(ViewBag.CallJSFuncOnPageLoad)
function IPDetction()
{
$.getJSON("http://ip-api.com/json/?callback=?", function (data) {
var items = [];
$.each(data, function (key, val)
{
if (key == 'city') {
document.cookie = "DetectedCityName=" + val;
}
if (key == 'region') {
document.cookie = "DetectedRegionName=" + val;
}
});
});
}
</script>
#{
string DetectedCityName = "Toronto";
try
{
RateMadnessfinal.DataModel.RateMadnessdbEntities db = new RateMadnessfinal.DataModel.RateMadnessdbEntities();
DetectedCityName = HttpContext.Current.Request.Cookies["DetectedCityName"].Value;
var getCityID = db.Macities.Where(c => c.CityName.Contains(DetectedCityName)).ToList();
if ((getCityID != null) && (getCityID.Count > 0))
{
DetectedCityName = getCityID.FirstOrDefault().CityName;
}
else
{
DetectedCityName = "Toronto";
}
}
catch (Exception e)
{
DetectedCityName = "Toronto";
}
}

Categories