Hi I want to open a specific panel in javascript after it completes 24 hours. I am trying to do it but its not working. Here is my code:
var currentTime = new Date().getTime();
var visitedTime = Get_Cookie('lastvisitedtime');
if (!visitedTime || visitedTime < (currentTime - 24*60*60*1000) ) {
alert('visitedTime = ' + visitedTime);
Set_Cookie("lastvisitedtime", currentTime);
}
else{
Set_Cookie("lastvisitedtime", currentTime); //first time
}
but it always go to else part. How can I achive it so that it goes to if condition and show alert part.
Any help is appreciated.
Thanks
corrected code..
Steps:
Set lastvisitedtime cookie value to 0 in start
call a setInterval() method which will call itself after 1000ms. It will call timeEvent() function after 1000ms.
Apply a if condition to check if visitedTime is 0 or it have some valied value
If visitedTime have some valied time value then Apply if condition to check time difference between visitedTime & currentTime
DEMO jsfiddle
// In start set cookie to null
setCookie("lastvisitedtime", 0);
setInterval(function(){timeEvent()}, 1000);
function timeEvent(){
var currentTime = (new Date()).getTime();
var visitedTime = getCookie('lastvisitedtime');
if (visitedTime != 0){
if((currentTime - visitedTime) >= 60*1000){
alert('visitedTime = ' + visitedTime);
setCookie("lastvisitedtime", currentTime);
}
}
else{
setCookie("lastvisitedtime", currentTime); //first time
}
}
function getCookie(c_name)
{
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1)
{
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1)
{
c_value = null;
}
else
{
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1)
{
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
{
alert("Welcome again " + username);
}
else
{
username=prompt("Please enter your name:","");
if (username!=null && username!="")
{
setCookie("username",username,365);
}
}
}
Related
I'm creating a program that can read .log files in certain directories and then dumps the data from the .log files into a local database.
However, i noticed in my testing that whenever the program reads the files and i happen to access the files during the test run - the program freezes.
How do i solve this issue?
public static void file(File[] files)
{
try
{
for (File lister : files)
{
System.out.println("HERE " + lister);
in = new FileReader(lister);
br = new BufferedReader(in);
try
{
while ((sCurrentLine = br.readLine()) != null)
{
if (sCurrentLine.contains("Performance"))
{
String[] aCurrentLine = sCurrentLine.split("\\|");
if (aCurrentLine.length >= 6) {
Date date = dateinsert.parse(aCurrentLine[0]);
CurrentTime = dateinsert.format(date);
CurrentFlow = aCurrentLine[2];
CurrentModule = aCurrentLine[5];
CurrentType = aCurrentLine[4];
sCurrentID = aCurrentLine[6];
aCurrentLine = aCurrentLine[6].split("ORDER_ID");
if (aCurrentLine.length >= 2)
{
aCurrentLine[1] = aCurrentLine[1].replace (":", "");
aCurrentLine[1] = aCurrentLine[1].replace (" ", "");
aCurrentLine[1] = aCurrentLine[1].replace ("_", "");
aCurrentLine[1] = aCurrentLine[1].replace ("{", "");
aCurrentLine[1] = aCurrentLine[1].replace ("}", "");
aCurrentLine = aCurrentLine[1].split ("\"");
sCurrentID = aCurrentLine[2];
}
else // Happens when there's no order id
{
sCurrentID = "N/A";
}
cal = Calendar.getInstance();
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH);
datenum = cal.get(Calendar.DAY_OF_MONTH);
hour = cal.get(Calendar.HOUR_OF_DAY);
minute = cal.get(Calendar.MINUTE);
second = cal.get(Calendar.SECOND);
if (month<9)
{
month = month + 1;
smonth = "0" + Integer.toString(month);
}
else
{
month = month + 1;
smonth = Integer.toString(month);
}
if (datenum<10)
{
sdatenum = "0" + Integer.toString(datenum);
}
else
{
sdatenum = Integer.toString(datenum);
}
if (hour<10)
{
shour = "0" + Integer.toString(hour);
}
else
{
shour = Integer.toString(hour);
}
if (minute<10)
{
sminute = "0" + Integer.toString(minute);
}
else
{
sminute = Integer.toString(minute);
}
if (second<10)
{
ssecond = "0" + Integer.toString(second);
}
else
{
ssecond = Integer.toString(second);
}
scalendar = Integer.toString(year) + "-" + smonth + "-" + sdatenum + " " + shour + ":" + sminute+ ":" + ssecond;
ls.insertdata(sCurrentID, CurrentTime, CurrentFlow, CurrentModule, CurrentType, scalendar);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
flag = 0;
}
}
1 - Do you need to worry about the fact that it does not work when the file is open or are you just interested in why it does not work as expected ?
2 - All of the code that you wrote to determine the value for scalendar can be reduced to 2 lines of code :
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = formatter.format(Calendar.getInstance().getTime());
Here is unit test
#Test
public void quickTest() {
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = formatter.format(Calendar.getInstance().getTime());
System.out.println(formattedDate);
}
where the result will look similar to : 2018-03-19 06:42:58
I have this java script code for ajax and I'm having trouble of get response.
xmlhttp.status always become 0. I have repeatCallHr Servlet and getting parameters from jsp page as follows.
function loadResults() {
var tt = document.getElementById("StartDate");
alert(tt);
if (xmlhttp) {
var query = "repeatCallHr?skill="
+ document.getElementById("ServiceCode").value
+"&startDate="+document.getElementById("StartDate").value
+"&startTime="+document.getElementById("StartTime").value
+"&endDate="+document.getElementById("EndDate").value
+"&endTime="+document.getElementById("EndTime").value;
xmlhttp.open("GET", query, true);
xmlhttp.onreadystatechange = loadStallsResponse;
xmlhttp.send(null);
} else {
alert("Browser not supported!");
}}
In following code I'm calling AJAX request and try to get response out of it.
function loadStallsResponse() {
alert("come here");
alert(xmlhttp.readyState);
if (xmlhttp.readyState == 4) {
alert("status is :"+xmlhttp.status);
if (xmlhttp.status == 200) {
resultList = [];
if (xmlhttp.responseText.indexOf("Error") == -1) {
alert("come to inside of status::")
console.log(xmlhttp.responseText);
stallList = $.parseJSON(xmlhttp.responseText);
populateStallData();
} else {
alert(xmlhttp.responseText);
}
} else {
alert("Error in loading salesman data");
}
}}
function populateStallData() {
var table = "<tr><th>Date</th><th>Time</th><th>Skill</th><th>Total Call</th><th>Unique Calls</th><th>Repeat Calls</th></tr>";
for (var i = 0; i < resultList.length; i++) {
table += "</td><td width='140'>"
+ resultList[i].date
+ "</td><td width='140'>"
+ resultList[i].time
+ "</td><td width='140'>"
+ resultList[i].skill
+ "</td><td width='140'><a style='color: -webkit-link; text-decoration: underline; cursor: auto;' href='http://"
+ resultList[i].totalCall
+ "</td><td width='140'>"
+ resultList[i].uniqueCall
+ "</td><td width='140'>"
+ resultList[i].repeatCall
+ "</td></tr>";
}
document.getElementById("ResultTable").innerHTML = table;}
But it gives xmlhttp.status as 0. Please help me to figure out what is the issue.
I have a GWT project which is very very simple: it's one module with a single EntryPoint that just calls GWT.log in order to tell me that it has compiled and run successfully.
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
public class Tester implements EntryPoint {
public void onModuleLoad()
{
GWT.log("I have compiled and run successfully");
}
}
It does compile - it spits out a bunch of files in the WAR folder.
My understanding of what I need to do to run it (based on http://www.gwtproject.org/doc/latest/FAQ_DebuggingAndCompiling.html) is that I need to run the hosted.html file in a browser and it will do all of its magic. I've put the entire WAR folder on a HTTP server (so that it can get the other files without being blocked by file:// stuff like I've had issues with in web development before) and fetched it in Chrome. It does nothing. I looked at the network monitor in it and recorded while refreshing the page - the only file ever loaded is hosted.html:
There are no errors or messages in the JavaScript console...
The resulting hosted.html is as follows:
<html>
<head><script>
var $wnd = parent;
var $doc = $wnd.document;
var $moduleName, $moduleBase, $entry
,$stats = $wnd.__gwtStatsEvent ? function(a) {return $wnd.__gwtStatsEvent(a);} : null
,$sessionId = $wnd.__gwtStatsSessionId ? $wnd.__gwtStatsSessionId : null;
// Lightweight metrics
if ($stats) {
var moduleFuncName = location.search.substr(1);
var moduleFunc = $wnd[moduleFuncName];
var moduleName = moduleFunc ? moduleFunc.moduleName : "unknown";
$stats({moduleName:moduleName,sessionId:$sessionId,subSystem:'startup',evtGroup:'moduleStartup',millis:(new Date()).getTime(),type:'moduleEvalStart'});
}
var $hostedHtmlVersion="2.1";
var gwtOnLoad;
var $hosted = "localhost:9997";
function loadIframe(url) {
var topDoc = window.top.document;
// create an iframe
var iframeDiv = topDoc.createElement("div");
iframeDiv.innerHTML = "<iframe scrolling=no frameborder=0 src='" + url + "'>";
var iframe = iframeDiv.firstChild;
// mess with the iframe style a little
var iframeStyle = iframe.style;
iframeStyle.position = "absolute";
iframeStyle.borderWidth = "0";
iframeStyle.left = "0";
iframeStyle.top = "0";
iframeStyle.width = "100%";
iframeStyle.backgroundColor = "#ffffff";
iframeStyle.zIndex = "1";
iframeStyle.height = "100%";
// update the top window's document's body's style
var hostBodyStyle = window.top.document.body.style;
hostBodyStyle.margin = "0";
hostBodyStyle.height = iframeStyle.height;
hostBodyStyle.overflow = "hidden";
// insert the iframe
topDoc.body.insertBefore(iframe, topDoc.body.firstChild);
}
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf("gecko") != -1) {
// install eval wrapper on FF to avoid EvalError problem
var __eval = window.eval;
window.eval = function(s) {
return __eval(s);
}
}
if (ua.indexOf("chrome") != -1) {
// work around __gwt_ObjectId appearing in JS objects
var hop = Object.prototype.hasOwnProperty;
Object.prototype.hasOwnProperty = function(prop) {
return prop != "__gwt_ObjectId" && hop.call(this, prop);
};
// do the same in our parent as well -- see issue 4486
// NOTE: this will have to be changed when we support non-iframe-based DevMode
var hop2 = parent.Object.prototype.hasOwnProperty;
parent.Object.prototype.hasOwnProperty = function(prop) {
return prop != "__gwt_ObjectId" && hop2.call(this, prop);
};
}
// wrapper to call JS methods, which we need both to be able to supply a
// different this for method lookup and to get the exception back
function __gwt_jsInvoke(thisObj, methodName) {
try {
var args = Array.prototype.slice.call(arguments, 2);
return [0, window[methodName].apply(thisObj, args)];
} catch (e) {
return [1, e];
}
}
var __gwt_javaInvokes = [];
function __gwt_makeJavaInvoke(argCount) {
return __gwt_javaInvokes[argCount] || __gwt_doMakeJavaInvoke(argCount);
}
function __gwt_doMakeJavaInvoke(argCount) {
// IE6 won't eval() anonymous functions except as r-values
var argList = "";
for (var i = 0; i < argCount; i++) {
argList += ",p" + i;
}
var argListNoComma = argList.substring(1);
return eval(
"__gwt_javaInvokes[" + argCount + "] =\n" +
" function(thisObj, dispId" + argList + ") {\n" +
" var result = __static(dispId, thisObj" + argList + ");\n" +
" if (result[0]) {\n" +
" throw result[1];\n" +
" } else {\n" +
" return result[1];\n" +
" }\n" +
" }\n"
);
}
/*
* This is used to create tear-offs of Java methods. Each function corresponds
* to exactly one dispId, and also embeds the argument count. We get the "this"
* value from the context in which the function is being executed.
* Function-object identity is preserved by caching in a sparse array.
*/
var __gwt_tearOffs = [];
var __gwt_tearOffGenerators = [];
function __gwt_makeTearOff(proxy, dispId, argCount) {
return __gwt_tearOffs[dispId] || __gwt_doMakeTearOff(dispId, argCount);
}
function __gwt_doMakeTearOff(dispId, argCount) {
return __gwt_tearOffs[dispId] =
(__gwt_tearOffGenerators[argCount] || __gwt_doMakeTearOffGenerator(argCount))(dispId);
}
function __gwt_doMakeTearOffGenerator(argCount) {
// IE6 won't eval() anonymous functions except as r-values
var argList = "";
for (var i = 0; i < argCount; i++) {
argList += ",p" + i;
}
var argListNoComma = argList.substring(1);
return eval(
"__gwt_tearOffGenerators[" + argCount + "] =\n" +
" function(dispId) {\n" +
" return function(" + argListNoComma + ") {\n" +
" var result = __static(dispId, this" + argList + ");\n" +
" if (result[0]) {\n" +
" throw result[1];\n" +
" } else {\n" +
" return result[1];\n" +
" }\n" +
" }\n" +
" }\n"
);
}
function __gwt_makeResult(isException, result) {
return [isException, result];
}
function __gwt_disconnected() {
// Prevent double-invocation.
window.__gwt_disconnected = new Function();
// Do it in a timeout so we can be sure we have a clean stack.
window.setTimeout(__gwt_disconnected_impl, 1);
}
function __gwt_disconnected_impl() {
__gwt_displayGlassMessage('GWT Code Server Disconnected',
'Most likely, you closed GWT Development Mode. Or, you might have lost '
+ 'network connectivity. To fix this, try restarting GWT Development Mode and '
+ 'refresh this page.');
}
// Keep track of z-index to allow layering of multiple glass messages
var __gwt_glassMessageZIndex = 2147483647;
// Note this method is also used by ModuleSpace.java
function __gwt_displayGlassMessage(summary, details) {
var topWin = window.top;
var topDoc = topWin.document;
var outer = topDoc.createElement("div");
// Do not insert whitespace or outer.firstChild will get a text node.
outer.innerHTML =
'<div style="position:absolute;z-index:' + __gwt_glassMessageZIndex-- +
';left:50px;top:50px;width:600px;color:#FFF;font-family:verdana;text-align:left;">' +
'<div style="font-size:30px;font-weight:bold;">' + summary + '</div>' +
'<div style="font-size:15px;">' + details + '</div>' +
'</div>' +
'<div style="position:absolute;z-index:' + __gwt_glassMessageZIndex-- +
';left:0px;top:0px;right:0px;bottom:0px;filter:alpha(opacity=60);opacity:0.6;background-color:#000;"></div>'
;
topDoc.body.appendChild(outer);
var glass = outer.firstChild;
var glassStyle = glass.style;
// Scroll to the top and remove scrollbars.
topWin.scrollTo(0, 0);
if (topDoc.compatMode == "BackCompat") {
topDoc.body.style["overflow"] = "hidden";
} else {
topDoc.documentElement.style["overflow"] = "hidden";
}
// Steal focus.
glass.focus();
if ((navigator.userAgent.indexOf("MSIE") >= 0) && (topDoc.compatMode == "BackCompat")) {
// IE quirks mode doesn't support right/bottom, but does support this.
glassStyle.width = "125%";
glassStyle.height = "100%";
} else if (navigator.userAgent.indexOf("MSIE 6") >= 0) {
// IE6 doesn't have a real standards mode, so we have to use hacks.
glassStyle.width = "125%"; // Get past scroll bar area.
// Nasty CSS; onresize would be better but the outer window won't let us add a listener IE.
glassStyle.setExpression("height", "document.documentElement.clientHeight");
}
$doc.title = summary + " [" + $doc.title + "]";
}
function findPluginObject() {
try {
return document.getElementById('pluginObject');
} catch (e) {
return null;
}
}
function findPluginEmbed() {
try {
return document.getElementById('pluginEmbed')
} catch (e) {
return null;
}
}
function findPluginXPCOM() {
try {
return __gwt_HostedModePlugin;
} catch (e) {
return null;
}
}
gwtOnLoad = function(errFn, modName, modBase){
$moduleName = modName;
$moduleBase = modBase;
// Note that the order is important
var pluginFinders = [
findPluginXPCOM,
findPluginObject,
findPluginEmbed,
];
var topWin = window.top;
var url = topWin.location.href;
if (!topWin.__gwt_SessionID) {
var ASCII_EXCLAMATION = 33;
var ASCII_TILDE = 126;
var chars = [];
for (var i = 0; i < 16; ++i) {
chars.push(Math.floor(ASCII_EXCLAMATION
+ Math.random() * (ASCII_TILDE - ASCII_EXCLAMATION + 1)));
}
topWin.__gwt_SessionID = String.fromCharCode.apply(null, chars);
}
var plugin = null;
for (var i = 0; i < pluginFinders.length; ++i) {
try {
var maybePlugin = pluginFinders[i]();
if (maybePlugin != null && maybePlugin.init(window)) {
plugin = maybePlugin;
break;
}
} catch (e) {
}
}
if (!plugin) {
// try searching for a v1 plugin for backwards compatibility
var found = false;
for (var i = 0; i < pluginFinders.length; ++i) {
try {
plugin = pluginFinders[i]();
if (plugin != null && plugin.connect($hosted, $moduleName, window)) {
return;
}
} catch (e) {
}
}
loadIframe("http://www.gwtproject.org/missing-plugin/");
} else {
if (plugin.connect(url, topWin.__gwt_SessionID, $hosted, $moduleName,
$hostedHtmlVersion)) {
// take over the onunload function, wrapping any existing call if it exists
var oldUnload = window.onunload;
window.onunload = function() {
// run wrapped unload first in case it is running gwt code
!!oldUnload && oldUnload();
try {
// wrap in try/catch since plugins are not required to supply this
plugin.disconnect();
} catch (e) {
}
};
} else {
if (errFn) {
errFn(modName);
} else {
__gwt_displayGlassMessage(
"Plugin failed to connect to Development Mode server at " + simpleEscape($hosted),
"Follow the troubleshooting instructions at "
+ "<a href='http://code.google.com/p/google-web-toolkit/wiki/TroubleshootingOOPHM'>"
+ "http://code.google.com/p/google-web-toolkit/wiki/TroubleshootingOOPHM</a>");
}
}
}
}
function simpleEscape(originalString) {
return originalString.replace(/&/g,"&")
.replace(/</g,"<")
.replace(/>/g,">")
.replace(/\'/g, "'")
.replace(/\"/g,""");
}
// Lightweight metrics
window.fireOnModuleLoadStart = function(className) {
$stats && $stats({moduleName:$moduleName, sessionId:$sessionId, subSystem:'startup', evtGroup:'moduleStartup', millis:(new Date()).getTime(), type:'onModuleLoadStart', className:className});
};
window.__gwt_module_id = 0;
</script></head>
<body>
<font face='arial' size='-1'>This html file is for Development Mode support.</font>
<script><!--
// Lightweight metrics
$stats && $stats({moduleName:$moduleName, sessionId:$sessionId, subSystem:'startup', evtGroup:'moduleStartup', millis:(new Date()).getTime(), type:'moduleEvalEnd'});
// OOPHM currently only supports IFrameLinker
var query = parent.location.search;
if (!findPluginXPCOM()) {
document.write('<embed id="pluginEmbed" type="application/x-gwt-hosted-mode" width="10" height="10">');
document.write('</embed>');
document.write('<object id="pluginObject" CLASSID="CLSID:1D6156B6-002B-49E7-B5CA-C138FB843B4E">');
document.write('</object>');
}
// look for the old query parameter if we don't find the new one
var idx = query.indexOf("gwt.codesvr=");
if (idx >= 0) {
idx += 12; // "gwt.codesvr=".length() == 12
} else {
idx = query.indexOf("gwt.hosted=");
if (idx >= 0) {
idx += 11; // "gwt.hosted=".length() == 11
}
}
if (idx >= 0) {
var amp = query.indexOf("&", idx);
if (amp >= 0) {
$hosted = query.substring(idx, amp);
} else {
$hosted = query.substring(idx);
}
// According to RFC 3986, some of this component's characters (e.g., ':')
// are reserved and *may* be escaped.
$hosted = decodeURIComponent($hosted);
}
query = window.location.search.substring(1);
if (query && $wnd[query]) setTimeout($wnd[query].onScriptLoad, 1);
--></script></body></html>
What do I do?
I have some complex objects that I would like to print out including the attributes names, types and values. As long as I don't know in advance the amount and depth of all attributes/sub-attributes, I need a recursive call including a loop. I have done it for 2 levels
StringBuilder descr = new StringBuilder();
foreach (PropertyInfo propertyInfo in req.GetType().GetProperties())
{
if (propertyInfo.CanRead)
{
string attributValue = "";
string attributName = propertyInfo.Name;
Type attributType = propertyInfo.PropertyType;
var propertyInfoValue = propertyInfo.GetValue(req, null);
//if (attributType == typeof(XFkType))
if (attributType != typeof(System.String) &&
attributType != typeof(System.Boolean))
{
PropertyInfo[] nestedpropertyInfoArray = propertyInfo.PropertyType.GetProperties();
attributValue += "{";
foreach (PropertyInfo subProperty in nestedpropertyInfoArray)
{
// var instance = (EntityBase)Activator.CreateInstance(subClass);
attributValue += subProperty.Name + "=";
try
{
attributValue += propertyInfoValue == null ? "" : subProperty.GetValue(propertyInfoValue, null).ToString();
}
catch (Exception e)
{
attributValue += "null";
}
attributValue += ",";
}
attributValue = attributValue.Length > 1 ? attributValue.Substring(0, attributValue.Length - 1) : attributValue;
attributValue += "}";
}
else
attributValue = propertyInfo.GetValue(req, null) == null ? "" : propertyInfo.GetValue(req, null).ToString();
descr.Append("[" + propertyInfo.PropertyType + "]" + attributName + "=" + attributValue + " | ");
}
}
The result is something like:
[XPhone]class{Phone,protocol=SIP,protocolSide=User,callingSearchSpaceName=XFkType,devicePoolName=XFkType,commonDeviceConfigName=XFkType,commonPhoneConfigName=XFkType,networkLocation=Use System Default,locationName=XFkType,mediaResourceListName=null,wirelessLanProfileGroup=null,ctiid=null} | [System.UInt64]sequence={} | [System.Boolean]sequenceSpecified=False |
It's a bit difficult to understand your structures but I would expect the solution to be in the following form:
public String propertyDescription(PropertyInfo[] properties) {
StringBuilder description;
for (PropertyInfo property: properties) {
if (property.containsNestedProperties()) {
description.append(propertyDescription(property.getNestedProperties()));
} else {
description.append( ... );
}
}
return description.toString();
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
This part is supposed to add a train to the TRAININFO table in my database. I have to use mysql.
So there are some constraints I have to see before adding the train.
jTextField1.getText(); TrainNo. should not have more than 6 characters and it should be an integer.
jTextField2.getText(); TrainName. Should not have more than 30 characters.
jTextField10,jTextField12 have Depttime and araivaltime respectively.
It has 5 characters,"hr:mn" So I have to check if 'hr'<=24 and 'mn'<=59.
If the value of jTextField3.getText()==0 (number of ac1 coaches), then the trainfare for ac1 coaches (tfac1) should also be ==0.
Keeping this in mind I have tried to code it. but it doesn't work.
when ever i run this there is an error message .
Please do tell me where I am wrong.
stacktrace:[Ljava.lang.StackTraceElement;#e596c9
okay heres how it should work:
String m="-",t="-",w="-",th="--",f="-",st="--",s="-",runson;
if(jCheckBox1.isSelected()==true)
{
m="m";
}
if(jCheckBox2.isSelected()==true)
{
t="t";
}
if(jCheckBox3.isSelected()==true)
{
w="w";
}
if(jCheckBox4.isSelected()==true)
{
th="th";
}
if(jCheckBox5.isSelected()==true)
{
f="f";
}
if(jCheckBox6.isSelected()==true)
{
st="st";
}
if(jCheckBox7.isSelected()==true)
{
s="s";
}
runson=m+t+w+th+f+st+s;
int h1=Integer.valueOf(jTextField10.getText().substring(0,2));
int mins1=Integer.valueOf(jTextField10.getText().substring(3,5));
int h2=Integer.valueOf(jTextField12.getText().substring(0,2));
int mins2=Integer.valueOf(jTextField12.getText().substring(2,3));
String time1=jTextField10.getText().substring(0,2)+jTextField10.getText().substring
(2,3)+jTextField10.getText().substring(3,5);
String time2=jTextField12.getText().substring(0,2)+jTextField12.getText().substring
(2,3)+jTextField12.getText().substring(3,5);
String tfac1=jTextField13.getText();
String tfac2=jTextField14.getText();
String tfac3=jTextField15.getText();
String tfsl=jTextField16.getText();
if(Integer.valueOf(jTextField3.getText())==0)
{
tfac1="0";
}
if(Integer.valueOf(jTextField4.getText())==0)
{
tfac2="0";
}
if(Integer.valueOf(jTextField5.getText())==0)
{
tfac3="0";
}
if(Integer.valueOf(jTextField6.getText())==0)
{
tfsl="0";
}
try
{
Class.forName("java.sql.DriverManager");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/bvdb","root","enter");
Statement stm=con.createStatement();
int n=jTextField1.getText().trim().length();
int m=jTextField2.getText().trim().length();
if( n<=6 && m<=30 && h1<=24 && h2<=24 && mins1<=59 && mins2<=59 )
//This should check the constraints(1,2,3).if the condition is true the following statement will be executed ..else the catch block should be executed. But this doesn't seem to happen when i run the code. There is always an Exception raised.//
{
String q="INSERT INTO TRAININFO VALUE ("+jTextField1.getText()+",'"+jTextField2.getText()+"','"+jTextField9.getText()+"','"+time1+"','"+jTextField11.getText()+"','"+time2+"','"+runson+"',"+tfac1+","+tfac2+ ","+tfac3+","+tfsl+","+jTextField3.getText()+","+jTextField4.getText()+","+jTextField5.getText()+","+jTextField6.getText()+")";
stm.executeUpdate(q);
System.out.print("ADDED");
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(this,"Enter valid details");
}
s will always be - if !jCheckBox7.isSelected(). Think about it, you have:
if(something) {
...
} else {
s = ...;
}
if(something2) {
...
} else {
s = ...;
}
...
if(somethingN) {
...
} else {
s = "-"; //This will always be executed if !somethingN
}
You might want to have if.. else if instead of if below if.
Also note that it's not a good practice to compare boolean by writing == true. This might lead to problems if you, for example, write = instead of ==. Just write if(isTrue()) instead of if(isTrue() == true).
Basically you need to split your code into many functions. That will make it more readable.
Below is an example of how to structure your code, not a complete working code.
public void InsertTrainInfo() {
String runson = GetRunSon();
Boolean validTime1 = IsTimeValid(jTextField10.getText());
Boolean validTime2 = IsTimeValid(jTextField12.getText());
String time1 = GetTheTime(jTextField10.getText());
String time2 = GetTheTime(jTextField12.getText());
String tfac1 = GetFact(jTextField13.getText());
String tfac2 = GetFact(jTextField14.getText());
String tfac3 = GetFact(jTextField15.getText());
String tfsl = GetFact(jTextField16.getText());
try {
Class.forName("java.sql.DriverManager");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/bvdb", "root", "enter");
Statement stm = con.createStatement();
if (jTextField1.getText().trim().length() <= 6 && jTextField2.getText().trim().length() <= 30 && validTime1 && validTime2) {
String q = "INSERT INTO TRAININFO VALUE (" + jTextField1.getText() + ",'" + jTextField2.getText() + "','" + jTextField9.getText() + "','" + time1 + "','" + jTextField11.getText() + "','" + time2 + "','" + runson + "'," + tfac1 + "," + tfac2 + "," + tfac3 + "," + tfsl + "," + jTextField3.getText() + "," + jTextField4.getText() + "," + jTextField5.getText() + "," + jTextField6.getText() + ")";
stm.executeUpdate(q);
ResetFOrm();
}
} catch (Exception e) {
GetValidDetails();
}
}
Boolean IsTimeValid(String timetext) {
Boolean isOK = false;
try {
int h1 = Integer.valueOf(timetext.substring(0, 2));
int mins1 = Integer.valueOf(timetext.substring(3, 5));
isOK = (h1 <= 24 && mins1 <= 59);
} catch (Exception e) {
isOK = false;
}
return isOK;
}
String GetTheTime(String timetext) {
// do some basic length checks
return timetext.substring(0, 2) + timetext.substring(2, 3) + timetext.substring(3, 5);
}
String GetFact(String facttext) {
String fact = facttext;
if (Integer.valueOf(fact) == 0) {
fact = "0";
}
return fact;
}
void ResetFOrm() {
jTextField1.setEditable(true);
jButton1.setEnabled(true);
jButton2.setEnabled(false);
jButton4.setEnabled(false);
jTextField2.setEditable(false);
jTextField9.setEditable(false);
jTextField10.setEditable(false);
jTextField11.setEditable(false);
jTextField12.setEditable(false);
jTextField13.setEditable(false);
jTextField14.setEditable(false);
jTextField15.setEditable(false);
jTextField16.setEditable(false);
jTextField3.setEditable(false);
jTextField4.setEditable(false);
jTextField5.setEditable(false);
jTextField6.setEditable(false);
jCheckBox1.setEnabled(false);
jCheckBox2.setEnabled(false);
jCheckBox3.setEnabled(false);
jCheckBox4.setEnabled(false);
jCheckBox5.setEnabled(false);
jCheckBox6.setEnabled(false);
jCheckBox7.setEnabled(false);
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
jTextField5.setText("");
jTextField6.setText("");
jTextField7.setText("");
jTextField8.setText("");
jTextField9.setText("");
jTextField10.setText("");
jTextField11.setText("");
jTextField12.setText("");
jTextField13.setText("");
jTextField14.setText("");
jTextField15.setText("");
jTextField16.setText("");
}
void GetValidDetails() {
JOptionPane.showMessageDialog(this, "Enter valid details");
jTextField9.setEditable(true);
jTextField10.setEditable(true);
jTextField11.setEditable(true);
jTextField12.setEditable(true);
jTextField13.setEditable(true);
jTextField14.setEditable(true);
jTextField15.setEditable(true);
jTextField16.setEditable(true);
jTextField2.setEditable(true);
jTextField3.setEditable(true);
jTextField4.setEditable(true);
jTextField5.setEditable(true);
jTextField6.setEditable(true);
jCheckBox1.setEnabled(true);
jCheckBox2.setEnabled(true);
jCheckBox3.setEnabled(true);
jCheckBox4.setEnabled(true);
jCheckBox5.setEnabled(true);
jCheckBox6.setEnabled(true);
jCheckBox7.setEnabled(true);
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
jTextField5.setText("");
jTextField6.setText("");
jTextField7.setText("");
jTextField8.setText("");
jTextField9.setText("");
jTextField10.setText("");
jTextField11.setText("");
jTextField12.setText("");
jTextField13.setText("");
jTextField14.setText("");
jTextField15.setText("");
jTextField16.setText("");
jCheckBox1.setSelected(false);
jCheckBox2.setSelected(false);
jCheckBox3.setSelected(false);
jCheckBox4.setSelected(false);
jCheckBox5.setSelected(false);
jCheckBox6.setSelected(false);
jCheckBox7.setSelected(false);
}
String GetRunSon() {
String m = "-", t = "-", w = "-", th = "--", f = "-", st = "--", s = "-", runson;
if (jCheckBox1.isSelected()) {
m = "m";
}
if (jCheckBox2.isSelected()) {
t = "t";
}
if (jCheckBox3.isSelected()) {
w = "w";
}
if (jCheckBox4.isSelected()) {
th = "th";
}
if (jCheckBox5.isSelected()) {
f = "f";
}
if (jCheckBox6.isSelected()) {
st = "st";
}
if (jCheckBox7.isSelected()) {
s = "s";
}
runson = m + t + w + th + f + st + s;
return runson;
}