Change status using Ajax in Java - java

I need to change status of my event in data base.For this I create button with drop down menu with all status that can be. When I push this button and choose some variant it is changing but in my event fields owner, city, address became empty. What is wrong??
function html_element(aData, status) {
var parent_element = $("<a/>",
{
"href" : "#"
}).click(aData, function(e) {
aData.status = status;
e.preventDefault();
$.ajax({
url : 'event-update',
dataType : 'json',
beforeSend : function() {
},
contentType : "application/json",
"type" : "POST",
data : JSON.stringify(aData),
success : function(response) {
$('td:eq(6)',nRow).html(response.status);
}
});
});
return parent_element;
};
var button = $(
"<button/>",
{
text : "Action",
"type" : "button",
"data-toggle" : "dropdown",
"class" : "btn btn-default dropdown-toggle",
});
function form_element(aData) {
var approve = html_element(aData, "APPROVED");
var pending = html_element(aData, "PENDING");
var refuse = html_element(aData, "REFUSED");
approve.html("Approve");
pending.html("Pending");
refuse.html("Refuse");
var final_element = div.append(button);
final_element.append(ul.append(li
.append(approve)
.append(pending)
.append(refuse)));
return final_element;
}
row = $('td:eq(7)', nRow).html(form_element(aData));
function change_request_status(id, element) {
$.ajax({
url : 'response-event',
beforeSend : function() {
console.log('start');
element.style.display = "none";
loader.insertAfter(element);
},
data : {
"status" : status,
"address": address,
"owner" : owner,
cityId : city
},
success : function(response) {
console.log(data);
element.nextSibling.style.display = "none";
if (response == "Request send") {
successRequest.insertAfter(element);
} else {
failRequest.insertAfter(element);
}
},
});
}

Related

Unable to load data in combobox store in extjs with a memory proxy

I am using Extjs 6. I want to get data from server and load data to combobox. But when I get data root property and success value is not comes with data still its goes in success call but unable to load data to combobox.
Any help would be appreciated!
Below are code snippets:
I have combobox as below :
xtype : 'thrcombobox',
fieldLabel : 'Select District',
store : Ext.create('thr.store.admin.master.DistrictStore'),
itemId : 'cmbDistrict',
name : 'cmbDistrict',
displayField : 'districtMarathi',
valueField : 'districtID',
queryMode : 'local'
Below is Store :
Ext.define('thr.store.admin.master.DistrictStore',{
extend : 'Ext.data.Store',
alias : 'store.districtStore',
storeId : 'districtStore',
requires : [
'thr.model.admin.master.District'
],
model : 'thr.model.admin.master.District',
autoSync : false,
autoLoad : false,
proxy: {
type : 'memory',
reader : {
type : 'json',
rootProperty: 'data'
}
}
});
Below is Model :
Ext.define('thr.model.admin.master.District',{
extend : 'Ext.data.Model',
fields : [
{
name : 'districtID'
},
{
name : 'districtMarathi'
},
{
name : 'districtEnglish'
}
]
});
And below is ajax call where I am getting data for store:
var districtStore = districtCombobox.getStore();
districtStore.loadData([]);
Above districtStore defines store of combobox.
Ext.Ajax.request({
url: <path goes here..>,
method: 'POST',
success: function(response, action){
var decodedResponse = Ext.decode(response.responseText);
if(!Ext.isEmpty(decodedResponse) && decodedResponse.success){
districtStore.loadData(decodedResponse.data);
}
},
failure: function(form, action){
return false;
}
});

WireMock Request was not matched

I am creating integration testing using spring cloud contract. Everything's working fine from configuration until adding stubs jar to the project. Hence I found that the request not match despite having all params and headers same.
{
"url" : "/my-project/api/checkTransaction/id?id=ASDFGHJKL",
"absoluteUrl" : "http://127.0.0.1:8085/my-project/api/checkTransaction/id?id=ASDFGHJKL",
"method" : "GET",
"clientIp" : "127.0.0.1",
"headers" : {
"Accept" : "application/json",
"X-B3-ParentSpanId" : "6f922af45db72e2e",
"User-Agent" : "Java/1.8.0_111",
"Connection" : "keep-alive",
"Host" : "127.0.0.1:8085",
"X-Span-Name" : "http://my-project/api/checkTransaction/id",
"X-B3-SpanId" : "886d8cfcdeec47ca",
"X-B3-Sampled" : "0",
"X-B3-TraceId" : "6f922af45db72e2e",
"requestKey" : "RANDOM",
"defaultId" : "12345",
"baggage-requestKey" : "RANDOM",
"baggage-defaultId" : "12345",
"Content-Type" : "application/json",
"username" : "589e329c-1cf1-4eb5-b7bb-eaffdd266560"
},
"cookies" : { },
"browserProxyRequest" : false,
"loggedDate" : 1526541502499,
"bodyAsBase64" : "",
"body" : "",
"loggedDateString" : "2018-05-17T07:18:22Z",
"queryParams" : {
"id" : {
"key" : "id",
"values" : [ "ASDFGHJKL" ]
}
}
}
Closest match:
{
"urlPath" : "/api/checkTransaction/id",
"method" : "GET",
"headers" : {
"defaultId" : {
"equalTo" : "12345"
},
"username" : {
"matches" : "[\\p{L}]*"
},
"requestKey" : {
"equalTo" : "RANDOM"
},
"Content-Type" : {
"matches" : "application/json.*"
},
"Accept" : {
"matches" : "application/json.*"
}
},
"queryParameters" : {
"id" : {
"equalTo" : "ASDFGHJKL"
}
}
}
Here's the Test for API
#Test
public void checkId_Contract() throws Exception {
// given:
MockMvcRequestSpecification request = given()
.header("requestKey", "RANDOM")
.header("accept-language", "en")
.header("accept-encoding", "gzip")
.header("Content-Type", "application/json;charset=UTF-8");
// when:
ResponseOptions response = given().spec(request)
.queryParam("id","ASDFGHJKL")
.when().async()
.timeout(10000)
.get("/api/id/ASDFGHJKL/check");
// then:
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.header("Content-Type")).matches("application/json;charset=UTF-8.*");
// and:
DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
assertThatJson(parsedJson).field("['errors']").isNull();
assertThatJson(parsedJson).field("['message']").isEqualTo("Id not found");
assertThatJson(parsedJson).field("['value']").isNull();
assertThatJson(parsedJson).field("['code']").isEqualTo("ID_NOT_FOUND");
}
Here's the contract that being called by the API
Contract.make {
request {
method 'GET'
url('/api/checkTransaction/id') {
headers {
header 'defaultId' : '12345'
header 'username' : $(anyAlphaUnicode())
header 'requestKey' : 'RANDOM'
contentType('application/json')
accept('application/json')
}
queryParameters {
parameter 'id' : 'ASDFGHJKL'
}
}
}
response {
status 200
async()
fixedDelayMilliseconds(5000)
headers{
contentType('application/json')
}
body '''\
{
"code": "ID_NOT_FOUND",
"message": "ID not found",
"errors": null,
"value": null,
"success": false
}
'''
}
}
even when I delete the username from contract request, still getting the same error.
Do I need to create headers for X-B3-ParentSpanId, etc to make it match?
Your url within the request is wrong, it is missing my-project in it.
It should look like this:
Contract.make {
request {
method 'GET'
url('/my-project/api/checkTransaction/id') {
...

Proxy sends multiply requests from ExtJs store

My app send multiply request to server each time I insert new item to store. When the first item inserted it calls POST once, one more item ... twice and so on.
Im new at ExtJs, so can you help me in solving some qustions:
First of all what the sync method do, why (GET, POST, PUT, DELETE) methods are not called without store.sync() method invok?
Why my post method multiply requests?
Why store.remove() (DELETE) method throws 400 error (Bad request) when the PUT method works fine?
Thank you in advance
my edit controller:
Ext.define('MVC.controller.Edit', {
extend: 'Ext.app.Controller',
init: function () {
this.control({
'editForm > button#SaveRecord': {
click: this.onSaveButtonClick
},
'editForm > button#DeleteButton': {
click: this.onDeleteButtonClick
}
});
},
onSaveButtonClick: function (btn) {
//get reference to the form
var detailView = btn.up('editForm');
//get the form inputs
var data = detailView.getValues();
//see if the record exists
var store = Ext.getStore('TestStore');
console.log(data.id);
var record = store.getById(data.id);
if (!record) {
record = Ext.create('MVC.model.Note', {
title: data.title,
created: new Date(),
updated: new Date(),
text: data.text
});
store.insert(0, record);
store.sync();
Ext.MessageBox.alert('Created', record.id);
return;
}
record.set(data);
store.sync();
//manually update the record
detailView.updateRecord();
},
onDeleteButtonClick: function (btn) {
//get reference to the form
var detailView = btn.up('editForm');
//get the form inputs
var data = detailView.getValues();
var store = Ext.getStore('TestStore');
var record = store.getById(data.id);
store.remove(record);
store.sync();
}
});
Store :
Ext.define('MVC.store.TestStore', {
extend : 'Ext.data.Store',
requires : [
'MVC.model.Note'
],
storeId : 'TestStore',
model : 'MVC.model.Note',
autoLoad: false,
proxy: {
type : 'rest',
url: 'rest/notes',
actionMethods : {
create : 'POST',
read : 'GET',
update : 'PUT',
destroy : 'DELETE'
},
reader: {
type: 'json',
rootProperty: 'data'
},
writer: {
type: 'json'
}
}
});
And model:
Ext.define('MVC.model.Note', {
extend: 'Ext.data.Model',
fields: [
{
name: 'id',
type: 'string'
},
{
name: 'title',
type: 'string'
},
{
name: 'created',
type: 'date'
},
{
name: 'updated',
type: 'date'
},
{
name: 'text',
type: 'string'
}
]
});
Try to use record's methods:
1)Add proxy to you'r model like this:
Ext.define('MVC.model.Note',{
extend: 'Ext.data.Model',
fields: [
{
name: 'id',
type: 'string'
},
{
name: 'title',
type: 'string'
},
{
name: 'created',
type: 'date'
},
{
name: 'updated',
type: 'date'
},
{
name: 'text',
type: 'string'
}],
proxy:
{
type: 'rest',
url: 'rest/notes',
reader:
{
type: 'json'
}
}
});
2)Now you can use methods: record.save() - will send PUT if it was loaded to store from server and record have id, or POST if this record was created with record.create();
record.destroy() - will send DELETE to server with id of record;
You can use Ext.ModelManager.getModel('Model_name').load(id) to send GET request to server for single record.
3)Use store.load() to GET array of records from server

Drag and drop file using ExtJS 6

I currently have a webapp whose view is written using ExtJS 6: we currently use a Java applet, whose purpose is to allow user to Drag & Drop file from the File System to the Web Server.
My aim is to remove that applet, and to handle the Drag & Drop using ExtJS6: is that possible?
I tried to search for it in the documentation, but the only topic I found (https://docs.sencha.com/extjs/6.0/core_concepts/drag_drop.html) is about dragging and dropping framework elements.
The Window contained in this fiddle allow users to Drag & Drop File from the File System to the Web Server.
Source code:
Ext.application({
name: 'Fiddle',
launch: function() {
var store = Ext.create('Ext.data.Store', {
fields: ['name', 'size', 'file', 'status']
});
var postDocument = this.postDocument;
Ext.widget('container', {
renderTo: Ext.getBody(),
items: [{
multiSelect: true,
xtype: 'grid',
id: 'UploadGrid',
columns: [{
header: 'Name',
dataIndex: 'name',
flex: 2
}, {
header: 'Size',
dataIndex: 'size',
flex: 1,
renderer: Ext.util.Format.fileSize
}, {
header: 'Status',
dataIndex: 'status',
flex: 1,
renderer: this.rendererStatus
}],
viewConfig: {
emptyText: 'Drop Files Here',
deferEmptyText: false
},
store: store,
listeners: {
drop: {
element: 'el',
fn: 'drop'
},
dragstart: {
element: 'el',
fn: 'addDropZone'
},
dragenter: {
element: 'el',
fn: 'addDropZone'
},
dragover: {
element: 'el',
fn: 'addDropZone'
},
dragleave: {
element: 'el',
fn: 'removeDropZone'
},
dragexit: {
element: 'el',
fn: 'removeDropZone'
},
},
noop: function(e) {
e.stopEvent();
},
addDropZone: function(e) {
if (!e.browserEvent.dataTransfer || Ext.Array.from(e.browserEvent.dataTransfer.types).indexOf('Files') === -1) {
return;
}
e.stopEvent();
this.addCls('drag-over');
},
removeDropZone: function(e) {
var el = e.getTarget(),
thisEl = this.getEl();
e.stopEvent();
if (el === thisEl.dom) {
this.removeCls('drag-over');
return;
}
while (el !== thisEl.dom && el && el.parentNode) {
el = el.parentNode;
}
if (el !== thisEl.dom) {
this.removeCls('drag-over');
}
},
drop: function(e) {
e.stopEvent();
Ext.Array.forEach(Ext.Array.from(e.browserEvent.dataTransfer.files), function(file) {
store.add({
file: file,
name: file.name,
size: file.size,
status: 'Ready'
});
});
this.removeCls('drag-over');
},
tbar: [{
text: "Upload",
handler: function() {
for (var i = 0; i < store.data.items.length; i++) {
if (!(store.getData().getAt(i).data.status === "Uploaded")) {
store.getData().getAt(i).data.status = "Uploading";
store.getData().getAt(i).commit();
//replace "insert your upload url here" with the real url
postDocument("insert your upload url here", store, i);
}
}
}
}, {
text: "Erase EVERYTHING",
handler: function() {
store.reload();
}
}, {
text: "Erase uploaded files",
handler: function() {
for (var i = 0; i < store.data.items.length; i++) {
var record = store.getData().getAt(i);
if ((record.data.status === "Uploaded")) {
store.remove(record);
i--;
}
}
}
}, {
text: "Erase selected files",
handler: function() {
store.remove(Ext.getCmp('UploadGrid').getSelection());
}
}]
}],
padding: 20
});
},
rendererStatus: function(value, metaData, record, rowIndex, colIndex, store) {
var color = "grey";
if (value === "Ready") {
color = "blue";
} else if (value === "Uploading") {
color = "orange";
} else if (value === "Uploaded") {
color = "green";
} else if (value === "Error") {
color = "red";
}
metaData.tdStyle = 'color:' + color + ";";
return value;
},
postDocument: function(url, store, i) {
var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append("serverTimeDiff", 0);
xhr.open("POST", url, true);
fd.append('index', i);
fd.append('file', store.getData().getAt(i).data.file);
//xhr.setRequestHeader("Content-Type","multipart/form-data");
xhr.setRequestHeader("serverTimeDiff", 0);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
//handle the answer, in order to detect any server side error
if (Ext.decode(xhr.responseText).success) {
store.getData().getAt(i).data.status = "Uploaded";
} else {
store.getData().getAt(i).data.status = "Error";
}
store.getData().getAt(i).commit();
} else if (xhr.readyState == 4 && xhr.status == 404) {
store.getData().getAt(i).data.status = "Error";
store.getData().getAt(i).commit();
}
};
// Initiate a multipart/form-data upload
xhr.send(fd);
}
});
For supporting drag & drop of files, you can use the following events:
drop, dragstart, dragenter, dragover, dragleave, dragexit.
A working example: https://fiddle.sencha.com/#fiddle/10v9
Ext.application({
name: 'Fiddle',
launch: function() {
var store = Ext.create('Ext.data.Store', {
fields: ['name', 'size', 'file']
});
Ext.widget('container', {
renderTo: Ext.getBody(),
items: [{
xtype: 'grid',
columns: [{
header: 'Name',
dataIndex: 'name',
flex: 2
}, {
header: 'Size',
dataIndex: 'size',
flex: 1,
renderer: Ext.util.Format.fileSize
}],
viewConfig: {
emptyText: 'Drop Files Here',
deferEmptyText: false
},
store: store,
listeners: {
drop: {
element: 'el',
fn: 'drop'
},
dragstart: {
element: 'el',
fn: 'addDropZone'
},
dragenter: {
element: 'el',
fn: 'addDropZone'
},
dragover: {
element: 'el',
fn: 'addDropZone'
},
dragleave: {
element: 'el',
fn: 'removeDropZone'
},
dragexit: {
element: 'el',
fn: 'removeDropZone'
},
},
noop: function(e) {
e.stopEvent();
},
addDropZone: function(e) {
if (!e.browserEvent.dataTransfer || Ext.Array.from(e.browserEvent.dataTransfer.types).indexOf('Files') === -1) {
return;
}
e.stopEvent();
this.addCls('drag-over');
},
removeDropZone: function(e) {
var el = e.getTarget(),
thisEl = this.getEl();
e.stopEvent();
if (el === thisEl.dom) {
this.removeCls('drag-over');
return;
}
while (el !== thisEl.dom && el && el.parentNode) {
el = el.parentNode;
}
if (el !== thisEl.dom) {
this.removeCls('drag-over');
}
},
drop: function(e) {
e.stopEvent();
Ext.Array.forEach(Ext.Array.from(e.browserEvent.dataTransfer.files), function(file) {
store.add({
file: file,
name: file.name,
size: file.size
});
console.log(file);
});
this.removeCls('drag-over');
}
}],
padding: 20
});
}
});
I'm using a solution I've found in the sencha forum:
Ext.define('FileDropper', {
extend: 'Ext.plugin.Abstract',
alias: 'plugin.filedropper',
overCls: '',
init: function(c) {
this.target = c;
c.on({
element: 'el',
scope: this,
dragover: this.onDragOver,
dragenter: this.onDragEnter,
dragLeave: this.onDragLeave,
drop: this.onDrop
});
},
onDragOver: function(e) {
e.stopEvent();
},
onDragEnter: function(e) {
this.target.addCls(this.overCls);
e.stopEvent();
},
onDragLeave: function() {
this.target.removeCls(this.overCls);
},
onDrop: function(e) {
var callback = this.callback,
scope = this.scope || this;
e.stopEvent();
this.target.removeCls(this.overCls);
if (callback) {
callback.call(scope, e.browserEvent.dataTransfer.files);
}
}
});
Add the plugin to your view like this:
Ext.define('MyPanel', {
extend: 'Ext.Panel',
// ... your content
plugins: [{
ptype: 'filedroppper'
overCls: 'foo'
callback: function(files) {
// handle your upload
}
}]
});
You just have to handle the dropped files in the callback:
callback: function (files) {
var url = 'example.org'
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open("POST", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// Handle response.
alert(xhr.responseText); // handle response.
}
};
for (var i = 0; i < files.length; i++) {
fd.append('files', files.item(i));
}
// Initiate a multipart/form-data upload
xhr.send(fd);
}
But if you use FormData() ensure you don't have to support old browsers.

Message alert box in servlet

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String action = request.getParameter("action");
try {
// System.out.println("in mail servlet");
if (action.equals("show")) {
List<EmailSetup> emailSetup_List = emailSetup_lf.findAll();
JSONObject returnJSON = new JSONObject();
JSONArray emailSetup_Array = ListToJSONArray(emailSetup_List);
returnJSON.put("success", true);
returnJSON.put("rows", emailSetup_Array);
// System.out.println(returnJSON.toJSONString());
sendJSONResponse(returnJSON, response);
} else if (action.equals("add")) {
if( emailSetup_lf.count() >= 1 ){
sendJSONResponseSimple("fail", response);
return;
}
// all data is sent to the servelet as strings
// when creating cast to proper DB type
String smtp_host = request.getParameter("SMTP_HOST");
String smtp_user = request.getParameter("SMTP_USER");
String smtp_pwd = request.getParameter("SMTP_PWD");
String smtp_port = request.getParameter("SMTP_PORT");
String smtp_from = request.getParameter("SMTP_FROM");
if ((!smtp_host.equals(""))
&& (!smtp_user.equals(""))
&& (!smtp_pwd.equals(""))
&& (!smtp_port.equals(""))
&& (!smtp_from.equals(""))) {
EmailSetup new_email_setup_record = new EmailSetup();
new_email_setup_record.setSmtpHost(smtp_host);
new_email_setup_record.setSmtpUser(smtp_user);
new_email_setup_record.setSmtpPwd(smtp_pwd);
new_email_setup_record.setSmtpPort(smtp_port);
new_email_setup_record.setSmtpFrom(smtp_from);
emailSetup_lf.create(new_email_setup_record);
// LOG
systemLog("Create (MailServerSevlet)", "Created Mail Server: " + new_email_setup_record.toString(), request);
}
} else if (action.equals("edit")) {
// all data is sent to the servelet as strings
// when creating cast to proper DB type
String e_id = request.getParameter("E_ID");
String smtp_host = request.getParameter("SMTP_HOST");
String smtp_user = request.getParameter("SMTP_USER");
String smtp_pwd = request.getParameter("SMTP_PWD");
String smtp_port = request.getParameter("SMTP_PORT");
String smtp_from = request.getParameter("SMTP_FROM");
if ((!smtp_host.equals(""))
&& (!smtp_user.equals(""))
&& (!smtp_pwd.equals(""))
&& (!smtp_port.equals(""))
&& (!smtp_from.equals(""))) {
EmailSetup email_setup_record = emailSetup_lf.find(new BigDecimal(e_id));
email_setup_record.setSmtpHost(smtp_host);
email_setup_record.setSmtpUser(smtp_user);
email_setup_record.setSmtpPwd(smtp_pwd);
email_setup_record.setSmtpPort(smtp_port);
email_setup_record.setSmtpFrom(smtp_from);
// CALL EDIT!
emailSetup_lf.edit(email_setup_record);
// LOG
systemLog("Update (MailServerSevlet)", "Updated Mail Server: " + email_setup_record.toString(), request);
} // systemLog
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short Description";
}// </editor-fold>
}
I have now tried using a JSON simple response, but it keeps calling the wrong error message
var db_drivers_Store = new Ext.data.JsonStore({
//url: '../DataBaseDriversServelet_show',
url: '../DataBaseDriversServelet?action=show',
root: 'rows',
idProperty: 'ID',
fields: [{
name: 'ID',
type: 'int'
},{
name: 'TYPE',
type: 'string'
},{
name: 'NAME',
type: 'string'
},{
name: 'ADDRESS',
type: 'string'
},{
name: 'PORT',
type: 'int'
}]
});
// ADD
var add_db_driver_Window = new Ext.Window({
title: 'Add DB Driver',
width: 400,
height:200,
minWidth: 300,
minHeight: 200,
layout: 'fit',
plain:true,
bodyStyle:'padding:5px;',
buttonAlign:'center',
border: true,
closable:false,
modal:true,
shim: false,
frame: true,
// forceLayout: true,
items: add_db_driver_FormPanel,
buttons: [{
text: 'Submit',
handler: function(){
if( add_db_driver_FormPanel.getForm().isValid()){
add_db_driver_FormPanel.getForm().submit({
success: function(){
add_db_driver_Window.hide();
db_drivers_Store.load();
add_db_driver_FormPanel.getForm().reset();
},
failure: function(){}
});
}else{
Ext.MessageBox.alert('Database Drivers', 'Could not Submit. Make sure all fields are valid.');
}
} // submit handler
},{
text: 'Cancel',
handler: function(){
add_db_driver_Window.hide();
add_db_driver_FormPanel.getForm().reset();
} // cancel handler
}]
});
// DBDRIVER - ADD POP UP UI (END)
// DBDRIVER - EDIT POP UP UI (START)
var edit_db_driver_FormPanel = new Ext.FormPanel({
url: '../DataBaseDriversServelet?action=edit',
// url:'../DataBaseDriversServelet_edit',
labelWidth: 125,
frame: true,
bodyStyle:'padding:5px 5px 0',
defaultType: 'textfield',
id: 'edit_db_driver_FormPanel',
items: [
{
fieldLabel: 'Type',
id: 'TYPE_edit_db_driver_FormPanel',
allowBlank: false,
name: 'TYPE',
width:190
},{
fieldLabel: 'Name',
id: 'NAME_edit_db_driver_FormPanel',
allowBlank: false,
name: 'NAME',
width:190
},{
fieldLabel: 'Address',
id: 'ADDRESS_edit_db_driver_FormPanel',
allowBlank: false,
name: 'ADDRESS',
width:190
},new Ext.form.NumberField ({
fieldLabel: 'Port',
id: 'PORT_edit_db_driver_FormPanel',
allowBlank: false,
name: 'PORT',
width:190
})
]
});
var recordToEdit;
var edit_db_driver_Window = new Ext.Window({
title: 'Edit DB Driver',
width: 400,
height:200,
minWidth: 300,
minHeight: 200,
layout: 'fit',
plain:true,
bodyStyle:'padding:5px;',
buttonAlign:'center',
border: false,
closable:false,
modal:true,
shim: false,
frame: true,
items: edit_db_driver_FormPanel,
buttons: [{
text: 'Submit',
handler: function(){
var db_driver_id = recordToEdit.get("ID");
if(edit_db_driver_FormPanel.getForm().isValid()){
edit_db_driver_FormPanel.getForm().submit({
// url:'../DataBaseDriversServelet_edit',
url: '../DataBaseDriversServelet?action=edit',
waitMsg:'Saving Data...',
params:{
ID: db_driver_id
},
success: function(){
edit_db_driver_Window.hide();
db_drivers_Store.load();
},
failure: function(){}
});
}else{
Ext.MessageBox.alert('Database Drivers', 'Could not Submit. Make sure all fields are valid.');
}
} // submit handler
},{
text: 'Cancel',
handler: function(){
edit_db_driver_Window.hide();
edit_db_driver_FormPanel.getForm().reset();
} // cancel handler
}]
});
// DBDRIVER - EDIT POP UP UI (END)
// DBDRIVER - POP UP UI (END)
var db_driver_btn_panel = [{
id: 'db_driver_add_btn',
text: 'Add',
iconCls: 'adddb',
handler: (function(){
add_db_driver_Window.show();
}) // add handler function
}, {
text: 'Edit',
iconCls: 'edit',
handler: (function(){
var edit_selModel = Ext.getCmp("db_drivers_UPanel").getSelectionModel();
var selRecord;
if(edit_selModel.getSelected()== undefined){
Ext.message.msg('Notice','Select Database Driver first');
}else{
selRecord = edit_selModel.getSelected();
recordToEdit = selRecord;
Ext.getCmp("TYPE_edit_db_driver_FormPanel").setValue(recordToEdit.get("TYPE"));
Ext.getCmp("NAME_edit_db_driver_FormPanel").setValue(recordToEdit.get("NAME"));
Ext.getCmp("ADDRESS_edit_db_driver_FormPanel").setValue(recordToEdit.get("ADDRESS"));
Ext.getCmp("PORT_edit_db_driver_FormPanel").setValue(recordToEdit.get("PORT"));
edit_db_driver_Window.show();
} // end if
}) // edit handler function
},{
text: 'Delete',
iconCls: 'delete',
handler: function() {
//get currently selected record
var rec = Ext.getCmp('db_drivers_UPanel').getSelectionModel().getSelected();
//rec will be undefined if nothing is selected so check for this.
if(rec){
//open delete confirmation box
Ext.MessageBox.confirm('Delete Confirmation', 'Delete Driver?', function(btn)
{//check if the user selected 'yes'
if (btn == 'yes'){
//create ajax request to send delete requesdt to the servlete
Ext.Ajax.request({
//specify servlet url
//url : '../DataBaseDriversServelet_delete' ,
url: '../DataBaseDriversServelet?action=delete',
params : {
//D_ID = driver id, send through as param to the servlet
'D_ID': rec.data.ID
},
//use post
method: 'POST',
//method will run if server returns success message
success: function ( result, request ) {
// Ext.MessageBox.alert('Success','Post Deleted');
Ext.message.msg('Driver - Removed.', 'Driver has successfully been removed!');
//Ext.message.msg('Success','Driver Deleted');
db_drivers_Store.load();
},
//method will run if server returns failure message
failure: function ( result, request) {
Ext.MessageBox.alert('Failure','Driver Deletion Failed');
}
});//ajax request
}//if btn
});//confirm box
}else
{
Ext.message.msg('Notice','Select driver first');
}
} // function
}];
var db_drivers_UPanel = new Ext.Panel({
id: 'databaseDriversUtil-form',
labelAlign: 'left',
bodyStyle:'padding:5px',
frame: true,
boder: true,
width: 450,
title:"Database Drivers",
items:[{
xtype: 'grid',
id: 'db_drivers_UPanel',
tbar: db_driver_btn_panel,
ds: db_drivers_Store, // ds = datastore
cm: db_drivers_ColModel, // cm = column model
autoScroll:true,
height:220
}]
});
return db_drivers_UPanel;
}
// Database Drivers UI (End)
// Database Setup UI (Start)
Ext.Dyno.databaseUtil.databaseSetupUtilPanel = function(){
var db_setup_Store = new Ext.data.JsonStore({
//url: '../DataBaseSetupServelet',
url: '../DataBaseSetupServelet?action=show',
root: 'rows',
idProperty: 'ID',
fields: [{
name: 'ID',
type: 'int'
},{
name: 'TYPE',
type: 'string'
},{
name: 'DRIVERNAME',
type: 'string'
},{
name: 'CONNECTSTART',
type: 'string'
},{
name: 'DEFAULTPORT',
type: 'int'
}]
});
// this displays the data in the gird
db_setup_Store.load();
var db_setup_ColModel = new Ext.grid.ColumnModel([
{
header: "ID",
width: 70,
sortable: true,
locked:false,
hidden: true,
dataIndex: 'ID'
},{
header: "Type",
width: 70,
sortable: true,
dataIndex: 'TYPE'
},{
header: "Driver Name",
width: 150,
sortable: true,
dataIndex: 'DRIVERNAME'
},{
header: "Connect Start",
width: 100,
sortable: true,
dataIndex: 'CONNECTSTART'
},{
header: "Default Port",
width: 80,
sortable: true ,
dataIndex: 'DEFAULTPORT'
}
]);
// DBTYPE - POP UP UI (START)
// DBTYPE - ADD POP UP UI (START)
var add_db_type_FormPanel = new Ext.FormPanel({
//url:'../DataBaseSetupServelet_add',
url: '../DataBaseSetupServelet?action=add',
labelWidth: 125,
frame: true,
bodyStyle:'padding:5px 5px 0',
defaultType: 'textfield',
items: [
{
fieldLabel: 'Type',
name: 'TYPE',
allowBlank: false,
width:190
},{
fieldLabel: 'Driver Name',
name: 'DRIVERNAME',
allowBlank: false,
width:190
},{
fieldLabel: 'Connect Start',
name: 'CONNECTSTART',
allowBlank: false,
width:190
},new Ext.form.NumberField ({
fieldLabel: 'Default Port',
name: 'DEFAULTPORT',
allowBlank: false,
width:190
})
]
});
// ADD
var add_db_type_Window = new Ext.Window({
title: 'Add DB Type',
width: 400,
height:200,
minWidth: 300,
minHeight: 200,
layout: 'fit',
plain:true,
bodyStyle:'padding:5px;',
buttonAlign:'center',
border: false,
//get currently selected record
var rec = Ext.getCmp('db_setup_UPanel').getSelectionModel().getSelected();
//rec will be undefined if nothing is selected so check for this.
if(rec){
//open delete confirmation box
Ext.MessageBox.confirm('Delete Confirmation', 'Delete Setup?', function(btn)
{//check if the user selected 'yes'
if (btn == 'yes'){
//create ajax request to send delete requesdt to the servlete
Ext.Ajax.request({
//specify servlet url
// url : '../DataBaseSetupServelet_delete' ,
url: '../DataBaseSetupServelet?action=delete',
params : {
//D_ID = driver id, send through as param to the servlet
'ID': rec.data.ID
},
//use post
method: 'POST',
//method will run if server returns success message
success: function ( result, request ) {
//Ext.MessageBox.alert('Success','Post Deleted');
//Ext.message.msg('Success','Setup Deleted');
Ext.message.msg('Setup - Removed.', 'Setup has successfully been removed!');
db_setup_Store.load();
},
//method will run if server returns failure message
failure: function ( result, request) {
Ext.MessageBox.alert('Failure','Setup Deletion Failed');
}
});//ajax request
}//if btn
});//confirm box
}else
{
Ext.message.msg('Notice','Select setup first');
}
} // function
}];
var db_setup_UPanel = new Ext.Panel({
id: 'databaseSetupUtil-form',
labelAlign: 'left',
bodyStyle:'padding:5px',
frame: true,
boder: true,
width: 450,
title:"Database Setup",
items:[{
xtype: 'grid',
id:'db_setup_UPanel',
tbar: db_setup_btn_panel,
ds: db_setup_Store, // ds = datastore
cm: db_setup_ColModel, // cm = column model
autoScroll:true,
height:220
}]
});
return db_setup_UPanel;
}
var cat_config_Store = new Ext.data.JsonStore({
url: '../configureCatogoriesServelet?action=show',
root: 'rows',
idProperty: 'C_ID',
fields: [{
name: 'C_ID',
type: 'int'
},{
name: 'C_NAME',
type: 'string'
},{
name: 'C_DESCRIPTION',
type: 'string'
}]
});
// this displays the data in the gird
cat_config_Store.load();
var categoryGridTable = new Ext.grid.GridPanel({
region:'center',
//columnWidth: 0.70,
layout: 'fit',
ds: cat_config_Store,
//cm: colModel,
columns:[
{
header: "ID",
width: 70,
sortable: true,
locked:false,
hidden: true,
dataIndex: 'C_ID'
}, {
header: "Name",
width: 100,
sortable: true,
dataIndex: 'C_NAME'
}, {
header: "Description",
width: 300,
sortable: true,
dataIndex: 'C_DESCRIPTION'
}
],
frame:true,
height:250,
// width:500,
border:false
});
var cat_config_FormPanel = new Ext.FormPanel({
url: '../configureCatogoriesServelet',
labelWidth: 125,
frame: true,
bodyStyle:'padding:5px 5px 0',
defaultType: 'textfield',
items: [
{
fieldLabel: 'Name',
name: 'C_NAME',
allowBlank: false,
maxLength: 256, // for validation
width:190
},{
fieldLabel: 'Description',
name: 'C_DESCRIPTION',
allowBlank: false,
maxLength: 256, // for validation
width:190
}] // items
}); // cat_config_FormPanel
var cat_config_Window = new Ext.Window({
//title: 'Add Category',
width: 400,
height:200,
minWidth: 300,
minHeight: 200,
layout: 'fit',
plain:true,
bodyStyle:'padding:5px;',
buttonAlign:'center',
border: false,
closable:false,
modal:true,
shim: false,
frame: true,
items: cat_config_FormPanel,
buttons: [{
text: 'Submit',
handler: function(){
var form = cat_config_FormPanel.getForm();
if(form.isValid()){
form.submit({
url: '../configureCatogoriesServelet',
waitMsg:'Saving Data...',
params:{
action:categoryAddEditAction,
ID:chosenCategoryIdToEdit
},
success: function(){
cat_config_Window.hide();
cat_config_Store.load();
form.reset();
},
failure: function(){}
});
}else{
Ext.MessageBox.alert('Database Drivers', 'Could not Submit. Make sure all fields are valid.');
}
} // submit handler
},{
text: 'Cancel',
handler: function(){
cat_config_Window.hide();
cat_config_FormPanel.getForm().reset();
} // cancel handler
}]
});
var cat_conf_btn_panel = [{
text: 'Add',
iconCls: 'adddb',
handler: (function(){
cat_config_FormPanel.getForm().reset();
categoryAddEditAction = 'add';
cat_config_Window.setTitle('Add Category');
cat_config_Window.show();
}) // add handler function
},{
text: 'Edit',
iconCls: 'edit',
handler: function(){
var selModel = categoryGridTable.getSelectionModel();
var selRecord;
//updatepassword=true;
if(selModel.getSelected()== undefined){
Ext.MessageBox.alert('Notice','Select Catogry first');
}else{
selRecord = selModel.getSelected();
chosenCategoryIdToEdit = selRecord.get("C_ID");
categoryAddEditAction = "edit";
cat_config_Window.setTitle('Edit Category Configuration');
cat_config_Window.show();
cat_config_Window.hide();
cat_config_FormPanel.getForm().findField("C_NAME").setValue(selRecord.get("C_NAME"));
cat_config_FormPanel.getForm().findField("C_DESCRIPTION").setValue(selRecord.get("C_DESCRIPTION"));
cat_config_FormPanel.getForm().loadRecord(selRecord);
cat_config_Window.show();
}
} // edit handler function
},{
text: 'Delete',
iconCls: 'delete',
handler: function() {
var selModel = categoryGridTable.getSelectionModel();
var selRecord;
if(selModel.getSelected()== undefined){
Ext.MessageBox.alert('Notice','Select category first');
}else{
selRecord = selModel.getSelected();
var recordToDelete = selRecord;
var add_app_Window = new Ext.Window({
//title: 'Add Application',
width: 700,
height:250,
layout: 'fit',
plain:true,
bodyStyle:'padding:5px;',
buttonAlign:'center',
border: false,
closable:false,
modal:true,
shim: false,
frame: true,
items: applicationForm,
buttons: [{
text: 'Submit',
handler: function(){
if( applicationForm.getForm().isValid()){
applicationForm.getForm().submit({
url: '../ApplicationServelet',
waitMsg:'Saving Data...',
params:{
action:schedulerAppAddEditAction,
ID:chosenSchedulerAppIdToEdit
},
success: function(){
add_app_Window.hide();
AppList_Store.load();
applicationForm.getForm().reset();
},
},
fail: function(){
Ext.MessageBox.alert('Email Server', 'Multiple Mail Server is not Allowed.');
},
failure: function(result, request){
var obj = Ext.util.JSON.decode(request.response.responseText);
Ext.MessageBox.alert('Add Application Failed.', obj.reason);
}
});
}else{
Ext.MessageBox.alert('Applications', 'Could not Submit. Make sure all fields are valid.');
}
This is the javascript part which contains all the error messages , which contains all the error messages, the message i want to call if the Fail message, which says that Multiple Mail Server is not allowed
That's not valid HTML or Javascript. You need to remove the script from inside the opening <body> tag and place it inside <script> tags of its own.
out.println ("<html><body><script>alert('Hello World!');</script></body></html>");
You should however avoid printing out HTML from a Servlet and consider redirecting to an error.jsp instead. This would also allow you to collate all the validation errors and display them to the user in one go.
Try this
out.println("<html><body onload=\"alert('Hello World')\"></body></html>");

Categories