Category: nice to know

  • pushing files via Netcat

    Netcat is a utility in unix to investigate network connections. It has now been ported to windows and it allows us to query network connections on a windows platform with netcat (nc). A nice possibility is to push files via nc from one machine to another. Assume for the moment that both machines have netcat installed. If not, it can be retrieved here,here – with passcode nc, or here – with passcode nc
    On the receiving machine a listener process is started with:

    nc -l -p 1234 > romme.txt  or nc -l 1234 > romme.txt, depending upon the version
    

    This process listens to local port 1234 and it will store all information in file “romme.txt”.
    On the sending machine, we reach out to the receiving machine. Doing so, we start a datastream that streams the contents of the file that we want to send across. This can be done via:

    type invoer.txt | nc 192.168.2.22 1234
    

    The file is sent to a stream (via type). The stream is captured via the pipe symbol. It is transmitted to the nc command. The nc reaches out to machine 192.168.2.22, where the listener process is invokes. Everything is handled via the 1234 port. On the receiving machine, signals are received on the 1234 port. The data are captured and they are stored in file romme.txt.

  • Flume

    Flume allows to directly tranfer messages into a file. It even allows such files to be stored on Hadoop. This opens a way to capture messages in a file that is stored on Hadoop, ready to be analysed. The example is a series of events from a log that are collected. The file is then transferred to another platform (say Hadoop) to be processed further.
    I got flume working on a sandbox for Cloudera. It looks as if three related parameters must be provided for: one parameter refers to a flume.conf file (found in /etc/flume-ng/conf.empty/flume.conf); one parameter refers to the name of the agent. This can be found in the flume.conf file which happens to be sandbox in my case. Finally a third parameter refers to a conf directory which parameters are set via flume-env.sh.

     flume-ng agent --conf-file /etc/flume-ng/conf.empty/flume.conf --name sandbox  --conf /opt/examples/flume/conf
    

    Another example is next statement, more or less similar to the command given above:

    sudo flume-ng agent -c /etc/gphd/flume/conf -f /etc/gphd/flume/conf/flume.conf -n agent
    

    This one uses a conf file that is stored on /etc/gphd/flume/conf/flume.conf. The name of the agent is “agent; the conf directory is /etc/gphd/flume/conf. From the conf file, we know that so-called netcat is set up, that listens to port 44444. We use this to start a terminal session that starts a stream on the local Linux platform:

    [pivhdsne:~]$ nc localhost 44444
    testing
    OK
    1
    OK
    3
    OK
    4
    OK
    

    From the conf file, we know that these streams are stored on hdfs in directory /user/flume. If we look there, we see this file:

    [pivhdsne:~]$ hadoop dfs -cat /user/flume/FlumeData.1442949290540
    DEPRECATED: Use of this script to execute hdfs command is deprecated.
    Instead use the hdfs command for it.
    
    testing
    1
    3
    4
    [pivhdsne:~]$ 
    

    We see a file that is created on hdfs that stores the streamed data from the Linux platform. This is a way to transfer files from Linux to hdfs. A final example is given below, with the same netcat listener:

    cat test|nc localhost 44444
    

    This creates a stream (via cat) that translates a file into a stream. The stream is sent to the netcat process that submits the stream to port 44444. The stream is then catched by flume and stored in hdfs files.

  • Serialise

    I encountered the term “serialise”. But what does it mean?
    I understood the term “serialise” when I read a comment that explained that data structures can be created inside, say, PHP. One may think of an object or an array. Such data structures can only be used inside PHP and they cannot be transported outside PHP. To transport such structures outside, one needs to translate the structure into strings and numerics. PHP has a very convenient function, serialize, that does this for you. In other languages, you have to write your own serialise fundtion whereby you export strings and numerics from an object.

    $a= array( 'piet', 'jan', 'klaas');
    print_r($a);
    $b=serialize($a);
    print_r($b);
    $c=unserialize($b);
    print_r($c);
    

    The output looks like:

    Array ( [0] => piet [1] => jan [2] => klaas ) 
    
    a:3:{i:0;s:4:"piet";i:1;s:3:"jan";i:2;s:5:"klaas";}
    
    Array ( [0] => piet [1] => jan [2] => klaas )
    

    The first line shows the PHP representation of an array. The second line shows a string that can be understood by an outside application. After that, the operation is reversed and the original, PHP-internal, representation is provided.

  • Avro in Java

    Another example shows a similar idea. In this example a stream is created. This stream consists of 3 objects that contain a name and a number. Once the stream is created, it is serialised. In other words: the stream is prepared to be stored. It is stored in a file that is called “test.avro”.
    Before continuing, one remark on serialisation.
    The idea on serialisation is that one creates a format that is understandable outside the original language. An object that is created in Java can only be handled inside Java. To communicate the content, one needs to use a format that is underable by other languages, such as a string or an integer. The translation from an object into strings/integers is called serialisation. One then creates something that is understood outside Java. In this case, everyting will be translated into strings and integers. These are wrtten to a file. They can be understood by, say, PHP or Oracle. The strings and integers are written to a file. That file can be read by Oracle or PHP as they will only encounter strings/integers that can be transmitted from say Java to Oracle/ PHP.
    In that file, we may detect the scheme along which the data are stored and the actual data. It takes a bit of courage as it is a binary file. Subsequently, it will be read from that file and the contents is shown.
    The programme is written in Java. It reads like:

    package avro;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    import org.apache.avro.Schema;
    import org.apache.avro.file.DataFileReader;
    import org.apache.avro.file.DataFileWriter;
    import org.apache.avro.generic.GenericData;
    import org.apache.avro.generic.GenericDatumReader;
    import org.apache.avro.generic.GenericDatumWriter;
    import org.apache.avro.io.Encoder;
    import org.apache.avro.io.EncoderFactory;
    import org.apache.avro.util.Utf8;
    
    @SuppressWarnings("deprecation")
    class EmployeeTom
    {
    	public static Schema SCHEMA;
    	
    	static {
    		try {
    			SCHEMA = Schema.parse(EmployeeTom.class.getResourceAsStream("EmployeeTom.avsc"));
    		}
    		catch (IOException e)
    		{
    			System.out.println("Couldn't load a schema: "+e.getMessage());
    		}
    	}
    	
    	private String name;
    	private int age;
    
    	public EmployeeTom(String name, int age){
    		this.name = name;
    		this.age = age;
    	}
    	public GenericData.Record serialize() {
    		  GenericData.Record record = new GenericData.Record(SCHEMA);
    		  record.put("name", this.name);
    		  record.put("age", this.age);
    		  return record;
    		}
    	public static void testWrite(File file, EmployeeTom[] people) throws IOException {
    		   GenericDatumWriter datum = new GenericDatumWriter(EmployeeTom.SCHEMA);
    		   DataFileWriter writer = new DataFileWriter(datum);
    		   writer.create(EmployeeTom.SCHEMA, file);
    		   for (EmployeeTom p : people)
    		      writer.append(p.serialize());
    		   writer.close();
    		}	
    
    	public static void testRead(File file) throws IOException {
    		GenericDatumReader datum = new GenericDatumReader();
    		DataFileReader reader = new DataFileReader(file, datum);
    		GenericData.Record record = new GenericData.Record(reader.getSchema());
    		while (reader.hasNext()) {
    			reader.next(record);
    			System.out.println("Name " + record.get("name") + 
    			                    " Age " + record.get("age") );
    		}
    		reader.close();
    	}
    	public static void main(String[] args) {
    		EmployeeTom e1 = new EmployeeTom("Joe",31);
    		EmployeeTom e2 = new EmployeeTom("Jane",30);
    		EmployeeTom e3 = new EmployeeTom("Zoe",21);
    		EmployeeTom[] all = new EmployeeTom[] {e1,e2,e3};
    
    		File bf = new File("test.avro");
    		
    		try {
    			testWrite(bf,all);
    			testRead(bf);
    		}
    		catch (IOException e) {
    			System.out.println("Main: "+e.getMessage());			
    		}
    	}
    	
    }
    

    A final remark. I stored the schema in the same directory as the class files. This allowed the class EmployeeTom to find the schema file. The schema looked like:

    {
      "type": "record", 
      "name": "Employee", 
      "fields": [
          {"name": "name", "type": "string"},
          {"name": "age", "type": "int"}
      ]
    }
    
  • Sending data via AVRO

    I got a better understanding when I used AVRO to write data via PHP and to read them via Java. It demonstrated to me how data can be written in one language and subsequently be read in another language.
    I use a file to have the data be written by PHP. Subsequently the data can be read by Java.
    The question then is: what is the advantage of using AVRO to have data been written in file. This can be compared to ordinary CSV files or a more advanced XML format.
    Let us first write the data via PHP:
    using this script
    We have now written in PHP some data to a file. The nice thing about it that the data are written with their description, as provided by the schema. Apparently, the schema shows that we write records with two elements: a number and a name. This schema is only written once and the data are written after the schema.
    When one compares this to a normal CSV file, one may notice that the schema is added to the file. Hence a programme that reads the data may verify that the data are in the correct format.
    One may argue that this is similar to XML but with XML, the schema is repeated with every data element. Hence XML files tend to very large as compared to CSV. An avro file avoids this by providing the sceme just once.

    The file may be read in Java by:

    package avro;
    
    import java.io.File;
    import java.io.IOException;
    
    import org.apache.avro.Schema;
    import org.apache.avro.Schema.Parser;
    import org.apache.avro.file.DataFileReader;
    import org.apache.avro.file.DataFileWriter;
    import org.apache.avro.generic.GenericData;
    import org.apache.avro.generic.GenericDatumReader;
    import org.apache.avro.generic.GenericDatumWriter;
    import org.apache.avro.generic.GenericRecord;
    import org.apache.avro.io.DatumReader;
    import org.apache.avro.io.DatumWriter;
    
    public class GenericMain {
    	public static void main(String[] args) throws IOException {
    		Schema schema = new Parser().parse(new File("C:/inetpub/wwwroot/user.avsc"));
    		File file = new File("C:/inetpub/wwwroot/data.avr");
    		DatumReader datumReader = new GenericDatumReader(schema);
    		DataFileReader dataFileReader = new DataFileReader(file, datumReader);
    		GenericRecord member = null;
    		while (dataFileReader.hasNext()) {
    			// Reuse user object by passing it to next(). This saves us from
    			// allocating and garbage collecting many objects for files with
    			// many items.
    			member = dataFileReader.next(member);
    			System.out.println(member);
    		}
    		
    	}
    }
    
    

    This demonstrates that the data can be read in another language. In this case, Java is used to read the file. The Java programme just needs to know where the data is stored (in data.avr) and how the schema looks like (provided in user.avsc). After that the file can be read and its records can be accessed.

  • Add data on Big Data in Hive and Impala

    This post provides info on how data may be added on a Big Data platform with help of Hive and Impala. We start with a dataset that is stored on a Linux platform. We will show how these data can be stored on a HDFS/ Hadoop platform. After that, we will show how these data can be included in a Hive database. Subsequently it is shown how these data can be accessed from a client (like SQL Developer).
    But the first step to have data on a Linux platform. Such data can be inserted via FTP or via de text editor like nano or vi. Let us assume we create a file with nano, inserting several comma-seperated records. I created a 5 record-file with two fields:

    [cloudera@quickstart ~]$ nano invoer3.txt
    [cloudera@quickstart ~]$ cat invoer3.txt
    1,tom
    2,ine
    3,paula
    4,stella
    5,bart
    [cloudera@quickstart ~]$
    

    The data are now on a Linux platform. They have to be moved to the HDFS platform. This can be be done with:

    cat invoer3.txt|hdfs dfs -put - /user/cloudera/invoer/invoer3.txt
    

    This command streams the data (using cat) and puts that stream into a file on the HDFS platform. To name the data lineage easy, I use the same name for the file as on Linux. In both cases, it is invoer3.txt. However, these are two physically different files. Once they are stored on the hfds platform, I would like to set the privilegs such that all users may access them. I use these commands to accomplish this:

    sudo -u hdfs hadoop fs -chmod 777 /user/cloudera/invoer
    sudo -u hdfs hadoop fs -chmod 777 /user/cloudera/invoer/invoer3.txt
    

    In subsequent steps, the files will be read by Hive/ Impala which is technically another user. I created privileges which allow other users to read the data and to create other files if necessary.
    I will subsequently create a table via Impala, using the HDFS file as an external file:

    [cloudera@quickstart ~]$ impala-shell
    Starting Impala Shell without Kerberos authentication
    Connected to quickstart.cloudera:21000
    Server version: impalad version 2.2.0-cdh5 RELEASE (build 2ffd73a4255cefd521362ffe1cfb37463f67f75c)
    Welcome to the Impala shell. Press TAB twice to see a list of available commands.
    
    Copyright (c) 2012 Cloudera, Inc. All rights reserved.
    
    (Shell build version: Impala Shell v2.2.0-cdh5 (2ffd73a) built on Tue Apr 21 12:09:21 PDT 2015)
    [quickstart.cloudera:21000] > create EXTERNAL TABLE invoer3
    (
    id INT,
    naam STRING
    )
    ROW FORMAT DELIMITED FIELDS TERMINATED BY ','
    LOCATION '/user/cloudera/sample_data/invoer3.txt';
    ...
    Fetched 0 row(s) in 0.08s
    [quickstart.cloudera:21000] > 
    

    In Impala, a file is indicated as an external file that provides the data for the table. In Hive, a similar exercise is possible, see:

    [cloudera@quickstart ~]$ hive
    
    Logging initialized using configuration in jar:file:/usr/lib/hive/lib/hive-common-1.1.0-cdh5.4.0.jar!/hive-log4j.properties
    WARNING: Hive CLI is deprecated and migration to Beeline is recommended.
    hive> CREATE EXTERNAL TABLE invoer3
        > (
        >    id INT,
        >    naam STRING
        > )
        > ROW FORMAT DELIMITED FIELDS TERMINATED BY ','
        > LOCATION '/user/cloudera/invoer';
    OK
    Time taken: 0.772 seconds
    hive> 
    

    However, in that case, a directory is used to indicate where the data come from.

    A slightly differnt way is to use the load command that loads data directly into a Hive default database. Let us assume, we have on Linux a file that is called invoer4.txt and which reads:

    [cloudera@quickstart ~]$ cat invoer4.txt
    2	tom
    3	ine
    [cloudera@quickstart ~]$ 
    

    .

    This file can be loaded into a Hive database in two steps:
    Step1: start Hive and create a table.
    Step2: load the data into the Hive table.

    hive> create table invoer4(k string, v string)row format delimited fields terminated by '\t'  stored as textfile;
    OK
    Time taken: 0.785 seconds
    hive> load data local inpath '/home/cloudera/invoer4.txt'  into table invoer4;
    Loading data to table default.invoer4
    Table default.invoer4 stats: [numFiles=1, totalSize=12]
    OK
    Time taken: 0.603 seconds
    

    In that case, the data are stored in a table – not as an external file as above.
    This can be assessed if we see on the hdfs platform a file like: /user/hive/warehouse/invoer4/invoer4.txt. This is a copy that results from load command as given by hive.

    As the data are now defined in Hive/ Impala, it is possible to access these data with a client that has a Hive connector. An example is the Oracle SQL Developer, that has a Hive connector. Once installed, one may access this file, see:
    Untitled
    In this case, I used ordinary SQL to access the table and to fetch the records.

    I realise, I use Hive and Impala as synonymns to each other, where they are in reality two different tools. Hive uses the map reduce logic to derive the results, while Impala is able to circumvent this bottleneck by their own deamons. As a result, Impala returns the results faster than Hive. Impala has been designed from its start as a better and faster tool than Hive. Hive (like Pig) is build on Map Reduce. Impala is completely new and is not built on Map Reduce. More information can be found in a wonderful article from Cloudera on Hive and Impala.

  • transpose a record in Oracle

    Transpose a record in Oracle isn’t easy. I had a small table with several records and one value in a record. I wanted to transpose that table into one record with the values adjacent to each other. The question: how to accomplish this? Recently, Oracle introduced the pivot facility that allowed this procedure. The code to undertake is as follows:

    select * from
        (select peri_omsch, 
            ROW_NUMBER ()  
            over (PARTITION BY een order by peri_omsch) as rn 
            from (select distinct '1' as een, peri_omsch from salesall order by peri_omsch))
           pivot
            (
              min(peri_omsch)
              for rn in (1 as a1,2 as a2,3 as a3,4 as a4,5 as a5,6 as a6,7 as a7,8 as a8,9 as a9,10 as a10,11 as a11,12 as a12)
            );
    

    Let us start with this table:
    Untitled
    The sql fetches the values from the original table (peri_omsch) and it adds an additional field that contains the row number. The code to add that additional field uses a ranking function where the whole table is seen as one set with a fixed value (‘een’) as an identifier for the set. Upon this set a rownumber is added.
    We get

    Untitled

    I use this rownumber to create the columns. Each value of the rownumber (1, 2, 3 etc ) is translated into a column. Hereby 1 is translated into column a1, 2 is translated into column a2 etc. I store the peri_omsch in this column. To enforce a unique value, I used the min function, which enforces one unique value to be stored.
    The final result looks like:
    Untitled

  • SQL Loader

    The SQL Loader is a facility that allows you to load data files blazingly fast. It is able to do as data files are directly written to disk without any overhead.
    It needs two files: a control file and a data file. The process generates a log file, that provides information on whether process has succeeded or not. It also generates a file on records that could not be loaded and a file that indicates whether some files could not be used.
    The sql loader is invoked at terminal level by a command that given on the server. It may look like:

    SQLLDR CONTROL=C:\Users\Administrator\Dropbox\Uitwisseling\gg_DATA_TABLE.ctl, LOG=sample.log, BAD=baz.bad, DATA=C:\Users\Administrator\Dropbox\Uitwisseling\gg_DATA_TABLE.ldr USERID=scott/binvegni, ERRORS=999, LOAD=500000, DISCARD=toss.dsc, DISCARDMAX=5
    

    In this command, ome may distinguish the control file that ends on .ctl. Likewise the data file can de seen as ending on .ldr. Another feature is the limit on the number of records. Setting this number at a low level, invokes only a low number of records being loaded.
    Luckily for us, the common Oracle clients, like SQL Developer and TOAD are able to generate these files automatically. Hence the files are generated and only some trivial actions must be undertaken such as copying the files in the correct location (accessible from teh server) and aboven SQL Loader script should be adjusted in accordance with the directory- and file names.
    Playing with this facility showed me that varchar fields were easy to load, but with both numerical fields and date files one may easily run into issues as the layout between different instances might be different. For me, it took quite some time to adjust the scripts as to have date fields and numeric fields being loaded without issues. I then discovered the value of the log file. Allthough exact reason for a rejected record was difficult to detect, it gave ample information on the records that were rejected and the fields that started the rejection.

    Just as an example, let me add the final code:

    OPTIONS (SKIP=1)
    LOAD DATA 
    TRUNCATE
    INTO TABLE "SCOTT"."ONLINEFORECAST"
    FIELDS TERMINATED BY'|'
    OPTIONALLY ENCLOSED BY '"' AND '"'
    TRAILING NULLCOLS ( 
    "NASA_NUM" ,
    "DATUM" DATE "DD-MM-YY" ,
    "SUM_CE_AANTAL" ,
    "AANTAL_ORDERS" ,
    "AANTAL_MET_ACTIE_IND" "to_number(:AANTAL_MET_ACTIE_IND,'99999.99')" )
    

    To finalise, another SQL Loader job I recently created:
    ctl – Copy

  • Calculate distances in Oracle

    Oracle allows you to calculate a distance between two points. Such calculation is not trivial as one must take into account that distances are calculated over the globe and the points are indicated on a longitude – latitude base. If we calculate the distance between longitude, latitude =(0,0) and (1,1), one has about 156 kilometers. In that case, we are calculating a distance between two points in the Atlantic Ocean, somewhere along the coast of Ghana. However, if we calculate the distance between one degree longitude and and one degree latitude on the North Pole, we only have 111 kilometers.
    Oracle allows you to calculate such distances. The code to do so is given below as an example:

    SELECT sdo_geom.sdo_distance(sdo_geom.sdo_geometry(2001, 8307, sdo_geom.sdo_point_type(4.7172715,52.030588, NULL), NULL, NULL),
                               sdo_geom.sdo_geometry(2001, 8307, sdo_point_type(-0.1223527,51.49065, NULL), NULL, NULL), 0.0001, 'unit=KM') distance_in_km
                               from DUAL;
    

    The points are given as:
    sdo_geom.sdo_geometry([gridtype], [points in latitude, longitude], sdo_geom.sdo_point_type([latitude][longitude], NULL), NULL, NULL).
    The function to calculate distance is given as sdo_geom.sdo_distance(point A, point B, 0,0001,’unit=[KM]’).

    It is also possible to store these points in a database. Oracle has a sdo_geometry type that allows to store point on a latitude, longitude base. An example:

    CREATE TABLE stores (
      plek_id NUMBER,
      description VARCHAR2(100),
      store_geo_location SDO_GEOMETRY);
    INSERT INTO stores VALUES
      (1,'Tom Gouda',
       SDO_GEOMETRY(2001, 8307, 
         SDO_POINT_TYPE (4.7172715,52.030588,NULL),NULL,NULL));
    INSERT INTO stores VALUES
      (2,'Tom Londen', 
       SDO_GEOMETRY(2001, 8307, 
         SDO_POINT_TYPE (-0.1223527,51.49065,NULL),NULL,NULL));
     

    A table store is defined with a field store_geo_location. Its field type is SDO_GEOMETRY. Values must be added as SDO_GEOMETRY(,,SDO_POINT_TYPE(,,),,,).
    The distance can then be calculated as:

    SELECT a.description,b.description,SDO_GEOM.SDO_DISTANCE(a.store_geo_location, b.store_geo_location, 0.0001, 'unit=KM') as dist_in_KM
       FROM stores a, stores b
       where a.plek_id>b.plek_id;
    

    This query showed a direct fly distance of 339 kilometers between Tom_Gouda and Tom_London.

    A final word.
    The question is where such latitude, longitude data can be found. As always, google is the master. If a certain point in google maps is found, the latitude, longitude can be found in the URL. One sees several such pairs in the URL, corresponding to different points on the map. However if one zooms in, the pairs do not deviate as the map only covers a small area. The first pair can be read, directly after the @ sign. For example, my home can be found as having this URL:https://www.google.nl/maps/place/Waterlelie+60,+2804+PW+Gouda/@52.0306982,4.717726. After the @, the longitude and latitude are displayed.

  • Transpose in Oracle

    Transposing data means changing data from a row into a column. Starting from version 11, this is possible in Oracle as well. It is possible to translate some values that appear in rows into columns. Doing so, a new table can be created that has an additional set of columns with column names being derived from row values. An example might clarify this:

    create table ff
    as
    select * from (
       select 
       times_purchased as "Puchase Frequency", 
       state_code
       from customers t
    )
    pivot 
    (
       count(state_code)
       for state_code in ('NY' as "New York",'CT' "Connecticut",'NJ' "New Jersey",'FL' "Florida",'MO' as "Missouri")
    )
    order by 1
    

    In this examples a table (ff) is created. It is created from another table, customers. From that table two columns are retrieved: a field “times_purchased” and a field “state_code”. The latter field is translated into columns. The state_code is translated into five columns: New York, Connecticut etc. Whenever a value ‘NY’ is encountered, the column ‘New York’ is updated.
    The update is defined under the key word “pivot”. Whenever a set of values in encountered, that is entered in another set, the count is incremented by 1; otherwise it is started at 1.

    Let us look at the customer table. It looks like:

    "STATE_CODE"	"TIMES_PURCHASED"
    "NY"	100
    "NY"	150
    "NY"	100
    "NY"	75
    "CT"	75
    

    Here, the state code values will be used to create columns. We will have a New York column and a Connecticut column.
    Every record will generate an update. In principle the update will be according to a count: an increment by one if the row already exists, otherwise a 1. The first record will generate a record having 100 as times_purchased value and 1 in the Nuew York column. The second record will generate a record having 150 in the times_purchased and 1 in the New York column. Th third record will update the first record (100,1,0) to (100,2,0). The fourth record will generate another record. The fifth record will update an existing record from (75,1,0) to (75,1,1). The end result is:

    "Puchase Frequency"	"New York"	"Connecticut"	
    75      1       1	
    100     2       0	
    150     1       0