IT

now browsing by category

 

Developing java apps on VS Code

VSCode

An integrated development environment (IDE) is a software suite that consolidates basic tools required to write and test software..
For a long time there have been basically 3 big players in the java IDE world: Netbeans, Eclipse and IntelliJ IDEA. According to some surveys IntelliJ IDEA is clearly winning the IDE battle, Eclipse is loosing popularity year over year, and Netbeans is basically hanging.
I personally I am part of the “minority” that uses Netbeans for my java development. There were simple things I liked about Netbeans over its competitors, and even though I tried to use Eclipse or IntelliJ, and I saw they are potentially way better than Netbeans, I was always coming back to my familiar Netbeans no matter what. Why was that? Here is the simple things I am looking for in an IDE:
- syntax highlighting for at least: Java, JavaScript, Html, CSS
- build/test/run project from IDE
- ability to see javadocs directly from IDE
- easy jump from one class to another
- code refactoring assistance
- intelligent code completion

Lots of features are great, but b/c I am using only a handful of those provided features, I rather not have to always dig into overpopulated drop down menus. Remembering shortcut keys will always solve this problem.

Most (all) of my projects are maven/gradle based; I like being able to just open my project directly, not having to import it in some kind of proprietary project format, setup workspaces and install external plugins before I get to work.

Over time I started finding Netbeans getting in the way of my productivity. There were numerous annoyances, small problems popping up all the time. The cause of these problems might by me, my project setup, the frameworks I use, my OS, my all around environment, Netbeans itself or a combination of all the above. The plan was to succomb to pressure and get a IntelliJ license. Everybody uses it, and I am being told it does everything but cooking your breakfast. Al I have to do is adjust my workflow to a new environment, and maybe lear some new shortcuts.

I am a big fan of opensource projects, and not a big fan of subscriptions, licenses and dealing with support. Those were some of the reasons why I did not buy the license after all. Plus I had the community version installed on my machine, but I was still using Netbeans for some reason.

I need to ditch Netbeans, but today as I am writing this, I know that my next IDE will not be IntelliJ (nor Eclipse). And this is b/c I tried Visual Studio Code/.

As their github page says https://github.com/Microsoft/vscode. VS Code is a type of tool that combines the simplicity of a code editor with what developers need for their core edit-build-debug cycle. I has powerful developer tooling, like IntelliSense code completion and debugging and gets out of your way.

Sounded good. But … First thing first. You might have noticed that this is a software coming from Microsoft, a company that historically has not been too friendly to the open source world, but they have changed their position/opinion in the last years. (Or have they???).

This product is open source and free for private or commercial use (MIT license). Nice.
Another big plus is the fact that VS Code is multi-platform. All my computers run Linux, so this is an important aspect.

First time you open VS Code, it does feel like you opened a simple editor. Similar layout, color palette, even the nice scrollbar with content preview (minimap) and highligting like the sublime text editor. The only additional thing is an activity bar with a few square icons:
- Explorer
- Search
- Source Control
- Debug
- Extensions

That’s it. Clicking on any of those icons brings in front different panels, often minimalist that are self explanatory, a user that has been previously exposed to a full fledged IDE can just explore and feel rigt at home in no time. I am using git, and the source control section allows me out of the box to see staged/unstaged changes in the current branch + allow to see a graphical diff between my current file and the one on HEAD. Of course there is support for other git operations directly from the UI, that I will probably not use b/c I like to do all my git operations directly in the terminal.

The editor that VS Code uses is a deparate project, have a look at the the Monaco Editor. Looks like it’s implemented in typeScript (typed JavaScript) and it is an editor that can run in a browser. Digging a little into it, I found out that they use Electron a tool which uses blink browser engine (used in chromium) and node.js to allow building cross platform desktop apps with JavaScript, HTML, and CSS (web technologies).

Looks like basic web front end development is supported from the get go, but java development, is supported via additional extensions.
Installing extensions is pretty easy. You just click the extension quick icon on the left bar and search through the market place. I searched for java, and I went with installing the following:
- Red Hat: Language Support for Java(TM) by Red Hat – Java Linting, IntelliSense, formatting, refactoring, Maven/Gradle support and more…
- Microsoft: Debugger for Java – a lightweight Java debugger for Visual Studio Code
- Microsoft: Java Test Runner – Run and debug JUnit or TestNG test cases
- Wei Shen: Tomcat for Java – Debug or run your java war package in Apache Tomcat

!!! Careful with the extensions. It might cause your IDE to become unstable. That’s the reason I tried to stay with the lowest number of installed extensions.
Also I wanted big reputable companies behind the chosen extensions. (The outliner is the Tomcat extension which is community supported).

The java Language Server here is where all the java magic is coming from. Features like auto complete, diagnostics, go to definition, find all references and alike can be found in one of the projects used. Eclipse JDT brings in important features like Java debug support, and annotation processing infrastructure.

I am not going to enumerate the few problems I run into, b/c judging by the release schedule and the amount of contributors, activity and attention this project gets, my issues will be solved in no time. Also the main things I rely on are coming from the Eclipse foundation, they are stable and proved projects. All I can say is that after I installed the java extension, there was absolutely no feature I was missing in an IDE. Here is what I tried/needed.
- open/setup maven project
- clean/build/test maven project
- run/debug independent Junit test
- format file
- run/debug war file on Tomcat
- auto reload jsp code on Tomcat
- InteliSense with all features: code completion, see java doc, jump to, etc
- built in bash terminal
- jump to current file in tree panel
- diff file(s) to HEAD or to other branches
- quickly search and jump to files in project
- highlighting of syntax error in the editor
- code refactoring assistance
- auto import
- generate code (java bean getters/setters)
- problems panel: where I can see my annotated TODO/FIXME + other potential problems

Conclusion. Although this IDE is relative new (about 3 years old), I feel like for me it’s the most suitable IDE I have ever tried. It seemed like it was designed for ease of use, with a minimalist default setup. It has about the right amount of features and it has the 21st century look and feel. It is not there yet, but I will be coming back on each one of the new releases, until I will fully adopt it as my main IDE.

JPA set null on delete

Java

I am sure a lot of you heard, when talking about RDBMS systems about a foreign key with “Set NULL on delete”. It means that if a record in the parent table is deleted, then the corresponding records in the child table will have the foreign key fields set to NULL. The records in the child table will not be deleted. A foreign key with set null on delete can be created at the beginning when a table gets created (CREATE TABLE statement) or later on (ALTER TABLE statement).

I needed the same type of behavior, but done in my DAO layer where I happened to use Java Persistence API.

Following is the solution. We will be working with 2 entities, here is are some simple implementations of a Child class and a Parent class.

@Entity
@Table(name = "c_child")
public class Child {
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "parent_id")
    private Parent parent;

    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Parent getParent() {
        return parent;
    }

    public void setParent(Parent parent) {
        this.parent = parent;
    }
}
@Entity
@Table(name = "c_parent")
public class Parent {
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    private Integer id;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent")
    private Set<Child> children;

    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Set<Child> getChildren() {
        return children;
    }

    public void setChildren(Set<Child> children) {
        this.children = children;
    }

    @PreRemove
    private void removeParentFromChildren() {
        for (Child child : this.getChildren()) {
            child.setParent(null);
        }
    }
}

With this setup in place whenever the parent will be removed from the storage ( entitymanager.remove(parent) ), after.if the transaction is commited, all the children that had the deleted parent will now have null. So, as you can see the solution is a simple callback method annotated with the JPA provided @PreRemove. A callback method is a no-arg method with no return type and any arbitrary name. The callback I used is only one of the many that JPA API provides

Type Description
@PrePersist Executed before the entity manager persist operation is
actually executed or cascaded. This call is synchronous with the
persist operation.
@PreRemove Executed before the entity manager remove operation is
actually executed or cascaded. This call is synchronous with the
remove operation.
@PostPersist Executed after the entity manager persist operation is
actually executed or cascaded. This call is invoked after the
database INSERT is executed.
@PostRemove Executed after the entity manager remove operation is
actually executed or cascaded. This call is synchronous with the
remove operation.
@PreUpdate Executed before the database UPDATE operation.
@PostUpdate Executed after the database UPDATE operation.
@PostLoad Executed after an entity has been loaded into the current
persistence context or an entity has been refreshed.

What is Slack?

slack

Slack is a different kind of messaging service that allows an unlimited number of people to communicate quickly and send ideas back and forth to team members with the push of a button.
Slack can be used both on desktop and notebook computers, as well as on smartphones via apps. Despite its name, the focus is on helping your team to be more productive than ever before.
Since its launch in 2014, Slack has become a popular tool for enterprise collaboration, more than six million people use Slack daily, around a third of whom are paying customers, people are spending on average more than two hours each day inside the chat app. Slack wants to make interactions more fun, which has been a big part of the secret behind its success: public channels messages can be accompanied with GIFs.
Three types of channels exist within each workplace for team members: public, private and, more recently, shared channels. The latter enables communications with staffers at external companies. Channels allow discussions to center on a specific project, team (such as sales or marketing) or a shared interest topic (video, for example). The app also offers direct messages for quick conversations with another team member, using private channel. And you can drag and drop just about any file into the system to quickly and effortlessly share it with team members.
Since launch, the platform has quickly added new features. Video and voice-calling capabilities were rolled out in 2016 and last year screen sharing was enabled – the result of Slack’s ScreenHero acquisition.

Can my boss read my messages?

There are two types of privileged Slack users: admins and “workspace owners.” Both of these special users can download a “standard export” of anything posted to public channels, but only workspace owners can see your messages, through what’s called a “compliance export.” Not all workplaces have compliance exports enabled.
Slack added the compliance exports feature in 2014 for some of its paid customers and the feature is only available on the Plus plan. If your workspace owner has the feature turned on, they will have access to a .zip file with your message history, both from private channels and direct messages. But if your company has such exports currently turned off, you will get a Slackbot notification if any change happens, and your message history prior to the feature being enabled will not be available to view.
A small number of people at Slack have access to the systems that store and process your data, but it’s unclear exactly how many Slack employees do, and who, exactly, those people are.

Has Slack been hacked?

In 2014, a programmer spotted a vulnerability in the chat app that let anyone view a company’s internal Slack teams. And in February 2015, the company suffered a data breach. In a March 2015 blog post, Slack described the news as a “security incident” and announced the rollout of two-factor authentication.

Google and Microsoft are far from the only competitors to Slack. Microsoft reportedly considered acquiring Slack two years ago before deciding to build out its existing collaboration and communication capabilities. The result was the launch in early 2017 of Teams, which is set to replace Skype for Business over time. Google, meanwhile, has relaunched its Hangouts tool, separating it into two apps: Meet and Chat.

JPA Injection in AttributeConverters

Java

Here is the use case. We have a table in the database that has a column where we keep a sensitive piece of information.
That is why this column was made of type VARBINARY and the data kept in it is encrypted. (using the AES algorithm)

 CREATE TABLE `example` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(25) NOT NULL,
  `password` varbinary(200) NOT NULL
  PRIMARY KEY (`id`),
) ENGINE=InnoDB;

We wanted to be able to load the decrypted password directly into the JPA @Entity that is modeled according to that table.

@Entity
@Table(name = "example")
public class Example {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id")
    private Integer id;

    @Column(name = "username", nullable = false, length = 25)
    private String username;

    @Column(name = "password", nullable = false)
    @Convert(converter = AesConverter.class)
    private char[] password;

    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public char[] getPassword() {
        return password != null ? password.clone() : null;
    }

    public void setPassword(char[] password) {
        this.password = password != null ? password.clone() : null;
    }
}    

As you can see we have a AesConverter class that is taking care of this. This is just an implementation of AttributeConverter that does the encryption/decryption, by delegating to another utility class AesUtil.

@Converter
public class AesConverter implements AttributeConverter<char[], byte[]> {

    @Resource(name = "dbEncryptionKey")
    private String dbEncryptionKey;

    @Override
    public byte[] convertToDatabaseColumn(char[] chars) {
        return AesUtil.encryptMySqlAes(chars, this.dbEncryptionKey);
    }

    @Override
    public char[] convertToEntityAttribute(byte[] bytes) {
        return AesUtil.decryptMySqlAes(bytes, this.dbEncryptionKey);
    }

}

In our example we use CDI and we configured the app in such a way that that the AesConverter.java file is picked up by the CDI container.
We are using Hibernate 5.3.x which implements JPA 2.2, so the bean named “dbEncryptionKey” which exists in the CDI context from a properties file just gets injected in our converter, so we are ready to go everything works like a charm.

Now, what to do, when using Hibernate 5.2.x or lower, or another JPA implementation that supports JPA 2.1 (did not upgrade to JPA 2.2)
Here is our solution.

@Converter
public class AesConverter implements AttributeConverter<char[], byte[]> {

    @Override
    public byte[] convertToDatabaseColumn(char[] chars) {
        return AES.getInstance().encrypt(chars);
    }

    @Override
    public char[] convertToEntityAttribute(byte[] bytes) {
        return AES.getInstance().decrypt(bytes);
    }

}

where AES.java is a singleton that uses a service locator to lazily load the needed encryption key from the CDI context only when first needed.

public class AES {

    private static final String DEFAULT_ENCRYPTION_KEY = "s3Cr!t";
    private String dbEncryptionKey = DEFAULT_ENCRYPTION_KEY;

    private static AES instance;

    private AES() {
        if (DEFAULT_ENCRYPTION_KEY.equals(this.dbEncryptionKey)) {
            this.getConfiguredEncryptionKey();
        }
    }    
    
    private AES(String dbEncryptionKey) {
        this.dbEncryptionKey = dbEncryptionKey;
    }

    public static AES getInstance(String dbEncryptionKey) {
        synchronized (AES.class) {
            if (instance == null) {
                instance = new AES(dbEncryptionKey);
            }
        }
        return instance;
    }

    public static AES getInstance() {
        synchronized (AES.class) {
            if (instance == null) {
                instance = new AES();
            }
        }
        return instance;
    }

    public char[] decrypt(byte[] bytes) {
        return AesUtil.decryptMySqlAesPassword(bytes, this.dbEncryptionKey);
    }

    public byte[] encrypt(char[] input) {
        return AesUtil.encryptMySqlAesPassword(input, this.dbEncryptionKey);
    }

    private void getConfiguredEncryptionKey() {
        try {
            this.mhqDbEncryptionKey = ContextLocator.getRegisteredBean("dbEncryptionKey");
        } catch (IllegalStateException isx) {
            isx.printStackTrace();
        }
    }
}

Microsoft acquires GitHub for $7.5 billion

GitHub

Microsoft is acquiring GitHub, the largest code repository in the world, for $7.5 billion, the companies announced on 4 June. GitHub, an online community for software developers to collaborate and share code, has never been profitable, though it was last valued at $2 billion in 2015. The company is host to a community of 28 million developers who maintain a total of 85 million code repositories. While GitHub offers a free version of its service to developers willing to share code, it began charging for private storage on the service six months after its launch.
GitHub is used by many developers and big tech companies including Apple, Amazon, Google, Facebook, and IBM to store their corporate code and privately collaborate on software, but Microsoft is one of the top contributors to the web-hosting service.
GitHub was acquired for close to 30x annual recurring revenue (an astronomical multiple). To put this in perspective, Microsoft acquired LinkedIn, the job-oriented professional social network, for $26 billion in 2016 (7.2x revenue), in what was considered one of the richest tech deals ever.

The decision has brought fear among some developers at open source community, with some Twitter users proclaiming the death of GitHub and open source software. The concern is completely rational and understandable. Despite the company’s lack of a CEO and money, Github holds a privileged position in the software development ecosystem and plays a critical role. Microsoft, on the other hand, has once opposed to such open-source software development, with its ex-CEO Steve Ballmer describing Linux as “cancer”. This changed over the years, Microsoft has been actively pushing open source technology and the company has open sourced PowerShell, Visual Studio Code and the Microsoft Edge JavaScript engine. Microsoft also partnered with Canonical to bring Ubuntu to Windows 10 and acquired Xamarin to assist with mobile app development.

Microsoft recently integrated Visual Studio App Center and GitHub, to help GitHub developers automate DevOps processes as they build mobile apps for iOS, Android, Windows, and macOS devices. Visual Studio App Center enables mobile developers to build, test and distribute mobile apps to a variety of different devices, including iOS and Android, monitor the performance of those apps and collect analytics and crash dumps to iteratively improve their apps. Additionally, integration with Microsoft’s Azure DevOps Project lets GitHub developers configure a DevOps pipeline and connect it to the cloud with no prior knowledge.These are moves that have been met with surprise by developers initially, but that have earned respect.

GitHub will now be led by CEO Nat Friedman, the founder of Xamarin, who will report to Microsoft’s Cloud and AI chief Scott Guthrie. GitHub CEO and co-founder Chris Wanstrath will now become a technical fellow at Microsoft, also reporting into Guthrie.
Microsoft killed its own GitHub competitor, Codeplex, in December and is now the top contributor to GitHub. Microsoft now has more than 1,000 employees actively pushing code to GitHub repositories.
In a blog post, Chief Executive Satya Nadella said Microsoft plans to “accelerate enterprise developers’ use of GitHub” by selling the service through Microsoft’s sales channels. He also expects GitHub to bring Microsoft’s developer tools and services to new customers. Microsoft said the GitHub acquisition is expected to have a negative impact on 2019 earnings but positive beginning in 2020.