Java, NoSQL, SQL, REST API and other scary words

Simple Java code examples to start with

Class

public class TallMan {
       static class TallOfMan {
             int tall;
       }
       static class WeihtandTallOfMen extends TallOfMan {
             int weight;
       }
       public static void main(String[] args) {
             WeihtandTallOfMen weihtandTallOfMen = new WeihtandTallOfMen();
             weihtandTallOfMen.tall = 10;
             TallOfMan tallOfMan = new TallOfMan();
             tallOfMan.tall = 10;
             if (weihtandTallOfMen.tall == tallOfMan.tall) {
                   System.out.println("works");
            }
       }
}

Initialize variable for Helpers (simplified example)

package playground;
import playground.BaseClass;;

public class Helper {
       private BaseClass baseClass;
       public BaseClass getBaseClass() {
        if (baseClass == null) {
             System.out.println("baseClass = new BaseClass();");
             baseClass = new BaseClass();
        }
        else{
             System.out.println("return baseClass");
        }
        return baseClass;
    }
}

Set and Get

package playground;
public class BaseClass {

       private int i;
       public void setInt(int i) {
             System.out.println("this.i = " + i);
             this.i = i;
       }
     
       public int getInt() {
            System.out.println("return " + i);
            return i;
       }
}

Static

public class staticTest {
       static class Animal {
             public static void isItFat(String type, int weight) {
                    if (type.equals("Dog") && weight > 20) {
                          System.out.println("Animal is fat!!");
                    }
             }
       }
       public static void main(String args[]) {
             Animal.isItFat("Dog", 120);
       }
}

Superclass

public class CopyOfAnimal {
       private final String noise;
       protected CopyOfAnimal(String noise) {
             this.noise = noise;
       }

       public void makeNoise() {
             System.out.println("Animal" + noise);
       }
}

class Pig extends CopyOfAnimal {
       public Pig() {
             super("Oink ");
       }
}

class Dog extends CopyOfAnimal {
       public Dog() {
             super("Gav ");
       }
}

class Action {
       public static void main(String[] args) {
             Pig piggie = new Pig();
             piggie.makeNoise();
             Dog dog = new Dog();
             dog.makeNoise();
       }
}

 Try/Catch/Finally

public class Math {
   private static int с;
   public static void main(String[] args) throws IOException {
      int a = 0;
      int b = 10;
      openDesctopFile();
      mathematical(a, b);
   }

   private static void openDesctopFile() throws IOException {
      File file = new File(“out.txt”);
      try {
         if (!file.exists())
         throw new FileNotFoundException(“no file, let’s open the other one”);
      }
      catch (IOException e) {
         System.out.println(” “);
         System.out.println(“file not found” + e.getMessage());
      }
   finally
   {
      Desktop.getDesktop().open(new File(“1.txt”));
   }
   }

   private static void fileOpen() {
      BufferedWriter out = null;
      FileWriter fstream = null;
      try {
         fstream = new FileWriter(“out.txt”, true);
         }
     catch (IOException e) {
         e.printStackTrace();
         System.out.println(e);
      }
      finally {
         int g = 20;
         System.out.println(“finally ” + (10 – g));
      }
      out = new BufferedWriter(fstream);
      try {
         out.write(“hello”);
      } catch (IOException e) {
         e.printStackTrace();
      }
      }
      private static void mathematical(int a, int b) {
         System.out.println(“a/b”);
         try {
            с = b / a;
         }
         catch (ArithmeticException e) {
            System.out.println(e);
            System.out.println(“devide by zero”);
         }
         finally {
            с = 0;
         }
         System.out.println(с);
      }
   }

JDBC

 void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
             Class.forName("com.mysql.jdbc.Driver").newInstance();
             Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test_base", "root", "");
             Statement st = con.createStatement();
             String sql = ("SELECT * FROM `table` ORDER BY AGE DESC LIMIT 1 ");
             ResultSet rs = st.executeQuery(sql);
             if (rs.next()) {
                    id = rs.getInt("id");
                    name = rs.getString("name");
                    age = rs.getInt("age");
             }
             int currentYear = Calendar.getInstance().get(Calendar.YEAR);
             String fullData = "User " + name + " is " + age + " yeras old and he/she was born in " + (currentYear - age);
             System.out.println(fullData);
             con.close();
       }
}

HTTP GET/POST

public class RequestToGetData {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
  RequestToGetData http = new RequestToGetData();
  System.out.println("Testing 1 - Send Http GET request");
  http.sendGet();                  
}

// HTTP GET request
private void sendGet() throws Exception {
String url = "http://online.ibs.ru/Pages/Default.aspx";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

// optional default is GET
con.setRequestMethod("GET");
// add request header
con.setRequestProperty("User-Agent", USER_AGENT);
system.out.println("ready for fail");

int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));

String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}

in.close();

// print result
String fullRespond = response.toString();
System.out.println(fullRespond);
String newURL = "";
String result;
Pattern MY_PATTERN = Pattern.compile(
"(http|ftp|https):\\/\\/([\\w\\-_]+(?:(?:\\.[\\w\\-_]+)+))([\\w\\-\\.,@?^=%&:/~\\+#]*[\\w\\-\\@?^=%&/~\\+#])?");
Matcher m = MY_PATTERN.matcher(fullRespond);
System.out.println("go");

int n = 0;
while (m.find()) {
String s = m.group(n);
newURL = newURL + s;
n++;
}

System.out.println("newURL: " + newURL);
}
}

JSP and SQL

<?xml version=“1.0”encoding=”UTF-8″?>
       <%
       @page import=”org.apache.jasper.tagplugins.jstl.core.Import”%>
<%@page import=”java.sql.*”%>
<%@page import=”java.util.Calendar”%>
<%@ page language=“java” contentType=“text/html; charset=UTF-8”
pageEncoding=”UTF-8″%>
<!DOCTYPE html PUBLIC“-//W3C//DTD XHTML 1.0 Transitional//EN”http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html xmlns=http://www.w3.org/1999/xhtml”&gt;
<head>
<meta httpequiv=“Content-Type”content=”text/html; charset=UTF-8″/>
<title>Get ID</title>
</head>
<body>
<p><%=”My application!”%></p>
<p><%out.println(“Your IP address is “+request.getRemoteAddr()); %></p>
<p><%String name = ” “;int age = 0;
Class.forName(“com.mysql.jdbc.Driver”).newInstance();
Connection con = DriverManager.getConnection(“jdbc:mysql://localhost/test_base”, “root”, “”);
Statement st = con.createStatement();
String sql = (“SELECT * FROM table WHERE id =2 LIMIT 0 , 30;”);
ResultSet rs = st.executeQuery(sql);
if(rs.next())
{
name = rs.getString(“name”);
age = rs.getInt(“age”);
}
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
int yearOfBirth = (currentYear – age);
String fullData = “User ” + name + ” is ” + age + ” yeras old and he/she was born in ” + (currentYear – age);
out.println(fullData);
con.close();
%></p>
       </body>
       </html>

Simple THREAD

class RunnableThread implements Runnable {
Thread runner;
public RunnableThread() {
}

public RunnableThread(String threadName) {
runner = new Thread(this, threadName); // (1) Create a new thread.
System.out.println(runner.getName());
runner.start(); // (2) Start the thread.
}

public void run() {
// Display info about this particular thread
System.out.println(Thread.currentThread());
}
}

public class RunnableExample {
public static void main(String[] args) {
Thread thread1 = new Thread(new RunnableThread(), “thread1”);
Thread thread2 = new Thread(new RunnableThread(), “thread2”);
RunnableThread thread3 = new RunnableThread(“thread3”);
// Start the threads
thread1.start();
thread2.start();
try {
// delay for one second
Thread.currentThread().sleep(10000);
} catch (InterruptedException e) {
}

// Display info about the main thread
System.out.println(Thread.currentThread());
}
}

THREAD no locks

class XThread extends Thread {
XThread() {
}

XThread(String threadName) {
super(threadName); // Initialize thread.
System.out.println(this);
start();
}

public void run() {
// Display info about this particular thread
System.out.println(Thread.currentThread().getName());
}
}

public class ThreadExample {
public static void main(String[] args) {
Thread thread1 = new Thread(new XThread(), "thread1");
Thread thread2 = new Thread(new XThread(), "thread2");
// The below 2 threads are assigned default names
Thread thread3 = new XThread();
Thread thread4 = new XThread();
Thread thread5 = new XThread("thread5");
// Start the threads
thread1.start();
thread2.start();
thread3.start();
thread4.start();

try {
// The sleep() method is invoked on the main thread to cause a
// one second delay.
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
}
// Display info about the main thread
System.out.println(Thread.currentThread());
}
}

THREAD with LOKS

///// main class///////////////
public class Animal {
//////// constructor ///////////
private final String noise;
protected Animal(String noise) {
this.noise = noise;
}

public void makeNoise() {
System.out.println("Animal" + noise);
}
}

//////////// extends of Animal class ////////////
class Pig extends Animal {
public Pig() {
super("Oink ");
}
}

class Dog extends Animal {
public Dog() {
super("Gav ");
}
}

//////////// action at thread ////////////////////
class makeShouting implements Runnable {
private Pig piggie;
private Dog dog;
public makeShouting(Pig piggie) {
this.piggie = piggie;
}

public makeShouting(Dog dog) {
this.dog = dog;
}

@Override
public void run() {
// TODO Auto-generated method stub
// ShoutingLoker shoutingLoker;
ShoutingLoker shoutingLoker = new ShoutingLoker();
try {
shoutingLoker.getLock();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (dog == null) {
piggie.makeNoise();
}
else
{
dog.makeNoise();
}
}
shoutingLoker.releaseLock();
System.out.println("thread ends");
}

///////////////// lockers for threads //////////////
class ShoutingLoker {
final Lock lock = new ReentrantLock();
void getLock() throws InterruptedException {
lock.lock();
}
void releaseLock() {
lock.unlock();
}
}
}

//////////////////// main class///////////////////
class Action {
public static void main(String[] args) {
Pig piggie = new Pig();
Dog dog = new Dog();
///////////////////////// implements of THREADs
Thread thread1 = new Thread(new makeShouting(piggie));
thread1.start();
Thread thread2 = new Thread(new makeShouting(dog));
thread2.start();
thread2.start();
}
}

DEADLOCK

class Human implements Runnable {
public static void main(String[] args) {
Human first = new Human("Vasia");
Human second = new Human("Petia");
Thread t1 = new Thread(first);
t1.start();
Thread t2 = new Thread(second);
t2.start();
}

private String name;
public Human(String name) {
this.name = name;
}

private int numberOfEater;
@Override
public void run()
{
Fork fork;
Knife knife;
if (this.name.equals("Vasia"))
{
while (true)
{
fork = new Fork();
knife = new Knife();
System.out.println("Eater zero ate!");
}
}
else
{
while (true)
{
knife = new Knife();
fork = new Fork();
System.out.println("Eater one ate!");
try {
wait(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

class Knife
{
final Lock lock = new ReentrantLock();
public Knife()
{
lock.lock();
}

void release()
{
lock.unlock();
}
}

class Fork
{
final Lock lock = new ReentrantLock();
public Fork()
{
lock.lock();
}

void release()
{
lock.unlock();
}
}
Advertisements
Standard

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s