Replace Java Applet with GWT - javascript

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

Related

sending file through webscoket in browser with js to c# server

I have a problem in sending file through webscoket in browser with js to c# server.
When I want to save the buffer, if it is a txt file, there is no problem
But if it is a photo, for example, the photo will not be opened after saving
Where am I going wrong?
private void BeginReceive()
{
try
{
Buffer = new byte[BufferSize];
Socket.BeginReceive(Buffer, 0, BufferSize, SocketFlags.None, new AsyncCallback(ReceiveCallback), this);
}
catch (SocketException ex)
{
Console.WriteLine("{0}: {1}", "BeginReceive", ex.Message);
Close();
}
catch (Exception ex)
{
Console.WriteLine("{0}: {1}", "BeginReceive", ex.Message);
}
}
private void ReceiveCallback(IAsyncResult ar)
{
try
{
if (CheckState(ar))
{
int bytesRead = Socket.EndReceive(ar);
Console.WriteLine("{0}: {1}", "bytesRead: ", bytesRead);
File.WriteAllText(#"c:\01.jpg", Helper.DecodedBytes(Buffer, bytesRead));
}
}
catch (SocketException)
{
Close();
}
catch (Exception ex)
{
Console.WriteLine("{0}: {1}", "ReceiveCallback", ex.Message);
}
finally
{
if(!Helper.SocketIsDisposed(Socket)) BeginReceive();
}
}
I think the problem is with the decode function
public static string DecodedBytes(byte[] buffer, int length)
{
if(buffer[0] == 136 && (buffer[1] == 130 || buffer[1] == 128)) throw new System.Net.Sockets.SocketException(10054); //[10054]: Connection reset by peer
byte b = buffer[1];
int dataLength = 0;
int totalLength = 0;
int keyIndex = 0;
if (b - 128 <= 125)
{
dataLength = b - 128;
keyIndex = 2;
totalLength = dataLength + 6;
}
if (b - 128 == 126)
{
dataLength = BitConverter.ToInt16(new byte[] { buffer[3], buffer[2] }, 0);
keyIndex = 4;
totalLength = dataLength + 8;
}
if (b - 128 == 127)
{
dataLength = (int)BitConverter.ToInt64(new byte[] { buffer[9], buffer[8], buffer[7], buffer[6], buffer[5], buffer[4], buffer[3], buffer[2] }, 0);
keyIndex = 10;
totalLength = dataLength + 14;
}
if (totalLength > length)
throw new Exception("The buffer length is small than the data length");
byte[] key = new byte[] { buffer[keyIndex], buffer[keyIndex + 1], buffer[keyIndex + 2], buffer[keyIndex + 3] };
int dataIndex = keyIndex + 4;
int count = 0;
for (int i = dataIndex; i < totalLength; i++)
{
buffer[i] = (byte)(buffer[i] ^ key[count % 4]);
count++;
}
return Encoding.UTF8.GetString(buffer, dataIndex, dataLength);
}
and js code:
connect:function(){
var root = this;
root.websocket = new WebSocket(root.url);
root.websocket.binaryType = "arraybuffer";
root.websocket.onopen = () => root.fireEvent('connect');
root.websocket.onmessage = (e) => {
root.fireEvent('receive',JSON.parse(e.data));
}
window.addEventListener("beforeunload", function() {
root.websocket.onclose = function () {};
root.websocket.close();
});
},
sendFile:function(){
var root = this;
var file = document.getElementById('filename').files[0];
var loader = new FileReader();
loader.onload = (e) => {
var a = e.target.result;
root.controller.websocket.send(e.target.result);
}
loader.readAsText(file)
},
Problem solved
JS code changed to:
sendFile:function(){
var root = this;
var file = document.getElementById('filename').files[0];
var loader = new FileReader();
loader.onload = (e) => {
var byteArray = new Uint8Array(e.target.result);
root.controller.websocket.send(byteArray.buffer);
}
loader.readAsArrayBuffer(file);
}
and C# code changed to:
WriteAllText to WriteAllBytes
File.WriteAllBytes(#"c:\01.jpg", Helper.DecodedBytes(Buffer, bytesRead));
and Encoding.Default.GetString(buffer, dataIndex, dataLength) to buffer.Skip(dataIndex).ToArray()
return buffer.Skip(dataIndex).ToArray();

Form a tree or nodes from a raw string

I have the following as a string
var string = "#anno1[ data1 xyz #anno2[data2 #anno3[data3] data4] data5 #anno4[data6] data7]"
And I would like to convert it an object as follows:
var childs = [
{
name : '#anno1',
text : 'data1 xyz data2 data3 data4 data5 data6 data7',
},
{
name : '#anno2',
text : 'data2 data3 data4'
},
{
name : '#anno3',
text : 'data3'
},
{
name : '#anno4',
text : 'data6'
}
]
I've tried out many ways but I was not successful, thanks in advance.
Here is the java code which i have tried
import java.util.HashMap;
import java.util.Map;
public class ExpressionTree {
static Map <String, String> resultMap = new HashMap<String, String>(16);
public static void main(String args[]) {
// String exp = "[data1 xyz #anno2[data2 #anno3[data3] data4] data5 #anno4[data6] data7]";
String exp = "#anno1[ data1 xyz #anno2[data2 #anno3[data3] data4] data5 #anno4[data6] data7 ]";
parseRecursively(exp);
}
private static void parseRecursively(String exp) {
String annotation = null;
String annotationValue = null;
if (exp.startsWith("#")) {
int dataStartIndex = exp.indexOf("[");
annotation = exp.substring(0, dataStartIndex);
annotationValue = exp.substring(0 + dataStartIndex, exp.lastIndexOf("]")+1).trim();
System.out.println(annotation);
System.out.println(annotationValue);
resultMap.put(annotation, annotationValue);
parseRecursively(annotationValue);
} else {
int annotationStartIndex = exp.indexOf("#");
int dataStartIndex = exp.substring(1).indexOf("[");
if( -1 != annotationStartIndex || -1 != dataStartIndex)
{
annotation = exp.substring(annotationStartIndex, dataStartIndex+1).trim();
String nextData = exp.substring(0 + dataStartIndex + 1).trim();
String tmpNextData = nextData;
int countOfOpenBrackets = 0;
for (int i = 0; tmpNextData.charAt(i) != ']'; i++) {
// System.out.println(tmpNextData.charAt(i));
if (tmpNextData.charAt(i) == '[') {
countOfOpenBrackets++;
}
// tmpNextData = tmpNextData.substring(1);
}
tmpNextData = nextData;
int endIndexOfCurrentData = 0;
for (int i = 0; i < tmpNextData.length() && endIndexOfCurrentData == 0; i++) {
// System.out.println(tmpNextData.charAt(i));
if (tmpNextData.charAt(i) == ']') {
countOfOpenBrackets--;
}
if (countOfOpenBrackets == 0) {
endIndexOfCurrentData = i + 1;
}
// tmpNextData = tmpNextData.substring(1);
}
annotationValue = nextData.substring(0, endIndexOfCurrentData).trim();
System.out.println(annotation);
System.out.println(annotationValue);
resultMap.put(annotation, annotationValue);
parseRecursively(annotationValue);
}
}
System.out.println(resultMap);
}
}
Here is a JavaScript (ES6) solution:
function toObject(string) {
"use strict";
const tokens = string.match(/[\[\]]|[^\s\[\]]+/g),
result = [];
let i = 0;
function recurse() {
const words = [];
let obj;
while (i < tokens.length) {
let token = tokens[i];
if (token[0] === '#') {
obj = {name: token};
result.push(obj);
} else if (token === '[') {
i++;
obj.text = recurse();
words.push(obj.text);
} else if (token === ']') {
break;
} else {
words.push(token);
}
i++;
}
return words.join(' ');
}
recurse();
return result;
}
const string = "#anno1[ data1 xyz #anno2[data2 #anno3[data3] data4] data5 #anno4[data6] data7]";
const result = toObject(string);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Liferay - Select item filled with json responseData

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

Validating ReCaptcha (Javascript API) User Answer on Localhost with ASP.NET

I am using ReCaptcha with the javascript API on my aspx page on localhost. I read somewhere that I don't need a key as long as I use it on localhost. So, I use some random key that I found somewhere. I could render the recaptcha challenge successfully. The following is my javascript code.
Recaptcha.create("6Ld4iQsAAAAAAM3nfX_K0vXaUudl2Gk0lpTF3REf", 'captchadiv',
{
tabindex: 1,
theme: "clean",
callback: Recaptcha.focus_response_field
});
//To Validate user response
function Recaptcha_IsCorrect()
{
var xmlHttpRequest;
var PageURL = document.URL;
var xmlDoc;
if (window.XMLHttpRequest)
{
xmlHttpRequest = new XMLHttpRequest();
}
else
{
xmlHttpRequest = new ActiveXObject("Microsoft.xmlHttpRequest");
}
var challenge = Recaptcha.get_challenge();
var userResponse = Recaptcha.get_response();
var url = "../Ajax/PIAsyncAjax.asmx/ValidateReCaptcha?clientIP=127.0.0.1&privateKey=6Ld4iQsAAAAAAM3nfX_K0vXaUudl2Gk0lpTF3REf&challenge=" + challenge + "&response=" + userResponse;
xmlHttpRequest.open("GET", url);
xmlHttpRequest.onreadystatechange = function ()
{
if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
{
alert(xmlHttpRequest.responseText);
}
};
xmlHttpRequest.send();
}
The following is my code for the webservice which exposed the webmethod to validate ReCaptcha user input. I get the error "invalid-site-private-key".
namespace YADA.YADAYADA{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class PIAsyncAjax : System.Web.Services.WebService
{
[WebMethod]
public string ValidateReCaptcha(string clientIP, string privateKey, string challenge, string response)
{
bool isValid = false;
string validationResponse = "";
reCaptchaValidation validator =
new reCaptchaValidation(null,
clientIP,
privateKey,
challenge,
response);
isValid = validator.Validate();
if (isValid)
{
validationResponse = "true";
}
else
{
if (!validator.IsErrored)
{
validationResponse = "false";
}
else
{
// oh dear, something not right
if (validator.Exception != null) // an exception occurred while
// trying to validate
validationResponse = validator.Exception.ToString();
else if (validator.ValidationResult != null) // the validation web service
// returned an error code
// (other than an invalid captcha solution)
validationResponse = "web service error: " + validator.ValidationResult;
}
}
return validationResponse;
}
}
public class reCaptchaValidation
{
private string challenge, response, privateKey, ip;
private IWebProxy proxy;
public reCaptchaValidation(string clientIP, string privateKey,
string challenge, string response) : this(null, clientIP, privateKey,
challenge, response) { }
public reCaptchaValidation(IWebProxy proxy, string clientIP,
string privateKey, string challenge, string response)
{
this.proxy = proxy;
this.ip = clientIP;
this.privateKey = privateKey;
this.challenge = challenge;
this.response = response;
}
private bool _errored;
public bool IsErrored
{
get
{
return _errored;
}
}
private Exception _ex;
public Exception Exception
{
get
{
return _ex;
}
}
private string _vr;
public string ValidationResult
{
get
{
return _vr;
}
}
public bool Validate()
{
try
{
string post = "privatekey=" + HttpUtility.UrlEncode(privateKey) +
"&remoteip=" + HttpUtility.UrlEncode(ip) + "&challenge=" +
HttpUtility.UrlEncode(challenge) + "&response=" +
HttpUtility.UrlEncode(response);
WebRequest wr = HttpWebRequest.Create
("http://www.google.com/recaptcha/api/verify");
wr.Method = "POST";
if (proxy != null)
wr.Proxy = proxy;
wr.ContentLength = post.Length;
wr.ContentType = "application/x-www-form-urlencoded";
using (StreamWriter sw = new StreamWriter(wr.GetRequestStream()))
{
sw.Write(post);
sw.Close();
}
HttpWebResponse resp = (HttpWebResponse)wr.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
string valid = sr.ReadLine();
if (valid != null)
{
if (valid.ToLower().Trim() == "false")
{
string errorcode = sr.ReadLine();
if (errorcode != null)
{
if (errorcode.ToLower().Trim() != "incorrect-captcha-sol")
{
_vr = errorcode;
_errored = true;
return false;
}
}
}
return (valid.ToLower().Trim() == "true");
}
else _vr = "empty web service response";
sr.Close();
return false;
}
}
catch (Exception caught)
{
_errored = true;
_ex = caught;
}
return false;
}
}}
What am I doing wrong? Should I have to get a private key? Any help would be great.
Thanks in advance,
Venkat.
It works with the public and private keys that I just created. Damn, I just assumed, "localhost" would not be accepted as a legal domain-name while signing up.

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