-2

I'm trying to implement a CSRF token, but all the info is programmed with Java 8+ version, so what I need is some help rewriting this line in Java 6/7:

tokenCookie = Arrays.stream(httpReq.getCookies()).filter(c -> c.getName().equals(csrfCookieExpectedName)).findFirst().orElse(null);

Actually from that line I'm only getting the error in:

c -> c.getName().equals(csrfCookieExpectedName)

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Martinez
  • 1
  • 1
  • 7
    Hello and welcome. Considering that it'd basically translate to a loop with an if, have you at least tried on your own before asking here? Please read [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Federico klez Culloca Apr 19 '22 at 09:21
  • 4
    Why do you ask for “Java 7” in the title but tag the question with `java-6`? – Holger Apr 19 '22 at 10:00

2 Answers2

1

In addition to @GIO's answer, you could try for-each loop like this:

public Cookie getExpectedCookieName(Cookie[] cookies) {
    for (Cookie c : cookies) {
        if (c.getName().equals(csrfCookiesExpectedName)) {
            return c;
        }
    }
    return null;
}

and call it like this : tokenCookie = getExpectedCookieName(httpReq.getCookies());

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Jacouille
  • 951
  • 8
  • 14
  • 1
    Well I can't return `c`, it's a cookie not a String, I supose I'll have to do `public Cookie getExpectedCookieName`, and also `tokenCookie = getExpectedCookieName(httpReq.getCookies(), csrfCookieExpectedName);`, but thank I will upvote you – Martinez Apr 19 '22 at 09:53
  • You are right, but i tried to stay as close as possible to your stream, which return ```Optional```, to fix this you could return ```c.getName()``` instead. You could also use code without putting it in a method. – Jacouille Apr 19 '22 at 09:56
  • 1
    @jacouille the original code one-liner returns a `Cookie` (because of that final `orElse(null)`), not an `Optional`. My edit should have fixed that by the way. – Federico klez Culloca Apr 19 '22 at 09:59
-1

This is can be converted using a pretty simple for loop. What you need is basically to check every single element of the array, find the first matching element that you need an exit from the loop, if no element matches then simply return null;

public Cookie getExpectedCookieName() {

   for (int i = 0; i < httpReq.getCookies().length; i++) {
       if(httpReq.getCookies()[i].getName().equals(csrfCookiesExpectedName)) {
           return httpReq.getCookies()[i];
       }
   }

   return null;
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
grigyan
  • 71
  • 7