[code snippet] How to cast types without warnings?

When we want to convert one type to another we usually cast it using round brackets:

 Object result = calculateResults();
 Foo foo = (Foo)result;
 // ...

This will cause IntelliJ to show Warning about casting. We could help it by adding condition with instanceof operator:

if (result instanceof Foo) {
   Foo foo = (Foo)result;
   // ...
}

Another way of casting can be done using cast() method:

Foo foo = Foo.class.cast(result);

And thisĀ  an be combined with isInstance() method:

if (Foo.class.isInstance(result)) {
   Foo foo = Foo.class.cast(result);
   //...
}

How to add <base> element to page header in ZK Framework

Sometimes it is useful to create <base> tag in a page header. This is easy when you have access to html files. It’s not so simple when you are on ZK Framework. This short snippet shows it should be done in a ZUL file:

<zk>
<zscript><![CDATA[ page.addBeforeHeadTags("<base href=\"http://localhost:8080/your-webapp/\" />"); ]]></zscript>
<!-- your zk elements -->
</zk>

[MongoDB] How to add a field to a subdocument of every document in a collection?

Let’s say that a collection named items:

{
    "_id" : "a",
    "authorization" : {
        "group1" : "lrw",
        "group2" : "lr-"
    }
},
{
    "_id" : "b",
    "authorization" : {
        "group1" : "lrw",
        "group2" : "lr-"
    }
},
{
    "_id" : "c",
    "authorization" : {
        "group1" : "lrw",
        "group2" : "lr-"
    }
}

Now I would like to add a field to every “authorization”. The field may look like this:

{ "group3" : "lrw" }

Here’s the query that does that:

db.items.find({}).forEach(item => {
    db.items.update(
        { _id: item._id },
        { $set: { "authorization.group3": "lrw" } }
    )    
});

How to mount a directory from QNAP NAS drive on Ubuntu

We will be exposing one of the directories originally created on NFS network drive – in my case it was called Multimedia.

Login with to your QNAP drive as root. This is the machine working as a host.
Edit /etc/exports file. It should contain the following content:

"/share/Multimedia" *(rw,async,no_subtree_check,insecure,no_root_squash) 

Run the following command:

exportfs -ra

It should recreate the exported file systems according to /etc/exports file.

Now, login to your Linux machine and run the following commands:
The following step might be not necessary:

sudo apt-get install portmap nfs-common

Create the mounting point directory:

mdkir -p /media/qnap

And finally mount the NFS directory:

sudo mount [ip_of_the_qnap_server]:/share/CACHEDEV1_DATA/Multimedia /media/qnap

git status shows that files are modified but.. they are not!

This can be a real pain. You are working on git repo to which many developers with different OS (and with different line endings) contribute.
So, you have such a repo and at some time you may notice that some files which are marked as if they had been modified. You try to git checkout, reset, clean, but nothing helps…
It happens because of the wrong interpretation of line ending characters. This case is described here and here.
But actually the command suggested there did not help in my last case (and I lost more than two hours). Eventually, the following command solved the issue:

git config core.filemode false

Web components & Polymer how-to

How to invoke method from outside of a Polymer component when you’re in in a *.zul file from ZK Framework?

Polymer Element:

<script src="https://www.polymer-project.org/components/webcomponentsjs/webcomponents.js"></script>
<link rel="import" href="https://www.polymer-project.org/components/polymer/polymer.html">
<dom-module id="my-component">
	<template></template>
	<script>
		Polymer({
			is: "my-component",
			alert: function() { alert("alert!"); }
		});
	</script>
</dom-module>

Sample usage:

<zk xmlns:n="native" xmlns:w="client">
	<n:my-component id="myComponent"></n:my-component>
	<button id="someButton" w:onClick="document.querySelector('#myComponent').alert()">Click Me</button>
</zk> 

How to attach event listener to custom Polymer component and propagate event to server side using zAu?

The event is fired inside of a Polymer element using fire() method:

     this.fire('close-finish', "more detailed data", { bubbles: false });		

Native JavaScript below adds a new event listener to the component. Event handler executes zAu engine command to forward the event to the server.

    <n:script xmlns:n="native">
        document.querySelector('my-component').addEventListener('close-finish',
        function() {
        zAu.send(new zk.Event(zk.Widget.$('$cancelButton'), 'onClick', 'finish', {toServer:true}));
        });
    </n:script>

UncheckedIOException

One of the small things introduced in Java 8 is unchecked java.io.UncheckedIOException. It can replace the standard checked exception java.io.IOException. As you may have already guessed, it was introduced because of the Streaming API.

Some handy code for JVM8

How to map with casting in Java8

Original code:

Stream.of(objects)
 .filter(c -> c instanceof Client)
 .map(c -> (Client) c)
 .map(Client::getID)
 .forEach(System.out::println);

Better one:

Stream.of(objects)
 .filter(Client.class::isInstance)
 .map(Client.class::cast)
 .map(Client::getID)
 .forEach(System.out::println);

How to convert an array to Stream?

Stream<String> str = Arrays.stream(array);
 str.forEach(x -> System.out.println(x));

How to find duplicates in a list?

The following snippet will filter out null values from the given list and then leave only those elements which are duplicated:

List<String> list = 
 Lists.newArrayList("aa", "bb", "cc", null, "aa", "bb", "aa", null, null);
 list.stream()
  .filter(Objects::nonNull)
  .filter(tag -> Collections.frequency(list, tag) > 1)
  .collect(Collectors.toSet())
  .forEach(System.out::println);

The results of the above code is aa, bb.

Cheap ONVIF camera hacking

Recently I’ve bought some cheap IP CCTV cameras. This post tries to summarize what ports are available on such devices as the docs on the internet are really weak:

  • standard telnet port – you can login as root with password xmhdipc. Yes, the password seems to be the same on all devices
  • 8899 – ONVIF W/S protocol
    <SOAP-ENV:Envelope>
    <SOAP-ENV:Body>
    <SOAP-ENV:Fault>
    <faultcode>SOAP-ENV:Client</faultcode>
    <faultstring>HTTP GET method not implemented</faultstring>
    </SOAP-ENV:Fault>
    </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
    
  • 34567 – what is it
  • 554 – is supposed to be RTSP protocol

However, the tested device opens more ports, you can see them when you login to shell:

# netstat -a
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 0.0.0.0:34561           0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:8899            0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:34599           0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:34567           0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:554             0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:www             0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:9527            0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:telnet          0.0.0.0:*               LISTEN
tcp        0    139 192.168.1.11:telnet     192.168.1.29:33700      ESTABLISHED
tcp        0      0 192.168.1.11:8899       192.168.1.74:34803      ESTABLISHED
tcp        0      0 192.168.1.11:34567      192.168.1.29:26664      ESTABLISHED
tcp        0      0 192.168.1.11:9527       192.168.1.29:34079      ESTABLISHED

The port 9527 seemed interesting – here is what can be observed on that port:

1], s_NatRunStatus[2]OnNatProbe: 52.29.246.211 : 8000 
username:password:login(Host: 192.168.1.11:9527, ******, Console, address:)
user:Host: 192.168.1.11:9527 account invalid
User not valid!
user name:password:login(Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8, ******, Console, address:)
user:Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 account invalid
User not valid!
user name:password:login(Accept-Encoding: gzip, deflate, ******, Console, address:)
user:Accept-Encoding: gzip, deflate account invalid
User not valid!
user name:password:login(Connection: keep-alive, ******, Console, address:)
user:Connection: keep-alive account invalid
User not valid!
user name:password:OnNatProbe: run Status[1], s_NatRunStatus[2]OnNatProbe: 52.29.246.211 : 8000 
Transport: Client ID[3] ---> SetDeadFlag to 1
Transport: SetDeadFlag --->Enter  
Transport: SetDeadFlag --->Exit 
Transprot: New Client ID[3] ___!!!___
@@@FILE -> ../..//Source/TransportClient.cpp, LINE -> 399Transport: client connect error
@@@FILE -> ../..//Source/TransportClient.cpp, LINE -> 214Treansport: ConnectSocket Failed 
_______DAS   Connct  IP[192.168.1.67]    Port [9400]   Failed!______ 
OnNatProbe: run Status[1], s_NatRunStatus[2]OnNatProbe: 52.29.246.211 : 8000 
Transport: Client ID[3] ---> SetDeadFlag to 1
Transport: SetDeadFlag --->Enter  
Transport: SetDeadFlag --->Exit 
Transprot: New Client ID[3] ___!!!___

Do it online

Online programming editors/debuggers are getting popular. Here are the couple of them which I use from time to time:

  • IDEOne – a broad choice of programming languages (there is even BrainF**k, however, there is no XSLT)
  • jsFiddle – a nice IDE for JavaScript.
  • jsBin – another one for JavaScript
  • XSLTCake – useful IDE for XSLT. It is still ‘beta’, but it offers three types of XSLT processing (JavaScript, web service or .NET 4.0)
  • XML Playground – another cool IDE for XSL templates. Unfortunately it doesn’t support XSLT 2.0
  • Rubular – IDE for checking regular expression written in Ruby
  • XSLTTest – Small and neat application for XSLT. Supports XSLT 2.0.