Category: Link set

[Linkset] Authorization termination: OAuth reverse proxy

UPDATE Today was released Nginx Plus with a new nginx-openid-connect module.

If you are looking for Authentication Server or OAuth library then OpenID Conect implementations page is a good place to start. I chose Keycloak but also want to look on FreeIPA or https://ipsilon-project.org

Keycloak Security Proxy but I want proxy as Nginx module and I need to implement something non standard.
Also there is some an OpenID/Keycloak Proxy service https://github.com/gambol99/keycloak-proxy

For Apache web server everything is clear:
https://github.com/zmartzone/mod_auth_openidc

But I need something for Nginx .

lua-resty-openidc and it’s intro blog post written in Lua so its easier to extend (so I did for implementing of custom grant flow+ sessions + reference tokens).

https://github.com/tarachandverma/nginx-openidc written fully in C++ and this is interesting because you don’t need to enable Lua on Nginx (believe me, this can be harmful).

What is also interesting is tha module for only one purpose: to use reference tokens (opaque tokens)
https://github.com/curityio/nginx_phantom_token_module it’s written in C so no needs for additional deps.

Authentication Based on Subrequest Result

Actually Nginx already has something that can satisfy 80% of your needs:

https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-subrequest-authentication/

https://www.nginx.com/blog/nginx-plus-authenticate-users/
http://nginx.org/en/docs/http/ngx_http_auth_request_module.html

https://github.com/nginxinc/nginx-ldap-auth
https://redbyte.eu/en/blog/using-the-nginx-auth-request-module/
https://news.ycombinator.com/item?id=7641148

But to use the sebrequest auth your auth server should support this or you need to setup another shim proxy:
https://github.com/bitly/oauth2_proxy
and here is docker container which integrates it https://github.com/sinnerschrader/oauth-proxy-nginx

Or you can use this one which is written in Lua
https://github.com/jirutka/ngx-oauth

Bonus:
Important article from Security researcher Egor Homakov who hacked several times GitHub and Facebook:

OAuth1, OAuth2, OAuth…?

[Linkset] Payment System, Payment Gateway and Credit Card Icons

https://github.com/muffinresearch/payment-icons SVG logos in flat, mono,outline and usual variants. Has Verve credit card logo

https://github.com/gilbarbara/logos most bigest collection of logos of popular brands, not only payments systems. SVG. See their demo site https://svgporn.com/

https://github.com/simple-icons/simple-icons collection which has icons for some cryptocurrencies. SVG

https://github.com/orlandotm/payment-webfont payment system logos as font. WOFF format

https://github.com/hiqdev/payment-icons list of payment logos in different dimensions but PNG only

https://github.com/diogomachado/payments-svg SVG and has CSS sprite

https://github.com/gregoiresgt/payment-icons SVG PNG with many variants

https://github.com/goodybag/credit-card-logos
Flexible SVG credit card logo assets and CSS

https://github.com/codefoundries/material-ui-credit-card-icons Library with credit card icons for Material-UI

https://github.com/slaterjohn/payment-logos payment gateway and credit card logo icons. Available in 4 sizes. Has Bitcoin logo and Contactless Payment Logo

Как жить на Legacy проекте

Несколько хороших и обязательных к просмотру лекций про то как разрабатывать и сопровождать старые легаси проекты.
Кстати тут нужно сказать что legacy — это переводится не просто как «наследство» а как некий дар, например когда бабушка передаёт внучке кольцо. Авторы термина хотели заложить какое-то позитивное значение 🙂

На эту тему почти на всех конференциях рассказывает Виктор Полищук:

Примечательна также классификация которую Виктор использует:

What is…

  • Very old projects, had been written long long ago.
  • The Highlander: Old mature projects, had been written ages ago. Optimization required.
  • Paragon: Die Hard Nobody knows why it is still alive.
  • Fashion or market victims: Nobody wants this sh%t anymore.
  • Problem Child: Nobody loves it. Sentenced Customer tired of supporting it, everything is up to you.
  • Apathetic: Nobody cares

What is usually NOT…

  • Badly written projects which are not in production.
  • Low quality designed projects.
  • Small projects.
  • Every project you don’t understand.

legacy code - переписать это говно мамонта

Виктор Полищук — Все что вы хотели знать о Legacy-коде, но стеснялись спросить

Виктор Полищук — Legacy: как победить в гонке

И этот доклад вдохновил ребят из ДатаАрта сделать свой доклад:

И продолжение «Travel, Legacy and SWAT. Q&A Session»

Презентация Michael Feather, автора книги Работа с унаследованным кодом:

Дмитрий Миндра: Refactoring Legacy Сode

Virtual JUG: Testing and Refactoring Legacy Code

Сергей Немчинский — Как создаются и поддерживаются Enterprise.
Очень хороший доклад где раскрывается суть легаси проектов, как они возникают и какая у них специфика.

Статья Практика рефакторинга в больших проектах в сотый раз о вечном. Для тех кто ещё халтурит и не прочёл замечательную книгу Working Effectively with Legacy Code

Ну и несколько интересных статей на окололегасиную тематику:
* Что иметь в виду при переписывании программного обеспечения
* Читайте код, с остальным справится компилятор
* Рентабельный код
* Поиск и чтение унаследованного кода
* Large scale refactoring

Небольшой конспект с добавлениями моих мыслей.
1. На легаси проекте всегда есть несколько параллельных подходов и технологий. В разное время были попытки и не всегда законченные сделать что-то правильно не выкидывая старого. Например если у вас был старый API и вы решили сделать новый — то у вас есть новый АПИ но клиенты всё равно используют старый потому что в нём были фичи которые вы в новый переносить не будете или ещё не решили как его сделать правильно. Точно также если у вас был JSF и вы решили переписать на Spring MVC то теперь у вас половина кода на Спринге и половина на JSF.
На моём текущем проекте живут одновременно чисто сервлеты, чисто JSP, JSF, JSP + Tiles, немного Velocity, Spring 3.0.7 и мы даже не можем перейти на Спринг 3.1, куча контролеров на Tapestry 4 (к которому уже даже документации не найдёшь), и Tapestry 5.0 который по сути совсем другой фреймворк и мы не можем даже переписать на Tapestry 5.3, просто потому что уже никто его не знает.
Всё это живёт одновременно и активно используется. Всё находится в полупереходном состоянии потому что пока начали переписывать и делать новые ошибки, вдруг выяснилось что чего-то сделать на новом практически невозможно и вообще уже наделали новых ошибок что уже и переписывать так пожалуй не стоит. Всё это устарело и затраты на обновление больше чем на переписывания с ноля.
Из-за версионного просака обновится невозможно. И иногда нужно просто смириться что это останется таким навсегда (привет Кобол программистам).
2. На лагаси проекте очень многое можно просто выкинуть. Очень много нуждается в оптимизации. Но как понять что можно менять а что нет? Как найти проблему? Т.е. здесь на первый план выходит и самое принципиальное это знать как используется программа: вам нужен мониторинг, вам нужно сборка и визуализация логов (logstash+elastic+kibana), или статистика юзаджей, вам нужен доступ к базе на продакшене, вам нужен доступ ко всем конфигам а то и вовсе к серверам. Насколько только это возможно. Именно с этого и следует начинать первым делом.
Допустим ты ковыряешься в коде и видишь кучу проблем связанных с тем что у вас регистрозависимые (case sensitive) логины пользователей, т.е. User и user это два разных пользователя. Потому что дальше ваша система шлёт эти юзернеймы через АПИ в другую систему которая их не поддерживает. И ты должен иметь возможность прямо сейчас посмотреть в конфигах включена ли эта возможность, посмотреть в базе как много пользователей с дублицироваными юзернеймами. Нужно погрепать логи как много пользователей столкнулось с этими проблемами.
Нужно поискать по истории ревизий кода когда добавлялся этот функционал и зачем. Нужно расспросить всех коллег кто что-то знает про это.
Т.е. на легаси проекте для того чтобы сделать какое либо изменение порой требуется настоящее и полноценное исследование, расследование, с допросами и большой археологической работой по изучения пластов кода и поиском то ишью трекеру.
Какая нибудь заброшенная страничка на Вики тебя может реально выручить. Отсюда следует следующий пункт…
3. Всё что только можно нужно записывать и потом никогда не выбрасывать. Желательно любые обсуждения и митинги потом записывать хотя бы тезисно и рассылать по почте, и её, корпоративную почта нужно беречь и лелеять. Возможно даже вам следует хранить логи и бекапы бд баз хотя бы за год. «Чем больше бумаги тем чище жопа». И не бойтесь что создаёте мусор — археологи по мусорным кучам восстанавливают знание о целых эпохах цивилизаций.
Просто поймите — даже самые очевидные для вас вещи следует записывать потому что команда совершенно точно поменяется полностью. Это всё равно что представьте что послезавтра весь ваш код, всю вики, все письма, весь репозиторий просто передадут на разработку в другую компанию.
4. На Вики писать и перечитывать\переписывать\обновлять статьи это абсолютно обязательная работа ничуть не меньшая чем писать код. Тикеты в ишью трекере периодически нужно проходить и перечитывать. Реально очень многие проблемы, уж поверьте, давно известны и даже были попытки их исправить. Это нудное занятие вам сэкономит кучу времени. Но читать их следует только после того как вы уже хоть немного разобрались с проектом, иначе вы не поймёте о чём там вообще идёт речь.
Дело в том что на легаси проекте из-за большого числа джира тикетов по закону больших чисел вы практически наверняка там точно есть практически все баги и проблемы, и вы можете достаточно точно оценить ситуацию с разными компонентами системы.
В совокупности с письмами из сапорта и логами это даёт хорошую картину на весь проект. Это важная метрика которая вам поможет вам понять размер трагедии.
5. На любом легаси проекте почти наверняка есть огромные проблемы со сборкой проекта. Обычно она не тривиальная, требуется ANT и Maven конкретной версии, собирается проект почти наверняка только под шестую джаву, требуются ручные действия. Билд долгий, тесты blinking (то падают то нет) и очень много из низ вообще отключены через @Ignore. Есть самодельно пропатченные версии библиотек. И это вам очень сильно повезёт если проект мавенизирован и зависимости вообще известны и доступны с Maven Central репозитория.
Из-за того что у вас много либ (а их наверняка много) а у вас нет возможности дать каждой свой classpath, у вас точно есть куча проблем с конфликтующими или дублирующимися зависимостями.
И для успешной жизни на проекте вам следует опустится вот это вот болото Мавена и стабилизировать билд. Это второе по важности после логов и мониторинга и метрик что следует сделать.
6. Любой код без тестов автоматически становится легаси. Ваша задача любой ценой покрыть код тестами. На каждый баг — покрываете то место тестами. Вплоть до драконовского правила не принимать новый код без тестов хотя и без фанатизма. Да, вам придётся замокать пол мира, написать кучу фикстур и стабов, написать долгие интеграционные тесты которые пол базы загрузят, но без этого вообще никак. Когда создавалось множество легаси проектов тогда тестирование ещё не было принято как промышленная практика или фреймворки которые были тогда не очень были рассчитаны на то что их нужно будет как-то тестировать. Сами тестовые библиотеки и техники с тех пор прошли большой и мучительный путь, и в каждом фреймворке уже изначально идёт куча вспомогательных классов и стабов и документации о том как тестировать.
Поэтому на легаси проекте это совершенно нормальная практика когда функционал написанный\исправленный за час вы в три раза дольше покрываете тестами. Постепенно самое гадкое вы всё таки покроете тестами а ваша архитектура всё таки начнёт постепенно становится лучшей для тестирования. Это трудозатратный путь, но он оправдан и рано или поздно принесёт плоды, просто верьте.
7. Дальше нужно улучшить логирование — подчистить лог от огромных стектрейсов и пофиксить то что их продуцирует. Дописать логи везде где только нужно, все входящие и выходящие реквесты в АПИ тоже логировать. При этом нужно сделать так чтобы логирование имело смысл по максимуму. Также в логах у вас почти наверняка будет множество секьюрной информации: пароли пользователей и ключи от АПИ, номера кредитных карт или что нибудь ещё такое чего там не должно быть. Представьте что ваши логи взломали хакеры — вы должны максимально им усложнить жизнь.
8. Улучшить мониторинг — через JMX пробросить все важные метрики: количество активных сессий или реквестов. Повключать всякие опции JVM для мониторинга. Об этом Виталий Тимчишин рассказывал в клубе анонимных программистов презентация, видео (часть 1), видео (часть 2) но лучше новую инфу поискать, особенно про FlightRecorder.
9. Билд нужно ускорить и улучшить насколько это возможно. У вас должен быть самый лучший CI tool — TeamCity. Собираться в нём должно всё что только может быть собрано.
10. Вам нужно ввести версионирование БД и db migration tool — DBMaintain, FlywayDB, LiquiBase.
11. Грамотно разнести тесты как в Гугле поделить их по времени выполнения. Тут ключевой момент в том что если для TDD разработки ваш тест должен отрабатывать быстро (максимум 15 секунд) иначе она не приживётся. Сам билд в CI тоже нужно ускорить как только можно (запуск тестов в параллели, использовать in-memory file system).
12. У вас совершенно точно будут множество проблем с базой данных — конекшен пул будет забиваться, будет множество проблем с уровнем изоляции транзакций, запросы будут долго тупить, N + 1 проблемы, данные будут неконсистентными итд. Эти проблемы нужно чётко методично разруливать — обновить либу Tomcat JDBC Connection Pool, загнать всю работу с базой строго в рамки DAO, самые используемые и статические данные закешировать и сделать так чтобы кеш можно было сбросить через JMX или JavaMelody.
13. Саму базу тоже как правило следует подчистить и хорошенько нормализировать. Делать это нужно очень аккуратно и осознано и обязательно основываясь на реальной статистике. Для PostgreSQL есть утилита pg_stats. По ней можно определить как данные используются и сравнив с кодом можно понять свойства данных: как часто они изменяются, как часто они инсертятся или они read only. Где нужно натянуть индексы. Это очень принципиально потому что даёт нормальный прирост скорости и вообще от данных следует отталкиваться.
14. Дальше вам следует возвести китайскую стену между старым кодом и новым, как рассказывал Витя Полищук. У вас должно быть чёткое понимание что в этой части системы мы пытаемся создать островок удачи и везения, где всё прилично и правильно и после этого перетащить на этот остров весь функционал из плохого кода. Этот островок может быть совершенно отдельным модулем\микросервисом отделённым чётким API и интерфейсами. И жёстко следить за тем чтобы в нём был порядок.
У меня например на проекте например даже уволили сотрудника за то что он не стал переписывать старый функционал а за уши притянул его скопипастив код в островок удачи. Теперь нам оставшимся сцыкотно там гадить.
15. Всё что только можно резать на модули, модули выделять в микросервисы которые общаются по простому протоколу типа REST или JSON-RPC.
У вас наверняка есть часть системы и код который никогда уже не перепишешь и всё что можно с этим сделать — только выделить эту гангрену в отдельный модуль.
16. Memento mori — вам следует честно и сразу думать даже о новом функционале как о выброшенном позже и заранее думать о том как его убрать. Микросервисы как раз неплохо решают эту проблему.
17. Стоит максимально улучшить процесс деплоя — для начала достичь zero downtime но конечно в идеале вообще continuous deployment, но даже не мечтайте 🙂 Даже без zero downtime ваш цикл комит — старт сервера должен быть максимально маленьким. Суть в том что если вы начнёте что-то менять то вам придётся постоянно выкатывать хотфиксы которые фиксят баги после ваших фиксов багов. Если вы начнёте наводить порядок на легаси проекте, да даже просто что-то делать особо ничего не трогая, всё равно у вас будут всплывать проблемы и их нужно будет фикисть по горячему.
18. Если у вас есть внешний API то вам следует проксировать его через фасад где чётко вести статистику кто его дёргает и как. Далее если ваш АПИ будет меняться вам следует самим сделать SDK где вы его сами заимплементите. Всё таки это относительно редкость когда клиенты вашего АПИ используют что-то другое кроме PHP, Java или JavaScript, ну или что там у них. Поэтому вы можете сами написать или попросить клиентов поделится с вами их обвёртками над вашим АПИ и сделать его своим официальным. Далее вы можете менять и экспериментировать с АПИ при этом каждый раз выкатывать новую версию SDK. Т.е. это вам даёт дополнительный рычаг гибкости.
Кроме того попытаться заимплементить ваше собственное АПИ очень хорошо поможет вам понять как мучаются ваши клиенты и заметить частые ошибки.
19. После этого можете пробовать постепенно обновлять ваши библиотеки зависимостей на новые версии, тщательно и внимательно просматривая их чейнджлоги и ища всякие баги которые есть с этой версией. Реально в интернете вы уведите много релевантной информации. Первым делом обновлять следует тестовые библиотеки, особенно моки (EasyMock, Mockito) потому что они изменяют байткод. Проверить что тесты проходят как и ранее и не сломались.
Далее следует обновлять сами плагины Мавена — это тоже довольно опасная операция как оказалось на практике.
После этого утильные либы: Apache Commons Lang, Apache Commons Collections, Guava, JodaTime, Jackson, итп.
Потом можно попробовать проайпдейтить Quartz который в основном используется для джоб и другие либы типа Apache POI чья поломка для пользователей пройдёт почти незаметно.
Потом нужно проадейтить те либы которые делают инструментацию байткода и всякую магию: Hibernate и куча всего другого. Это самое злобное.
После этого можно пробовать перейти на новую джаву.
После перехода на новую джаву можно выкинуть JodaTime и JodaMoney и кучу другого хлама. И обновить остальные либы типа Спринга.

Продолжение следует

[LinkSet] Compatibility

Theoretical part

 

Articles from Oracle

http://JEP 223: New Version-String Scheme

 

Six kinds of compatibility

Each Joda-Time relase has descriptions of incompatible changes categorized by six kinds:

Compatibility between 2.8 and 2.9
———————————
Build system — Yes
Binary compatible — Yes
Source compatible — Yes
Serialization compatible — Yes
Data compatible — Yes
— DateTimeZone data updated to version 2015g
Semantic compatible — Yes

When binary compatibilities are broken then Majour Version changed. For example v2.0 changelist

Explanation from  Stephen Colebourne, author of Joda-Time:

Build system

Not part of compatibility, just a fact about the build system in use

Example:  in v2.2

 - Ant build removed. Build only on Maven now.

Also, I think, it may be changing in artifact coordinates: groupId, artifactId or even changed repository. Maybe some changes in manifest, for example required dependencies. Or added OSGI manifest info. Maybe some classes was repackaged. Or old artifact was built with ANT and doesn’t contains a Maven’s pom.xml manifest like horrible Xerex library  and then was mavenized.

It also may be recompilation with optimizations or without debug information.

But I think that changing in packaging may be a separate kind of compatibility change.

Binary compatible and Source compatible

Whether the whole API is binary compatible or source compatible. See this document

Serialization compatible

Whether the serialization format is compatible with the previous version.

Data compatible

Whether the data, time-zone data in this case, has changed.

For example: some time zone was changed or even removed. If your database stores old timezone id and application trying to create a date object with this timezone id you’ll get an exception.

Semantic compatible

Whether there is some other semantic change. This is relevant when the classes and methods have not changed, but the meaning of a method has.

See section Serialization incompitables below

For example:  v2.0 has a lot of semantic changes

Previously, DateTimeZone.forID matched time zone names case-insensitively, now it is case-sensitive

I think it always hard to separate semantic changes when dealing with bugs. For example, JDK has bug when using null as key in Map

And that was a question is this a bug or feature.

Another one example, is Apache Commons Lang library. In version 3 the methods StringUtils.isAlpha(), isNumeric() and isAlphanumeric() now all return false when passed an empty String. Previously they returned true.

Semantic looks like correlated with behavior compatibility. When changed not signatures but they flow or contract.

Also it’s often situation when behavior was just undefined by contract. For example old class Vector doesn’t declare behavior about removing elements during iteration.  That’s why was created new class ArrayList and Vector was accepted as Superseded.
So, deprecation, as any changes in contract may be also some kind of semantic change.

 

Serialization incompitables

Compatible incopatibility

Also I think that it should be some kind of «reverse compatibility» that means a contract usage. For example, I saw an issue when subclass of HashMap doesn’t follow a contract. This change was compatible in all ways but all clients become incompatible. How to predict it, I don’t know.

Each of developer has experience when you can’t change something in your API because there is some clients that abuse it or implemented incorrectly. So it should have it’s own classification and developers should think about this kind of reverse incompatibility.

Complexity compatibility

I mean the complexity of program in wide sense: algorithm speed, it’s derivate and consumption of resources (memory, i/o, CPU, disk space), and even source code beautification and structural changes like refactoring. You know,  some algorithms may use more memory but use low processor.

For example, in some early versions of 64 bit JDK your application may fail with OutOfMemory error. This was change absolutely compatible in all categories mentioned before.

Another one sample is when new version of program is working more slowly than previous.

It may not change a contract and flow or anything else may it’s also may be changes that requires an attention.

 

Tool for checking API and BPI

Service provider interface (SPI)

https://stackoverflow.com/questions/2954372/difference-between-spi-and-api
https://en.wikipedia.org/wiki/Service_provider_interface

Also interesting

JAR Hell

[LinkSet] Dependency duplicates in Maven and Jar Hell with Java Classloader

Theoretical part:
Java Classloader

Maven: Introduction to the Dependency Mechanism

What is JAR hell? (Or is it classpath hell? Or dependency hell?)

Jar Hell made Easy — Demystifying the classpath with jHades
See JHades documentation, it very useful to find overlapping jars.

Another tool for dealing with Jar Hell is Weblogic Classloader Analysis Tool.

One of the most problematic dependency is Xeres Xerces Hell. It’s a good example how not to do library.

This presentation is a great resource about Jar Hell and the different type of classpath related exceptions:

But little bit boring.

Maven Dependency Wrangling

dealing with dependency chain issues in maven

Maven Enforcer plugin has extra rule
Ban Duplicate Classes
Also it should be very useful if you have legacy project that still runs under Java 6 or 7 you should avoid dependencies compiled with never Java 8.
You can use enforceBytecodeVersion

Please also make sure that you also specified requireJavaVersion (to compile), requireUpperBoundDeps, requireReleaseDeps, requirePluginVersions and other useful standard rules .

Also if you have a submodules in project it will be also useful ono-extra-enforcer-rules

So, your enforcer rules may looks like:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-enforcer-plugin</artifactId>
    <version>1.4.1</version>
    <executions>
        <execution>
            <id>enforce</id>
            <goals>
                <goal>enforce</goal>
            </goals>
            <configuration>
                <rules>
                    <bannedPlugins>
                        <!-- will only display a warning but does not fail the build. -->
                        <level>WARN</level>
                        <excludes>
                            <exclude>org.apache.maven.plugins:maven-verifier-plugin</exclude>
                        </excludes>
                        <message>Please consider using the maven-invoker-plugin (http://maven.apache.org/plugins/maven-invoker-plugin/)!</message>
                    </bannedPlugins>
                    <requireMavenVersion>
                        <version>3.0.5</version>
                    </requireMavenVersion>
                    <requireJavaVersion>
                        <version>1.8</version>
                    </requireJavaVersion>
                    <requireReleaseDeps>
                        <onlyWhenRelease>true</onlyWhenRelease>
                        <message>No Snapshots Allowed!</message>
                    </requireReleaseDeps>
                    <requireUpperBoundDeps>
                        <!-- 'uniqueVersions' (default:false) can be set to true if you want to compare the timestamped SNAPSHOTs  -->
                        <!-- <uniqueVersions>true</uniqueVersions> -->
                    </requireUpperBoundDeps>
                    <reactorModuleConvergence>
                        <message>The reactor is not valid</message>
                        <ignoreModuleDependencies>true</ignoreModuleDependencies>
                    </reactorModuleConvergence>
                    <requirePluginVersions>
                        <message>Best Practice is to always define plugin versions!</message>
                        <banLatest>true</banLatest>
                        <banRelease>true</banRelease>
                        <banSnapshots>true</banSnapshots>
                        <phases>clean,deploy,site</phases>
                        <additionalPlugins>
                            <additionalPlugin>org.apache.maven.plugins:maven-eclipse-plugin</additionalPlugin>
                            <additionalPlugin>org.apache.maven.plugins:maven-reactor-plugin</additionalPlugin>
                        </additionalPlugins>
                        <unCheckedPluginList>org.apache.maven.plugins:maven-enforcer-plugin,org.apache.maven.plugins:maven-idea-plugin</unCheckedPluginList>
                    </requirePluginVersions>
                    <enforceBytecodeVersion>
                        <maxJdkVersion>1.6</maxJdkVersion>
                        <excludes>
                            <exclude>org.mindrot:jbcrypt</exclude>
                        </excludes>
                    </enforceBytecodeVersion>
                    <banDuplicateClasses>
                        <ignoreClasses>
                            <!-- example of ignoring one specific class -->
                            <ignoreClass>com.xyz.i18n.Messages</ignoreClass>

                            <!-- example of ignoring with wildcards -->
                            <ignoreClass>org.apache.commons.logging.*</ignoreClass>
                        </ignoreClasses>
                        <findAllDuplicates>true</findAllDuplicates>
                    </banDuplicateClasses>
                    <banCircularDependencies/>
                    <ForbidOverridingManagedDependenciesRule>
                        <excludes>
                            <!-- guava in parent is too old, so allow to override it -->
                            <exclude>com.google.guava:guava</exclude>
                        </excludes>
                    </ForbidOverridingManagedDependenciesRule>
                    <ForbidOverridingManagedPluginsRule/>
                    <ForbidDependencyManagementInSubModulesRule/>
                    <ManageAllModulesRule/>
                </rules>
            </configuration>
        </execution>
    </executions>
    <dependencies>
        <dependency>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>extra-enforcer-rules</artifactId>
            <version>1.0-beta-3</version>
        </dependency>
        <dependency>
            <groupId>net.oneandone.maven</groupId>
            <artifactId>ono-extra-enforcer-rules</artifactId>
            <version>0.1.1</version>
        </dependency>
    </dependencies>
</plugin>

Two attempts to find duplicated classes with Maven
Remove duplicate classes the agile way: Maven Duplicate Finder Plugin

Finding Duplicate Class Definitions Using Maven

Both of this plugins are discussed here:
Figuring out duplicate class definitions using the Analyze goal

Also maven-shade-plugin does check for overlapping classes during packaging of uber-jar.

Resolving conflicts using the dependency:tree -Dverbose
It shows which dependencies are duplicated (omitted for duplicate), with are evicted with newer version (version managed from 1.6) but it doesn’t show which dependencies was excluded.

Another one good thing that worst to do is enable Failing the build on dependency analysis warnings. Note: it binded to verify phase that runed after package.

JDEPS Java Dependency Analysis Tool from JDK 8

Also some related articles

Versions compitable

For example changelog of Joda-Time v2.9

Compatibility with 2.8

Build system — Yes
Binary compatible — Yes
Source compatible — Yes
Serialization compatible — Yes
Data compatible — Yes
— DateTimeZone data updated to version 2015g
Semantic compatible — Yes

See another [Linkset] Compatibility

Jigsaw

It is possible a situation when some two libraries wanting to use the same dependency but of different versions. Unfortunately, in this cases we can’t manage this and should use -nodep versions.
Finally this problem will be resolved in JDK 9 Jigsaw: a jar can be declared as a module and it will run in it’s own isolated class loader, that reads class files from other similar module class loaders in an OSGI sort of way.
This will allow multiple versions of the same Jar to coexist in the same application if needed.

Working with deprecation

Upgrading of dependncies may require to remove some old codebase that depends on them.
This is also should be done in right way, so here some links that may helps:
* JEP 277
* Dr. Deprecator Prescriptions: important things that you should know about obsolete Java API

Speed up maven build

It’s also related topic. The main reason why I decided to add it here is because usually during speeding up build you will find a lot of problems with dependency graph.
It will helps you to make yoir project more modulized. Also for example paralell build may fails if your tests are in conflict (shares same resources, for example integration tests may use the same port).

Dependency analyzers

Also useful

* jApiCmp japicmp is a tool to compare two versions of a jar archive
* Java API Compliance Checker: A Perl script that uses javap to compare two jar archives. This approach cannot compare annotations and you need to have Perl installed.
* Clirr: A tool written in Java that compares two libraries for binary compatibility. Tracking of API changes is implemented only partially, tracking of annotations is not supported. Development has stopped around 2005.
* JDiff: A Javadoc doclet that generates an HTML report of all API changes. The source code for both versions has to be available, the differences are not distinguished between binary incompatible or not. Comparison of annotations is not supported.
* revapi: An API analysis and change tracking tool that was started about the same time as japicmp. It ships with a maven plugin and an Ant task, but the maven plugin currently (version 0.4.1) only reports changes on the command line.

Power Assert in Vim

Power Assert for Java and others

Peter Niederwieser, creator of Spock, the best testing framework ever, also contributed to Groovy programming language a very handy feature: Power Asserts.

int x = 1;
assert x == 2;

// Output:
//
// Assertion failed:
// assert x == 2
//        | |
//        1 false

As you can see, we can see each value of each statement, and this is very cool, especially for unit tests.
It makes all this JUnit bullshit like assertEquals(), assertTrue, assertNull, and all matchers like Hamcrest absolutely unneeded.
I really hate all matchers like FEST or Hamcest, because they aren’t natural and repeat code itself.

So now you can breathe freely without any repeating yourself.

You can see a talk where Peter Niederwieser present Spock specifications
https://vimeo.com/33947244

Also Peter created Power Asserts lib for Scala
https://github.com/pniederw/expecty

But,
Unfortunately, you can’t make a Power Asserts in Java, because it doesn’t have an AST preprocessor.
UPD Now we have the library https://github.com/jkschneider/java-power-assert but with limitations

If you, like me, have a big project with tests written in Java+JUnit, the only one way that I found, is convert them to Groovy (in 99% just change file extension from Java to Groovy) or you can compile your tests with groovyc — it’s Groovy Compiler but compiles Java too as well.
After compiling with groovyc asserts in Java behaves like in Groovy. Maybe this is the only one case when something written in Java works differently when compiled with Groovy.

For example here is simple test in Java

import org.junit.Test

class UserTest {
@Test
public void testName() {
String username = "olololo";
assert username.equals("trololo");
}

}

After compiling with groovyc it’s decompiled bytecode will looks like:

// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;
import org.codehaus.groovy.runtime.ScriptBytecodeAdapter;
import org.codehaus.groovy.runtime.callsite.CallSite;
import org.codehaus.groovy.runtime.powerassert.AssertionRenderer;
import org.codehaus.groovy.runtime.powerassert.ValueRecorder;
import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
import org.junit.Test;

public class UserTest implements GroovyObject {
public UserTestGroovy() {
CallSite[] var1 = $getCallSiteArray();
MetaClass var2 = this.$getStaticMetaClass();
this.metaClass = var2;
}

@Test
public void testName() {
CallSite[] var1 = $getCallSiteArray();
String username = "olololo";
ValueRecorder var3 = new ValueRecorder();

try {
CallSite var10000 = var1[0];
var3.record(username, 8);
Object var6 = var10000.call(username, "trololo");
var3.record(var6, 17);
if(DefaultTypeTransformation.booleanUnbox(var6)) {
var3.clear();
} else {
ScriptBytecodeAdapter.assertFailed(AssertionRenderer.render("assert username.equals(\"trololo\")", var3), (Object)null);
}

} catch (Throwable var5) {
var3.clear();
throw var5;
}
}
}

As you can see, it uses ValueRecorder to store all evaluated expressions and it will render a source code line. And it may be executed as class file (may require groovy-all dependency in classpath):

Assertion failed:

assert username.equals("trololo")
|        |
olololo  false

at org.codehaus.groovy.runtime.InvokerHelper.assertFailed(InvokerHelper.java:402)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.assertFailed(ScriptBytecodeAdapter.java:650)
at com.github.stokito.UserTest.testName(UserTest.java:9)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)

Unfortunately currently IntelliJ can’t compile Java files with Groovyc. It always compiles *.java files with javac.
I created an issue Allow groovyc as compiler for Java classes, please vote for it.

Power Asserts in other languages

Kotlin

does not exist but authors know about Power Assertions and had intentions to do them.

.NET languages

https://github.com/PowerAssert/PowerAssert.Net

JavaScript

https://github.com/power-assert-js/power-assert
https://github.com/power-assert-js/espower-typescript for TypeScript
https://github.com/power-assert-js/espower-babel
https://github.com/power-assert-js/babel-plugin-espower
https://github.com/twada/battlefield-sourcemaps
https://github.com/deepblue-will/coffee-power-assert for Cofee Script
https://github.com/twada/fly-espower

Ruby

There is a gem https://github.com/k-tsj/power_assert and here is presentation from author:
https://speakerdeck.com/k_tsj/power-assert-in-ruby

https://github.com/joker1007/rspec-power_assert
https://rubygems.org/gems/power_assert/versions/0.2.4
https://github.com/hsbt/minitest-power_assert
https://github.com/yui-knk/pry-power_assert for Pry REPL

Others

https://github.com/keygx/PAssert XCTest for Swift
https://github.com/rosylilly/power_assert.cr for Crystal (static Ruby)
https://github.com/ma2gedev/power_assert_ex for Elixir
https://github.com/gifnksm/power-assert-rs for Rust
https://github.com/haya14busa/vital-power-assert for Vim script
https://github.com/ToQoz/gopwt for Go

TODO: write about power assets in https://en.wikipedia.org/wiki/Assertion_(software_development)

[LinkSet] Database migration tools

Версионная миграция структуры базы данных: основные подходы

DBMaintain and Unitils

dbmaintain.org
Использование Unitils для тестирования в Java

LiquiBase

LiquiBase
Grails Database Migration Plugin
Использование Liquibase без головной боли. 10 советов из опыта реальной разработки

FlywayDB

FlywayDB

Other

Tapestry 5 Database Migrations

For .NET

SSDT

http://msdn.microsoft.com/ru-ru/data/tools.aspx
Плюсы: процесс создания и редактирования БД напоминает то, как бы вы это делали с Management Studio.
Минусы: сложность написания миграционных скриптов. Т.к. инкрементальные изменения строит сам проект, сохранность данных обеспечивается за счет pre-deploy и post-deploy-скриптов. Придется опираться на наличие/отсутствие полей в БД или «изобретать» таблицу schema version, уже реализованную в миграционных движках.

ECM7 Migrator

http://code.google.com/p/ecm7migrator/
Движок миграций с открытым кодом. Проект поддерживает хабраюзер dima117.
Плюсы: поддерживаются разные СУБД, если что-то вас не устраивает, код открыт. Мигратор поддерживается и обрастает новыми функциями. И, пожалуй, самое важное, поддерживает несколько ключей миграций в одной базе данных. Это может быть очень полезно, если ваше приложение модульное и поддерживает плагины в том или ином виде. Каждый плагин может выполнять свои миграции и при этом использовать одну БД
Минусы: нет плюшек Entity Framework Migrations.

Entity Framework Migrations

http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-code-based-migrations-walkthrough.aspx
Плюсы: работает из коробки, автоматически создает миграции по Db-контексту, понимает команды из консоли visual studio, миграции публикуются с помощью стандартного Publish из Visual Studio.
Минусы: зависит от Entity Framework.

FluentMigrator

FluentMigrator — система версионных миграций

[LinkSet] OWASP

[Linkset] Migration to Java 8

Notes from Oracle http://www.oracle.com/technetwork/java/javase/8-compatibility-guide-2156366.html

Also possible problems:

  • switching to 64bit JVM can require more memory (actually as I know it was only in few builds of Oracle JDK 6 and all next versions comes with enabled flag -XX:+UseCompressedOops)
  • changes in garbage collection can lead to unexpected pauses
  • inclusion of XML parsers into JDK proper requires changes to web application packaging or configuration
  • memory and runtime characterics of String#substring completely change in «minor» JDK revision
  • sorting a collection with a custom (incorrectly implemented) comparator suddenly throws exceptions it did not throw before  (Java error: Comparison method violates its general contract)
  • Calling Thread#stop(Throwable) (which was never a good idea and has been deprecated for a very long time) throws a UnsupportedOperationException since Java 8
  • Updated Unicode support changing sorting and casing behavior for some strings
  • Changes in generics compilation
  • inability to extend BitSet and implement Set<Integer> due to new default methods
  • Bigin rounding behavior (affected early builds of JDK7 and JDK8)

http://stackoverflow.com/questions/28228450/java-is-backward-compatible-but-why-we-need-to-upgrade-many-libraries-when-we-u

Also I tried to mark all this issues on StackOverflow with tags migration+java-8 and migration+java-7

Most valuable article http://product.hubspot.com/blog/upgrading-to-java-8-at-scale
Key points: you need to update ASM lib and use cglib-nodep where possible.

Managing compatibility

See linkset [LinkSet] Compatibility
Tool for checking API and BPI http://ispras.linuxbase.org/index.php/Java_API_Compliance_Checker
http://wiki.apidesign.org/wiki/SignatureTests
https://stackoverflow.com/questions/2040693/how-to-identify-a-missing-method-binary-compatibility-in-a-jar-statically
http://clirr.sourceforge.net/
http://www.sab39.org/Software/Japitools/42/
http://tattletale.jboss.org/

How Spring achieves compatibility with Java 6, 7 and 8

And don’t forget to enable -parameters option https://julien.ponge.org/blog/java8-parameter-names-and-jdk-dogfooding/

https://stackoverflow.com/questions/8111310/java-7-jdk-7-garbage-collection-and-documentation

http://allegrotech.io/How-to-migrate-to-Java-8.html

https://www.techempower.com/blog/2013/03/26/everything-about-java-8/

http://zeroturnaround.com/rebellabs/what-migrating-to-java-8-will-do-to-your-codebase-a-practical-example/

In some cases it possible speed downgrade
https://stackoverflow.com/questions/23756966/why-is-stringbuilderappendint-faster-in-java-7-than-in-java-8

Also from my experience of migration from JDK6 to JDK8:

1 . APT (Annotations Processing Tool) was removed. We used Enunciate for Web Services and it uses APT. So now we waiting next version of Enunciate that will use JSR 269 instead of APT.

And actually there was a lot of API that was removed from Java and in first link Oracle told about it just see «Features Removed from Java SE 8» and «Features Removed from JDK 8».

2 . java.util.Locale class was updated and it causes error in our application.
We have some users with ISO country code CS i.e. Serbia and Montenegro. In 2004 Montenegro separated from Serbia and this code CS was removed in new version of Locale.getISOCountries().
Since our application had checks on this code we got a lot of exceptions.

3 . maven-tomcat-plugin hasn’t yet version for Tomcat 8. You can vote or contribute MTOMCAT-234. And in Tomcat 8 in some configs we needed to change path starting with root /

4 . HashMap descendants should keep contract between put() and putAll()
All classes that extends HashMap and overrides `put() method may have errors if not overrides putAll() method.
You can see interest bug in Spring framework for details https://jira.spring.io/browse/SPR-7969.

5 . Clashing Getters.
Also we had an error when our domain classes contains two getters for the same property.
For example, class MerchantData contains two methods getParentMerchant() and isParentMerchant()

public void setParentMerchant(MerchantData parentMerchant) {
this.parentMerchant = parentMerchant;
}

public MerchantData getParentMerchant() {
return parentMerchant;
}

public boolean isParentMerchant() {
return subMerchants != null &amp;&amp; !subMerchants.isEmpty();
}

According to JavaBeans specification all getters of boolean properties should be named isSomething().
Hibernate tries to determine the type of property parentMerchant and it looks that type is Boolean.
Then he tries to get id of parentMerchant ant fail with error:

Caused by: org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of com.example.merchant.dao.MerchantData.id
at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:171)

To fix that we need to rename method isParentMerchant() or get rid of it.
This kind of issues are happened only when we run project on JDK8.
So, please take it into account when you create a new getters.

I asked guys from JetBrains to make inspection for IntelliJ that reports about this potential bugs, please vote.
Also I created plugin https://github.com/stokito/IntellijClashingGettersInspection

Something similar Why did PropertyDescriptor behavior change from Java 1.6 to 1.7?

6 . Groovy code may fails with java.lang.IncompatibleClassChangeError during constructing exceptions that was compiled in Java 6. Good article How to fix IncompatibleClassChangerError with groovy on jdk7
It’s very often error in Grails applications

7 . Maven is not working in Java 8 when JavaDoc tags are incomplete
You can easily find all this incomplete tags in IntelliJ by running inspection Ctrl+Alt+Shift+i «Declaration has JavaDoc problems»
Also there was few other errors in maven plugins, most of them already fixed but check them anyway
https://cwiki.apache.org/confluence/display/MAVEN/Java+8+Upgrade

8 . ActiveMQ still has a bug that occurs only in JDK 8 AMQ-5356 Unable to see message contents from the web UI

9 . You really should resolve your JAR HELL before upgrading.

Also known bug:
Xstream no-args constructor error

Tutorial: Migrating to Java 8

Migration plan:

  1. Make build stable: migrate to the latest Maven, introduce Continuous Integration.
  2. Resolve JAR hell, explicitly define all libraries and plugins versions.
  3. Improve test coverage, take care to rounding of BigDecimal, working with dates, localization (country codes and time zones),  Comparators, XML parsing,  Reflection and serialization. Integration tests for all parts of application that using external JAR’s or classes for example database  (JDBC drivers).
  4. Fix basic and common errors: clashing geters, missing @Override annotations.
  5. Upgrade all bytecode-level manipulation libraries (CGLIB, ASM, JavaAssist)
  6. Try to compile with old JDK (6, 7) but try to run with new JDK (8, 9).
  7. Run all regression tests and fix all bugs that you’ll find.
  8. Upgrade other core libraries (Hibernate, Spring, JDBC divers) and try to remove obsolete (com.sun package)
  9. Test again and fix new founded bugs.
  10. Then try to compile with new JDK (8,9) but with target language level 6. But still run with new one.
  11. Test again and fix new founded bugs.
  12. Then try to compile with new JDK (8,9) and with last target language level (8, 9). And run with last.
  13. Test again and fix new founded bugs. Migration finished