Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package gmailcontacts;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.io.UnsupportedEncodingException;
- import java.io.IOException;
- import java.util.HashMap;
- import java.util.TreeMap;
- import java.util.Map;
- public class GmailContacts {
- // Define input and output file names
- private static final String CT_OLD = "contactsOld.tsv",
- CT_NEW = "contactsNew.tsv",
- CT_GMAIL = "contactsGmail.tsv";
- // Define file encoding (US-ASCII, UTF-8, etc.)
- private static final String CT_ENCODING = "US-ASCII";
- // Define sorting method for the output file
- // 0 -> sort by first name, 1 -> sort by last name
- private static final int SORT_METHOD = 0;
- public static void main(String[] args) {
- // Store contacts in a HashMap, using their names as the Key
- Map<String, String> allContacts = new HashMap<>();
- // Use a TreeMap here, which is automatically sorted by the Key
- // In other words, the output is auto sorted
- Map<String, String> gmailOnly = new TreeMap<>();
- try {
- // Make sure that both input files exist
- File f1 = new File(CT_OLD);
- File f2 = new File(CT_NEW);
- if (!f1.isFile()) {
- System.err.println("Error: Input file " + CT_OLD + " does not exist! Aborting.");
- System.exit(1);
- }
- if (!f2.isFile()) {
- System.err.println("Error: Input file " + CT_NEW + " does not exist! Aborting.");
- System.exit(1);
- }
- // Read OLD contacts from file, and add them to 'allContacts'
- allContacts = readTSV(CT_OLD);
- // Read NEW contacts from file, and add them to 'allContacts'
- // All duplicate contacts are replaced with their new details
- allContacts.putAll(readTSV(CT_NEW));
- // Filter out '@gmail.com' contacts from 'allContacts'
- gmailOnly = getGmail(allContacts);
- // Print results
- for (Map.Entry<String, String> entry : gmailOnly.entrySet()) {
- System.out.println(entry.getValue());
- }
- System.out.println();
- System.out.println("Writing results to file " + CT_GMAIL + " ...");
- // Write results to file
- writeTSV(CT_GMAIL, gmailOnly);
- } catch (Exception e) {
- System.err.println(e.getMessage());
- System.exit(1);
- }
- }
- /**
- *
- * Filter out and return only those contacts with one or more
- * email address matching '@gmail.com'
- */
- private static Map<String, String> getGmail(Map<String, String> data) {
- // Use a TreeMap which is automatically sorted by the Key
- Map<String, String> gmailOnly = new TreeMap<>();
- try {
- for (Map.Entry<String, String> entry : data.entrySet()) {
- String[] newSplit = entry.getValue().split("\t");
- // Check for existence of additional fields
- if (newSplit.length >= 2) {
- // In case there are multiple emails separated by comma,
- // check if any matches '@gmail.com', except the last one
- if (newSplit[newSplit.length - 1].toLowerCase().contains("@gmail.com,")) {
- gmailOnly.put(entry.getKey(), entry.getValue());
- // Check if the last email address matches '@gmail.com'
- } else if (newSplit[newSplit.length - 1].trim().toLowerCase().endsWith("@gmail.com")) {
- gmailOnly.put(entry.getKey(), entry.getValue());
- }
- }
- }
- } catch (Exception e) {
- System.err.println(e.getMessage());
- }
- return gmailOnly;
- }
- /**
- *
- * Read TSV file 'tsvIn' and return results as a Map, with the first column
- * (contact names) as the Key, and the entire line as the Value
- */
- private static Map<String, String> readTSV(String tsvIn) {
- Map<String, String> data = new HashMap<>();
- BufferedReader br = null;
- try {
- File file = new File(tsvIn);
- br = new BufferedReader(
- new InputStreamReader(
- new FileInputStream(
- file.getAbsoluteFile()), CT_ENCODING));
- while (true) {
- String newLine = br.readLine();
- String fullName = null,
- mapKey = null,
- phoneNo = "",
- emailAddr = "",
- lastValue = null;
- String[] lastSplit,
- newSplit,
- nameSplit;
- if (newLine == null) {
- // No more lines to read
- break;
- } else if (newLine.trim().length() > 0) {
- // Split line at TABs
- newSplit = newLine.split("\t");
- fullName = newSplit[0];
- // Determine the Map Key according to SORT_METHOD
- if (SORT_METHOD == 0) {
- mapKey = fullName;
- } else {
- // Split fullName at spaces
- nameSplit = fullName.split(" +");
- if (nameSplit.length > 1) {
- // Add last name in front (for sorting by last name)
- mapKey = nameSplit[nameSplit.length - 1] + fullName;
- } else {
- mapKey = fullName;
- }
- }
- // Check for existence of phone number field
- if (newSplit.length >= 2) {
- phoneNo = newSplit[1];
- }
- // Check for existence of email field
- if (newSplit.length >= 3) {
- emailAddr = newSplit[2];
- }
- lastValue = data.put(mapKey, newLine);
- // A duplicate Key (contact name) is found. We need to
- // merge fields from these two records
- // Skip if the two records are identical
- if (lastValue != null && !lastValue.trim().equals(newLine.trim())) {
- lastSplit = lastValue.split("\t");
- // Check for existence of phone number field
- if (lastSplit.length >= 2) {
- if (!"".equals(phoneNo)) {
- phoneNo = lastSplit[1] + "," + phoneNo;
- } else {
- phoneNo = lastSplit[1];
- }
- }
- // Check for existence of email field
- if (lastSplit.length >= 3) {
- if (!"".equals(emailAddr)) {
- emailAddr = lastSplit[2] + "," + emailAddr;
- } else {
- emailAddr = lastSplit[2];
- }
- }
- // Add the merged record to Map 'data'
- data.put(mapKey, fullName + "\t" + phoneNo + "\t" + emailAddr);
- }
- }
- }
- } catch (UnsupportedEncodingException e) {
- System.err.println("An UnsupportedEncodingException was caught: " + e.getMessage());
- } catch (IOException e) {
- System.err.println("An IOException was caught: " + e.getMessage());
- } catch (Exception e) {
- System.err.println(e.getMessage());
- } finally {
- try {
- if (br != null) {
- br.close();
- }
- } catch (IOException e) {
- System.err.println("An IOException was caught: " + e.getMessage());
- }
- }
- return data;
- }
- /**
- *
- * Write to the TSV file 'tsvOut', using Values from input Map 'data' as
- * each line in the output.
- */
- private static void writeTSV(String tsvOut, Map<String, String> data) {
- BufferedWriter bw = null;
- try {
- File file = new File(tsvOut);
- if (!file.exists()) {
- file.createNewFile();
- }
- bw = new BufferedWriter(
- new OutputStreamWriter(
- new FileOutputStream(
- file.getAbsoluteFile()), CT_ENCODING));
- for (Map.Entry<String, String> entry : data.entrySet()) {
- bw.write(entry.getValue());
- bw.newLine();
- }
- System.out.println("All done!");
- } catch (UnsupportedEncodingException e) {
- System.err.println("An UnsupportedEncodingException was caught: " + e.getMessage());
- } catch (IOException e) {
- System.err.println("An IOException was caught: " + e.getMessage());
- } catch (Exception e) {
- System.err.println(e.getMessage());
- } finally {
- try {
- if (bw != null) {
- bw.flush();
- bw.close();
- }
- } catch (IOException e) {
- System.err.println("An IOException was caught: " + e.getMessage());
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement