Sunday 29 December 2013

How to Connect Java With Mysql in eclipse

Step 1: Download mysql Connector from the link Below.

http://mirrors.ibiblio.org/pub/mirrors/maven2/mysql/mysql-connector-java/5.0.8/mysql-connector-java-5.0.8.jar

Step2: Right Click on project name select properties, then select java Build Path and go to Libraries tab.

Step 3: Click  on add External jar browse to the downloaded mysql-connector jar file then Click ok.
Step 4:  write the following code.

import java.sql.*;

public class ConnectToMySql {
   
    public static void main(String[] args) throws Exception {
   
       Class.forName("com.mysql.jdbc.Driver"); //checking for drivers
//DriverManager.getConnection("jdbc:mysql://servername/database","username","password")
       Connection con =  DriverManager.getConnection("jdbc:mysql://localhost/test","root","");

       Statement st=con.createStatement();
       System.out.println("Connected To MySql 5.0");
       ResultSet rs=st.executeQuery("SELECT * FROM users"); //users table name
       while ( rs.next()) {
           System.out.println( rs.getString("username") + ":" + rs.getString("password"));//username and password are the fields of users table
       }
       con.close();
    }
}

Tuesday 24 December 2013

Creating a Client Proxy in Java

@WebServiceClient(name = "CalculatorWSService", 
targetNamespace = "http://calculator.me.org/", 
wsdlLocation = "http://localhost:4933/CalculatorApp/CalculatorWSService?wsdl")
public class CalculatorWSService extends Service { //...
@WebEndpoint(name = "CalculatorWSPort")
public CalculatorWS getCalculatorWSPort() {
return super.getPort(new QName("http://calculator.me.org/", 
"CalculatorWSPort"), CalculatorWS.class);
}

Here  the  getCalculatorWSPort method  returns  an  object  that  implements  the
CalculatorWSinterface, which is discussed next. The no-arg  getPortmethod can be
used  in  general;  the  second  getPort method  accepts  a  variable-length  array  of
javax.xml.ws.WebServiceFeatureobjects that can be used by clients to configure certain
aspects of the invocation, such as whether to enable MTOM or WS-Addressing.


In the calculator example, the port has one method, to match the single addoperation
defined in the WSDL. Let’s take a step back and unpack this for a moment, as there’s
a lot going on here:
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "add", 
targetNamespace = "http://calculator.me.org/", 
className = "org.me.calculator.Add")
@ResponseWrapper(localName = "addResponse", 
targetNamespace = "http://calculator.me.org/", 
className = "org.me.calculator.AddResponse")
public int add(
@WebParam(name = "i", targetNamespace = "")
int i,
@WebParam(name = "j", targetNamespace = "")
int j);

As you can see, your seemingly simple, innocuous addmethod suddenly has a variety

of annotations adorning it. We’ll account for these one by one.
First, your WSDL specifies the following in the messages section:
<message name="add"> <part name="parameters" element="tns:add"></part> </message>
So the SEI needs to account for this message, and creates an annotation indicating that
the runtime will create a message with a QNamethat contains a local part of add, in the
specified  namespace. That message is derived from the Java class that is also generated,
org.me.calculator.Add, which looks like this:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "add", propOrder = {
"i",
"j"
})
public class Add {
protected int i;
protected int j;
//getters and setters omitted
That class acts as the wrapper for each of the integers that will be sent in the request.
The @Xml annotations on this class come from JAXB. They indicate how JAXB should
marshal and unmarshal instances of this class to and from XML. The @XmlTypeannotation is used to specify that this  Addclass matches a top-level complex type (or an
enum) within an XML schema, and the “name” property is specified as “add” in it, to
match the item’s name within the schema. If you look at the schema that your WSDL
refers to, you see the following complex type, which matches your Addclass:
<xs:complexType name="add">
<xs:sequence>
<xs:element name="i" type="xs:int"></xs:element>
<xs:element name="j" type="xs:int"></xs:element>
</xs:sequence>
</xs:complexType>
But why does this type get created for you? Integers are defined as basic types provided
with XML Schema; they are not custom types that you have written that require something special. The complex type that wraps these two integers is created in order to
match your WSDL, which uses the document/literal style. Here is the portion of the
WSDL that tells you this:
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" 
style="document"></soap:binding>
<operation name="add">
<soap:operation soapAction=""></soap:operation>
<input>
<soap:body use="literal"></soap:body>
</input>
Had you been using RPC and not document, the values would have been passed separately to the operation invocation just like method parameters.

The  @RequestWrapperand  @ResponseWrapperannotations capture information that JAXB
needs to perform the marshaling and unmarshaling operations. If your service is defined
as using document/literal mode, as ours is, this annotation also serves to resolve overloading conflicts.
Now, let’s write a quick program to invoke the generated client code and get a result
from your service. Here are the steps in their simplest form, stripped of any unnecessary
items so you can get the clearest picture.

import org.me.calculator.*;

public class CalculatorInvoker {
public static void main(String... arg) {
CalculatorWSService service = new CalculatorWSService();
CalculatorWS port = service.getCalculatorWSPort();
int result = port.add(2, 3);
System.out.println("Result: " + result);
}
}

Then you can run it:
>java -cp . CalculatorInvoker
Result: 5



Invoking the Simplest Web Service In Java

import java.net.URL;
import java.util.Iterator;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class HelloClient {
public static void main(String[] args) throws Exception {
//Specify the WSDL 
//Create a Qualified Name that represents the 
//namespace and local part of the service
QName serviceName = new QName("http://ch03.soacookbook.com/", 
"HelloWSService");
//Create a proxy to get a port stub from
Service service = Service.create(wsdlLocation, serviceName);
// Return a list of QNames of ports
System.out.println("QNames of service endpoints:");
Iterator<QName> it = service.getPorts();
QName lastEndpoint = null;
while (it.hasNext()) {
lastEndpoint = it.next();
System.out.println("Name: " + lastEndpoint);
//prints: Name: {http://ch03.soacookbook.com/}HelloWSPort
}
// Get the Hello stub
Hello hello = service.getPort(lastEndpoint, Hello.class);
//Invoke the business method
String result = hello.sayHello("Duke");
System.out.println("\nResponse: " + result);
}
}

ITERATORS in C++

Iterators are similar to pointers in that they point to elements in a container. Iterators
are commonly used in C++ and are very important when using the STL.
 A number of functions dealt with iterators, and in the following section we will
take a closer look at them and how they relate to the vector template class.

#include<iostream>
#include<vector>
#include<algorithm>
#include<numeric>
using namespace std;
void PrintVector(vector<int> &array)
{

cout << "Contents (" << "Size: " << (int)array.size() <<
" Max: " << (int)array.capacity() << ") - ";
ostream_iterator<int> output(cout, " ");
copy(array.begin(), array.end(), output);
cout << endl;
}
int main(int args, char **argc)
{
cout << "STL Vector Example 2: Iterators" << endl;
cout << "Data Structures for Game Developers" << endl;
cout << "Allen Sherrod" << endl << endl;
vector<int> array;
array.reserve(5);
// Add items then print.
array.push_back(10);
array.push_back(20);
array.push_back(30);
array.push_back(40);
array.push_back(50);
// Calling the copy algorithm.
vector<int> array2;
for(int i = 0; i < 5; i++)
array2.push_back(0);
copy(array.begin(), array.end(), array2.begin());
cout << " Inserted into vector: ";
PrintVector(array);
// Run the accumulate algorithm.
cout << " Accumulate: "
<< accumulate(array.begin(), array.end(), 0)
<< endl;
// Pop off the container.
array.pop_back();
array.pop_back();
cout << "Popped two from vector: ";
PrintVector(array);
// Clear the container.
array.clear();
cout << " Cleared vector: ";
PrintVector(array);
cout << endl;
// Test if the container is empty.
if(array.empty() == true)
cout << "Vector is empty.";
else
cout << "Vector is NOT empty.";
cout << endl << endl;
return 1;
}
the demo application stlvector in Listing  Vector Demo by creating an integer container and
filling it with elements. Once the container is filled, the STL copy algorithm is used
to copy the first container into another. Before the copying, a loop is used to create
the element space in the second container because to copy the first container into
the second, the second must have at least the number of elements required by the
range, which is specified by the iterators begin(first element or [0]) and end(last
element or [4]in this case).
After the copy algorithm is performed and the container is displayed, the
accumulate STL algorithm is performed to demonstrate that to get the sum of all
the elements, a few pop()calls are performed, the container is cleared, and it is
tested for emptiness. Inside the function used to print the container is new code
that replaces the forloop in the first vectordemo application stlvector. In this
function an output iterator is created and the STL copy algorithm is called. The call
states that the range of elements from the first parameter (the beginning of the container in this case) to the second parameter (the end of the container in this case)
should be copied to the output iterator. The output iterator for this demo application is set up to point to the C++ STD count object. This is an example of how to use
algorithms and iterators together to perform fast tasks in C++ code. Using a for
loop is one option, which was seen in the first stl vector demo, but it is slower than
using STL algorithms. Whenever possible use STL algorithms for traditional arrays
and containers because the performance is efficient. The output iterator that is set
up in points to the coutobject and appends a ""character to every
element that is passed to it. This is what gives the output a space between each
element that is printed

C++ Vector Demo

#include<iostream>
#include<vector>
using namespace std;
void PrintVector(vector
&array)
{
cout << "Contents (" << "Size: " << (int)array.size() <<
" Max: " << (int)array.capacity() << ") - ";
for(int i = 0; i < (int)array.size(); i++)
{
cout << array[i] << " ";
}
cout << endl;
}

int main(int args, char **argc)
{
cout << "STL Vector Example" << endl;
cout << "Data Structures for Game Developers" << endl;
cout << "Allen Sherrod" << endl << endl;
vector
array;
array.reserve(5);
array.push_back(10);
array.push_back(20);
array.push_back(30);
array.push_back(40);
cout << " Inserted into vector. ";
PrintVector(array);
array.pop_back();
array.pop_back();
cout << "Popped two from vector. ";
PrintVector(array);
array.clear();
cout << " Cleared vector. ";
PrintVector(array);
cout << endl;
if(array.empty() == true)
cout << "Vector is empty.";
else
cout << "Vector is NOT empty.";
cout << endl << endl;
return 1;
}


the demo application creates an integer array and populates it with data using the push_back()method . The container is empty until items are pushed onto it. Once on the list, the array [] operators can be used to access the element by reading or writing to it. In the example code four items are pushed onto the list before popping  (removal) of the last two and displaying the contents of the container.
The container is cleared, displayed again, and tested to see if it is empty. Inside
the function used to print a container, the code uses size()to determine how many
valid elements are currently pushed onto the container while capacity()is used to
determine how much space the container can hold without being resized. To access
the elements, we use the array operators [] for convenience.

The Entire Ordered and Unordered Array Classes

template<class T>
class UnorderedArray
{
public:
UnorderedArray(int size, int growBy = 1) :
m_array(NULL), m_maxSize(0),
m_growSize(0), m_numElements(0)
{
if(size)
{
m_maxSize = size;
m_array = new T[m_maxSize];
memset(m_array, 0, sizeof(T) * m_maxSize);
m_growSize = ((growBy > 0) ? growBy : 0);
}
}
virtual ~UnorderedArray()
{
if(m_array != NULL)
{
delete[] m_array;
m_array = NULL;
}
}
virtual void push(T val)
{
assert(m_array != NULL);
if(m_numElements >= m_maxSize)
{
Expand();
}
m_array[m_numElements] = val;
m_numElements++;
}
void pop()
{
if(m_numElements > 0)
m_numElements—;
}
void remove(int index)
{
assert(m_array != NULL);
if(index >= m_maxSize)
{
return;
}
for(int k = index; k < m_maxSize - 1; k++)
m_array[k] = m_array[k + 1];
m_maxSize—;
if(m_numElements >= m_maxSize)
m_numElements = m_maxSize - 1;
}
virtual T& operator[](int index)
{
assert(m_array != NULL && index <= m_numElements);
return m_array[index];
}
virtual int search(T val)
{
assert(m_array != NULL);
for(int i = 0; i < m_numElements; i++)
{
if(m_array[i] == val)
return i;
}
return -1;
}
void clear() { m_numElements = 0; }
int GetSize() { return m_numElements; }
int GetMaxSize() { return m_maxSize; }
int GetGrowSize() { return m_growSize; }
void SetGrowSize(int val)
{
assert(val >= 0);
m_growSize = val;
}
private:
bool Expand()
{
if(m_growSize <= 0)
return false;
T *temp = new T[m_maxSize + m_growSize];
assert(temp != NULL);
memcpy(temp, m_array, sizeof(T) * m_maxSize);
delete[] m_array;
m_array = temp;
m_maxSize += m_growSize;
return true;
}
private:
T *m_array;
int m_maxSize;
int m_growSize;
int m_numElements;
};

Ordered Array Class

template <class T>
class OrderedArray
{
public:
OrderedArray(int size, int growBy = 1) :
m_array(NULL), m_maxSize(0),
m_growSize(0), m_numElements(0)
{
if(size)
{
m_maxSize = size;
m_array = new T[m_maxSize];
memset(m_array, 0, sizeof(T) * m_maxSize);
m_growSize = ((growBy > 0) ? growBy : 0);
}
}
virtual ~OrderedArray()
{
if(m_array != NULL)
{
delete[] m_array;
m_array = NULL;
}
}
void push(T val)
{
assert(m_array != NULL);
if(m_numElements >= m_maxSize)

{
Expand();
}
for(int i = 0; i < m_numElements; i++)
{
if(m_array[i] > val)
break;
}
for(int k = m_numElements; k > i; k—)
{
m_array[k] = m_array[k - 1];
}
m_array[i] = val;
m_numElements++;
}
void pop()
{
if(m_numElements > 0)
m_numElements—;
}
void remove(int index)
{
assert(m_array != NULL);
if(index >= m_maxSize)
{
return;
}
for(int k = index; k < m_maxSize - 1; k++)
m_array[k] = m_array[k + 1];
m_maxSize—;
if(m_numElements >= m_maxSize)
m_numElements = m_maxSize - 1;

}
// Making this const allows for reading but not writing.
virtual const T& operator[](int index)
{
assert(m_array != NULL && index <= m_numElements);
return m_array[index];
}
int search(T searchKey)
{
if(!m_array)
return -1;
int lowerBound = 0;
int upperBound = m_numElements - 1;
int current = 0;
while(1)
{
current = (lowerBound + upperBound) >> 1;
if(m_array[current] == searchKey)
{
return current;
}
else if(lowerBound > upperBound)
{
return -1;
}
else
{
if(m_array[current] < searchKey)
lowerBound = current + 1;
else
upperBound = current - 1;
}
}
return -1;
}
void clear() { m_numElements = 0; }
int GetSize() { return m_numElements; }
int GetMaxSize() { return m_maxSize; }
int GetGrowSize() { return m_growSize; }
void SetGrowSize(int val)
{
assert(val >= 0);
m_growSize = val;
}
private:
bool Expand()
{
if(m_growSize <= 0)
return false;
T *temp = new T[m_maxSize + m_growSize];
assert(temp != NULL);
memcpy(temp, m_array, sizeof(T) * m_maxSize);
delete[] m_array;
m_array = temp;
m_maxSize += m_growSize;
return true;
}
private:
T *m_array;
int m_maxSize;
int m_growSize;
int m_numElements;
};

BINARY SEARCHES

A binary search can be performed on an ordered array. It works by taking a value
that is being searched for and testing it by the element in the middle of the array. If
the value being searched for is lower than the item in the middle of the ordered
array, it can be determined that if the value exists, it is in the first half of the array.
If the value is larger than the element in the middle, the value might exist in the
upper half. Once the direction is known, half of that new section is tested to further
narrow down where the value can be. This is repeated until the value is found or
until there are no more elements left. The binary search gets its name from the fact
that the remaining elements are always split in half (binary equals 2). Because a binary search requires the elements to be in order, this algorithm cannot work for an unordered array since the
unordered array can be unpredictable in terms of item positions.
The binary search can eliminate large sections of an array in an effort to narrow
down the list to find the value, assuming it exits. When compared to the linear
search, this can result in a huge difference in performance as Ngrows larger. For example, an array being searched with a linear algorithm that is made up of 1 million
elements will take on average 500,000 steps for items that exist, which can mean
that some checks can go up to the whole million depending on the item. Using a
binary search on an ordered array with that same number of elements will take
20 comparisons. To go from an average of 500,000 comparisons to just 20 is a huge
difference. To go from 1 million comparisons to 20 with items that are not found


while(1)
{
current = (lowerBound + upperBound) >> 1;
if(m_array[current] == searchKey)
{
return current;
}
else if(lowerBound > upperBound)
{
return -1;
}
else
{
if(m_array[current] < searchKey)
lowerBound = current + 1;
else
upperBound = current - 1;
}
}
return -1;
}
};


The binary search  starts off by defining the bounds that make up
the search range, which is initially set to the entire array. Once the range is set, the
middle of the range is determined and the element at the position is tested. If the
item is found, the index is returned; if the lower bound’s value becomes higher than
the upper bound’s value (which will happen when the search has stepped through
the entire array), then the value is not found. If neither of these two cases are true,
the lower bound, which is the minimum search range position, is adjusted if
the item is greater than the item in the middle, or else the upper bound is adjusted.
Adjusting the range values will quickly shrink the search range until the value is
found or until there are no more elements to check this

operation is pretty fast as N grows larger.