Is there way to do it with programming? In theory, or may be is there some programming library written in java (perfect variant)?
The simple answer is yes. Applying the rules of music theory, you can certainly program something to do this.
The problem is that not all music follows conventional patterns and there is sometimes debate over if a voicing is actually one chord or another. This could change the key of the song and affect the way your program interprets the music. The amount of exception logic required to do this would suck. You basically need to programmatically identify the tonic and work from there. It would not be easy to do for sure.
Is it possible, certainly. Does it already exist, I haven't seen a library that can do it. Is it worth it, probably not. Most people interested would rather do the analysis themselves anyway.
I studied classical guitar at university for 2 years before withdrawing and completing my studies in computer science. I have contemplated making a program/library like this, but as I said, the people who would actually use this info, actually enjoy analyzing the music.
Unfortunately, even when a song has a clear tonal centre and could be usefully described as being 'in the key of x' it very likely won't confine itself to the diatonic notes and chords of that key. A key-detection program would need a long list of special cases and exceptions.
For instance. This is indisputedly in D major. Despite the C#7 chords and Fnat notes.
And this is firmly in A major.
Yes, there are ways to algorithmically detect the tonality from MIDI notes, and the algorithms seem to work surprisingly well. If you can use Python, there's a library called "music21" that's easily available and very easy to use. If Python is a no-go, there are implementations for other languages, or you could even try rolling your own.
Look at the answers to this question: https://stackoverflow.com/questions/14734644/is-there-an-algorithm-to-get-the-scale-and-key-of-a-song-from-a-series-of-notes
The best-working algorithm in my very short testing of about five songs with the music21 library was "Krumhansl", which I think is the Krumhansl-Schmuckler algorithm. http://rnhart.net/articles/key-finding/
However, it might be worth knowing that many songs don't stay in one single tonality all the way from beginning to end. You could try splitting the song to shorter segments to see if they're detected as being in different keys. Or perhaps you could do a "sliding window" approach to see if there are modulations. Here are some powerpoint slides found on the web, "Visualizing Harmony" by Craig Stuart Sapp https://ccrma.stanford.edu/~craig/papers/01/icmc01-harmony-6up.pdf
(sliding windows seem to be mentioned - so much for my clever idea)