GIT delete merged branches

How to delete merged branches from local copy:

When you work on a project for a while, there is a good chance that you will have a list of old/already merged branches showing on your local git. 

When you run $git branch it will show all the branches since you started working on the project including the ones that are not currently active.

$git branch
    PROJX-1024-add-new-button
    PROJX-1026-add-another-button
    PROJX-1027-titleupdates
    build-fix
    develop
    release
    master 

Here's how you can find the merged branches: It will only list a branch if it exists in local but not in remote(deleted from remote after merging).

$git branch --merged
    PROJX-1024-add-new-button
    build-fix
    develop
    release


Here's how you delete the merged branches except develop and release

$git branch --merged | egrep -v "(^\*|develop|release)" | xargs git branch -d


You can add any number of branches to the skip list separated by pipe |

$git branch --merged | egrep -v "(^\*|develop|release|another_branch|yet_another_branch)" | xargs git branch -d

Java view,download,filter email using javax.mail

Java SDK doesn't come with inbuilt mail API but Java-EE (now called Jakarta EE) provides several utility library like json, servlet, web-service, jms, validation, xml, regexp including email.

In this example I'm going to show how we can connect to email server (eg: gmail) and download/view seen/unseen emails.

Required Dependency :jakarta.mail

Add this dependency with latest version in your pom.xml or manually download/add the jar file to your project's lib.

<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>jakarta.mail</artifactId>
</dependency>

The API Usage:

Ideally, the steps would be as following:

- Create Session with host, protocal type etc

- Get message store (Store) for the email protocol. The supported protocols are IMAP, POP, SMTP etc

- Connect to the host using username/password

- Open folder and search for messages


The API Usage with code example:

- Create Session with host, protocol type etc

Properties properties = new Properties();
properties.put("mail.imap.host", host);
properties.put("mail.store.protocol", protocal);
Session emailSession = Session.getDefaultInstance(properties);

 - Get message store (Store) for the email protocol. The supported protocols are IMAP, POP, SMTP etc

Store store = emailSession.getStore(protocal);

- Connect to the host using username/password

store.connect(host, user, password);

- Open folder and search for messages

Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);

Search using filters

Flags seen = new Flags(Flags.Flag.SEEN);
FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
Message[] messages = emailFolder.search(unseenFlagTerm);

Complete Example:


import javax.mail.*;
import javax.mail.search.FlagTerm;
import java.util.Properties;

public class MailllllIMAP {

public static void check(String host, String protocal, String user, String password) {
try {
Properties properties = new Properties();
properties.put("mail.imap.host", host);
properties.put("mail.store.protocol",
protocal);
Session emailSession = Session.getDefaultInstance(properties);

Store store = emailSession.getStore(storeType);
store.connect(host, user, password);
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);

//unseen email filter
Flags seen = new Flags(Flags.Flag.SEEN);
FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
Message[] messages = emailFolder.search(unseenFlagTerm);

System.out.println("Total messages: " + messages.length);

for (Message m : messages) {
System.out.println(("From: " + m.getFrom()[0]));
System.out.println(("Subject: " + m.getSubject()));
System.out.println(("Subject: " + m.getContent()));
//other fields
}


//close or do more stuff
emailFolder.close(false);
store.close();

} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {

String host = "pop.gmail.com";
String protocal = "imaps";
String username = "XXXX@gmail.com";
String password = "XXXXXXX";

check(host, protocal, username, password);

}

}


What if you get an error like this?

    AuthenticationFailedException: [AUTH] Username and password not accepted.

You get this error when trying to gmail. You will need to turn ON the "Allow less secure apps" option on https://www.google.com/settings/security/lesssecureapps



Java HttpClient tutorial with File Upload example

Java 11 comes with a nice HttpClient API/Implementation so that we no longer need to rely on external libraries like Apache HttpClient execute http requests.

It has the following simple classes(namely HttpClient, HttpRequest, HttpResponse, BodyPublisher, BodyHandler) and they all follow builder pattern to create objects.

Creating HttpClient:

HttpClient client = HttpClient.newBuilder().build();

Creating request:

HttpRequest request = HttpRequest.newBuilder()
.header("key1", "value1")
.header("key2", "value2")
.uri(URI.create("http://localhost:8080/hello"))
.POST(HttpRequest.BodyPublishers.ofString("Request Body"))
.build();

Sending request:

client.send(request, HttpResponse.BodyHandlers.APPROPRIATE_HANDLER);

Here, BodyPublisher and BodyHandler can be used to create request body and process returned response respectively. They both support string, byte, file, input stream etc

Upload file using BodyPublishers.ofFile

Normally file upload using a web page are implemented using multi-part(file data with additional properties). But in this example we are going to upload file's byte array in request body and file name in request param.

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;

public class HttpTest {
public static void main(String[] args) throws Exception {
uploadFile(Path.of("testFile.txt"));
}

public static void uploadFile(Path file) throws IOException, InterruptedException {
HttpClient client = HttpClient.newBuilder().build();

HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:8080/uploadFile?uploader=HttpTestApp&fileName="
+ file.getFileName()))
.POST(HttpRequest.BodyPublishers.ofFile(file))
.build();

client.send(request, HttpResponse.BodyHandlers.ofString());
}
}

To make the example complete, let's assume we have a following simple Spring Boot app that receives the file byte array as request body:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.*;

@SpringBootApplication
public class FileUploadApp {
public static void main(String[] args) {
SpringApplication.run(FileUploadApp.class, args);
}
}

@Controller
class FileUplCtrl {

@PostMapping(path = "/uploadFile")
public void addPhoto(@RequestBody byte[] barr,
@RequestParam(name = "uploader") String uploader,
@RequestParam(name = "fileName") String fileName) throws Exception {

System.out.println("Received file " + fileName + " , uploaded by " + uploader + " Size: " + barr.length);

//write to disk
try (OutputStream os = new FileOutputStream(new File("UPL" + fileName))) {
os.write(barr);
}

}
}


Required Dependency on Spring Boot app:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>


Enjoy coding!