Author Archive

Quartz Job Scheduler Example

Step1:

Create a Job like following:


public class TestJob implements Job {

public void execute(JobExecutionContext arg0) throws JobExecutionException {

System.out.println("test job executed succesfully");
}

}
Step2:

In the main java file add following:


public static void main(String[] args) {

try {

JobDetail job = JobBuilder.newJob(TestJob.class)
.withIdentity("testjob")
.build();

Trigger trigger = TriggerBuilder.newTrigger()                        .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever()).build();

SchedulerFactory factory = new StdSchedulerFactory();
Scheduler sch = factory.getScheduler();
sch.start();

sch.scheduleJob(job,trigger);

}catch (Exception e) {
// TODO: handle exception
}

}

Spring Bean Auto-Wiring Example

The @Autowired annotation can be used to autowire bean on the setter method,  constructor, a property or methods:

@Autowired on Setter Methods:

public class HelloWorld {

private String message;
@Autowired
public void setMessage(String message){
this.message = message;
}

public void getMessage(){
System.out.println("Message : " + message);
}
}

Beans.xml file:

"<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd


http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:annotation-config/>

<bean id="helloWorld" class="com.schogini.Example.HelloWorld"/>
</beans>"

In the Main.java:

public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");

HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");

helloWorld.getMessage();
}
}

Java Based Spring Bean Configuration

For Java based spring bean configuration, you have to create a bean configuration class file(PersonConfig.java)  instead of bean.xml file

Example:

//PersonConfig.java

@Configuration
public class PersonConfig {
@Bean
public Person person() {
return new Person();
}

}

Secondly, you have to create a POJO file:

//Person.java

public class Person {

private String name;
private String gender;
private int age;
private String country;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Override
public String toString() {
return "Person [name=" + name + ", gender=" + gender + ", age=" + age
+ ", country=" + country + "]";
}

}

Finally, you have to add following in your main java file:

//Main.java

public class MainApps {

public static void main(String[] args) {

ApplicationContext ctx = new AnnotationConfigApplicationContext(PersonConfig.class);

Person person1 = (Person) ctx.getBean(Person.class);

person1.setName("Philip");
person1.setAge(20);
person1.setGender("Male");
person1.setCountry("US");

System.out.println(person1);

}

}

Java Singleton design pattern example

The Singleton class is used to ensure that there is only one instance of the object is created.  Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class,  just like static fields. Singletons often control access to resources such as database connections or sockets.

Example:


public class Singleton {

private static Singleton singleton = null;

private Singleton(){ }

public static Singleton getInstance( ) {
if (null == singleton) {
singleton = new Singleton();
}
return singleton;
}

public void printSingleton() {
System.out.println("Inside Singleton");
}
}

That’s it!

Step1: Create a class Person with all getters and setters.

public class Person {

private String name;

private String gender;

private String age;

private String country;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getGender() {

return gender;

}

public void setGender(String gender) {

this.gender = gender;

}

public String getAge() {

return age;

}

public void setAge(String age) {

this.age = age;

}

public String getCountry() {

return country;

}

public void setCountry(String country) {

this.country = country;

}

@Override

public String toString() {

return "Person [name=" + name + ", gender=" + gender + ", age=" + age

+ ", country=" + country + "]";

}

}

 

Step2: Create a Bean xml file to initialize Person object.


"<bean id="person">
<property name="name" value="Philip"></property>
<property name="gender" value="Male"></property>
<property name="age" value="25"></property>
<property name="country" value="US"></property>
</bean>"

Step3: Create an instance of the Person and display.


public class MainApps {

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext("PersonBeans.xml");

Person person1 = (Person) context.getBean("person");

System.out.println("Person:" + person1);

}

}

MySql Database Integration in Java

JDBC driver name and database URL

static final String JDBC_DRIVER = “com.mysql.jdbc.Driver”;

static final String DB_URL = “jdbc:mysql://localhost/db_myjava”;

// Database credentials

static final String USER = “root”;

static final String PASS = “”;

Example:

var1 = ‘Hello World!’

Built-in String Methods:

Methods: Description
capitalize(): Capitalizes first letter of string
center(width,fillchar): Returns a space-padded string with the original string centered to a total of width columns
count(str,beg=0,end=len(string)): Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given
find(str, beg=0 end=len(string)) Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise
rfind(str,beg=0,end=len(string)) Same as find(), but search backwards in string
index(str, beg=0, end=len(string)) Same as find(), but raises an exception if str not found.
rindex(str,beg=0,end=len(string)) Same as index(), but search backwards in string
isalnum() Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise
isalpha() Returns true if string has at least 1 character and all characters are alphabetic and false otherwise
isdigit() Returns true if string contains only digits and false otherwise
islower() Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise
isnumeric() Returns true if a unicode string contains only numeric characters and false otherwise
isspace() Returns true if string contains only whitespace characters and false otherwise
istitle() Returns true if string is properly “titlecased” and false otherwise
isupper() Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise
len(string) Returns the length of the string
lower() Converts all uppercase letters in string to lowercase
upper() Converts lowercase letters in string to uppercase
lstrip() Removes all leading whitespace in string
max(str) Returns the max alphabetical character from the string str
min(str) Returns the min alphabetical character from the string str
replace(old,new[,max]) Replaces all occurrences of old in string with new or at most max occurrences if max given
rstrip() Removes all trailing whitespace of string
split(str=”“,num=string.count(str)) Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given
isdecimal() Returns true if a unicode string contains only decimal characters and false otherwise

Python String functions

String

Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes.

Example:

var1 = ‘Hello World!’

Built-in String Methods:

Methods: Description
capitalize(): Capitalizes first letter of string
center(width,fillchar): Returns a space-padded string with the original string centered to a total of width columns
count(str,beg=0,end=len(string)): Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given
find(str, beg=0 end=len(string)) Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise
rfind(str,beg=0,end=len(string)) Same as find(), but search backwards in string
index(str, beg=0, end=len(string)) Same as find(), but raises an exception if str not found.
rindex(str,beg=0,end=len(string)) Same as index(), but search backwards in string
isalnum() Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise
isalpha() Returns true if string has at least 1 character and all characters are alphabetic and false otherwise
isdigit() Returns true if string contains only digits and false otherwise
islower() Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise
isnumeric() Returns true if a unicode string contains only numeric characters and false otherwise
isspace() Returns true if string contains only whitespace characters and false otherwise
istitle() Returns true if string is properly “titlecased” and false otherwise
isupper() Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise
len(string) Returns the length of the string
lower() Converts all uppercase letters in string to lowercase
upper() Converts lowercase letters in string to uppercase
lstrip() Removes all leading whitespace in string
max(str) Returns the max alphabetical character from the string str
min(str) Returns the min alphabetical character from the string str
replace(old,new[,max]) Replaces all occurrences of old in string with new or at most max occurrences if max given
rstrip() Removes all trailing whitespace of string
split(str=”“,num=string.count(str)) Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given
isdecimal() Returns true if a unicode string contains only decimal characters and false otherwise

SQLite in Android

Sqlite Data Types

DataType: Description
NULL: The value is a NULL value.
INTEGER: The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.
REAL: The value is a floating point value, stored as an 8-byte IEEE floating point number.
TEXT: The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16LE)
BLOB: The value is a blob of data, stored exactly as it was input.

Create table query

The SQLite CREATE TABLE statement is used to create a new table in any of the given database. Creating a basic table involves naming the table and defining its columns and each column’s data type.

Syntax:

CREATE TABLE table_name( column1 datatype , column2 datatype, column3 datatype, ….. columnN datatype, );

Example:

CREATE TABLE employee( id integer primary key autoincrement, name text, job text, age integer, salary decimal);

Insert query

The SQLite INSERT INTO Statement is used to add new rows of data into a table in the database.

Syntax:

INSERT INTO TABLE_NAME (column1, column2, column3,…columnN) VALUES (value1, value2, value3,…valueN);

Example:

INSERT INTO employee(name, job, age, salary) values(“Steve”, “Clerk”, 27, 15000);

Select query

SQLite SELECT statement is used to fetch the data from a SQLite database table which returns data in the form of result table. These result tables are also called result-sets.

Syntax:

SELECT column1, column2, columnN FROM table_name;

Example:

SELECT name, job, age, salary FROM employee;

Delete query

The SQLite DELETE Query is used to delete the existing records from a table. You can use WHERE clause with DELETE query to delete selected rows, otherwise all the records would be deleted.

Syntax:

DELETE FROM table_name WHERE [condition];

Example:

DELETE FROM employee WHERE ID = 1;

What is new in Python 3.4

Example:

Python 2.7: print “hello world”

Python 3.0: print(“hello world”)

Integers: long renamed to int

Python 2.7: long stars

Python 3.0: int stars

Views And Iterators Instead Of Lists

dict methods dict.keys(), dict.items() and dict.values() return “views” instead of lists. For example, this no longer works: k = d.keys(); k.sort(). Use k = sorted(d) instead (this works in Python 2.5 too and is just as efficient).

Also, the dict.iterkeys(), dict.iteritems() and dict.itervalues() methods are no longer supported.

map() and filter() return iterators. If you really need a list, a quick fix is e.g. list(map(…)), but a better fix is often to use a list comprehension, or rewriting the code so it doesn’t need a list at all. Particularly tricky is map() invoked for the side effects of the function; the correct transformation is to use a regular for loop.

range() now behaves like xrange() used to behave, except it works with values of arbitrary size. The latter no longer exists.

zip() now returns an iterator.

Ordering Comparisons

The ordering comparison operators (<, <=, >=, >) raise a TypeError exception when the operands don’t have a meaningful natural ordering. Thus, expressions like 1 < ‘’, 0 > None or len <= len are no longer valid, and e.g. None < None raises TypeError instead of returning False. A corollary is that sorting a heterogeneous list no longer makes sense – all the elements must be comparable to each other. Note that this does not apply to the == and != operators: objects of different incomparable types always compare unequal to each other.

builtin.sorted() and list.sort() no longer accept the cmp argument providing a comparison function. Use the key argument instead. N.B. the key and reverse arguments are now “keyword-only”.

The cmp() function should be treated as gone, and the cmp() special method is no longer supported. Use lt() for sorting, eq() with hash(), and other rich comparisons as needed. (If you really need the cmp() functionality, you could use the expression (a > b) – (a < b) as the equivalent for cmp(a, b).)

Text Vs. Data(binary) Instead Of Unicode Vs. 8-bit

Python 3.0 uses the concepts of text and (binary) data instead of Unicode strings and 8-bit strings. All text is Unicode; however encoded Unicode is represented as binary data. The type used to hold text is str, the type used to hold data is bytes. The biggest difference with the 2.x situation is that any attempt to mix text and data in Python 3.0 raises TypeError, whereas if you were to mix Unicode and 8-bit strings in Python 2.x, it would work if the 8-bit string happened to contain only 7-bit (ASCII) bytes, but you would get UnicodeDecodeError if it contained non-ASCII values.

You can no longer use u”…” literals for Unicode text. However, you must use b”…” literals for binary data.

As the str and bytes types cannot be mixed, you must always explicitly convert between them. Use str.encode() to go from str to bytes, and bytes.decode() to go from bytes to str. You can also use bytes(s, encoding=…) and str(b, encoding=…), respectively.

Like str, the bytes type is immutable. There is a separate mutable type to hold buffered binary data, bytearray. Nearly all APIs that accept bytes also accept bytearray. The mutable API is based on collections.MutableSequence.

All backslashes in raw string literals are interpreted literally. This means that ‘\U’ and ‘\u’ escapes in raw strings are not treated specially.

Tuples, Lists and Dictionaries in Python

1. Tuples:

Tuples are just like lists, but you can’t change their values. The values that you give it first up, are the values that you are stuck with for the rest of the program. Again, each value is numbered starting from zero, for easy reference. Example: the names of the months of the year.

Example:

months = (‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’, ‘November’, ‘December’);

2. Lists

Lists are extremely similar to tuples. Lists are modifiable or mutable, so their values can be changed. Most of the time we use lists, not tuples, because we want to easily change the values of things if we need to.

Example:

//create names list

names = [‘Philip’, ‘Karan‘, ‘Mathew’];

//To add one more name

names. append(‘Thomas’);

//To remove a name

names.remove[2];

3. Dictionaries

Dictionaries are associative arrays. They have keys, and values. Just like a phone book, with people’s names and their numbers.

Example:

//create a phonebook

phonebook = {‘Philip’:4033224455, ‘Karan’:4033224456, ‘Mathew’:4033224457}

Page 2 of 5912345...102030...Last »