Wednesday, October 24, 2018

Find out possible short names for a given company name or a String

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class ShortNameGenerator {

public static void main(String[] args) {
String companyName = "Advitha Technoloigies";
showPossibleShortNames(companyName);
}

private static void showPossibleShortNames(String companyName) {
String words[] = companyName.split(" ");

List<Integer> indexes = new ArrayList<Integer>();
StringBuilder builder = null;
Set<String> shortNames = new LinkedHashSet<String>();
int wordTobeIncremented = 0;
String companyNameWithoutSpaces = companyName.replaceAll(" ", "");
while(true) {
builder = new StringBuilder();
for(int wordIndex = 0; wordIndex < words.length; wordIndex++) {
if(wordTobeIncremented == words.length) {
wordTobeIncremented = 0;
}
String word = words[wordIndex];
if(shortNames.isEmpty()) {
builder.append(word.charAt(0));
indexes.add(wordIndex, 1);
} else {
if(wordIndex == wordTobeIncremented) {
if(indexes.get(wordIndex) < word.length()) {
indexes.set(wordIndex, indexes.get(wordIndex) + 1);
}
}
builder.append(word.substring(0, indexes.get(wordIndex)));
}
}
if(!shortNames.isEmpty()) {
wordTobeIncremented++;
}
shortNames.add(builder.toString());
if(builder.toString().equalsIgnoreCase(companyNameWithoutSpaces)) {
break;
}
}
Iterator<String> shortNamesIterator = shortNames.iterator();
while(shortNamesIterator.hasNext()) {
System.out.println(shortNamesIterator.next());
}
}

}


Output:
---------
AT
AdT
AdTe
AdvTe
AdvTec
AdviTec
AdviTech
AdvitTech
AdvitTechn
AdvithTechn
AdvithTechno
AdvithaTechno
AdvithaTechnol
AdvithaTechnolo
AdvithaTechnoloi
AdvithaTechnoloig
AdvithaTechnoloigi
AdvithaTechnoloigie
AdvithaTechnoloigies

Monday, August 13, 2018

Update XML Content

package com.advitha.util;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.lang.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class UpdateXMLContent {
public static void main(String args[]) {
try {
Set<String> controllerClasses = new HashSet<String>();
String filepath = "D:\\file.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(StrutsConfigToSpringConfig.class.getClass()
.getResourceAsStream("/resources/new/spring-config.xml")));

Node beans = doc.getFirstChild();

NodeList beanList = doc.getElementsByTagName("bean");

for(int index = 0; index < beanList.getLength(); index++) {
Node bean = beanList.item(index);
if(bean.hasAttributes()) {
Node idAttribute = bean.getAttributes().getNamedItem("id");
Node classAttribute = bean.getAttributes().getNamedItem("class");
controllerClasses.add(classAttribute.getNodeValue());
idAttribute.setTextContent(toCamelCase(idAttribute.getNodeValue()));
}
}

System.out.println(controllerClasses);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);

System.out.println("Done");

} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
}

private static String toCamelCase(String input) {
int lowercaseIndex = 0;
char charArray[] = input.toCharArray();
if(Character.isUpperCase(charArray[0]) && Character.isUpperCase(charArray[1])) {
for(char ch: charArray) {
if(Character.isLowerCase(ch)) {
break;
}
lowercaseIndex++;
}
for(int index = 0; index < lowercaseIndex - 1; index++) {
charArray[index] = Character.toLowerCase(charArray[index]);
}
input = new String(charArray);
} else if(Character.isUpperCase(charArray[0])) {
input = StringUtils.uncapitalise(input);
}
return input;
}
}

Add @Controller annotation to given classes

package com.advitha.util;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.SetUtils;
import org.apache.commons.lang.SerializationUtils;

public class AddLinesOfCodeToClasses {

public static Set<String> controllerClassesWithPackageInfo = null;
public static Set<String> controllerClasses = null;
public static Set<String> classesFound = new HashSet<>();
static {
controllerClassesWithPackageInfo = getControllerClassesWithPackageInfo();
controllerClasses = getControllerClasses(controllerClassesWithPackageInfo);
System.out.println("Set Size: " + controllerClasses.size());
}
    public static int counter = 0;
   

    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);

        File projectHome = null;

        do {
            System.out.println("Enter Project Home Path: ");
            String projectHomeLocation = scanner.nextLine();
            projectHome = new File(projectHomeLocation);

            if (!projectHome.exists()) {
                System.out.println("Project home specfied doesn't exists!!!");
            }
            if (projectHome.exists() && !projectHome.isDirectory()) {
                System.out.println("Select path to a directory!!!");
            }

        } while (!projectHome.exists() || !projectHome.isDirectory());

        listFilesForFolder(projectHome);

        System.out.println("\nYour project has " + counter
                + " lines of Java code!!!");
        System.out.println("Classes Found: " + classesFound.size());
        List<String> classesMissing = (java.util.List<String>) CollectionUtils.disjunction(controllerClassesWithPackageInfo, classesFound);
        for(String name: classesMissing) {
        System.out.println(name);
        }
    }

    public static void listFilesForFolder(final File folder) throws IOException {

        for (final File fileEntry : folder.listFiles()) {

            if (fileEntry.isDirectory()) {
               
                listFilesForFolder(fileEntry);
            } else {

                if (fileEntry.getName().contains(".java")) {
                if(controllerClasses.contains(getFileNameWithoutExtension(fileEntry.getName()))){
               
                Path FILE_PATH = Paths.get(fileEntry.getPath());
                List<String> fileContent = new ArrayList<>(Files.readAllLines(FILE_PATH, StandardCharsets.UTF_8));

                if(fileContent.contains("@Controller")) {
                System.out.println("@Controller annotation is already available!" + fileEntry.getName());
                continue;
                }
                boolean packageDefFound = false;
                boolean packageMatchFound = false;
                String clsNmWithPkgPfx = null;
                for (int i = 0; i < fileContent.size(); i++) {
               
                if(packageDefFound == false && fileContent.get(i).contains("package ")) {
                String packageDefLine = fileContent.get(i).trim();
                clsNmWithPkgPfx = getPacakgeNameFromPackageDeclaration(packageDefLine) + "." + getFileNameWithoutExtension(fileEntry.getName());
                if(controllerClassesWithPackageInfo.contains(clsNmWithPkgPfx)) {
                packageMatchFound = true;
                }
                packageDefFound = true;
                continue;
                }
               
                if(packageDefFound == true && packageMatchFound == false) {
                break;
                }
                    if (packageMatchFound == true && fileContent.get(i).contains("class " + getFileNameWithoutExtension(fileEntry.getName()))) {
                        fileContent.set(i, "import org.springframework.stereotype.Controller;" + System.lineSeparator() + "@Controller"+ System.lineSeparator() + fileContent.get(i));
                    classesFound.add(clsNmWithPkgPfx);
//                    counter++;
                        break;
                    }
                }

                Files.write(FILE_PATH, fileContent, StandardCharsets.UTF_8);
               
                }
                }
            }
        }
    }

    public static boolean readInput(String inputMsg, Scanner scanner) {
        String temp = null;
       
        do {
           
            System.out.println(inputMsg);
            temp = scanner.nextLine().trim();
           
            if (temp.matches("[^yYnN]")) {
                System.out.println("Invalid input!!!");
            }
           
        } while (temp.matches("[^yYnN]"));

        return getBoolValue(temp);
    }

    public static boolean getBoolValue(String input) {
        return input.matches("[yY]") ? true : false;
    }
   
    public static Set<String> getControllerClassesWithPackageInfo() {
String controllerClassesString = "com.advitha.controllers.Controller1, com.advitha.controllers.Controller2, com.advitha.controllers.Controller3";
String[] controllerClassesArray = controllerClassesString.split(", ");

Set<String> controllerClassesSet = new HashSet<>(Arrays.asList(controllerClassesArray));
return controllerClassesSet;
}
   
    public static Set<String> getControllerClasses(Set<String> classNamesWithPackagePrefixes) {
    Set<String> controllerClasses = new HashSet<>();
    for(String name: classNamesWithPackagePrefixes) {
    controllerClasses.add(getClassNameFromAbsoluteName(name));
    }
    return controllerClasses;
    }
   
    public static String getClassNameFromAbsoluteName(String absoluteFileName) {
return absoluteFileName.substring(absoluteFileName.lastIndexOf(".")+1);
}
   
    public static String getFileNameWithoutExtension(String fileName) {
return fileName.substring(0, fileName.lastIndexOf("."));
}
   
    public static String getPacakgeNameFromPackageDeclaration(String line) {
return line.substring(line.indexOf(" ")).trim().replaceAll(";", "");
}
}