git with IntelliJ IDEA: Could not read from remote repository

Since a few weeks, I'm not able to pull or push from or to the remote repository. I thought it happend when upgrading to IntelliJ IDEA 14, but I can reproduce the problem with IDEA 13.1.5 as well.

Since a few weeks, I'm not able to pull or push from or to the remote repository. I thought it happend when upgrading to IntelliJ IDEA 14, but I can reproduce the problem with IDEA 13.1.5 as well.

The tooltip says "Fetch failed fatal: Could not read from remote repository."

and the exception in the Version Control tab reads

14:02:37.737: cd C:\dev\project
14:02:37.737: git -c core.quotepath=false fetch origin --progress --prune
java.io.IOException: Padding in RSA public key!
    at com.trilead.ssh2.signature.RSASHA1Verify.decodeSSHRSAPublicKey(RSASHA1Verify.java:37)
    at com.trilead.ssh2.KnownHosts.addHostkey(KnownHosts.java:98)
    at com.trilead.ssh2.KnownHosts.initialize(KnownHosts.java:414)
    at com.trilead.ssh2.KnownHosts.initialize(KnownHosts.java:440)
    at com.trilead.ssh2.KnownHosts.addHostkeys(KnownHosts.java:137)
    at org.jetbrains.git4idea.ssh.SSHMain.configureKnownHosts(SSHMain.java:462)
    at org.jetbrains.git4idea.ssh.SSHMain.start(SSHMain.java:155)
    at org.jetbrains.git4idea.ssh.SSHMain.main(SSHMain.java:137)
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.

Using the built-in terminal of IntelliJ, executing git -c core.quotepath=false fetch origin --progress --prune, it works just as it should.

According to the stacktrace, there seems to be a problem with my KnownHosts, so I deleted our git server from ~/.ssh/known_hosts, hoping IntelliJ would insert it again. But the problem still appears when updating via the UI, and there is no new entry written in known_hosts; thinking about some caching of the file, I restarted IntelliJ, without success.

When doing another git fetch from the terminal, now I'm getting asked if I want to permanently add the server. After that, it has been written to known_hosts again, but IntelliJ still won't let me update my project.

I haven't found anything about this behavior online, so I guess it's not a known bug with the new IntelliJ version. Nevertheless, I updated to 14.0.2, but the problem still exists.

IntelliJ is configured to use the built-in SSH executable.

Does anybody have a clue what could be the problem here?

An Introduction to Refactoring with IntelliJ IDEA

An Introduction to Refactoring with IntelliJ IDEA

In this tutorial, we're going to focus on IntelliJ IDEA, the JetBrains Java code editor. We'll see a few features offered by the editor to refactoring with IntelliJ IDEA.

In this tutorial, we're going to focus on IntelliJ IDEA, the JetBrains Java code editor. We'll see a few features offered by the editor to refactoring with IntelliJ IDEA.

1. Overview

Keeping the code tidy is not always easy. Fortunately for us, our IDEs are pretty smart nowadays and can help us in achieving this. In this tutorial, we’re going to focus on IntelliJ IDEA, the **JetBrains **Java code editor.

We’ll see a few features offered by the editor to refactor code, from renaming variables to changing a method signature.

2. Renaming

2.1. Basic Renaming

First, let’s start with the basics: renaming. IntelliJ offers us the possibility to rename different elements of our code: types, variables, methods, and even packages.

To rename an element, we need to follow these steps:

  • Right-click the element
  • Trigger the Refactor > Rename option
  • Type the new element name
  • Press Enter

By the way, we can replace the first two steps by selecting the element and pressing Shift + F6.

When triggered, the renaming action will search across the code for every usage of the element and then change them with the provided value.

Let’s imagine a SimpleClass class with a poorly named addition method, someAdditionMethod, called in the main method:

public class SimpleClass {
    public static void main(String[] args) {
        new SimpleClass().someAdditionMethod(1, 2);
    }

    public int someAdditionMethod(int a, int b) {
        return a + b;
    }
}

Thus, if we choose to rename this method into add, IntelliJ will produce the following code:

public class SimpleClass() {
    public static void main(String[] args) {
        new SimpleClass().add(1, 2);
    }

    public int add(int a, int b) {
        return a + b;
    }
}

2.2. Advanced Renaming

However, IntelliJ does more than searching for code usages of our elements and rename them. As a matter of fact, a few more options are available. IntelliJ can also search for occurrences in comments and strings, and even in files that don’t contain source code. As for parameters, it can rename them in the class hierarchy in case of overridden methods.

Those options are available by hitting Shift + F6 once more before renaming our element and a popup will appear:

The Search in comments and strings option is available for any renaming. As for the Search for text occurrences option, it’s not available for method parameters and local variables. Finally, the Rename parameters in hierarchy option is available for method parameters only.

So, if any match is found with one of those two options, IntelliJ will show them and offer us the possibility to opt out of some of the changes (say, in case it matches something unrelated with our renaming).

Let’s add some Javadoc to our method, and then rename its first parameter, a:

/**
  * Adds a and b
  * @param a the first number
  * @param b the second number
  */
public int add(int a, int b) {...}

By checking the first option in the confirmation pop-up, IntelliJ matches any mention of the parameters in the Javadoc comment of the method and offers to rename them as well:

/**
  * Adds firstNumber and b
  * @param firstNumber the first number
  * @param b the second number
  */
public int add(int firstNumber, int b) {...}

Finally, we must note that IntelliJ is smart and searches mostly for usages in the scope of the renamed element. In our case, that would mean that a comment situated outside the method (except for the Javadoc) and containing a mention to a would not have been considered for renaming.

3. Extracting

Now, let’s talk about extraction. Extraction enables us to grab a piece of code and put it into a variable, a method or even a class. IntelliJ handles this pretty smartly as it searches for similar pieces of code and offers to extract them in the same way.

So, in this section, we’ll learn how to leverage the extraction feature offered by IntelliJ.

3.1. Variables

First, let’s start with variables extraction. That means local variables, parameters, fields, and constants. To extract a variable, we must follow these steps:

  • Select an expression that fits in a variable
  • Right-click the selected area
  • Trigger the Refactor > Extract > Variable/Parameter/Field/Constant option
  • Choose between the Replace this occurrence only or Replace all x occurrences options, if proposed
  • Enter a name for the extracted expression (if the chosen one doesn’t suit us)
  • Press Enter

As for renaming, it’s possible to use keyboard shortcuts instead of using the menu. The default shortcuts are, respectively, Ctrl + Alt + V, Ctrl + Alt + P, Ctrl + Alt + F and Ctrl + Alt + C.

IntelliJ will try to guess a name for our extracted expression, based on what the expression returns. If it doesn’t match our needs, we’re free to change it before confirming the extraction.

Let’s illustrate with an example. We could imagine adding a method to our SimpleClass class telling us if the current date is between two given dates:

public static boolean isNowBetween(LocalDate startingDate, LocalDate endingDate) {
    return LocalDate.now().isAfter(startingDate) && LocalDate.now().isBefore(endingDate);
}

Let’s say we want to change our implementation because we use LocalDate.now() twice and we would like to make sure it has the exact same value in both evaluations. Let’s just select the expression and extract it in a local variable, now:

Then, our LocalDate.now() call is captured in a local variable:

public static boolean isNowBetween(LocalDate startingDate, LocalDate endingDate) {
    LocalDate now = LocalDate.now();
    return now.isAfter(startingDate) && now.isBefore(endingDate);
}

By checking the Replace all option, we made sure that both expressions have been replaced at once.

3.2. Methods

Let’s now check how to extract methods using IntelliJ:

  • Select the expression or lines of code fitting the method we want to create
  • Right-click the selected area
  • Trigger the Refactor > Extract > Method option
  • Type in the method information: its name, its visibility and its parameters
  • Press Enter

Hitting Ctrl + Alt + M after selecting the method body works as well.

Let’s reuse our previous example and say we want to have a method checking if any date is between to other dates. Then, we would just have to select our last line in the isNowBetween method and trigger the method extraction feature.

In the opened window, we can see that IntelliJ has already spotted the three needed parameters: startingDate, endingDate and now. As we want this method to be as generic as possible, we rename the now parameter into date. And for cohesion purposes, we place it as the first parameter.

Finally, we give our method a name, isDateBetween, and finalize the extraction process:

We would then obtain the following code:

public static boolean isNowBetween(LocalDate startingDate, LocalDate endingDate) {
    LocalDate now = LocalDate.now();
    return isDateBetween(now, startingDate, endingDate);
}

private static boolean isDateBetween(LocalDate date, LocalDate startingDate, LocalDate endingDate) {
    return date.isBefore(endingDate) && date.isAfter(startingDate);
}

As we can see, the action triggered the creation of the new isDateBetween method, which is also called in the isNowBetween method. The method is private, by default. Of course, this could have been changed using the visibility option.

3.3. Classes

After all that, we might want to get our date-related methods in a specific class, focused on dates management, let’s say: DateUtils. Again, this is pretty easy:

  • Right-click in the class that has our elements we want to move
  • Trigger the Refactor > Extract > Delegate option
  • Type in the class information: its name, its package, the elements to delegate, the visibility of those elements
  • Press Enter

By default, no keyboard shortcut is available for this feature.

Let’s say, before triggering the feature, that we call our date-related methods in the main method:

isNowBetween(LocalDate.MIN, LocalDate.MAX);
isDateBetween(LocalDate.of(2019, 1, 1), LocalDate.MIN, LocalDate.MAX);

Then we delegate those two methods to a DateUtils class using the delegate option:

Trigger the feature would produce the following code:

public class DateUtils {
    public static boolean isNowBetween(LocalDate startingDate, LocalDate endingDate) {
        LocalDate now = LocalDate.now();
        return isDateBetween(now, startingDate, endingDate);
    }

    public static boolean isDateBetween(LocalDate date, LocalDate startingDate, LocalDate endingDate) {
        return date.isBefore(endingDate) && date.isAfter(startingDate);
    }
}

We can see that the isDateBetween method has been made public. That is the result of the visibility option, that is set to escalate by default. Escalate means that visibility will be changed in order toensure current calls to the delegated elements are still compiling.

In our case, isDateBetween is used in the _main _method of SimpleClass:

DateUtils.isNowBetween(LocalDate.MIN, LocalDate.MAX);
DateUtils.isDateBetween(LocalDate.of(2019, 1, 1), LocalDate.MIN, LocalDate.MAX);

Thus, when moving the method it’s necessary to make it not private.

However, it’s possible to give specific visibility to our elements by selecting the other options.

4. Inlining

Now that we covered extraction, let’s talk about its counterpart: inlining. Inlining is all about taking a code element and replace it with what it’s made of. For a variable, this would be the expression it has been assigned. For a method, it would be its body.

In order to inline an element, we must right-click this element – either its definition or a reference to it – and trigger the Refactor > Inline option. We can also achieve this by selecting the element and hitting the Ctrl + Alt + N keys.

At this point, IntelliJ will offer us multiple options, whether we wish to inline a variable or a method, whether we selected a definition or a reference. These options are:

  • Inline all the references and remove the element
  • Inline all the references, but keep the element
  • Only inline the selected reference and keep the element

Let’s take our isNowBetween method and get rid of the now variable, which now seems a bit overkill:

By inlining this variable, we would obtain the following result:

public static boolean isNowBetween(LocalDate startingDate, LocalDate endingDate) {
    return isDateBetween(LocalDate.now(), startingDate, endingDate);
}

In our case, the only option was to remove all the references and remove the element. But let’s imagine we also want to get rid of the isDateBetween call and choose to inline it. Then, IntelliJ would offer us the three possibilities we spoke about before:

Choosing the first one would replace all calls with the method body and delete the method. As for the second one, it would replace all calls with the method body but keep the method. And finally, the last one would only replace the current call with the method body:

public class DateUtils {
    public static boolean isNowBetween(LocalDate startingDate, LocalDate endingDate) {
        LocalDate date = LocalDate.now();
        return date.isBefore(endingDate) && date.isAfter(startingDate);
    }

    public static boolean isDateBetween(LocalDate date, LocalDate startingDate, LocalDate endingDate) {
        return date.isBefore(endingDate) && date.isAfter(startingDate);
    }
}

Our main method in the SimpleClass remains untouched as well.

5. Moving

Earlier, we saw how to create a new class and delegate some of our code elements to it. But there are times **we might want to **delegate a method to an existing class. That’s what this section is about.

In order to move an element, we must follow these steps:

  • Select the element to move
  • Right-click the element
  • Trigger the Refactor > Move option
  • Choose the recipient class and the method visibility
  • Press Enter

We can also achieve this by pressing F6 after selecting the element.

Let’s say we add a new method to our SimpleClass, isDateOutstide(), that will tell us if a date is situated outside an interval of dates:

public static boolean isDateOutside(LocalDate date, LocalDate startingDate, LocalDate endingDate) {
    return !DateUtils.isDateBetween(date, startingDate, endingDate);
}

We then realize that its place should be in our DateUtils class. So we decide to move it:

Our method is now in the DateUtils class. We can see that the reference to DateUtils inside the method has disappeared as it’s no longer needed:

public static boolean isDateOutside(LocalDate date, LocalDate startingDate, LocalDate endingDate) {
    return !isDateBetween(date, startingDate, endingDate);
}

The example we just did works well as it concerns a static method. However, in the case of an instance method, things are not so straight-forward.

If we want to move an instance method, IntelliJ will search for classes referenced in the fields of the current class and offer to move the method to one of those classes (provided they are ours to modify).

If no modifiable class is referenced in the fields, then IntelliJ proposes making the method static before moving it.

6. Changing a Method Signature

Finally, we’ll talk about a feature allowing us to change a method signature. The purpose of this feature is to manipulate every aspect of a method signature.

As usual, we must go through a few steps to trigger the feature:

  • Select the method to change
  • Right-click the method
  • Trigger the Refactor > Change signature option
  • Bring changes to the method signature
  • Press Enter

If we prefer to use keyboards shortcut, it’s possible to use Ctrl + F6 as well.

This feature will open a window very similar to the method extraction feature. And so we have the same possibilities that when we extract a method: changing its name, its visibility and also adding/removing parameters and fine-tuning them.

Let’s imagine we want to change our implementation of isDateBetween to either consider the date bounds as inclusive or exclusive. In order to do that we want to add a boolean parameter to our method:

By changing the method signature we can add this parameter, name it and give it a default value:

public static boolean isDateBetween(LocalDate date, LocalDate startingDate,
   LocalDate endingDate, boolean inclusive) {
    return date.isBefore(endingDate) && date.isAfter(startingDate);
}

After that, we just have to adapt the method body according to our needs.

If we wanted, we could have checked the Delegate via overloading method option in order to create another method with the parameter instead of modifying the current one.

7. Conclusion

In this article, we had the chance to deep dive into some of the refactoring features offered by IntelliJ. Of course, we didn’t cover all the possibilities as IntelliJ is a very powerful tool. To learn more about this editor, we can always refer to its documentation.

We saw a few things like how to rename our code elements and how to extract some behaviors into variables, methods or classes. We also learned how to inline some elements if we didn’t need them standing alone, move some code elsewhere or even fully change an existing method signature.

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