Categories
discuss

When and why would you use Java’s Supplier and Consumer interfaces?

As a non-Java programmer learning Java, I am reading about Supplier and Consumer interfaces at the moment. And I can’t wrap my head around their usage and meaning.

When and why you would use these interfaces? Can someone give me a simple layperson example of this?

I’m finding the Doc examples not succinct enough for my understanding.

Answer

This is Supplier:

public Integer getInteger() {
    return new Random().nextInt();
}

This is Consumer:

public void sum(Integer a, Integer b) {
    System.out.println(a + b);
}

So in layman terms, a supplier is a method that returns some value (as in its return value). Whereas, a consumer is a method that consumes some value (as in method argument), and does some operations on them.

Those will transform to something like these:

// new operator itself is a supplier, of the reference to the newly created object
Supplier<List<String>> listSupplier = ArrayList::new;
Consumer<String> printConsumer = a1 -> System.out.println(a1);
BiConsumer<Integer, Integer> sumConsumer = (a1, a2) -> System.out.println(a1 + a2);

As for usage, the very basic example would be: Stream#forEach(Consumer) method. It takes a Consumer, which consumes the element from the stream you’re iterating upon, and performs some action on each of them. Probably print them.

Consumer<String> stringConsumer = (s) -> System.out.println(s.length());
Arrays.asList("ab", "abc", "a", "abcd").stream().forEach(stringConsumer);
Categories
discuss

Reading email from gmail is not working

I am using Java Mail API along with the following code to read email from my gmail account.

import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;

public class CheckMails {

   public static void check(String host, String storeType, String user,
      String password) 
   {
      try {
      Properties properties = new Properties();

      properties.put("mail.pop3.host", host);
      properties.put("mail.pop3.port", "995");
      properties.put("mail.pop3.starttls.enable", "true");
      Session emailSession = Session.getDefaultInstance(properties);

      //create the POP3 store object and connect with the pop server
      Store store = emailSession.getStore("pop3s");

      store.connect(host, user, password);

      //create the folder object and open it
      Folder emailFolder = store.getFolder("INBOX");
      emailFolder.open(Folder.READ_ONLY);

      // retrieve the messages from the folder in an array and print it
      Message[] messages = emailFolder.getMessages();
      System.out.println("messages.length---" + messages.length);

      for (int i = 0, n = messages.length; i < n; i++) {
         Message message = messages[i];
         System.out.println("---------------------------------");
         System.out.println("Email Number " + (i + 1));
         System.out.println("Subject: " + message.getSubject());
         System.out.println("From: " + message.getFrom()[0]);
         System.out.println("Text: " + message.getContent().toString());

      }

      //close the store and folder objects
      emailFolder.close(false);
      store.close();

      } catch (NoSuchProviderException e) {
         e.printStackTrace();
      } catch (MessagingException e) {
         e.printStackTrace();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
   public static void main(String[] args) {
      String host = "pop.gmail.com";// change accordingly
      String mailStoreType = "pop3";
      String username = "myemai@gmail.com";// change accordingly
      String password = "*******";// change accordingly

      check(host, mailStoreType, username, password);

   }

}

But I am getting the following exceptions:

javax.mail.AuthenticationFailedException: [AUTH] Web login required: `    https://support.google.com/mail/bin/answer.py?answer=78754`
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:209)
at javax.mail.Service.connect(Service.java:364)
at javax.mail.Service.connect(Service.java:245)
at CheckMails.check(CheckMails.java:26)
at CheckMails.main(CheckMails.java:66)

But i have recieved an email from gmail in my inbox which is saying that “We recently blocked-in a sign in attempt to your Google Account”. How can i make the program to work properly?

Answer

Change Your emailSession variable with

Session emailSession = Session.getInstance(props, new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(userName, password);
    }
});

As said by Gmail

Some apps and devices use less secure sign-in technology, which makes your account more vulnerable. You can turn off access for these apps, which we recommend, or turn on access if you want to use them despite the risks. Learn more

Just click below link and disable Gmail security settings.It will work.

Disable Security settings

Here is a nice article about Password Authentication in Java Mail Api

Categories
discuss

Difference between Array.apply(null, Array(x) ) and Array(x)

What exactly is the difference between:

Array(3)
// and
Array.apply(null, Array(3) )

The first returns [undefined x 3] while the second returns [undefined, undefined, undefined]. The second is chainable through Array.prototype.functions such as .map, but the first isn’t. Why?

Answer

There is a difference, a quite significant one.

The Array constructor either accepts one single number, giving the lenght of the array, and an array with “empty” indices is created, or more correctly the length is set but the array doesn’t really contain anything

Array(3); // creates [], with a length of 3

When calling the array constructor with a number as the only argument, you create an array that is empty, and that can’t be iterated with the usual Array methods.

Or… the Array constructor accepts several arguments, whereas an array is created where each argument is a value in the array

Array(1,2,3); // creates an array [1,2,3] etc.

When you call this

Array.apply(null, Array(3) )

It get’s a little more interesting.

apply accepts the this value as the first argument, and as it’s not useful here, it’s set to null

The interesting part is the second argument, where an empty array is being passed in.
As apply accepts an array it would be like calling

Array(undefined, undefined, undefined);

and that creates an array with three indices that’s not empty, but have the value actually set to undefined, which is why it can be iterated over.

TL;DR
The main difference is that Array(3) creates an array with three indices that are empty. In fact, they don’t really exist, the array just have a length of 3.

Passing in such an array with empty indices to the Array constructor using apply is the same as doing Array(undefined, undefined, undefined);, which creates an array with three undefined indices, and undefined is in fact a value, so it’s not empty like in the first example.

Array methods like map() can only iterate over actual values, not empty indices.

Categories
discuss

No longer able to use ddescribe or iit

I used to be able to use ddescribe and iit to have jasmine/karma run just a specific test or set of tests. However, now it no longer works, and I get this error: (or a similar one for iit).

INFO [karma]: Karma v0.12.31 server started at http://localhost:8081/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.8 (Windows 7)]: Connected on socket jIMgciNEN5VXBdZOhDz2 with id 78471739
PhantomJS 1.9.8 (Windows 7) ERROR
  ReferenceError: Can't find variable: ddescribe
  at /.../test.js:146

I am running: karma 0.12.28, jasmine 2.2.0, karma-jasmine: 0.3.5, karma-phantomjs-launcher: 0.1.4

Here is what the test file basically looks like:

'use strict';

ddescribe('MyController', function() {
    it('should do xyz', function() {
       ...
    });
});

Any ideas at all? Is there some definition or configuration change that I have missed so that now ddescribe is no longer defined?

Answer

Ok, I finally found the bug report: https://github.com/karma-runner/karma-jasmine/issues/73

Apparently they have changed from using ddescribe and iit to using fdescribe and fit for ‘focused’ testing.

Categories
discuss

How do you set a value in the IntelliJ Registry?

How can I override a value that is used internally in IntelliJ, for example this expression:

Registry.intValue("a.b.c")

I can access the registry Registry.getInstance() but it doesn’t allow updating any key/value pairs.

Any tips?

Answer

Press CtrlAltShift/ and select “Registry” from the menu that appears.

(If that keyboard shortcut is not working for you, use your configured keyboard shortcut for Find Action. On Mac by default it is Shift++A, on Windows it is Shift+Ctrl+A (docs). Then type “Registry” and click or hit enter.)

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..