How to prevent open last projects when intellij idea start

By default intellij idea open last project when starting. How to open intellij idea without openning last projects?

By default intellij idea open last project when starting. How to open intellij idea without openning last projects?

Main class not found in project IntelliJ IDEA: Java Application

IntelliJ does not find a main class in my Java application project. The project was cloned from a git repository so had no run configuration. I go to Edit Configurations, add a new Application template, go to Main class: and it says "No matches found in project".

IntelliJ does not find a main class in my Java application project. The project was cloned from a git repository so had no run configuration. I go to Edit Configurations, add a new Application template, go to Main class: and it says "No matches found in project".

So, manually searching through the hierarchy I find the .java file that contains the main function but it will not accept it as the main class. I've pasted the file below to prove that it has the correct main function.

public class AdvanceWarsGameHandler implements IGame
{
private Image mImage;
private String mTitle;

public AdvanceWarsGameHandler()
{
    mTitle = "Advance Wars Game";
    mImage = new Image("/OffBrandCerealOopsAllCarries2-01.png");
}

//Game logic unrelated to graphics goes here
@Override
public void update(Game game, float deltaTime) 
{

}

//Update, but for graphics
@Override
public void render(Game game, Renderer renderer) 
{
    renderer.drawImage(mImage, game.getInput().getMouseX(), game.getInput().getMouseY());
}

 public static void main(final String args[])
{
    //Creating and starting an instance of AdvanceWarsGameHandler
    AdvanceWarsGameHandler advancewars = new AdvanceWarsGameHandler();
    Game myGame = new Game(advancewars);
    myGame.start();
}

public String getTitle()
{
    return mTitle;
}

}

So the question is, why is the IntelliJ project not recognizing the main function in this file, or what is IntelliJ looking for as the "Main class" of an application?

IntelliJ IDEA generating serialVersionUID

How do generate this value in IntelliJ IDEA?

How do generate this value in IntelliJ IDEA?

I go to Settings -> Errors -> Serialization issues -> Serializable class without ‘serialVersionUID’, but it still doesn't show me the warning. My class PKladrBuilding parent implements interface Serializable.

Part of the code:

public class PKladrBuilding extends PRQObject

public abstract class PRQObject extends PObject

public abstract class PObject implements Serializable


Java 12 and IntelliJ IDEA

Java 12 and IntelliJ IDEA

Java 12 and IntelliJ IDEA. In this article, we’ll cover the pain points of using existing switch statements, define switch expressions, and explain why they are good for you.

With switch expressions, Java 12 is enhancing one of its basic language constructs – switch – to improve everyday coding experience for developers. Benefits are multi-fold. As compared to the ‘traditional’ switch constructs, switch expressions can return a value. The ability to define multiple constants with a switch branch, and improved code semantics, makes it concise. By removing default fall-through switch branches, you are less likely to introduce a logical error in a switch expression.


Let’s get started.


Traditional switch constructs

If you think of a switch construct as a multi-way condition, using an expression seems to be a better fit. However, switch could only be used as a statement until now. The current switch syntax is constrained and verbose. It often leads to error-prone code that is difficult to debug.

Here’s an example that uses a switch statement to calculate the height of a chair, based on the size value passed to it:

public enum Size {S, M, L, XL};
public class Chair {
    public void calcHeight(Size size) {
        int height = 0; 
        switch (size) {
            case S:
                height = 18;
            case M:
                height = 20;
                break;
            case L:
                height = 25;
                break;
        }
    }
}

The preceding code has multiple issues:

  • Repetitive break and assignment statements add noise to code.
  • Code verbosity makes it difficult to comprehend the code.
  • Default fall-through in switch branches sneaks in a logical error – the missing break statement for case label S lets the control fall through to case label M. This results in assignment of 20 instead of 18 to height when you execute calcHeight(Size.S).
Switch expressions

Let’s rewrite the preceding example using a switch expression. In IntelliJ IDEA, you can use Alt+Enter on the switch keyword to see the suggestions. Select ‘Replace with enhanced ‘switch’ statement’ to convert the traditional switch statement to a switch expression:

The preceding code offers multiple benefits:

  • Code in a switch branch is concise and easy to read. You define what to execute to the right of ->.
  • Switch branches can return a value, which can be used to assign value to a variable.
  • Switch branches don’t need a break statement to mark their end. In absence of a break statement, the control doesn’t fall through the switch labels – which helps avoid logical errors.
Returning value vs. executing statements

When you aren’t using a switch expression to return a value, a switch branch can choose to execute a statement or block of statements, or even throw an exception:

public enum Size {S, M, L, XL};
public class NotReturningValueFromSwitchLabel {
    public void calcHeight(Size size) {
        int height = 0; 
        switch (size) {
            case S -> height = 18;
            case M -> { 
                           height = 20; 
                           System.out.println(height);
                      }
            case L -> height = 25;
        }
    }
}
Handling all possible argument values

When you are using a switch expression to return a value, it should be able to handle all possible values that you could pass to it as an argument. For instance, if you miss a case label corresponding to an enum constant, IntelliJ IDEA detects it. It offers to insert the specific case label or default case label.

By default, IntelliJ IDEA inserts a default value depending on the variable type. You can edit the placeholder value:

Types other than an enum can have infinite values. When you pass types like byte, short, int, or String and miss including the default label, IntelliJ IDEA can detect and fix it:


Define multiple constants in the same case label

Unlike switch statements, switch expressions allow you to define comma-separated multiple constants in a case label. This cuts down code redundancy – you can execute the same code for all case labels.

If you define redundant code for your case labels in a switch expression, IntelliJ IDEA can fix it for you:


Local variables and break statements in switch branches

With switch expressions, you can define local variables in switch branches. The block must include a break statement specifying the value to return:

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

enum Size {S, M, L, XL};

public class LocalVariablesWithSwitch {
public void assignValue(Size size) {
int height = 0;
height = switch(size) {
case S -> 18;
case M -> {
int weight = 19;
break (weight > 10 ? 15 : 20);
}
case L, XL -> 25;
};
}
}

The case label for value M defines a block statement. A block can also define local variables (weight in this case). The scope and accessibility of the local variable weight is limited to the case label M. Notice how a switch expression uses a break statement to return a value.

Just in case you miss defining a return value for a switch branch, IntelliJ IDEA underlines the keyword case. When you hover the mouse pointer over it, you can view the message about the missing return value:


Preview language feature

Switch expressions is a preview language feature. This essentially means that even though it is complete, it has a possibility of not being confirmed as a permanent feature in a future Java release. This happens for a reason.

Java runs on billions of devices and is used by millions of developers. Risks are high for any mistake in a new Java language feature. Before permanently adding a language feature to Java, the architects of Java evaluate what the developers have to say about it – how good or bad it is. Depending on the feedback, a preview feature might be refined before it’s added to Java SE, or dropped completely. So, if you have any feedback on Switch expressions, please share it here.


IntelliJ IDEA Configuration

Since Switch expressions is a Java 12 language feature, please download and install OpenJDK 12 and configure it to use with IntelliJ IDEA:

Java is evolving and switch expressions is one of the welcome changes in Java 12.

Happy Coding!


Originally published by Mala Gupta at https://blog.jetbrains.com

Build Spring Boot Apps using the Kotlin Programming

Build Spring Boot Apps using the Kotlin Programming

In this tutorial, you will build a Spring Boot application from scratch, using Kotlin as the main language. You will learn how Kotlin works with Spring and how to integrate the code with other Java libraries.

Java, once considered the coolest kid on the block, is now seen by many as a legacy language. Some developers believe it stopped evolving when it comes to features and many consider it too verbose, claiming it makes code hard to read.

JetBrains, the company behind IntelliJ decided to do something about it and create a modern language that would run inside the Java Virtual Machine. This project became Kotlin, a quickly growing and popular language.

Google then announced official support for Kotlin on Android, further accelerating its adoption. Many companies started to replace Java with Kotlin as their main language to take advantage of the new features it provides. Kotlin is now an increasingly important language for developers inside the JVM ecosystem to know and understand.

In this tutorial, you will build a Spring Boot application from scratch, using Kotlin as the main language. You will learn how Kotlin works with Spring and how to integrate the code with other Java libraries. By the end, you will have a secure Spring application running in Kotlin that authenticates users via OAuth 2.0.

Create the Kotlin Application with Spring Initializr

Let’s start by creating the project using Spring Initializr.

Go to the Spring Initializr website and type in the following information:

  • Project: Gradle Project
  • Language: Kotlin
  • Group: com.okta
  • Artifact: spring-kotlin
  • Options:
  • Package Name: com.okta
  • Dependencies: Spring Web

You can also use the command line to get the same result:

curl https://start.spring.io/starter.zip \
       -d language=kotlin \
       -d style=web \
       -d packageName=com.okta \
       -d name=spring-kotlin \
       -d type=gradle-project \
       -o spring-kotlin.zip

You can choose to use either Maven or Gradle. Since Gradle is the most common build tool to go along with Kotlin, this tutorial will go for it.

Import the project into your favorite IDE. Although you can choose your favorite, I strongly recommend IntelliJ, from the creators of Kotlin.

If you use IntelliJ, you don’t need to download Kotlin since it ships included with the IDE. Otherwise download the latest release.

Once you’ve imported the project, it will have a single file named SpringKotlinApplication.kt. Inside the file, you will find the following code:

@SpringBootApplication
class SpringKotlinApplication

fun main(args: Array<String>) {
   runApplication<SpringKotlinApplication>(*args)
}

This file contains the main function, which bootstraps the application. To declare a function in Kotlin you use the keyword fun, followed by its name, the parameters, and the return type. When there is no return type, you don’t specify anything, which is the case with this function.

Here you also have a class annotated with SpringBootApplication that will behave the same way as in Java. You may also notice that SpringKotlinApplication is not declared as public. The reason is pretty simple: all classes are public in Kotlin by default!

Next, create a REST endpoint. As with Java, you need to create a class and annotate it with RestController.

Inside src/com/okta/controller/, create the class GreetController with the following code:

package com.okta.controller

import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController

@RestController
class GreetController {

   @GetMapping("/greet")
   fun greet(): String {
       return "Hello, World"
   }
}

As with classes, all functions are public by default so there is no need to add an explicit modifier. The other big difference is the function declaration: the return type goes after the name of the method, separated by a colon.

That’s it! You have created your first application in Spring using Kotlin.

Run the application by executing the class SpringKotlinApplication in your IDE (or with ./gradlew bootRun). After that, go to http://localhost:8080/greet and you should see the following greeting message in your browser:

Hello, World!
Make the Kotlin Application Endpoint Dynamic

You can make the message in your endpoint available to greet any person. Let’s update it to receive a name as the input and display a personalized greeting message:

Inside the GreetController file, make the following changes:

@GetMapping("/greet")
fun greet(@RequestParam("name") name: String): String {
   return "Hello, $name!"
}

The greet function now receives a parameter called name. In Kotlin, you declare parameters by specifying the name first, followed by a colon and its type. This is the same convention used to declare a function. The RequestParam annotation is placed in the same position as you would in Java code.

You might also have noticed that you didn’t have to concatenate Strings to display the input value. Kotlin has a built-in feature called String templates, which allows you to reference a variable by putting the $ sign, followed by the variable name itself.

Run the application again and open http://localhost:8080/greet?name=john. You should see the message below:

Hello, john!

Great! With very little effort, your application can greet any user by name from now on.

Extensions: Say Farewell to Utility Classes

Your endpoint is working, but there is little problem with the current version: the user might input their name in all lowercase characters.

To fix this, you can capitalize the first character of the name before returning it. In Java, you usually achieve this by creating or importing a utility class that you then call to do the action. For instance, you could import StringUtils from Apache Commons to your project and add the following code:

String capitalizedName = StringUtils.capitalize(name);
return "Hello, " + capitalizedName + "!";

In Kotlin, you don’t need to use a utility class. Instead, use a feature called extension functions. This feature allows you to add functions to existing classes, even when they are final or outside your project scope. All you have to do is inform the class you want to extend with the method to make it available:

fun String.capitalize(): String {
   if (this.isEmpty()) {
       return this
   } else if (this.length == 1) {
       return this.toUpperCase()
   } else {
       return this[0].toTitleCase() + this.substring(1).toLowerCase()
   }
}

The function above ensures the first letter of the word is in uppercase and all others are in lowercase.

The extension function is declared in the same way as a regular function. The only difference is you have to specify the class you want to extend before the name of the method. In our case, you want to add a capitalize function in the String class, which means you need to declare the function as String.capitalize.

Go to the greet function and make the following changes:

@GetMapping("/")
fun greet(@RequestParam("name") name: String): String {
   val capitalizedName = name.capitalize()
   return "Hello $capitalizedName!"
}

Although you declared the function in your project, you make the call as it was defined inside the String class! This eliminates the need to create utility classes and concentrates the methods in one place, making it easier to find the function you want to use.

Restart the application and reload http://localhost:8080/greet?name=john you should see the following message:

Hello, John!

There you go! Now your application displays the name with a capitalized first letter :-)

When: An Enhanced Switch Operator

Take a closer look at the capitalize method you created earlier and note that all three if statements are related. This is a common programming pattern the creators of Kotlin decided to handle with a new keyword: when.

You can think of the when as an enhanced switch statement. In Java, you can verify if an enum is of a particular type by using switch:

switch(myEnum) {
   case ENUM_A:
       // code here
   case ENUM_B:
       // code here
   default:
   // code here
}

This is very useful to make cleaner code, but it’s also limited because it can only verify the type of the variable. In Kotlin, when lets you verify any condition. That way you get cleaner code while performing more advanced operations.

Let’s rewrite the previous capitalize method using when.

fun String.capitalize(): String {
   when (this.length) {
       0 -> return this
       1 -> return this.toUpperCase()
       else -> return this[0].toTitleCase() + this.substring(1).toLowerCase()
   }
}

In this new version, you verify the length of the current String and return the result based on its length.

But the power of when doesn’t end there. You can even mix up different types of conditionals in the same clause. For instance, you could write the above method like this:

fun String.capitalize(): String {
   when {
       this.isEmpty() -> return this
       this.length == 1 -> return this.toUpperCase()
       else -> return this[0].toTitleCase() + this.substring(1).toLowerCase()
   }
}

As you can see, one of the conditionals calls isEmpty(), while the other one verifies the length of the String. As long as your expression can be evaluated as a boolean value, you can use it inside of a when expression.

Leverage Java Libraries In Your Kotlin App

Although your application is still very simple, you can make it look like a professional app with just a few small tweaks. For instance, greet the logged-in user by name instead of asking for it as a parameter every time.To make that work of course, you need to implement user authentication first.

Authentication is a vital part of any modern app, but can you incorporate auth into your project without layers of configuration and code? The answer is yes! We’ll use OAuth 2.0 to authenticate users and display a greeting message based on the user’s name with no headache.

Recall how Kotlin can use libraries from the Java ecosystem? Add Okta’s Java library written to handle the OAuth 2.0 flow inside your application.

To start, open the build.gradle.kts file. Inside the dependencies tag, add the following line:

implementation("com.okta.spring:okta-spring-boot-starter:1.2.1")

Your dependencies object should look like this:

dependencies {
   implementation("org.springframework.boot:spring-boot-starter-web")
   implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
   implementation("org.jetbrains.kotlin:kotlin-reflect")
   implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
   implementation("com.okta.spring:okta-spring-boot-starter:1.2.1")
   testImplementation("org.springframework.boot:spring-boot-starter-test")
}

This dependency adds both Okta and Spring Security to your project. They make it simple to ensure only authenticated users can access protected areas of your application.

If you don’t have an Okta account, go ahead and create a free one. After registering, go through the following steps:

  • Log into your account
  • Click Applications
  • Click on Add Application. You will be redirected to the following page:

Now that you have your Okta application, you can use it to authenticate users in your Kotlin app.

Add the following environment variables to your application:

OKTA_OAUTH2_ISSUER=https://{yourOktaDomain}/oauth2/default
OKTA_OAUTH2_CLIENT_ID={CLIENT_ID}
OKTA_OAUTH2_CLIENT_SECRET={CLIENT_SECRET}

You will find {CLIENT_ID} and {CLIENT_SECRET} on the application page in Okta’s dashboard. To find it, follow the steps below:

  • In your Okta Admin Console’s menu, go to Applications
  • Select the “hello-world” application
  • Click on the General tab

You should see both values inside the Client Credentials area.

Your {yourOktaDomain} will be visible in your Okta dashboard, just click on Dashboard in the menu. You will see the Org URL in the right upper corner.

The last step is to modify your greet endpoint to pull the name from the authenticated user. Go to the GreetController class and apply the following changes:

package com.okta.controller

import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.security.web.bind.annotation.AuthenticationPrincipal
import org.springframework.security.oauth2.core.oidc.user.OidcUser

@RestController
class GreetController {

   @GetMapping("/greet")
   fun greet(@AuthenticationPrincipal user: OidcUser): String {
       val capitalizedName = user.givenName.capitalize()
       return "Hello, $capitalizedName!"
   }

   fun String.capitalize(): String {
       when {
           this.isEmpty() -> return this
           this.length == 1 -> return this.toUpperCase()
           else -> return this[0].toTitleCase() + this.substring(1).toLowerCase()
       }
   }
}

The main difference here is that you are not receiving the user as a parameter anymore. Since you annotated the function with AuthenticationPrincipal, Spring knows that you want to retrieve the current user and will do it automatically.

That’s it! You now have an application with secure authentication out of the box. Go to http://localhost:8080/greet. and you should be redirected to the Okta’s login page:

Once the user enters their username and password they’ll be redirected to your greeting page again. In my case, I see the following:

 Hello, Daniel!

Congratulations! You just finished your first app written in Kotlin. You also took advantage of the JVM ecosystem by adding authentication in a simple, secure way. Take a look at the final code on GitHub.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

☞ Angular 7 + Spring Boot CRUD Example

☞ Angular 8 + Spring Boot 2.2: Build a CRUD App Today! 

☞ Top 5 Kotlin Features That Every Android App Developer Must Know

☞ Java Vs. Kotlin: Which One Will Be the Best in 2019?



Originally published by Daniel Pereira at https://developer.okta.com