Showing posts with label Programs. Show all posts
Showing posts with label Programs. Show all posts

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(";", "");
}
}

Wednesday, January 24, 2018

RenameFilesInADirectory

package dummy;

import java.io.File;

public class RenameFilesInADirectory {

public static void main(String[] args) {
File directory = new File("D:\\Songs");
File[] files = directory.listFiles();
for(File file : files) {
// file.toString() gives absolute path to file
file.renameTo(new File(file.toString().replaceAll("_"," ")));
}
}

}

Tuesday, March 26, 2013

Search PDF for a given String : Java

 Third party jars used:
 itextpdf-5.3.3.jar

package com.pramod;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

/**
 * @author PramodKumarGampa
 *
 *         This program reads list of PDF files available in the directory
 *         specified through "absolutePathToDir" and shows the occurences of
 *         search string specified through "searchString"
 *
 */
public class FindStringInPDF {

    public static void main(String[] args) throws IOException {

        String absolutePathToDir = "C:\\PDFS\\";
        String searchString = "ABC";
        showSearchResults(absolutePathToDir, searchString);
        System.out.println("End of the program");

    }

    public static void showSearchResults(String absolutePathToDir,
            String searchString) throws IOException {
        PdfReader reader;
        File file = new File(absolutePathToDir);

        String[] listOfFiles = file.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith("pdf");
            }

        });

        for (String fileName : listOfFiles) {
            reader = new PdfReader(absolutePathToDir + fileName);
            int noOfPages = reader.getNumberOfPages();
            String pageText = null;
            for (int i = 1; i < noOfPages; i++) {
                pageText = PdfTextExtractor.getTextFromPage(reader, i);
                if (pageText.contains(searchString)) {
                    System.out.println("Search string '" + searchString
                            + "' found in file: " + fileName);
                    break;
                }

            }

        }

    }

}

Wednesday, February 27, 2013

Strict Alpha Numeric Validation

public class StrictAlphaNumericValidation {

    public static void main(String[] args) {
        System.out.println(isStrictAlphaNumeric("123abc"));
        System.out.println(isStrictAlphaNumeric("abc"));
        System.out.println(isStrictAlphaNumeric("123"));
        System.out.println(isStrictAlphaNumeric("abc123!@#"));
        System.out.println(isStrictAlphaNumeric("!@#abc123"));
    }

    public static boolean isStrictAlphaNumeric(String str) {
       if(str.matches("\\d{1,}[a-zA-Z]{1,}") || str.matches("[a-zA-Z]{1,}\\d{1,}")){
            return true;
        } else{
            return false;
        }
    }

}

Output:
true
false
false
false
false

Tuesday, January 29, 2013

Ignore case while string substitution

The following program shows how to replace a string by ignoring its case:

public class CaseInsensitiveStringReplace {
    public static void main(String[] args) {
        String testString = "Replace me iRResPecTive of my case!!!";
        System.out.println(testString.replaceAll("(?i)IRRESPECTIVE", ""));
    }
}

Output:
Replace me  of my case!!!

Explanation: String.replaceAll(,) has an overloaded version, which accepts the regular expression as first argument. (?i) says ignore case in regular expression terminology.

Note: Always make sure that regular expression related characters are escaped. For example, $ means at the end in regular expression terminology, which can be escaped by adding two backward slashes(\\).

Tuesday, January 22, 2013

Even or Odd

How to find out whether a given number is even or odd?

Traditional way:

int number = 10;

if(number%2 == 0){
System.out.println("Even number");
}else{
System.out.println("Odd number");
}

Output:
Even number

But what we an interviewer asks, not to use operator (%). Then we will be in trouble :).

Enhanced way:

public class EvenOrOddNumber {
 public static void main(String[] args) {

  System.out.println(isEvenNumber(10));
  System.out.println(isEvenNumber(13));

 }
 public static boolean isEvenNumber(int number){
  return (number & 1) == 0 ? true : false;
 }
}

Output:
true
false

Monday, November 12, 2012

Java Regular Expression Utils

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

public class RegExUtils {
 
 public static boolean matches(String line, String regEx) {

  boolean regExpMatches = false;

  if (StringUtils.isNotBlank(line) && StringUtils.isNotBlank(regEx)) {
   if (line.matches(regEx)) {
    regExpMatches = true;
   }
  }
  return regExpMatches;
 }
 
 public static List<String> getMatches(String line, String regEx, int group){
  Pattern pattern = Pattern.compile(regEx);
  Matcher matcher = pattern.matcher(line);
  List<String> matches = new ArrayList<>();

  while (matcher.find()) {

   matches.add(matcher.group(group));
  }
  
  return matches;
 }

 public static String getMatchedContent(String line, String regEx){
  Pattern pattern = Pattern.compile(regEx);
  Matcher matcher = pattern.matcher(line);
  String matchedContent = null;
  if (matcher.find()) {
   matchedContent = matcher.group();
  }
  
  return matchedContent;
 }
}


Sunday, October 28, 2012

PDF Bookmarks Reader

NOTE: Requires iText jar

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.SimpleBookmark;

public class BookmarkFetcher {

    public static void main(String[] args) throws IOException {

        PdfReader reader = new PdfReader("C:\\abc.pdf");
        List<HashMap<String, Object>> list = SimpleBookmark.getBookmark(reader);

        for (Iterator<HashMap<String, Object>> i = list.iterator(); i.hasNext();) {
            showBookmark((Map<String, Object>) i.next());
        }
    }

    @SuppressWarnings("unchecked")
    private static void showBookmark(Map<String, Object> bookmark) {

        System.out.println(bookmark.get("Title").toString());

        ArrayList<Object> kids = (ArrayList<Object>) bookmark.get("Kids");

        if (kids == null)
            return;

        for (Iterator<Object> i = kids.iterator(); i.hasNext();) {
            showBookmark((Map<String, Object>) i.next());
        }
    }
}
Output:
Displays bookmars from the pdf passed.

Friday, October 12, 2012

Blank Spaces Remover

Java program to remove extra spaces from a String

public class BlankRemover {
     
    private BlankRemover () {}

    /* remove leading whitespace */
    public static String ltrim(String source) {
        return source.replaceAll("^\\s+", "");
    }

    /* remove trailing whitespace */
    public static String rtrim(String source) {
        return source.replaceAll("\\s+$", "");
    }

    /* replace multiple whitespaces between words with single blank */
    public static String itrim(String source) {
        return source.replaceAll("\\b\\s{2,}\\b", " ");
    }

    /* remove all superfluous whitespaces in source string */
    public static String trim(String source) {
        return itrim(ltrim(rtrim(source)));
    }

    public static String lrtrim(String source) {
        return ltrim(rtrim(source));
    }
}

Tuesday, September 18, 2012

Extract place holders from an error message

String errMsg = "{1} and {2} values can't be same!!!";
Pattern pattern = Pattern.compile("\\{[1-9]+\\}");
Matcher matcher = pattern.matcher(errMsg);
       
while(matcher.find()){
   System.out.println(matcher.group());
}

Output:
{1}
{2}

Friday, September 14, 2012

Use Default Browser to Open a Web Page from a Swing Application

Prerequisite: Java 6+

public class DesktopBrowser {

   public static void main(String[] args) {
      try {
         String url = "http://www.google.com";
         java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
         }
      catch (java.io.IOException e) {
         System.out.println(e.getMessage());
         }
      }

   }
}

Wednesday, September 12, 2012

Count Lines of Code

Overview:
Below program displays lines of Java code that your project has. You just need to specify your project home(absolute path), followed by some flags.

NOTE: Java 7 features used

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class CountLinesOfCode {
    public static int counter = 0;

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

        boolean skipDocComments = readInput(
                "Do you want to skip doc comments? (y/n): ", scanner);

        boolean skipBlankLines = readInput(
                "Do you want to skip blank lines? (y/n): ", scanner);

        boolean skipMultiLineComments = readInput(
                "Do you want to skip multiline comments? (y/n): ", scanner);

        boolean skipSingleLineComments = readInput(
                "Do you want to skip single line comments? (y/n): ", scanner);

        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, skipDocComments, skipBlankLines,
                skipMultiLineComments, skipSingleLineComments);

        System.out.println("\nYour project has " + counter
                + " lines of Java code!!!");
    }

    public static void listFilesForFolder(final File folder,
            final boolean skipDocComments, final boolean skipBlankLines,
            boolean skipMultiLineComments, final boolean skipSingleLineComments) {

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

            if (fileEntry.isDirectory()) {
               
                listFilesForFolder(fileEntry, skipDocComments, skipBlankLines,
                        skipMultiLineComments, skipSingleLineComments);
            } else {

                if (fileEntry.getName().contains(".java")) {
                   
                    boolean docCommentStart = false;
                    boolean multiLineCommentsStart = false;
                   
                    System.out.println(fileEntry.getName());
                   
                    try (FileReader fileReader = new FileReader(fileEntry);
                            BufferedReader reader = new BufferedReader(fileReader)) {

                        String line = null;
                       
                        while ((line = reader.readLine()) != null) {
                           
                            if (skipDocComments) {
                                if (line.trim().startsWith("/**")) {
                                    if (line.trim().endsWith("*/")) {
                                        continue;
                                    }
                                    docCommentStart = true;
                                    continue;
                                }
                                if (docCommentStart) {
                                    if (line.trim().endsWith("*/")) {
                                        docCommentStart = false;
                                    }
                                    continue;
                                }
                            }

                            if (skipMultiLineComments) {
                                if (line.trim().startsWith("/*")
                                        && !line.trim().startsWith("/**")) {
                                    if (line.trim().endsWith("*/")) {
                                        continue;
                                    }
                                    multiLineCommentsStart = true;
                                    continue;
                                }
                                if (multiLineCommentsStart) {
                                    if (line.trim().endsWith("*/")) {
                                        multiLineCommentsStart = false;
                                    }
                                    continue;
                                }
                            }

                            if (skipSingleLineComments) {
                                if (line.trim().startsWith("//")) {
                                    continue;
                                }
                            }

                            if (skipBlankLines) {
                                if (line.trim().isEmpty()) {
                                    continue;
                                }
                            }
                           
                            counter++;
                        }
                    } catch (FileNotFoundException e) {
                        System.out.println("Specified file not found!!!");
                    } catch (IOException e) {
                        System.out.println("An exception is thrown while reading/writing a file!!!");
                    }
                }
            }
        }
    }

    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;
    }
}

Tuesday, September 4, 2012

Get list of strings between two strings

public static List<String> getStringInBetween(String strBegin, String strEnd, String strSource){

    List<String> list = new ArrayList<String>();
   int iEnd = 0;
   int iIndexOfBegin = strSource.indexOf(strBegin);
  
   while(iIndexOfBegin != -1 ){
       strSource = strSource.substring(iIndexOfBegin  + strBegin.length());
       iEnd = strSource.indexOf(strEnd);
       list.add(strSource.substring(0, iEnd));
       iIndexOfBegin = strSource.indexOf(strBegin);
   }
  
   return list;
}


Use:

List<String> tokens =getStringInBetween("[\"","\"]", "Input: {attr[\"role\"] == 'admin' ? attr[\"admintitle\"] :  attr[\"supertitle\"]}");
for(String token: tokens){
   System.out.println(token);
}


Output:
role
admintitle
supertitle

Friday, August 31, 2012

String validations

Q: How to validate a string that contains characters other than alphabets, digits and some optional characters?

Assumption: Options characters here are:  -!@#$%^&*()_+|~-=\\’{

Answer:

String optonalChars = "-!@#$%^&*()_+|~-=\\’{";
String str = "pramod-!@#$%^&*()_+|~-=\\’{]";
for(int i = 0; i< str.length(); i++){
       char ch = str.charAt(i);
       if(!Character.isAlphabetic(ch) && ! Character.isDigit(ch) && optonalChars.indexOf(ch)<0){
             System.out.println("Invalid string");
             System.out.println("Invalid char is: " + ch);
             break;
       }
}
 
Output:
Invalid string
Invalid char is: ]