Thymeleaf in IntelliJ: cannot resolve variables

Intellij Not Recognizing Model Variables in HTML. How to resolve model variables. I don’t get any idea for this issue.

Here is my Controller

@Controller 
public void someController {
  @RequestMapping("/")
  public String someMethod() {
    model.addAttribute("message", "message");
    return "index";
}

And here is my “index.html”

<p th:text="${message}"> </p>

and of course in my html tag i’m using thymeleaf :

<html xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/html">

the problem is in myth:text="${message}" i see red squiggly lines saying that “Cannot resolve “message” variable…”

Solution:

I’ve been ignoring that issue for as long as I’ve been using Thymeleaf. Even though it shows the squiggly lines, it should still work when you run the application.

IntelliJ would almost have to compile the code in the background to be able to automatically (and accurately, since you could have multiple methods who uses the same template) resolve the variables.

I’ve never given a tip like this, but after reading your comment that you just find the wiggly line annoying, I decided to suggest it anyways:

Disable the tip.

configure inspections

disable expression variables validation

I feel absolutely barbaric for posting this answer, forgive me SO

About special characters in java

In my application about World of Warcraft mythic dungeons i have to do some queries into the raiderio Public API. I having a big issue when the players name it’s something like this :

https://raider.io/api/v1/characters/profile?region=US&realm=https://raider.io/characters/us/zuljin/Børomìr&name=&fields=mythic_plus_best_runs%3Aall

this name : Børomìr

In the API this query doesn’t work because it manages special characters like this:

https://raider.io/api/v1/characters/profile?region=us&realm=zuljin&name=B%C3%B8rom%C3%ACr&fields=mythic_plus_best_runs%3Aall

becomes this : B%C3%B8rom%C3%ACr

where:

ø becomes %C3%B8

ì becomes %C3%AC

which tool do i need to generate this conversion in java?

Heres is the URL request code:

            String body = "";
            URL url = new URL("https://raider.io/api/v1/characters/profile?region="+region.toString()+"&realm="+realm+"&name="+name+"&fields=mythic_plus_best_runs%3Aall");
            System.out.println(url.toString());
            URLConnection uc = url.openConnection();
            uc.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
            InputStream in = uc.getInputStream();
            String encoding = uc.getContentEncoding();
            encoding = encoding == null ? "UTF-8"
                    // "windows-1251"
                    // "Cp1251"
                    : encoding;
            body = IOUtils.toString(in, encoding);

Solution:

You would use Java’s URLEncoder As in URLEncoder.encode("Børomìr", "UTF-8");

Finding the least double greater than in Java

Is there a built-in method to find the next greatest double number in Java?

When writing a test, I sometimes want to verify that an operation succeeds for x but fails for values greater than x. One way to do this is to show that the operations fails for x + eps. But eps must be chosen taking into account the value of x to avoid problems like 180 + 1e-15 == 180.

To automatically select eps, I’d like to find the smallest representable number greater than x. I was surprised that I didn’t find a standard library method, so I wrote the following:

public static double nextDouble(double d) {
    if (d < 0) {
        return -prevDouble(Math.abs(d));
    } else {
        return Double.longBitsToDouble(Double.doubleToLongBits(d) + 1);
    }
}

public static double prevDouble(double d) {
    if (d < 0) {
        return -nextDouble(-d);
    } else {
        return Double.longBitsToDouble(Double.doubleToLongBits(d) - 1);
    }
}

Should I use these custom functions, or is there a built-in approach available?

Solution:

There is the Math.nextUp method.

Returns the floating-point value adjacent to d in the direction of positive infinity.

There are overloads to take double and float. There are also corresponding Math.nextDown methods.

Function .contains() not working in Groovy on expected way

I am trying to check if number is member of list by using Groovy programming language.

I have this piece of code:

List<Long> list = [1, 2, 3]
Long number = 3

println(list.contains(number))​

Expected output is true, but the result I get is false.

Does anybody have an explanation?

Solution:

Generic type parameters don’t feature at runtime. Check this:

List<Long> list = [1, 2, 3]
list.each{println it.getClass()}

Which prints:

class java.lang.Integer
class java.lang.Integer
class java.lang.Integer

The true confusion is introduced by the bizarre behavior difference between .equals and == implementations:

Long.valueOf(3).equals(Integer.valueOf(3))
===> false
Long.valueOf(3) == Integer.valueOf(3)
===> true

List.contains seems to be using .equals, which checks the class of the parameter, thus explaining why forcing element types to Long resolves the problem.

So, in the midst of this uncertainty, I think the only sure thing is that Groovy’s == execution performs the most intuitive and predictable comparison. So I’d change the check to:

boolean contains = list.grep{it == 3L} //sets value to true if matches at least 1

It helps when one doesn’t have to be cognizant of data types linked to literals:

def ints = [1, 2, 3]
def longs = [1L, 2L, 3L]

boolean found1 = ints.grep{it == 3L}
boolean found2 = ints.grep{it == 3}
boolean found3 = longs.grep{it == 3L}
boolean found4 = longs.grep{it == 3}

println found1
println found2
println found3
println found4

Which works as anyone would want:

true
true
true
true

Why can I collect a parallel stream to an arbitrarily large array but not a sequential stream?

From answering this question, I ran into a peculiar feature. The following code works as I assumed it would (the first two values within the existing array would be overridden):

Integer[] newArray = Stream.of(7, 8)
                           .parallel()
                           .toArray(i -> new Integer[] {1, 2, 3, 4, 5, 6});

System.out.println(Arrays.toString(newArray));

Output:

[7, 8, 3, 4, 5, 6]

However, attempting this with a sequential stream throws an IllegalStateException:

Integer[] newArray = Stream.of(7, 8)
                           .toArray(i -> new Integer[] {1, 2, 3, 4, 5, 6});

System.out.println(Arrays.toString(newArray));

Output:

Exception in thread "main" java.lang.IllegalStateException: Begin size 2 is not equal to fixed size 6
    at java.base/java.util.stream.Nodes$FixedNodeBuilder.begin(Nodes.java:1222)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:483)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:550)
    at java.base/java.util.stream.AbstractPipeline.evaluateToArrayNode(AbstractPipeline.java:260)
    at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:517)
    at test/test.Test.main(Test.java:30)

I’m curious as to why the sequential stream does not overwrite elements of the array as the parallel stream does. I searched around a bit and was not able to find documentation regarding this, but I assume it exists somewhere.

Solution:

The generator function is required to produce “a new array of the desired type and the provided length.” If you don’t comply with the spec, behavior is undefined.

Why can’t this static inner class call a non-static method on its outer class?

I’m currently reading Effective Java by Joshua Bloch and I love it! But on page 112 (Item 24) Bloch writes:

A static member class is the simplest kind of nested class. It is best
thought of as an ordinary class that happens to be declared inside
another class and has access to all of the enclosing class’s members,
even those declared private.

And that really confuses me. I would rather say:

A static member class is the simplest kind of nested class. It is best
thought of as an ordinary class that happens to be declared inside
another class and has access to all of the enclosing class’s static members,
even those declared private.

Here is a snippet that illustrates my understanding of the quote:

public class OuterClass {

    public void printMessage(String message) {
        System.out.println(message);
    }

    private static class InnerClass {

        public void sayHello() {
            printMessage("Hello world!"); //error: Cannot make a static reference to the non-static method printMessage(String)
        }

    }
}

You can see that InnerClass’s sayHello method does not have access to OuterClass’s printMessage method as it is declared in a static inner class while the printMessage method is an instance method. It looks like the author suggests that a static member class can access nonstatic fields of the enclosing class. I am convinced that I have misunderstood something in his last sentence but I cannot figure out what. Any help will be appreciated!

edit: I changed the visibility of the two methods because it is irrelevant to my question. I’m interested in static members, not private members.

Solution:

Just because InnerClass is static, doesn’t mean it couldn’t obtain a reference to an instance of OuterClass through other means, most commonly as a parameter, e.g.

public class OuterClass {

    private void printMessage(String message) {
        System.out.println(message);
    }

    private static class InnerClass {

        private void sayHello(OuterClass outer) {
            outer.printMessage("Hello world!"); // allowed
        }

    }
}

If InnerClass had not been nested inside OuterClass, it would not have had access to the private method.

public class OuterClass {

    private void printMessage(String message) {
        System.out.println(message);
    }

}

class InnerClass {

    private void sayHello(OuterClass outer) {
        outer.printMessage("Hello world!"); // ERROR: The method printMessage(String) from the type OuterClass is not visible
    }

}

Is there @JsonView equivalent in ASP.NET Web API

I have much more experience in Spring and Java, but now I am working on ASP.NET Web API project.

So in Spring there is @JsonView annotation with which I can annotate my DTOs, so I could select which data I will show through REST. And I find that very useful. But I cannot find any equivalent in ASP.NET. So I would need to create DTO for every special usecase.

So for example in Java if I have UserEntity that contains information about users. Some information can be seen publicly and some can be seen only by admins. The siple solution could be this

public class UserEntity {
  @JsonView(Views.Public.class)
  @JsonProperty("ID")
  private Integer id;

  @JsonView(Views.Public.class)
  private String name;

  @JsonView(Views.Admin.class)
  @JsonFormat(
  shape = JsonFormat.Shape.STRING, 
  pattern = "dd-MM-yyyy hh:mm:ss")
  private Date dateOfBirth;

  @JsonView(Views.Admin.class)
  private String email;

  @JsonIgnore
  private String password;
  private Integer version;
}

So in this case for equivalent functionality in ASP.NET I would need to create 2 DTOs. One for user that can be seen publicly and one for user that can be seen only by admin.

public class PublicUserDto {

  public int ID {get; set;}

  public String Name {get; set;}

}

public class AdminUserDto {

  public int ID {get; set;}

  public String Name {get; set;}

  public DateTime DateOfBirth {get; set;}

  public string Email {get; set;}
}

Is there any better solution? Is there some mechanism that I can use to create view over my data in ASP.NET Web API?

Solution:

JSON.NET has something called Conditional Property Initialization. You can write a method with the following format:

public bool ShouldSerialize[YourPropertyName]() => someBoolCondition;

JSON.NET will call that method to determine if that property should be serialized or not. So you could have something like:

public DateTime DateOfBirth {get; set;}

public bool ShouldSerializeDateOfBirth() => isAdmin;

It’s not as pretty as JsonView but it should do the job.

Does java.util.HashMap.containsKey(Object key) implementation violate java.util.Map.containsKey(Object key) documentation?

java.util.Map.containsKey(Object key) documentation says:
@throws ClassCastException if the key is of an inappropriate type for this map.

The java.util.HashMap.containsKey(Object key) implementation does not say anything about it.

My problem:

If i create a Map<String,String> map = new HashMap<>(); and call the containsKey method with an Integer the value is hashed (as a String) but the method does not throw an Exception.

Btw: The hash of 4 differs from the hash of “4”.

Is this really the intended behavior?

THX in advance!

Solution:

This seems to be an optional restriction, not applied in HashMap.

As stated in API for containsKey:

[…]

Throws:
ClassCastException – if the key is of an inappropriate type for this map (optional)

Note the “optional”, and see linked documentation:

Some collection implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the collection may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as “optional” in the specification for this interface.

Java: Can a child thread outlive the main thread

I came to know in Java that: children threads won’t outlive the main thread, but, seemingly, the behavior of this application shows different results.

The child thread keeps working while the main one has done working!

Here is what I do:

public class Main {

public static void main(String[] args) {

    Thread t = Thread.currentThread();

    // Starting a new child thread here
    new NewThread();

    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println("\n This is the last thing in the main Thread!");


    }
}

class NewThread implements Runnable {

private Thread t;

NewThread(){
    t= new Thread(this,"My New Thread");
    t.start();
}

public void run(){
    for (int i = 0; i <40; i++) {
        try {
            Thread.sleep(4000);
            System.out.printf("Second thread printout!\n");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

}

What do I fail to understand here … Or that’s a new feature in Java starting from JDK 9?

Solution:

According to the documentation of Thread#setDaemon:

The Java Virtual Machine exits when the only threads running are all daemon threads.

Your child thread is not a daemon thread, so the JVM does not exit even though the main thread no longer runs. If you call t.setDaemon(true); in the constructor of NewThread, then the JVM will exit after the main thread has finished executing.

Using advanced for loop instead of for loop

I am a bit confused and I would need some clarification. Not too sure if I’m on the right track, hence this thread.

Here is my code that I want to decipher into advanced foreach loop.

    int[] arrayA = {3, 35, 2, 1, 45, 92, 83, 114};
    int[] arrayB = {4, 83, 5, 9, 114, 3, 7, 1};
    int n = arrayA.length;
    int m = arrayB.length;
    int[] arrayC = new int[n + m];
    int k = 0;

    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < m; j++)
        {
            if(arrayB[j] == arrayA[i])
            {
                arrayC[k++] = arrayA[i];
            }
        }
    }
    for(int i=0; i<l;i++)
        System.out.print(arrayC[i] + " ");
    System.out.println();

So far this is the point where I am stuck at:

    int[] a = {3, 8, 2, 4, 5, 1, 6};
    int[] b = {4, 7, 9, 8, 2};
    int[] c = new int[a.length + b.length];
    int k = 0;
    for(int i : a)
    {
        for(int j : b)
        {
            if(a[i] == b[j]) 
            {
                c[k++] = a[i];
            }
        }
        //System.out.println(c[i]);
    }
    for(int i=0; i<c.length;i++)
        System.out.print(c[i] + " ");
    System.out.println();
}

Solution:

You are almost there

for(int i : a)
{
    for(int j : b)
    {
        if(i == j) 
        {
            c[k++] = i;
        }
    }
}

With for(int i : a) access the elements in the array a using i.
If a is {3, 8, 2, 4, 5, 1, 6}, then i would be 3,8,2,.. on each iteration and you shouldn’t use that to index into the original array. If you do, you would get either a wrong number or a ArrayIndexOutOfBoundsException


Since you want to pick the numbers that are present in both the arrays, the length of array c can be max(a.length, b.length). So, int[] c = new int[Math.max(a.length, b.length)]; will suffice.

If you want to truncate the 0s at the end, you can do

c = Arrays.copyOf(c, k);

This will return a new array containing only the first k elements of c.