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

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.

Related

reset the form data after submission in struts

I am very new to struts and the application is using struts , and every time I submit the form the old values are submitted until and unless I change the values by selecting different options from drop down or I go to other tab and come back again to the same tab then in this case the values are resetting..
In my scenario what I want to achieve is to reset some of the values after they executed once.on the basis of those values I have to search some data and show it on the form, if I don't remove this value then it .
This is my execute method :
public class ListTerminalDevicesAction extends BaseQueryAction {
private RetailerService retailerService;
private DataBinder<OmposTerminalQuery> dataBinder;
private TerminalDeviceService terminalDeviceService;
private ImportCSVService importCSVService;
#Inject
public void setImportCSVService(ImportCSVService importCSVService) {
this.importCSVService = importCSVService;
}
#Inject
public void setRetailerService(final RetailerService retailerService) {
this.retailerService = retailerService;
}
#Inject
public void setTerminalDeviceService(final TerminalDeviceService terminalDeviceService) {
this.terminalDeviceService = terminalDeviceService;
}
#Inject
private DataBinder<OmposTerminalQuery> getDataBinder() {
if (dataBinder == null) {
final BeanBinder<OmposTerminalQuery> binder = BeanBinder.instance(OmposTerminalQuery.class);
binder.registerBinder("pageParameters", DataBinderHelper.pageBinder());
binder.registerBinder("retailer", PropertyBinder.instance(OmposRetailer.class, "retailer"));
binder.registerBinder("branch", PropertyBinder.instance(OmposBranch.class, "branch"));
binder.registerBinder("store", PropertyBinder.instance(OmposStore.class, "store"));
binder.registerBinder("terminalId", PropertyBinder.instance(String.class, "terminalId"));
binder.registerBinder("terminalSearchByTid",
PropertyBinder.instance(String.class, "terminalSearchByTid"));
dataBinder = binder;
}
return dataBinder;
}
#Override
protected void executeQuery(ActionContext context, QueryParameters queryParameters) {
final OmposTerminalQuery query = (OmposTerminalQuery) queryParameters;
query.setResultType(ResultType.PAGE);
// List<OmposRetailer> retailerList = retailerService.searchRetailers();
// context.getRequest().setAttribute("retailers", retailerList);
// if (query.getRetailer() != null) {
// OmposBranchQuery branchQuery = new OmposBranchQuery();
// branchQuery.setOmposRetailer(query.getRetailer());
// List<OmposBranch> branchList = retailerService.searchBranchByRetailer(branchQuery);
// context.getRequest().setAttribute("branches", branchList);
// if (query.getBranch() != null) {
// OmposStoreQuery storeQuery = new OmposStoreQuery();
// storeQuery.setOmposBranch(query.getBranch());
// List<OmposStore> storeList = retailerService.searchStore(storeQuery);
List<OmposStore> storeList = retailerService.searchStores();
context.getRequest().setAttribute("stores", storeList);
if (query.getStore() != null) {
ListTerminalDevicesForm form = context.getForm();
final FormFile uploadTerminal = form.getUploadTerminal();
if (uploadTerminal != null && uploadTerminal.getFileSize() != 0) {
try {
ImportCSVDTO uploadDtoForTerminal = new ImportCSVDTO();
// uploadDtoForTerminal.setRetailer(query.getRetailer());
// uploadDtoForTerminal.setBranch(query.getBranch());
uploadDtoForTerminal.setStore(query.getStore());
int records = importCSVService.importCSV(TMSEntity.TERMINAL, uploadDtoForTerminal,
uploadTerminal.getInputStream());
if (records > 0) {
context.getRequest().setAttribute("uploadMsgTerminal", records);
}
} catch (final UnknownColumnException | IOException e) {
// context.sendError("general.error.csv.unknownColumn",
// e.getColumn());
} finally {
uploadTerminal.destroy();
}
}
OmposTerminalQuery terminalQuery = new OmposTerminalQuery();
List<OmposTerminal> terminalList = null;
if (query.getStore() != null && query.getTerminalSearchByTid() != null) {
terminalQuery.setTerminalSearchByTid(query.getTerminalSearchByTid());
terminalQuery.setStore(query.getStore());
terminalList = terminalDeviceService.searchTerminalByTidAndStoreId(terminalQuery);
} else {
terminalQuery.setStore(query.getStore());
terminalList = terminalDeviceService.searchByStore(terminalQuery);
}
context.getRequest().setAttribute("terminals", terminalList);
if (query.getTerminalId() != null) {
OmposTerminal omposTerminal = new OmposTerminal();
omposTerminal.setTerminalId(query.getTerminalId());
OmposDeviceQuery deviceQuery = new OmposDeviceQuery();
deviceQuery.setOmposTerminal(omposTerminal);
final FormFile uploadDevice = form.getUploadDevice();
if (uploadDevice != null && uploadDevice.getFileSize() != 0) {
try {
ImportCSVDTO uploadDtoForDevice = new ImportCSVDTO();
uploadDtoForDevice.setRetailer(query.getRetailer());
uploadDtoForDevice.setBranch(query.getBranch());
uploadDtoForDevice.setStore(query.getStore());
uploadDtoForDevice.setTerminal(new OmposTerminal(null, query.getTerminalId(), null));
int records = importCSVService.importCSV(TMSEntity.DEVICE, uploadDtoForDevice,
uploadDevice.getInputStream());
if (records > 0) {
context.getRequest().setAttribute("uploadMsgDevice", records);
}
} catch (final UnknownColumnException | IOException e) {
// context.sendError("general.error.csv.unknownColumn",
// e.getColumn());
} finally {
uploadDevice.destroy();
}
}
context.getRequest().setAttribute("terminalId", query.getTerminalId());
List<OmposDevice> deviceList = terminalDeviceService.searchByTerminal(deviceQuery);
context.getRequest().setAttribute("devices", deviceList);
}
}
// }
// }
}
#Override
protected QueryParameters prepareForm(ActionContext context) {
final ListTerminalDevicesForm form = context.getForm();
final OmposTerminalQuery query = getDataBinder().readFromString(form.getQuery());
return query;
}
#Override
protected boolean willExecuteQuery(final ActionContext context,
final QueryParameters queryParameters) throws Exception {
return true;
}
}
I have to reset "terminalSearchByTid" field after the execution.
override Struts' Action reset() method

Stuck with response.flushBuffer

Can somebody find what is wrong with this code. I've tried to flush the content partially to the client. But it sends data from initial value rather than sending data in chunks.
public String execute()
{
String action = request.getParameter("action");
try
{
switch(action)
{
case "flush":
response.setContentType(ContentTypeConstants.APP_JSON_UTF8);
PrintWriter pw = response.getWriter();
for(int i = 0 ; i < 10; i++)
{
JSONObject json = new JSONObject();
json.put("key", i+"");
pw.print(json+"");
response.flushBuffer();
Thread.sleep(500);
}
break;
default:
break;
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
My script code is
var http=getHTTPObject();
http.open("GET", url, true);
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
http.setRequestHeader("X-Requested-With","XMLHttpRequest");
http.onreadystatechange = function () {
if (http.readyState == 3)
{
console.log(http.responseText)
}
}
http.send();

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

#Controller returns empty page with "ok"

I'm trying to save a file with js from modal window. I save it all right but then I'm redirected to the page with only "ok" written on it.
I mean this:
My js looks like:
var name = $('#upload-track-name').val();
var description = $('#upload-track-description').val();
var file = document.getElementById('input-file').files[0];
var isValidate = true;
if (name.trim() == '') {
$('#error-upload-track-name').show();
isValidate = false;
}
if (!file) {
$('#error-upload-track-file').show();
isValidate = false;
}
if (!isValidate) {
return;
}
$.ajax({
url: '/tracks/upload',//I see this empty page on this url
type: 'post',
data: {
file: file,
name: name,
description: description
},
success: function (data){
if (data == 1) {
$('#error-upload-track-file').hide();
$('#error-upload-track-name').show();
} else if (data == 2) {
$('#error-upload-track-name').hide();
$('#error-upload-track-file').show();
} else {
$('#modal-upload-success').show();
}
})
And here is my #Controller:
#ResponseBody
#RequestMapping(value = TracksGeopointsRoutes.UPLOAD, method = RequestMethod.POST)
public String uploadTrack(#RequestParam MultipartFile file,
#RequestParam String name,
#RequestParam(required = false, defaultValue = "") String description,
Model model){
TracksGeopointsDoc tracksGeopointsDoc = new TracksGeopointsDoc();
if (name.equals("")) {
return "1";
}
if (file.getSize() == 0 || file == null){
return "2";
}
ObjectId fileId = fileService.saveWithDelete(file, null);
tracksGeopointsDoc.setFile(fileId);
tracksGeopointsDoc.setUploadDate(new Date());
tracksGeopointsDoc.setName(name);
tracksGeopointsDoc.setDescription(description);
tracksGeopointsService.saveTrack(tracksGeopointsDoc);
try {
File convFile = tracksGeopointsService.convert(file);
String s = convFile.getAbsolutePath();
mySaxParser.setUpMySaxParser(convFile.getAbsolutePath(), tracksGeopointsDoc.getId(), convFile.getName());
} catch (IOException e) {
e.printStackTrace();
}
return "ok";
}
I suspect that it is because of #ResponseBody annotation. And if I am right can anyone tell me how can I avoid this.

Additional request are sending after first request upload file using xhr ajax with formData

I have spend many hours of trying simulate this error on localhost, but without success.This error happend sometime on live version of web. From live version of web is send error email.
Here is Error
The parameters dictionary contains a null entry for parameter 'isJsonResponse' of non-nullable type 'System.Boolean' for method 'System.Web.Mvc.ActionResult UploadFileDocument(Model, Boolean)' in Controller'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Here is javascript:
$('#uploadFile').click(function () {
var input = $('#file')[0];
if (input.files.length == 0) return;
$(".titleRed", $('#files')).remove();
var dObject = new Object();
dObject.TypeID = $('#types').val();
dObject.FileName = input.files[0].name;
dObject.File = input.files[0];
dObject.ID = '#HttpUtility.JavaScriptStringEncode(Model.ID)';
var formData = new FormData();
for (var key in dObject) {
formData.append(key, dObject[key]);
}
formData.append('isJsonResponse', false);
uploadFiles(formData, function (result) {
if (typeof result == 'object') {
console.log(result.msg);
} else {
$('#files').append(result);
$('#fileAlert').remove();
}
});
document.getElementById('file').value = '';
$('#types').val('1');
return false;
});
Function uploadFile:
function uploadFiles(formData, updateCallback,progressCallback,startCallback,errorCallback) {
var xhr = new XMLHttpRequest();
xhr.open('POST', _uploadFilesURL);
//listner on progress (%) for progress bar
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
if (typeof progressCallback != "undefined") {
//count %
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
debugLog(percentComplete);
progressCallback(percentComplete, this.progressId);
}
}
}, false);
// when downloading start create unique ID for progress bar
xhr.upload.addEventListener("loadstart", function (e) {
if (typeof startCallback != "undefined") {
// generating uniqe ID (GUID)
this.progressId = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : r & 0x3 | 0x8; return v.toString(16); });
startCallback(this.progressId);
}
});
//callback on final result of request
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = null;
//if crash JSON.Parse then is possible that result is pure text(partialView)
try {
data = JSON.parse(xhr.responseText);
} catch (e) {
}
if (data == null) {
//supose it is pure text if json parse crash
updateCallback(xhr.responseText);
} else {
updateCallback(data.result);
}
} else if (xhr.readyState == 4 && xhr.status != 200) {
if (typeof errorCallback != "undefined") {
errorCallback(xhr);
}
}
}
xhr.send(formData);
}
Here is Asp net MVC method code:
[HttpPost]
public ActionResult UploadFile(Model mode, bool isJsonResponse)
{
Model :
public class Model
{
public string FileName { get; set; }
public int TypeID { get; set; }
public int? ModelID { get; set; }
public HttpPostedFileBase File { get; set; }
public int ID { get; set; }
}
The file is normaly uploaded. But after that, sometimes is send another request but without fileBody and other parametrs like is isJsonResponse. The post only contains TypeID and FileName.
The error is comming from IE,FF,Chrome
Have somebody experience with this? Or something similiar
OK , so after another testing with application clumsy, i finally simulate the behaviour. I release that happend when internet connection is unstable.

Categories