18 Temmuz 2016 Pazartesi

How can it be possible that HTTP is stateless, although HTTP uses TCP protocol?

- TCP is connection-oriented, stateful and reliable.
- UDP is connectionless, stateless and unreliable.
- HTTP uses most commonly TCP protocol.

By taking information above into consideration, how can it be possible that HTTP is stateless?

* HTTP does not inherit from TCP or any other lower-level protocols used to transport itself. Using one of these protocols in transport layer doesn’t mean that HTTP becomes stateful automatically or is required to be stateful [1].

HTTP will work the same without considering a transport technology such TCP, SCTP or another protocol over HTTP;

- HTTP provides a stateful connection by using TCP, but then it makes this connection disconnect. Later on, it can connect again, if it is needed. Many different connections are created while a user browses a web-site. These connections are surely stateful, but the whole, I mean the conversation, is not, because each connection in the conversation is started and ended in a way of being independent of any other connection [2].

There is good example here about what I tell above;

" Consider the phone service to be TCP and consider your relationship with distant family members to be HTTP. You will contact them with the phone service. Each call to them would be a stateful TCP connection. However, you don't constantly stay on the phone with them, as you will disconnect and call them back again at a later time. You would certainly expect them to remember what you talked about on the last call. HTTP in itself does not do that, but it is rather a function of the web server that maintains the state of the overall conversation." [3]

If you have a popular server that has a million hits per day, management of these hits is very important in this sense. Each hit consists of a quick connect and disconnect. However, if each user open a connection in your web-site, then it could potentially overwhelm your server.

As a result, HTTP itself is stateless without considering its transport technology. It means that applications have to implement another layer on top of HTTP to establish state. Session cookies are typically used for this reason [1].

References:
  1. http://superuser.com/a/825372
  2. http://whatis.techtarget.com/definition/stateless
  3. http://fixunix.com/tcp-ip/66544-tcp-stateful-protocol-then-why-not-http.html#post214883

18 Mayıs 2016 Çarşamba

Caused by: java.io.NotSerializableException: bean.Example

NotSerializableException is common exception type on run-time of Java web applications when Tomcat server restarts. This is due to Tomcat's default behavior of serializing all the sessions and after restart trying to deserialize them. This is the persistance feature of Tomcat server.

Caused by: java.io.NotSerializableException: bean.Example

1) In the exception above, "bean.example" is fully qualified name of class that does not implement the Serializableinterface while it is been expected by the code behind. To fix it:

package bean;

import java.io.Serializable;

public class Example implements Serializable {
   private static final long serialVersionUID = 1L;
  private DeviceManager deviceManager = new DeviceManager();
// ... }
There is another important thing that Tomcat persists sessions and all objects in each session. Hence, if there is a variable that is used to keep instance of another classses, they also should be implemented with the Serializableinterface.

2) Sometimes, finding the class that throws the exception and making it implement theSerializableinterface may not be feasible when the class belongs to a third-party library. Objects that are created from this kind of class should not be serialized, but these objects can be declared as transient. Once a field of a class is declared as transient, then, it is ignored by the serializable runtime.


package bean;

import java.io.Serializable;
import com.google.gson.*;
public class Example implements Serializable { private static final long serialVersionUID = 1L;
  private transient Object deviceInformation = null;
// ... }
3) Another solution to get rid of NotSerializableException may be disabling session persistence in Tomcat server. To disable it, find tomcat_dir/conf/context.xml and find a place where it says:

<!-- Uncomment this to disable session persistence across Tomcat restarts -->

* This solution is valid for both Tomcat 6 and Tomcat 7.
References:
  1. http://stackoverflow.com/a/11692208/1194553
  2. https://mihail.stoynov.com/2011/04/11/disable-session-persistence-in-tomcat/
  3. https://examples.javacodegeeks.com/java-basics/exceptions/java-io-notserializableexception-how-to-solve-not-serializable-exception/
  4. http://stackoverflow.com/a/1904705/1194553

22 Mart 2016 Salı

How to run Java console application as a Windows service?

I needed to run Java console application as a Windows service. When I googling, I found out two solution such as;

1) Java service wrapper such as Tanuki and YAJSW. It provides reaching the solution in a direct way. However, configuration in wrapping process is more difficult than the second solution.

2) It is a little long, but easy way. Instruction of second solution is indicated below;

  • Export Java console application project as a jar file. I used Eclipse as Java code editor that's why I made it easily.
  • Download Launch4j and convert the jar file to exe file. This program has user-friendly UI. Also, the tutorial video can be reached through this link.
  • Download NSSM - the Non-Sucking Service Manager and install the exe file as a Windows service. This link shows how to do it. Configuration is very easy, because of its GUI (Figure-1).

I use the second solution and the console application works properly as a Windows service in my computer.

11 Şubat 2016 Perşembe

Rebuild .apk file of Android project on Eclipse without run

For Mac: Eclipse -> Preferences
For Windows: Windows -> Preferences
then, Preferences -> Android -> Build.
Uncheck "Skip packaging and dexing until export or launch. (Speeds up automatic builds on file save.)"
Lastly, restart Eclipse. You will realize that when you change something on your code and save it, .apk file of your project will be updated corresponding your changes on your code.

17 Aralık 2015 Perşembe

SSL/TLS based communication between Mosquitto Broker and Mqtt Java Client

I see that there is not so many source to provide SSL/TLS based communication between Mosquitto broker and Mqtt client on Windows. I have gained some experinces about it while developing Mqtt java client. I'll share main points of them;

:. MQTT provides username/password authentication as part of the protocol. Use 'password_file' option on mosquitto.conf to define usernames/passwords. Be sure to use network encryption if you are using this option otherwise the username and password will be vulnerable to interception (1).

.: As a network encryption, SSL/TLS feature of Mosquitto should be used. There are two encryption models in Mosquitto; certificate based encryption and pre-shared key based encryption.

a) I used certificate based encryption with username/password authentication. First, I created username/password from command prompt by using mosquitto_passwd(2);
mosquitto_passwd -c /demo username
b) To create certificates,  I downloaded OpenSSL v1.0.2e (If Visual C++ 2008 Redistributables is not installed already, it should be downloaded and setup initially). I set some environment variables before I start OpenSSL; 
set RANDFILE=c:\demo\.rnd
set OPENSSL_CONF=C:\OpenSSL-Win32\bin\openssl.cfg
c) I started OpenSSL by running start "openssl.exe" in directory of OpenSSL. Then, I created certificates by using OpenSSL. I followed instructions on (3)The root CA certificate (ca.crt) was created initially.


Related certificate information is shown above. I also entered "trialca" as PEM password for ca.crt. Then, I created server.key, server.csr and server crt;


client.key and client.crt was created like server.key and server.crt.

d) I made some configuration on mosquitto conf;
# Default listener;
listener 1883 127.0.0.1

# Certificate based SSL/TLS support(for default listener);
require_certificate false
use_identity_as_username false

# Extra listeners;
listener 8883

# Certificate based SSL/TLS support(for extra listeners);
cafile /demo/ca.crt
certfile /demo/server.crt
keyfile /server.key
require_certificate true
use_identity_as_username false

# Security;
allow_anonymous false

# Default authentication and topic access control
password_file /demo/mosquitto_passFile 
(username and password is added by using mosquitto_passwd)
e) I loaded mosquitto.conf from command prompt on Mosquitto server running on PC. 
c:\Program Files (x86)\mosquitto> mosquitto -c mosquitto.conf
f) To run these new configuration on Mosquitto, Mosquitto-service should be restarted from 'Services' on Windows.

Note: I had entered "trialsrv" as a password for server.key, but while Mosquitto was made restarted, it could not be started. It threw an error. About this problem, I wrote an question on stackoverflow.com (4) . I used the recommendation in this link and removed password for server.key. Then, I saw that Mosquitto could be restarted properly!

**  Configuration of Mosquitto broker was finished!

g)  For the client's side, first, I added ca.crt, client.key and client.crt in Mqtt Java client project.that is already developed by using Eclipse MQTT Paho Project (5). My client project is a kind of web application (used JSF framework), that's why I added certificates under the folder - WebContent/resources/certificates/.

h) Then, I googled for some Mqtt SSL/TLS java codes to give me an idea about how to bind my project with the broker. I found Sharonbn's SslUtil java class(6) and a new version of Sharonbn's class by Rohanag12(7). I used Rohanag12 solution, because it was newer and compatible with Mqtt and related other libraries.

i) I included path of certificates, that were added in the project in (g), in my codes. 
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
conOpt.setSocketFactory(SslUtil.getSocketFactory(servletContext.getRealPath("/resources/certificates/ca.crt"), servletContext.getRealPath("/resources/certificates/client.crt"), servletContext.getRealPath("/resources/certificates/client.key"), "trialclt"));

Eureka! Setup of SSL/TLS based authentication and messaging is made successfully. 

Note: Be careful! Firewall of antivirus programs and Windows firewall may prevent communication between Mosquitto broker and Mqtt java client.

References: 
1) https://eclipse.org/mosquitto/man/mosquitto-conf-5.php/
2) https://eclipse.org/mosquitto/man/mosquitto_passwd-1.php/
3) https://eclipse.org/mosquitto/man/mosquitto-tls-7.php/
4) http://stackoverflow.com/questions/34226717/how-to-provide-ssl-tls-based-communication-on-mosquitto/
5) https://www.eclipse.org/paho/
6) https://gist.github.com/sharonbn/4104301/
7) https://gist.github.com/rohanag12/07ab7eb22556244e9698/
8) http://blog.didierstevens.com/2015/03/30/howto-make-your-own-cert-with-openssl-on-windows/

11 Kasım 2015 Çarşamba

How to create standalone executable file of Windows Forms Application project?

When you build a Windows Forms Application project, a single executable file and some other related files to be needed for the application are created in debug or release folder in the project directory. When you copy this executable file outside of the folder(debug/release) and run, you see that it does not work properly.

If you want to use a single executable file while running Windows Forms Application, all images and .dll files used in the application should be embedded into this executable file;

1) Images should be added into Resources;

2) Images should be configured as embedded resource in build action of properties of related image file;
3) .dll files should be added into Resources;
4) Some code should be added into Test.cs that contains Test.Designer.cs or any related C# file;
public Test()
{
    AppDomain.CurrentDomain.AssemblyResolve +=new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}

private System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    string dllName = args.Name.Contains(',') ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll","");

    dllName = dllName.Replace(".", "_");

    if (dllName.EndsWith("_resources")) return null;

    System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + ".Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());

    byte[] bytes = (byte[])rm.GetObject(dllName);

    return System.Reflection.Assembly.Load(bytes);
}
5) Build your project! Executable file of your project is ready to be used independently. You can copy/paste and run it anywhere else. Well done!

References: 
* http://codeblog.larsholm.net/2011/06/embed-dlls-easily-in-a-net-assembly/

2 Ekim 2015 Cuma

What is "Event Bubbling" in JS?

When an event is occured, this event reaches root of DOM tree.

For example, imagine that there are two DOM element that has click events. If child element is clicked, then event of parent element is also fired.

To prevent this, use properties or methods of event object of child element.

* Here is process that shows an element during event bubbling;
--------------------------------------------------------------------------
 $("p").click( function(event) {
      alert ( event.currentTarget === this ); // returns true!
 });
--------------------------------------------------------------------------

* The code below prevents "Event Bubbling” that is defined above.
It keeps the event happened in child element out of parent elements.
--------------------------------------------------------------------------
$("p").click( function(event) {
     event.stopPropagation();
     // Do smth.
});
--------------------------------------------------------------------------

References: 
1) http://ulviercan.com/teknoblog/jquery/jquery-ve-olaylar-events/
2) http://www.kazimsoylu.com/javascript/event-bubbling-javascript.html
3) http://javascript.info/tutorial/bubbling-and-capturing