Ag Grid – I


AgGridInMemory

 

 

 

+ –

 

 

 

Select list (select one):

 

{{t}}

 

 

 

Delete <!– Update –>

 

<!–

Upload a Document :

–>

{{ error.message }}
{{ uploadResponse.message }}
{{uploadResponse.message}}%

 

Upload

 

 

 

 

Angular Code Sample

import { Component, OnInit } from ‘@angular/core’;
import { FormControl } from ‘@angular/forms’;
import { NgbActiveModal, NgbModal, NgbModalRef } from ‘@ng-bootstrap/ng-bootstrap’;
import { AppModalForm } from ‘./app.modal.form’;
import { AppCommonService } from ‘./app.common.service’;
import { FormObject } from ‘./formObject’;
import { FormBuilder, FormGroup } from ‘@angular/forms’;
import { UploadService } from ‘./upload.service’;

@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [‘./app.component.css’]
})
export class AppComponent implements OnInit {

private gridApi: any;
private gridColumnApi: any;

private columnDefs: any;
private defaultColDef: any;
private rowData: any[];
private rowSelection: any;
private editType: any;

private formTypes: any[];
private selectedFormType: any;
private data: any[];
private activeModalRef: NgbModalRef;

form: FormGroup;
error: string;
selectedFileList: FileList;
selectedFile: File;
uploadResponse = { status: ”, message: ”, filePath: ” };
formData = [];

private formObject: FormObject

title = ”;
constructor(
private modalService: NgbModal,
private appCommonService: AppCommonService,
private formBuilder: FormBuilder,
private uploadService: UploadService
) {
//called first time before the ngOnInit()
}

ngOnInit() {
//called after the constructor and called after the first ngOnChanges()

/** Form upload code start **/

this.appCommonService.getFormData().subscribe(
(data : any[]) => {
console.log(JSON.stringify(data));
this.data = data;
this.rowData = this.data.filter(e => e.tag == ‘Published’);
},
error => {
console.log(error);
}
);

this.form = this.formBuilder.group({
file: [”]
});

/** Form upload code end **/

this.selectedFormType = “Published”;
this.appCommonService.submitFormData.subscribe((data) => {
try {

switch (data[‘key’]) {
case “SaveToDraft”: {
data[‘data’].tag = “Draft”;
console.log(data[‘data’]);
data[‘data’].id === -1 ? this.data.push(data[‘data’]) : console.log(‘Record saved to draft …!’);
this.rowData = this.data.filter(e => e.tag == ‘Draft’);
this.selectedFormType = data[‘data’].tag;
this.activeModalRef.close();
break;
}
case “SubmitOrUpdate”: {
data[‘data’].tag = “Published”;
console.log(data[‘data’]);
data[‘data’].id === -1 ? this.data.push(data[‘data’]) : console.log(‘Record submit to table …!’);
this.rowData = this.data.filter(e => e.tag == ‘Published’);
this.selectedFormType = data[‘data’].tag;
this.activeModalRef.close();
break;
}
default: {
break;
}
}

} catch (e) {
console.error(e);
}

});

this.formTypes = [
“Published”,
“InProgress”,
“Draft”
];

// this.data = [
// { id: 1, tag: ‘Published’, make: ‘Toyota’, model: ‘Celica’, price: 35000 },
// { id: 2, tag: ‘Published’, make: ‘Ford’, model: ‘Mondeo’, price: 32000 },
// { id: 3, tag: ‘Published’, make: ‘Porsche’, model: ‘Boxter’, price: 72000 },
// { id: 4, tag: ‘InProgress’, make: ‘InProcess-Audi’, model: ‘A9’, price: 69000 },
// { id: 5, tag: ‘InProgress’, make: ‘InProcess-Jaguar’, model: ‘Jaguar XF’, price: 89000 },
// { id: 6, tag: ‘Draft’, make: ‘Draft-Maruti Suzuki’, model: ‘Vitara Brezza’, price: 98000 }
// ];

this.columnDefs = [
{
headerName: ‘Make’, field: ‘make’,
headerCheckboxSelection: true,
headerCheckboxSelectionFilteredOnly: true,
checkboxSelection: true
},
{ headerName: ‘Model’, field: ‘model’ },
{ headerName: ‘Price’, field: ‘price’ }
];

// this.rowData = this.data.filter(e => e.tag == ‘Published’);
this.rowSelection = “multiple”;
this.editType = “fullRow”;
}

onFilterTextBoxChanged(event) {
console.log(event);
this.gridApi.setQuickFilter(event.target.value);
}

applyTypeChange(event) {
console.log(event.target.value);
this.selectedFormType = event.target.value;

switch (this.selectedFormType) {
case “Draft”: {
this.rowData = this.data.filter(e => e.tag == ‘Draft’);
break;
}
case “InProgress”: {
this.rowData = this.data.filter(e => e.tag == ‘InProgress’);
break;
}
case “Published”: {
this.rowData = this.data.filter(e => e.tag == ‘Published’);
break;
}
default: {
this.rowData = this.data.filter(e => e.tag == ‘Published’);
break;
}
}

}

onSelectionChanged() {
var selectedRows = this.gridApi.getSelectedRows();
this.activeModalRef = this.modalService.open(AppModalForm, { size: ‘lg’, backdrop: ‘static’ });
this.formObject = selectedRows[0];
this.activeModalRef.componentInstance.formObject = this.formObject;
}

addNewRow() {
this.activeModalRef = this.modalService.open(AppModalForm);
this.formObject = new FormObject();
this.formObject.setId(-1);
this.formObject.setTag(‘Draft’);
this.formObject.setMake(”);
this.formObject.setModel(”);
this.formObject.setPrice(”);
this.activeModalRef.componentInstance.formObject = this.formObject;
}

removeRows() {
var selectedRows = this.gridApi.getSelectedRows();

for (let i = 0; selectedRows.length > i; i++) {
this.data.splice(this.data.indexOf(selectedRows[i]), 1);
//this.data.filter(e => e.id == selectedRows[i].id).length > 0 ? this.data.splice(i,1) : console.log(“Nothing record deleted..!”);
}
this.rowData = this.data.filter(e => e.tag == this.selectedFormType);

}

onGridReady(params) {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;

params.api.sizeColumnsToFit();

// this.http
// .get(
// “https://data.json&#8221;
// )
// .subscribe(data => {
// this.rowData = data;
// });
}

/** Form upload code start **/

onFileChange(event) {
if (event.target.files.length > 0) {
this.selectedFile = event.target.files[0];
}
}

onSubmit() {
const formData = new FormData();
formData.append(‘file’, this.selectedFile);

this.uploadService.upload(formData).subscribe(
(res) => this.uploadResponse = res,
(err) => this.error = err
);
}

/** Form upload code end **/

}

 

common service js

import {Injectable} from ‘@angular/core’;
import {Subject} from ‘rxjs’;
import { HttpClient } from ‘@angular/common/http’;

// @Injectable makes to available services in root level.
@Injectable({providedIn:’root’})
export class AppCommonService {

baseUrl:string = “http://localhost:8080&#8221;;

constructor(private httpClient : HttpClient) {}
submitFormData = new Subject();

getFormData(){
return this.httpClient.get(‘/assets/mock.json’);
}

}

 

Git Commends

1. git clone <url>

 

2. git branch <branch name>
3. git checkout <branch name>
make changes
4. git add .
5. git commit -m “commit comments”
6. git push –set-upstream origin <branch name>

Angular js Unit Test with Karma Jasmine

Angular js Unit Test

 

Karma

Karma is a JavaScript command line tool that can be used to spawn a web server which loads your application’s source code and executes your tests. You can configure Karma to run against a number of browsers, which is useful for being confident that your application works on all browsers you need to support. Karma is executed on the command line and will display the results of your tests on the command line once they have run in the browser.

Karma is a NodeJS application, and should be installed through npm

Jasmine

Jasmine, which is a behaviour driven development framework for JavaScript. This sometimes causes confusion as it describes itself as a behaviour driven development framework (BDD) but it can also be used to write unit tests with a test driven development (TDD) approach. Aren’t TDD and BDD supposed to be different? Shouldn’t we use a test driven development framework?

Yes the styles are different, but as we will see you can use Jasmine with a TDD approach also. The framework offers structure for organising the tests and functions for asserting the output of our code.

 

example : https://github.com/NaughtyCodes/KarmaExample

 

 

ref:

https://docs.angularjs.org/guide/unit-testing

http://www.bradoncode.com/blog/2015/05/12/angularjs-testing-getting-started/

http://www.bradoncode.com/blog/2015/05/19/karma-angularjs-testing/

 

spring mvc configuration

Add filter to mvc configutation

http://stackoverflow.com/questions/33463918/how-to-add-a-filter-with-webmvcconfigureradapter-in-spring

Bean life cycle example link

http://stackoverflow.com/questions/11359607/understanding-basic-spring-framework-and-total-flow

web.xml vs initializer

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/support/AbstractAnnotationConfigDispatcherServletInitializer.html

https://www.intertech.com/Blog/how-to-use-springs-webapplicationinitializer/

http://www.baeldung.com/spring-xml-vs-java-config

https://dzone.com/articles/spring-1

http://stackoverflow.com/questions/18524524/passing-json-data-to-a-spring-mvc-controller

http://stackoverflow.com/questions/22195065/how-to-send-a-json-object-using-html-form-data

Spring Zip Link to download

https://repo.spring.io/release/org/springframework/spring/

Spring MVC

http://websystique.com/spring-4-mvc-tutorial/

Call OFS using java jremote.jar

JAVA Source to connect T24 jbase using jremote.jar

import com.jbase.jremote.DefaultJConnectionFactory;
import com.jbase.jremote.JConnection;
import com.jbase.jremote.JConnectionFactory;
import com.jbase.jremote.JDynArray;
import com.jbase.jremote.JRemoteException;
import com.jbase.jremote.JExecuteResults;
import com.jbase.jremote.JSubroutineParameters;
import java.util.Properties;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.io.UnsupportedEncodingException;

public class t24callsub {
	private JConnectionFactory factory = null;

	public t24callsub(JConnectionFactory f) {
		factory = f;
	}

	public void perform(String subr, String cmd, String host) {
		try {
			Properties prop = new Properties();
			prop.setProperty("allow input", "true");
			JConnection c = factory.getConnection(null, null, prop);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			Writer writer = new OutputStreamWriter(bos, "UTF-8");
			c.setTerminalOutputWriter(writer);
			System.out.println(host + ": CALL " + subr + '(' + cmd + ')');

			JSubroutineParameters subroutineParams = new JSubroutineParameters();
			subroutineParams.add(new JDynArray(cmd));

			subroutineParams = c.call(subr, subroutineParams);
			// ~ System.out.println(Str.substring(10, 15) );
			if (subroutineParams != null) {
				String res_all = subroutineParams.toString();
				int res_length = res_all.length();
				// remove "["... "]"
				System.out.println(res_all.substring(4, res_length - 1));
			}

			c.close();

		} catch (UnsupportedEncodingException e) {
			System.out.println("Error creating OutputStreamWriter.");
		} catch (JRemoteException e) {
			// ~ System.out.println("Connection or other error.");
			System.out.println(e);
			// ~ e.printStackTrace(); // it goes to stderr
		} catch (Exception e) {
			System.out.println("Unknown error.");
		}
	}

	public static String strJoin(String[] aArr, String sSep) {
		StringBuilder sbStr = new StringBuilder();
		for (int i = 3, il = aArr.length; i < il; i++) { 			if (i > 3)
				sbStr.append(sSep);
			sbStr.append(aArr[i]);
		}
		return sbStr.toString();
	}

	public static void main(String[] args) {
		DefaultJConnectionFactory factory = new DefaultJConnectionFactory();
		// mandatory host
		String host = args[0];
		factory.setHost(host);

		// mandatory port
		int port = Integer.valueOf(args[1]);
		factory.setPort(port);

		// mandatory subroutine name
		String subr = args[2];

		String extcmd = "";

		if (args != null && args.length > 3) {
			extcmd = strJoin(args, " ");
			t24callsub example = new t24callsub(factory);
			example.perform(subr, extcmd, host);
		} else {
			System.out.println("Wrong number of parameters.");
		}

	}
}

cmd line parameter example:

>>java <JAVA FILE> <HOST> <PORT> <ROUTINE NAME> <OFS>

>>java t24callsub 127.0.0.1 20001 TESTOFS ABBREVIATION,/I/VALIDATE,INPUTT/123456,QWERTY,ORIGINAL.TEXT::=\”123?45\”

Use ofs source type : OFSONLINE

Routine : TESTOFS

File MOHAN.BP , Record 'TESTOFS'                                                                                                                   Insert      10:06:59
Command->
0001 SUBROUTINE TESTOFS(param)
0002 $INCLUDE ../T24_BP I_COMMON
0003 $INCLUDE ../T24_BP  I_EQUATE
0004
0005    request = param
0006    result = ''
0007
0008    IF PUTENV('OFS_SOURCE=ECAP.TC') THEN NULL
0009
0010    CALL JF.INITIALISE.CONNECTION
0011    CALL OFS.BULK.MANAGER(request, result, '')
0012
0013    CHANGE ',' TO ',':CHAR(10) IN result
0014    param = result
0015
0016 RETURN
0017 END

source : https://groups.google.com/forum/#!topic/jbase/pecj4VncabY

What is an abstract class, and when should it be used?

Abstract classes are classes that contain one or more abstract methods.

An abstract method is a method that is declared, but contains no implementation .

Abstract classes may not be instantiated and required sub-classes to provide implementations for the abstract methods.

example code :

public abstract Car

{

   public void start(String on)

   {

        // do something to start a car.... 
   }

   public void stop(String of)

   {

        // do something to stop a car.... 
   }

   public abstract void ride();
}

Note: The abstract keyword is used to denote both an abstract method and an abstract class.

Now any car that wants to be instantiate car class, that must need to implement the “ride” method otherwise it is impossible to create an instance of that class. (like Honda or MarutiSuzuki)

public Honda extends Car

{

   public void ride(){.......} 
}

public MaruthiSuzuki extends Car

{

   public void ride(){.......}
}

Now you may get a question in your mind ?? Y not declare an abstract class as an interface ?

The Honda and MaruthiSuzuki implement the interface , yes sure you could do – but you’d also need to implement the methods “start” and “stop” .

By using abstract classes, you can inherit the implementation of other (non-abstract) methods is optional.

you can’t do that with interfaces – an interface cannot provide any method implementations and all the methods has to be in abstract manner in interface.

source & ref : http://www.javacoffeebreak.com/faq/faq0084.html

set up connect mysql from remote host

mysql >  GRANT ALL ON database_name.* TO user@xx.xxx.xx.xx IDENTIFIED BY ‘your_password’;

Replace xx.xx.xx.xx with your local IP address of your laptop/desktop
or
if it is dynamic you can add them either by: ‘192.168.0.%’ as a dynamic C-class
or
‘%’ if you want to be able to connect from anywhere (this is less secure)

And also, if there’s a firewall installed, you should open the port on the firewall
Ubuntu: use following cmd to open firewall


>sudo ufw allow 3306/tcp

>sudo service ufw restart

ref : https://www.digitalocean.com/community/questions/how-to-allow-remote-mysql-database-connection

CREATING TEMPLATE IN T24

LOGIN IN TO T24 APPLICATION

Create a local BP Folder in BNK.run

mkdir LOCAL.BP

Copy Template files from core GLOBUS.BP or T24.BP

COPY FROM GLOBUS.BP TO MOHAN.BP TEMPLATE,<YOURTEMPLATE>

COPY FROM GLOBUS.BP TO MOHAN.BP TEMPLATE.FIELDS,<YOURTEMPLATE.FIELDS>

Python *args and **kwargs?

What does ** (double star) and * (star) do for Python parameters..?

The syntax is the * and **. The names *args and **kwargs are only by convention but there’s no hard requirement to use them.

You would use *args when you’re not sure how many arguments might be passed to your function, i.e. it allows you pass an arbitrary number of arguments to your function. For example:

>>> def print_everything(*args):
for count, thing in enumerate(args):
… print ‘{0}. {1}’.format(count, thing)

>>> print_everything(‘apple’, ‘banana’, ‘cabbage’)
0. apple
1. banana
2. cabbage
Similarly, **kwargs allows you to handle named arguments that you have not defined in advance:

>>> def table_things(**kwargs):
… for name, value in kwargs.items():
… print ‘{0} = {1}’.format(name, value)

>>> table_things(apple = ‘fruit’, cabbage = ‘vegetable’)
cabbage = vegetable
apple = fruit
You can use these along with named arguments too. The explicit arguments get values first and then everything else is passed to *args and **kwargs. The named arguments come first in the list. For example:

def table_things(titlestring, **kwargs)
You can also use both in the same function definition but *args must occur before **kwargs.

You can also use the * and ** syntax when calling a function. For example:

>>> def print_three_things(a, b, c):
… print ‘a = {0}, b = {1}, c = {2}’.format(a,b,c)

>>> mylist = [‘aardvark’, ‘baboon’, ‘cat’]
>>> print_three_things(*mylist)
a = aardvark, b = baboon, c = cat
As you can see in this case it takes the list (or tuple) of items and unpacks it. By this it matches them to the arguments in the function. Of course, you could have a * both in the function definition and in the function call.

ref: http://stackoverflow.com/questions/3394835/args-and-kwargs