Свалка личных заметок, не адаптированная для представления собой общественно полезного материала.

Sunday, 25 December 2016

Http request/response

try {

    ServerSocket serverSocket = new ServerSocket(8080);
    Socket clientSocket = serverSocket.accept();
    PrintWriter out =
            new PrintWriter(clientSocket.getOutputStream(), true);
    BufferedReader in =
            new BufferedReader(
                    new InputStreamReader(clientSocket.getInputStream()));

    String request = in.readLine();

    out.println("HTTP/1.0 200");
    out.println("Content-type: text/html");
    out.println("Server-name: myserver");
    String response = "<html>"            + "<head>"            + "<title>My Web Server</title></head>"            + "<h1>Welcome  Web Server!</h1>"            + "</html>";
    out.println("Content-length: " + response.length());
    out.println("");
    out.println(response);
    out.flush();
    out.close();
    clientSocket.close();

}
catch (IOException e){
    System.out.println(e.getMessage());
}

Wednesday, 8 June 2016

JDBC

<dependency>
    <groupId>com.oracle.jdbc</groupId>
    <artifactId>com.springsource.oracle.jdbc</artifactId>
    <version>10.2.0.2</version>
</dependency>

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

public class OracleJDBC {

 public static void main(String[] args) {

  try {

   Class.forName("oracle.jdbc.driver.OracleDriver");

  } catch (ClassNotFoundException e) {

   System.out.println("Oracle Driver not found");
   e.printStackTrace();
   return;

  }

  System.out.println(Driver Registered!");

  Connection connection = null;

  try {

   connection = DriverManager.getConnection(
     "jdbc:oracle:thin:@host:port:SID", "username", "password");
//OR jdbc:oracle:thin:@//host:port/service_name
  } catch (SQLException e) {

   System.out.println("Connection Failed");
   e.printStackTrace();
   return;

  }

  if (connection != null) {
   System.out.println("Connected to DB");
  } else {
   System.out.println("Something went wrong");
  }
 }

}

SQL-queries execution

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
...

Statement stmt = connection.createStatement();
String sql = "<select * from dual>";
ResultSer rs = stmt.executeQuery(sql);

Put results into HashMap

import java.util.HashMap;
import java.util.Map;
...

Map<String,String> resultData = new HashMap<>();
while (rs.next()){
resultData.put("key_value", rs.getString("column_name"));
}
sysout(resultData); //print key-data pairs

Wednesday, 1 June 2016

Grep & regexp

ls *.txt
grep PATTERN FILE
. #any one character
* #any amount of characters
[a-c]at = bat, cat #defined class of characters
[0-9][0-9] = 42, 37
c[qwerty]t = cqt, cyt
\s #spaces
\S #characters without spaces
\w #word [A-Za-z0-9_]
\W #non-word [^A-Za-z0-9_]
\d #digits
\D #non-digits
\b #word boundary
\B #not a word boundary

\bDate\b = Date
Date\b = Date, SubDate
\BDate\B = SubDates

grep -P #Perl regexp

'^[\s<]+title' #beginning with tabs&spaces+<title
'title>'$ #ending with title>

wc -w FILE #words count + filename
wc -l FILE #lines count + filename
cat FILE | wc -l #filename is ignored in the output

sed '10q;d' FILE #view 10th line of the file (quit before deletion); can be parametrized as "${NUM}q;d"
head -10 FILE | tail -1 #view 10th line; can't be parametrized

TOTAL=$(cat NYRegion.xml | wc -l)
for i in $(seq ${TOTAL})
do
sed "${i}q;d" NYRegion.xml | grep -oP '(?<=title>)[^<]+' | sed s/'&gt;'/'>'/
done

Quantifiers

bo?t = 0 or 1 char: subtropical, turbot
bo+t = 1 or more chars: booth, robot
bo*t = 0 or more chars: subtropical, booth, robot

{3} = certain number of chars
^\w*@\w*\.\w{2,6}$ #poor regexp for email; \. to be not interpreted as a special char

Tuesday, 31 May 2016

Bash basics

execute script:
bash test.sh or ./test.sh

read var #var input into $var
echo $var > test.txt #save data into file with (previous data will be cleaned up)
echo $var >> test.txt #new data will be appended to the end
clear

cat temp.txt #display file content

ls #file listing
rm file.txt #remove file
https://ru.wikipedia.org/wiki/Chmod #access to file

pwd #present working directory
echo 'text' #simple string
echo "text $PATH" or echo "text ${PATH}" or echo "text $(pwd)" #string with variables
$(pwd) #grab the command's output
${PATH} #grab the variable's value

Passing options into the script:
./test.sh option1
echo "Option is ${@}" #${@} - all options, ${1} - first option, ${2} - second option

touch newfile.${ext} #create new empty file with user's extension

for i in $(seq 1 10) # sequence from 1 to 10
do
echo "Value is: $i"
done

Bash operates with Integers onlyecho $((3+3))
echo $((5%2)) #get the remainder

if [ $((${1}%2)) -eq 0 ]; then
echo "Even"
else
echo "Odd"
fi

-ne #not equals
-lt #less than
-le #less than or equal to
-gt #greater than
-ge #greater than or equal to

OSI & TCP/IP

Open systems interconnection basic reference model

Levels:

1. Application
Interaction between user application & network: HTTP, FTP, SMTP...

2. Presentation
Transformation/encryption/decryption

3. Session
Open/close session

4. Transport
Data transportation: TCP, UDP

5. Network
Routing: IP

6. Link
Network interaction on physical level: Ethernet, Wi-Fi

7. Physical
Binary data transfer between PCs 

CIDR-адрес (безклассовая адресация) - запись IP-адреса с указанием маски подсети: 192.168.1.0/24 
24 разряда в маске подсети для идентификации сети: 255.255.255.0
192.168.5.0 -> идентификатор сети
192.168.5.255 -> широковещательный адрес сети. Адресованный пакет получат все узлы сети
192.168.5.1 - 192.168.5.254 -> диапазон хостов сети

192.168.1.0/25 -> первые 25 разрядов IP-адресов = 1
11111111.11111111.11111111.10000000
Маска 255.255.255.128

Tuesday, 10 May 2016

PL/SQL subprogramms

Anonymous block

In contrast to the stored procedure, anonymous block is unloaded from the memory after code execution.
Byte-code of the SP remains in the memory while instanse is not restarted or it's cleaned up in case of lack of memory (in accordance with 'first in, first out' principle).

Structure:

DECLARE
 <constant name> CONSTANT <data type> := <value>;
 <constant name> CONSTANT <data type> DEFAULT <value>;
BEGIN
  <valid statement>;
EXCEPTION
  <exception handler>;
END;
/


Procedure

Can return none or many values.

CREATE OR REPLACE PROCEDURE remove_emp (employee_id IN/OUT/IN OUT NUMBER) IS/AS tot_emps NUMBER; BEGIN DELETE FROM employees WHERE employees.employee_id = remove_emp.employee_id; tot_emps := tot_emps - 1; END; /

Specification of the default parameters:

CREATE OR REPLACE PROCEDURE remove_emp (employee_id IN NUMBER := 100)

or

CREATE OR REPLACE PROCEDURE remove_emp (employee_id IN NUMBER DEFAULT 100)

Get type from table column:

tot_emps employees.employee_id%TYPE;

Procedure having output:

CREATE OR REPLACE PROCEDURE get_employee
(p_empid IN NUMBER,
v_sal OUT NUMBER,
v_depid OUT NUMBER)
IS
BEGIN
SELECT salary, job_id
INTO v_sal, v_depid
FROM employees
where employee_id = p_empid;
END  get_employee;

VARIABLE v_sal  NUMBER
VARIABLE v_depid NUMBER
EXECUTE get_employee(171, :v_sal , :v_depid) //procedure output will be stored in p_name
print v_sal  v_depid;

Writing into the variable:

VARIABLE a NUMBER
BEGIN
:a := 1;
end;
print a

:a -> external variable. it's created for the session and dropped after disconnect;
a -> inner variable. declared inside procedure.

Passing of the parametres:

execute add_dept (p_loc => 2400, p_name => 'education')

Parametres can be passed in random order

Random notes

id.NEXTVAL -> sequence usage (should be created before);
describe table_name/package_name/procedure_name;
select * from user_source -> view functions/procedures bodies;
views: user_tables -> own tables; all_tables -> own tables and tables by other users where current user has an access; dba_tables -> for admin rights.
user_errors -> compillation errors. cleaned up after sucsessfull compilation.

RAISE_APPLICATION_ERROR

IF SQL%NOTFOUND
THEN
RAISE_APPLICATION_ERROR (-20202, 'No job updated');
END IF;

Functions

Functions return the only one value and can be called from sql-statements.

CREATE OR REPLACE Function FindCourse
   ( name_in IN varchar2 )
   RETURN number
IS
   cnumber number;

BEGIN
   cnumber := 9999;
RETURN cnumber;

EXCEPTION
WHEN OTHERS THEN
   raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);
END;

Friday, 22 April 2016

Conditions

Сonjunction

Both a and b are true
If the first checked operand is false-> the whole condition is false

a = false;
b = true;
if (a & b){} //both operands will be calculated
if (a && b){} //operand b will not be checked, because a is aleady false

In case a and b are integer -> a & b = a * b

Disjunction

a or b or both are true
If the first checked operand is true -> the whole condition is true

a = true;
b = false;
if (a | b){} //both operands will be calculated
if (a || b){} //operand b will not be checked, because a is aleady true

In case a and b are integer -> a | b = a + b

Exclusive disjunction

a or b are true, but not both

a = true;
b = false;
if(a^b){}