Sending email via Gmail SMTP in Java

Gradle

// https://mvnrepository.com/artifact/javax.mail/javax.mail-api
compile group: 'javax.mail', name: 'javax.mail-api', version: '1.6.0'

// https://mvnrepository.com/artifact/com.sun.mail/javax.mail
compile group: 'com.sun.mail', name: 'javax.mail', version: '1.6.0'

GMail via SSL

package com.mkyong.common;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMailSSL {
	public static void main(String[] args) {
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");

		Session session = Session.getDefaultInstance(props,
			new javax.mail.Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication("username","password");
				}
			});

		try {

			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress("[email protected]"));
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse("[email protected]"));
			message.setSubject("Testing Subject");
			message.setText("Dear Mail Crawler," +
					"\n\n No spam to my email, please!");

			Transport.send(message);

			System.out.println("Done");

		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
}

If you want to send HTML message :

message.setContent(someHtmlMessage, "text/html; charset=utf-8");

References
https://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
https://stackoverflow.com/questions/5068827/how-do-i-send-an-html-email
https://www.campaignmonitor.com/css/
https://stackoverflow.com/questions/16807758/java-lang-noclassdeffounderror-com-sun-mail-util-maillogger-for-junit-test-case
https://stackoverflow.com/questions/46663/how-can-i-send-an-email-by-java-application-using-gmail-yahoo-or-hotmail
https://developers.google.com/gmail/api/guides/sending

Set a timer in Android using Handler

Runnable:

private final int interval = 1000; // 1 Second
private Handler handler = new Handler();
private Runnable runnable = new Runnable(){
    public void run() {
        Toast.makeText(MyActivity.this, "C'Mom no hands!", Toast.LENGTH_SHORT).show();
    }
};
...
handler.postAtTime(runnable, System.currentTimeMillis()+interval);
handler.postDelayed(runnable, interval);

Message:

private final int EVENT1 = 1; 
private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {         
        case Event1:
            Toast.makeText(MyActivity.this, "Event 1", Toast.LENGTH_SHORT).show();
            break;

        default:
            Toast.makeText(MyActivity.this, "Unhandled", Toast.LENGTH_SHORT).show();
            break;
        }
    }
};

...

Message msg = handler.obtainMessage(EVENT1);
handler.sendMessageAtTime(msg, System.currentTimeMillis()+interval);
handler.sendMessageDelayed(msg, interval);

References
https://stackoverflow.com/questions/1877417/how-to-set-a-timer-in-android

View value of Password EditText while a button is pressed

yourButton.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {

               switch ( event.getAction() ) {
                case MotionEvent.ACTION_DOWN: 
                   editText.setInputType(InputType.TYPE_CLASS_TEXT);
                break;
                case MotionEvent.ACTION_UP: 
                    editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                break;
                }
                return true;
        }
    });

References
https://stackoverflow.com/questions/28185979/view-value-of-password-edittext-while-a-button-is-pressed

Transparent ProgressDialog with ProgressBar

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context="net.pupli.lastlab.PupliProgressDialogFragment">

    <android.support.constraint.Guideline
        android:id="@+id/guideline12"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.5" />

    <me.zhanghai.android.materialprogressbar.MaterialProgressBar
        android:id="@+id/progressbarMain"
        style="@style/Widget.MaterialProgressBar.ProgressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:indeterminate="true"
        app:layout_constraintEnd_toEndOf="@id/guideline12"
        app:layout_constraintStart_toStartOf="@id/guideline12"
        app:mpb_progressStyle="circular" />

</android.support.constraint.ConstraintLayout>
public class PupliProgressDialogFragment extends DialogFragment {

    MaterialProgressBar progressbarMain;

    public PupliProgressDialogFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_pupli_progress_dialog, container, false);

        // make dialogFragment transparent
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        // remove title of dialog fragment
        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);

        // set dialogFragment non cancelable, so users can not dismiss progressbar from screen
        this.setCancelable(false);

        progressbarMain = view.findViewById(R.id.progressbarMain);

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();

        // set width and hight of dialogFragment
        getDialog().getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
    }
}

Hash String via SHA-256 in Android

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.charset.StandardCharsets;
import java.math.BigInteger;

public class CryptoHash {
  public static void main( String[] args ) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance( "SHA-256" );
    String text = "Text to hash, cryptographically.";

    // Change this to UTF-16 if needed
    md.update( text.getBytes( StandardCharsets.UTF_8 ) );
    byte[] digest = md.digest();

    String hex = String.format( "%064x", new BigInteger( 1, digest ) );
    System.out.println( hex );
  }
}

References
https://stackoverflow.com/questions/3103652/hash-string-via-sha-256-in-java

Full screen background image in an activity

There are several ways you can do it.

Option 1:

Create different perfect images for different dpi and place them in related drawable folder. Then set

android:background=”@drawable/your_image

Option 2:

Add a single large image. Use FrameLayout. As a first child add an ImageView. Set the following in your ImageView.

android:src="@drawable/your_image"
android:scaleType = "centerCrop"

References
https://stackoverflow.com/questions/16135984/full-screen-background-image-in-an-activity

How to Use CommandLineRunner in Spring Boot Application

package com.therealdanvega;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
 
@Component
public class DataLoader implements CommandLineRunner {
 
    private final Logger logger = LoggerFactory.getLogger(DataLoader.class);
 
    @Override
    public void run(String... strings) throws Exception {
        logger.info("Loading data...");
 
    }
}

References
https://www.quickprogrammingtips.com/spring-boot/how-to-use-commandlinerunner-in-spring-boot-application.html
http://therealdanvega.com/blog/2017/04/07/spring-boot-command-line-runner