Java Error: Can not find Symbol [duplicate] - javascript

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 5 years ago.
I've been working on this program for sometime now and I've been struggling with it. I'm new to programming so I don't understand how to fix it. So far I've managed to get rid of most of the errors but this one is the one I, for some reason, cannot fix. Can someone help me? I would really appreciate it.
import java.util.Scanner;
import java.util.ArrayList;
public class PetSorter
{
public static void main (String [] args)
{
ArrayList<Pet> strList = new ArrayList<Pet>();
Boolean another = true;
Scanner keyboard = new Scanner(System.in);
while(another)
{
System.out.println("Enter the pet's name: ");
String nam = keyboard.nextLine();
Pet p = new Pet(nam); //here is where the Error occurs
strList.add(p);
System.out.println("Would you like to enter another pet's name? (y/n)");
String answer = keyboard.nextLine();
another = answer.equalsIgnoreCase("y");
}
PetSorter.nameSort(strList);
for (int x = 0; x < strList.size(); x++)
{
System.out.println(strList.get(x).getName());
}
}
public static void nameSort (ArrayList<Pet> array)
{
for (int i = 1; i < array.size(); i++)
{
int j = i;
Pet tp = array.get(i);
String B = array.get(i).getName();
while ((j > 0) && (array.get(j-1).getName().compareTo(B) > 0 ))
{
array.set(j, array.get(j-1));
j--;
}
array.set(j,tp);
}
}
}
Here is the pet class below
import java.util.ArrayList;
import java.util.Scanner;
public class Pet
{
private String name;
private int age; //in years
private double weight; //in pounds
/**
This main is just a demonstration program.
*/
public static void main(String[] args)
{
Pet myDog = new Pet( );
myDog.set("Fido", 2, 5.5);
myDog.writeOutput( );
System.out.println("Changing name.");
myDog.set("Rex");
myDog.writeOutput( );
System.out.println("Changing weight.");
myDog.set(6.5);
myDog.writeOutput( );
System.out.println("Changing age.");
myDog.set(3);
myDog.writeOutput( );
}
public void writeOutput( )
{
System.out.println("Name: " + name);
System.out.println("Age: " + age + " years");
System.out.println("Weight: " + weight + " pounds");
}
public void set(String newName)
{
name = newName;
//age and weight are unchanged.
}
public void set(int newAge)
{
if (newAge <= 0)
{
System.out.println("Error: illegal age.");
System.exit(0);
}
else
age = newAge;
//name and weight are unchanged.
}
public void set(double newWeight)
{
if (newWeight <= 0)
{
System.out.println("Error: illegal weight.");
System.exit(0);
}
else
weight = newWeight;
//name and age are unchanged.
}
public void set(String newName, int newAge, double newWeight)
{
name = newName;
if ((newAge <= 0) || (newWeight <= 0))
{
System.out.println("Error: illegal age or weight.");
System.exit(0);
}
else
{
age = newAge;
weight = newWeight;
}
}
public String getName( )
{
return name;
}
public int getAge( )
{
return age;
}
public double getWeight( )
{
return weight;
}
}

Add to your Pet class the required constrcutor :
public class Pet {
String name;
...
public Pet (String name) {
this.name = name;
}
...
}

replace with
Pet p = new PetSorter().new Pet(nam); //here is where the Error occurs
and add class Pet
new code:
import java.util.Scanner;
import java.util.ArrayList;
public class PetSorter
{
public class Pet
{
String name;
public Pet(String _name)
{
name=_name;
}
public String getName()
{
return name;
}
}
public static void main (String [] args)
{
ArrayList<Pet> strList = new ArrayList<Pet>();
Boolean another = true;
Scanner keyboard = new Scanner(System.in);
while(another)
{
System.out.println("Enter the pet's name: ");
String nam = keyboard.nextLine();
Pet p = new PetSorter().new Pet(nam); //here is where the Error occurs
strList.add(p);
System.out.println("Would you like to enter another pet's name? (y/n)");
String answer = keyboard.nextLine();
another = answer.equalsIgnoreCase("y");
}
PetSorter.nameSort(strList);
for (int x = 0; x < strList.size(); x++)
{
System.out.println(strList.get(x).getName());
}
}
public static void nameSort (ArrayList<Pet> array)
{
for (int i = 1; i < array.size(); i++)
{
int j = i;
Pet tp = array.get(i);
String B = array.get(i).getName();
while ((j > 0) && (array.get(j-1).getName().compareTo(B) > 0 ))
{
array.set(j, array.get(j-1));
j--;
}
array.set(j,tp);
}
}
}

Pet p = new Pet(nam); , Pet class doesn't have a constructor that takes any arguments.

Related

How to use ActionResult in onkeyup and onkeydown in a input which type is number?

I am trying to use an action result in a input function,here is my code,my goal is that when user Keyup or keydown or type a number in input,Sum of ProductPrice changes.i dont know,which event is proper for my goal,i have used onkeydown & onkeyup events.but nothing changes.
<td><input type="number" onkeyup="#Url.Action("CountUp","ShoppingCart",new { id = #item.ProductId })"
onkeydown="#Url.Action("CountDown","ShoppingCart",new { id = #item.ProductId })"
value="#item.ProductCount" min="0" style="width:70px"></td>
and Here is My controller
// GET: ShoppingCart
public ActionResult Index()
{
List<ShowShoppingCart> shopcart = new List<ShowShoppingCart>();
if (Session["ShoppingCart"] != null)
{
List<ShopCartItem> shop = Session["ShoppingCart"] as List<ShopCartItem>;
foreach (var item in shop)
{
var product = db.Products.Find(item.ProductId);
shopcart.Add(new ShowShoppingCart()
{
ProductCount = item.ProductCount,
ProductId = item.ProductId,
ProductPrice = product.ProductPrice,
ProductTitle = product.ProductTitle,
Sum = item.ProductCount * product.ProductPrice
});
}
}
return View(shopcart);
}
public ActionResult CountUp(int id)
{
List<ShopCartItem> shop = Session["ShoppingCart"] as List<ShopCartItem>;
int index = shop.FindIndex(s => s.ProductId == id);
shop[index].ProductCount += 1;
Session["ShoppingCart"] = shop;
return RedirectToAction("Index");
}
public ActionResult CountDown(int id)
{
List<ShopCartItem> shop = Session["ShoppingCart"] as List<ShopCartItem>;
int index = shop.FindIndex(s => s.ProductId == id);
shop[index].ProductCount -= 1;
if (shop[index].ProductCount == 0)
{
shop.Remove(shop[index]);
}
Session["ShoppingCart"] = shop;
return RedirectToAction("Index");
}
and this is ShopCart
public class ShopCartItem
{
public int ProductId { get; set; }
public int ProductCount { get; set; }
}
and another question?
when user type a number in input which event should i use? onChange()? or another?
Not really sure about your main question, but about the second one, you should really use onChange()

Primefaces 6 And materialprime - widget not available: selectOne

I'm trying to port materialprime to primefaces 6. I already updated the widgets to use core.js and components.js but I have a problem rendering the materialprime. selectOne is not rendering also the jsf selectOneMenu is not rendering only the priemfaces SelectOneMenu works, the console says:
widget not available: selectOne
Any ideas?
This is the code of the 4 files related to selectOne:
MaterialWidgetBuilder.java:
public class MaterialWidgetBuilder extends WidgetBuilder {
private static final String KEY = MaterialWidgetBuilder.class.getName();
public static MaterialWidgetBuilder getInstance(final FacesContext context) {
MaterialWidgetBuilder wb = (MaterialWidgetBuilder) context.getExternalContext().getRequestMap().get(KEY);
if (wb == null) {
wb = new MaterialWidgetBuilder(context);
context.getExternalContext().getRequestMap().put(KEY, wb);
}
return wb;
}
public MaterialWidgetBuilder(FacesContext context) {
super(context);
}
protected WidgetBuilder init(String widgetClass, String widgetVar, String id, String resourcePath, boolean endFunction) throws IOException {
this.endFunction = endFunction;
context.getResponseWriter().write("MaterialPrime.cw(\"");
context.getResponseWriter().write(widgetClass);
context.getResponseWriter().write("\",\"");
context.getResponseWriter().write(widgetVar);
context.getResponseWriter().write("\",{");
context.getResponseWriter().write("id:\"");
context.getResponseWriter().write(id);
if (widgetVar == null) {
context.getResponseWriter().write("\"");
} else {
context.getResponseWriter().write("\",widgetVar:\"");
context.getResponseWriter().write(widgetVar);
context.getResponseWriter().write("\"");
}
return this;
}
}
SelectOne.java:
#ResourceDependencies({
#ResourceDependency(library = "primefaces", name = "jquery/jquery.js"),
#ResourceDependency(library = "primefaces", name="core.js"),
#ResourceDependency(library = "primefaces", name="components.js"),
#ResourceDependency(library = "material-prime", name = "libs/materialize.css"),
#ResourceDependency(library = "material-prime", name = "libs/materialize.js"),
#ResourceDependency(library = "material-prime", name = "core/material-prime.js"),
#ResourceDependency(library = "material-prime", name = "core/material-prime.css"),
#ResourceDependency(library = "material-prime", name = "selectone/selectOne.js")
})
public class SelectOne extends SelectOneMenu{
public static final String COMPONENT_TYPE = "org.primefaces.material.component.SelectOne";
protected enum PropertyKeys {
nativeMode
}
public SelectOne() {
setRendererType(SelectOneRenderer.RENDERER_TYPE);
}
#Override
public String getFamily() {
return MaterialPrime.COMPONENT_FAMILY;
}
public boolean isNativeMode(){
return (Boolean) getStateHelper().eval(PropertyKeys.nativeMode,false);
}
public void setNativeMode(boolean nativeMode){
getStateHelper().put(PropertyKeys.nativeMode, nativeMode);
}
}
SelectOneRenderer.java:
public class SelectOneRenderer extends InputRenderer {
public static final String RENDERER_TYPE = "org.primefaces.material.component.SelectOneRenderer";
#Override
public void decode(FacesContext context, UIComponent component) {
SelectOne selectOne = (SelectOne) component;
if(selectOne.isDisabled()) {
return;
}
decodeBehaviors(context, selectOne);
String clientId = selectOne.getClientId(context);
String submittedValue = (String) context.getExternalContext().getRequestParameterMap().get(clientId + "_input");
if(submittedValue!=null){
selectOne.setSubmittedValue(submittedValue);
}
}
#Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
SelectOne selectOne = (SelectOne) component;
encodeMarkup(context, selectOne);
encodeScript(context, selectOne);
}
private void encodeMarkup(FacesContext context, SelectOne selectOne) throws IOException {
ResponseWriter writer = context.getResponseWriter();
String inputId = selectOne.getClientId() + "_input";
List<SelectItem> selectItems = getSelectItems(context, selectOne);
writer.startElement("div", selectOne);
writer.writeAttribute("class", "input-field", null);
writer.startElement("select", selectOne);
writer.writeAttribute("class", getSelectClass(selectOne), null);
writer.writeAttribute("id", inputId, null);
writer.writeAttribute("name", inputId, null);
for (SelectItem selectItem : selectItems) {
writer.startElement("option", null);
if(selectItem.getValue().equals(selectOne.getValue())){
writer.writeAttribute("selected", "selected", null);
}
writer.writeAttribute("value", selectItem.getValue(),null);
writer.write(selectItem.getLabel());
writer.endElement("option");
}
writer.endElement("select");
writer.endElement("div");
}
private String getSelectClass(SelectOne selectOne) {
String toReturn = "";
if(selectOne.isNativeMode()){
toReturn += " browser-default ";
}
return toReturn;
}
private void encodeScript(FacesContext context, SelectOne selectOne) throws IOException {
String clientId = selectOne.getClientId();
String widgetVar = selectOne.resolveWidgetVar();
WidgetBuilder wb = MaterialWidgetBuilder.getInstance(context);
wb.initWithDomReady("SelectOne", widgetVar, clientId);
wb.attr("widgetName", widgetVar);
encodeClientBehaviors(context, selectOne);
wb.finish();
}
}
SelectOne.js
MaterialPrime.widget.SelectOne = PrimeFaces.widget.BaseWidget.extend({
init : function(cfg) {
this._super(cfg);
this.input = jQuery(this.jqId+"_input");
var that = this;
this.input.material_select();
this.input.on("change",function(){
if(that.cfg.behaviors && that.cfg.behaviors.valueChange) {
that.cfg.behaviors.valueChange.call(that.input);
}
});
}
});

values modified in javascript not getting updated in JSF PhaseListener

Initially hold_mode value is set to 0, after commandButton click, it changed to 1 through JavaScript onclick event...but in PhaseListener beforePhase() method, the value is 0. I did not understand why the value is still 0.
Can anyone please explain me on this.?
info.xhtml
<h:form id="userForm">
<h:inputHidden id="hold_mode" value="0" />
<h:commandButton id="hold" style="width: 60px;" value="#{myForm.holdbtntitle}" disabled="#{myForm.holdbtn}" action="#{myForm.hold}" actionListener="#{convo.holdListener}" onclick="return send(true,'3');" rendered="#{myForm.holdpanelflg}"/>
JavaScript
function send(confirmFlg,msgFlg) {
isClicked = true;
if(confirmFlg) {
msg = 'From Hold';
if(confirm(msg) == false) {
isClicked = false;
event.returnValue = false;
return false;
}
}
if(isClicked) {
if(msgFlg == '3') {
document.all.item('myForm:hold_mode').value='1';
}
pep_OpenWaitDirect('../../../html/common/printwait.xhtml');
return true;
} else {
return false;
}
}
PhaseListener
public class RemoveValidateListener implements PhaseListener {
private static final long serialVersionUID = 3556867423746720962L;
private FacesContext old = null;
public void beforePhase(PhaseEvent e) {
System.out.println("Before "+e.getPhaseId());
if(e.getPhaseId().equals(PhaseId.PROCESS_VALIDATIONS)) {
UIComponent comp = FacesContext.getCurrentInstance().getViewRoot();
if(findHoldMode(comp)){
old = FacesContext.getCurrentInstance();
removeValidatorsForComponentTree(comp);
}
}
}
public void afterPhase(PhaseEvent e) {
System.out.println("After "+e.getPhaseId());
if(e.getPhaseId().equals(PhaseId.PROCESS_VALIDATIONS)) {
FacesContext context = FacesContext.getCurrentInstance();
UIComponent comp = FacesContext.getCurrentInstance().getViewRoot();
if(findHoldMode(comp)){
StateManager stateManager = (StateManager)context.getApplication().getStateManager();
stateManager.restoreView(old,old.getViewRoot().getViewId(),old.getViewRoot().getRenderKitId());
}
}
}
private boolean findHoldMode(UIComponent comp){
boolean rtnFlg = false;
List list = comp.getChildren();
for (int i = 0; i < list.size(); i++) {
UIComponent temp = (UIComponent) list.get(i);
if (!(temp instanceof HtmlBody)) {
continue;
} else {
List<UIComponent> childList = temp.getChildren();
for (int j = 0; j < childList.size(); j++) {
UIComponent childTemp = (UIComponent) childList.get(j);
if (!(childTemp instanceof HtmlPanelGrid)) {
continue;
} else {
List<UIComponent> child2List = childTemp.getChildren();
for (int k = 0; k < child2List.size(); k++) {
UIComponent child2Temp = (UIComponent) child2List.get(k);
if (!(child2Temp instanceof HtmlForm)) {
continue;
}
UIComponent hold = child2Temp.findComponent(JsfBase.HOLD_MODE_COMPNAME);
if (hold == null) {
continue;
}
if (!(hold instanceof UIInput)) {
continue;
}
Object mode = ((UIInput) hold).getValue();
if (mode == null || !(mode.toString().equals(JsfBase.HOLD_MODE_ON))) {
continue;
} else {
rtnFlg = true;
((UIInput) hold).setValue("0");
break;
}
}
}
}
}
}
return rtnFlg;
}
private void removeValidatorsForComponentTree(UIComponent comp){
removeValidators(comp);
List complist = comp.getChildren();
if (complist.size()>0){
for(int i = 0; i < complist.size(); i++) {
UIComponent uicom = (UIComponent) complist.get(i);
removeValidatorsForComponentTree(uicom);
}
}
}
private void removeValidators(UIComponent comp){
if(comp instanceof UIInput){
removeValidator((UIInput)comp);
}
}
public void removeValidator(UIInput comp){
Validator[] validator = comp.getValidators();
for(int i=0;i < validator.length;i++){
comp.removeValidator(validator[i]);
}
if(comp.isRequired()){
comp.setRequired(false);
}
}
}
I tried this <h:inputHidden id="hold_mode" value="0" immediate="true" /> and it works for the current screen but the problem is when I click the commandButton in other screens, the following exception occured
java.lang.IllegalStateException: FacesContext already released
Issue got fixed after modified PhaseListener
Why I got IllegalStateException is as I have declared FacesContext object old globally. In that case, I had declared it inside befoerPhase method as we don't declare FacesContext globally..
Before code modification, what we did is we removed validators in beforePhase and we are restoring the view state in afterPhase, but it did not worked properly. So now I am saving the view state before validators removal in beforePhase instead of restoring it in afterPhase..
public class RemoveValidateListener implements PhaseListener {
private static final long serialVersionUID = 3556867423746720962L;
public void beforePhase(PhaseEvent e) {
if (e.getPhaseId().equals(PhaseId.PROCESS_VALIDATIONS)) {
FacesContext context = FacesContext.getCurrentInstance();
UIComponent comp = context.getViewRoot();
StateManager stateManager = (StateManager) context.getApplication().getStateManager();
stateManager.saveView(context);
if (findHoryuMode(comp)) {
removeValidatorsForComponentTree(comp);
}
}
}
public void afterPhase(PhaseEvent e) {
}
}

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]);
}
}
}

Get the javascript push object array in a MVC3 controller action

This is my javascript code:
var bankOptions = {};
var playerOptions = [];
bankOptions["BankTotalAmount"] = $("#totalBankAmountID").val();
bankOptions["SinglePlayerAmount"] = $("#singlePlayerAmountID").val();
while (_playerNumber != 0) {
if (_playerNumber == 1) {
var player1Option = {};
player1Option["Name"] = $("#p" + _playerNumber + "Name").val();
player1Option["Color"] = $("#p" + _playerNumber + "Color").val();
playerOptions.push(player1Option);
}
if (_playerNumber == 2) {
var player2Option = {};
player2Option["Name"] = $("#p" + _playerNumber + "Name").val();
player2Option["Color"] = $("#p" + _playerNumber + "Color").val();
playerOptions.push(player2Option);
}
if (_playerNumber == 3) {
var player3Option = {};
player3Option["Name"] = $("#p" + _playerNumber + "Name").val();
player3Option["Color"] = $("#p" + _playerNumber + "Color").val();
playerOptions.push(player3Option);
}
if (_playerNumber == 4) {
var player4Option = {};
player4Option["Name"] = $("#p" + _playerNumber + "Name").val();
player4Option["Color"] = $("#p" + _playerNumber + "Color").val();
playerOptions.push(player4Option);
}
_playerNumber--;
}
alert(playerOptions);
$.ajax({
url: "/StartOption/setOptions/",
contentType: 'application/json',
data: JSON.stringify({ bankOptions: bankOptions, playerOptions: playerOptions }),
type: "POST",
timeout: 10000,
success: function (result) {
}
});
and i have this Controller class
public class StartOptionController : Controller
{
private MonopolyDB db = new MonopolyDB();
//
// GET: /StartOption/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult setOptions(BankOptions bankOptions, Playeroptions[] playerOptions)
{
//int length = (int)playerOptions.GetType().InvokeMember("length", BindingFlags.GetProperty, null, playerOptions, null);
BankAccount bankaccount = new BankAccount();
bankaccount.ID = 1;
bankaccount.TotalAmmount = bankOptions.BankTotalAmount;
db.BankAccount_Table.Add(bankaccount);
db.SaveChanges();
//Here i want to get each (player1Option, player2Option...) object array from that playerOptions object array
//return RedirectToAction("Index");
return View();
}
}
public class BankOptions
{
public int BankTotalAmount { get; set; }
public int SinglePlayerAmount { get; set; }
}
public class Playeroptions
{
public string Name { get; set; }
public string Color { get; set; }
}
My question is how i can get those object array that i push into playerOptions object array in my setOptions action?
as like i want to save each player info in my DB from playerOptions object array where i push each player info in my javascript code.
Well first to make it easy I would like to recommend that changes the sign of your action
from
public ActionResult setOptions(BankOptions bankOptions, Playeroptions[] playerOptions)
To
public ActionResult setOptions(BankOptions bankOptions, List<PlayerOptions> playerOptions)
That's it's going to make it easy the handle of each element of the array, and there's not problem for the framework to serialize this object.
Now to answer your question you could iterate the array like this
[HttpPost]
public ActionResult setOptions(BankOptions bankOptions, Playeroptions[] playerOptions)
{
//int length = (int)playerOptions.GetType().InvokeMember("length", BindingFlags.GetProperty, null, playerOptions, null);
BankAccount bankaccount = new BankAccount();
bankaccount.ID = 1;
bankaccount.TotalAmmount = bankOptions.BankTotalAmount;
db.BankAccount_Table.Add(bankaccount);
db.SaveChanges();
//Here i want to get each (player1Option, player2Option...) object array from that playerOptions object array
for ( int i = 0 ; i< playerOptions.Length, i++)
{
playerOptions[i]; //<-- this give's the specific element
}
//return RedirectToAction("Index");
return View();
}
Nevertheless if you follow my recommendation and changes the sign of your action you could iterate your code like this
[HttpPost]
public ActionResult setOptions(BankOptions bankOptions, List<PlayerOptions> playerOptions)
{
//int length = (int)playerOptions.GetType().InvokeMember("length", BindingFlags.GetProperty, null, playerOptions, null);
BankAccount bankaccount = new BankAccount();
bankaccount.ID = 1;
bankaccount.TotalAmmount = bankOptions.BankTotalAmount;
db.BankAccount_Table.Add(bankaccount);
db.SaveChanges();
//Here i want to get each (player1Option, player2Option...) object array from that playerOptions object array
foreach( var item in playerOptions){
item //<--- in this variable you have the element PlayerOption
}
//return RedirectToAction("Index");
return View();
}

Categories