CodeByAkram: Java
Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Read Files from classpath or resource folder and subfolder - Java

 The below code shows hot to read the list of resources(files) from a classpath folder and subfolder.

Below is the example code



import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.util.*;

public class ReadResourceFiles {

    public static void main(String[] args) throws IOException {
        List resourceFolderFiles = getResourceFolderFiles("static");
        resourceFolderFiles.stream().filter(f -> f.endsWith(".json")).forEach(System.out::println);
    }

    static List getResourceFolderFiles(String folder) {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        URL url = loader.getResource(folder);
        String path = url.getPath();
        File file = new File(path);
        List files = new ArrayList<>();
        if(file.isDirectory()){
            try {
                Files.walk(file.toPath()).filter(Files::isRegularFile)
                        .filter(f-> f.toFile().getName().toLowerCase().endsWith(".json"))
                        .forEach(f -> files.add(f.toFile().getPath()));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }else if(file.getName().toLowerCase().endsWith(".json")){
            files.add(file.getPath());
        }
        return files;
    }
}

How to push data to solace queue using JMS?

 In this blog, lets check how we can push the data to solace mq or solace queue using JMS. Message queues are the endpoints which guarantees you the delivery of a message without fail.

So to implement the Java code to push messages, first add the below dependency in pom.xml file if you are using the maven project in case.

<dependency>

<groupId>com.solacesystems</groupId>

<artifactId>sol-jms</artifactId>

<version>10.10.0</version>

</dependency>

 You can find the latest version of sol-jms from  Solace Queue Maven

Below is the sample program to push the message to Solace Queue by using JMS. Please enter your queue connection details.

package com.services.impl;

import java.util.Properties;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.log4j.Logger;
import com.solacesystems.jms.SolQueue;
import com.solacesystems.jms.SolTopic;
import com.solacesystems.jms.SupportedProperty;

public class PushData {

	private final static Logger logger = Logger.getLogger(PushData.class);

	public String pushDataToSolaceQueue(String requestText) {
		TextMessage textMessageToSend = null;
		String response = null;
		Session session = null;
		MessageProducer queueSender = null;
		MessageConsumer queueReceiver = null;

		Connection connection = null;
		String messageID;
		Properties env = new Properties();
		env.put(InitialContext.INITIAL_CONTEXT_FACTORY, "com.solacesystems.jndi.SolJNDIInitialContextFactory");
		env.put(InitialContext.PROVIDER_URL, "enter providerURL");
		env.put(Context.SECURITY_PRINCIPAL, "enter userName");
		env.put(Context.SECURITY_CREDENTIALS, "Enter password");

		env.put(SupportedProperty.SOLACE_JMS_VPN, "Enter VPN Name");

		env.put(SupportedProperty.SOLACE_JMS_JNDI_CONNECT_TIMEOUT, 60000);
		// InitialContext is used to lookup the JMS administered objects.
		InitialContext initialContext;
		try {
			initialContext = new InitialContext(env);

			// Lookup ConnectionFactory.
			ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("Enter Connection Factory");

			// JMS Connection
			connection = cf.createConnection();
			// Create a session
			// Create a non-transacted, Auto Ack session.
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

			textMessageToSend = session.createTextMessage("");
			textMessageToSend.setText(requestText);
			textMessageToSend.setJMSType("mcd://xmlns");
			textMessageToSend.setJMSDeliveryMode(DeliveryMode.PERSISTENT);
			// textMessageToSend.setJMSReplyTo((Destination) responseQueue);
			Object torQ = initialContext.lookup("request topic here");
			if (torQ instanceof SolTopic) {
				logger.info("assigning the request to a SolTopic");
				SolTopic requestTopic = (SolTopic) torQ;
				queueSender = session.createProducer(requestTopic);
				logger.info("sending message");
				queueSender.send(requestTopic, textMessageToSend);

			} else {
				logger.info("assigning the request to a SolQueue");
				SolQueue requestTopic = (SolQueue) torQ;
				queueSender = session.createProducer(requestTopic);
				logger.info("sending message");
				queueSender.send(requestTopic, textMessageToSend);
			}
			logger.info("pushDataToSolaceQueue() : message sent to queue is " + textMessageToSend.getText());
			// remember the messageID
			messageID = textMessageToSend.getJMSMessageID();
			logger.info("MessageID is " + messageID);
			connection.start();
			response = messageID;

			return response;

		} catch (JMSException jmsException) {
			logger.error("JMSException occurred due to " + jmsException.getLinkedException(), jmsException);

		} catch (NamingException jmsException) {
			logger.error("NamingException occurred  due to " + jmsException.getMessage(), jmsException);

		} catch (Exception exception) {
			logger.error("Unhandeled exception occurred  due to " + exception.getMessage(), exception);

		} finally {
			if (queueReceiver != null) {
				try {
					queueReceiver.close();
				} catch (Exception e) {
					logger.error("Exception in closing the Queue Receiver: " + e.getMessage());
				}
			}
			if (queueSender != null) {
				try {
					queueSender.close();
				} catch (Exception e) {
					logger.error("Exception in closing the Queue Sender: " + e.getMessage());
				}
			}
			if (session != null) {
				try {
					session.close();
				} catch (Exception e) {
					logger.error("Exception in closing the Queue Session: " + e.getMessage());
				}
			}
			if (connection != null) {
				try {
					connection.stop();
				} catch (Exception e) {
					logger.error("Exception in stopping the Queue Connection: " + e.getMessage());
				}
				try {
					connection.close();
				} catch (Exception e) {
					logger.error("Exception in closing the Queue Connection: " + e.getMessage());
				}
			}
		}
		return response;
	}

}

Write a program to print first non repeated char in a string in Java.


Write a program to print first non repeated char in a string in Java.

We are using the HashMap to store the character as key and count of times it is repeated as value.


package com.string.codebyakram;

import java.util.HashMap;

public class NonReapingCahr {
 public static void main(String[] args) {
  String string = "hello";
  System.out.println(findNonReapingCahr(string));
 }

 public static char findNonReapingCahr(String string) {

  HashMap< character > countChar = new HashMap<>();

  for (int i = 0; i < string.length(); i++) {
   int count = countChar.get(string.charAt(i)) == null ? 1 : countChar.get(string.charAt(i)) + 1;
   countChar.put(string.charAt(i), count);
  }

  for (int i = 0; i < string.length(); i++) {
   if (countChar.get(string.charAt(i)) == 1) {
    return string.charAt(i);
   }
  }
  return '\0';

 }
}

How to create multiple log file using same log4j property file?

You can create multiple logs file by using same log4j properties file or you can send logs to multiple files by using same log4j file.

How to create multiple log file using same log4j property file?
Add this below to your log4j properties file.

log4j.rootLogger=TRACE, stdout
log4j.appender.dataLogs=org.apache.log4j.FileAppender
log4j.appender.dataLogs.File=logs/logFile1.log
log4j.appender.dataLogs.layout=org.apache.log4j.PatternLayout
log4j.appender.dataLogs.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n
log4j.appender.reportsLog=org.apache.log4j.FileAppender
log4j.appender.reportsLog.File=logs/logFile2.log
log4j.appender.reportsLog.layout=org.apache.log4j.PatternLayout
log4j.appender.reportsLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.category.dataLogger=TRACE, dataLogs
log4j.additivity.debugLogger=false
log4j.category.reportsLogger=DEBUG, reportsLog
log4j.additivity.reportsLogger=false
Then configure the loggers in the code accordingly as shown below:

static final Logger debugLog = Logger.getLogger("dataLogger");
static final Logger resultLog = Logger.getLogger("reportsLogger");

How to delete log4j/log file older than N number of days?

How to delete log4j/log file by N number of days?

package com.avaya.deletelogs;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.List;

public class DeleteLogs {

 private String baseDir = "/opt/java/IVRLog";
 private int daysBack = 4;

 public void invokeProcess() {
  getFolders();
 }

 public void getFolders() {

  try {
   File file = new File(baseDir);
   String[] directories = file.list(new FilenameFilter() {

    public boolean accept(File current, String name) {
     return new File(current, name).isDirectory();
    }
   });
   deleteFiles(daysBack, baseDir, Arrays.asList(directories));
  } catch (Exception e) {
   System.out.println(e);
  }
 }

 public void deleteFiles(int daysBack, String dirWay, List< string> directories) {
  for (String dir : directories) {
   deleteFilesOlderThanNdays(daysBack, dir);
  }

 }

 public void deleteFilesOlderThanNdays(int daysBack, String dirWay) {

  File directory = new File(baseDir + "/" + dirWay);
  if (directory.exists()) {

   File[] listFiles = directory.listFiles();
   long purgeTime = System.currentTimeMillis() - (daysBack * 24 * 60 * 60 * 1000);
   for (File listFile : listFiles) {
    try {
     if (listFile.isFile()) {
      if (listFile.lastModified() < purgeTime) {
       if (!listFile.delete()) {
        System.err.println("Unable to delete file: " + listFile);
       }
      }
     } else {
      continue;
     }
    } catch (Exception e) {
     System.out.println(e);
    }
   }
  }
 }

}

How to get keys and values from Map in Java?

As we know, map is based on key-value pair associations, so interviewer can ask you this question if you are a beginner or having less than 3 years of experience.

So lets see how we can the key and values from a Map?

How to get keys and values from Map, codebyakram


In Java we have and Map.Entry method that returns a collection-view of map.


Map< string string=""> map = new HashMap<>();

 // Get keys and values
 for (Map.Entry< string string=""> entry : map.entrySet()) {
  String k = entry.getKey();
  String v = entry.getValue();
  System.out.println("Key: " + k + ", Value: " + v);
 }

 // In Java 8 we can use for each
 map.forEach((k, v) -> {
  System.out.println("Key: " + k + ", Value: " + v);
 });

How to Sort a Stack using Merge Sort?

Interviewer may ask you this question if you have more than 3 years of experience in java development. So lets have a look, how to sort a stack using merge sort?

Lets see sample input and output for better understanding:

How to Sort a Stack using Merge Sort? codebyakram


Algorithm
For this we will follow these below two steps,
1. Break the stack into two parts by using two temporary stack.

2. When only one element remains on a Stack, Merge it.

Lets have a look on the program,


package com.codebyakram;
 
import java.util.Stack;
 
public class SortStack {
 
    public static void main(String args[]) {
        Stack stack = new Stack();
        stack.push(5);
        stack.push(9);
        stack.push(4);
        stack.push(1);
        stack.push(2);
        stack.push(-1);

 
        sort(stack);
 
        System.out.println(stack);
    }
 
    private static void sort(Stack stack) {
        Stack s1 = new Stack();
        Stack s2 = new Stack();
 
        while (stack.size() != 0) {
            if (stack.size() % 2 == 0) {
                s1.push(stack.pop());
            } else {
                s2.push(stack.pop());
            }
        }
 
        if (s1.size() > 1) {
            sort(s1);
        }
 
        if (s2.size() > 1) {
            sort(s2);
        }
 
        merge(s1, s2, stack);
    }
 
    private static void merge(Stack s1, Stack s2, Stack stack) {
        Stack mergedStack = new Stack();
        while (!s1.isEmpty() && !s2.isEmpty()) {
            if ((Integer) s1.peek() < (Integer) s2.peek()) {
                mergedStack.push(s2.pop());
            } else {
                mergedStack.push(s1.pop());
            }
        }
 
        while (!s1.isEmpty()) {
            mergedStack.push(s1.pop());
        }
 
        while (!s2.isEmpty()) {
            mergedStack.push(s2.pop());
        }
 
        while (!mergedStack.isEmpty()) {
            stack.push(mergedStack.pop());
        }
    }
}