CodeByAkram

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

}

How to use / implement OWASP ESAPI Logger in Java

Before going further lets talk about Log Forging or JVM Log Forging. 

Log Forging

According to OWASP , writing invalidated logs can allow attackers to forge log or inject malicious content in log file. Log forging is when attackers tries to add/modify the log content by exploring the security loopholes of application.

Lets understand the log forging by an example.


private void printLog(String amount) {
logger.info("Amount credited in account Rs. {}" + amount);
}
above code will print the logs like:

Amount credited in account Rs. 500

 Now suppose attacker provide the input \n\n Amount debited in account Rs.500

Amount credited in account Rs. 500

Amount debited in account Rs.500

So, attacker forged the logs by making a fake or forge entry in log.


Avoid directly embedding user input in log files when possible. Sanitize untrusted data used to construct log entries by using safe logging mechanism such as OWASP ESAPI logger, which will automatically remove unexpected carriage returns. So, to prevent this, we use use ESAPI Logger mechanism.

Here is the dependency of ESAPI: 

<dependency>

<groupId>org.owasp.esapi</groupId>

<artifactId>esapi</artifactId>

<version>2.2.2.0</version>

</dependency>

We can encode the logs using ESAPI‘s Encoder method and interface:


    public String encode(String message) {
    message = message.replace( '\n' ,  '_' ).replace( '\r' , '_' )
      .replace( '\t' , '_' );
    message = ESAPI.encoder().encodeForHTML( message );
    return message;
}
How to use / implement OWASP ESAPI Logger in Java





Multi threading using Executor Services in Java

 The ExecutorService interface, executes tasks in parallel in background and represents an asynchronous execution mechanism. The ExecutorService create and maintain the reusable thread pool.


How to create ExecutorService?

To create ExecutorService, you can use Executors factory to create the instance of ExecutorService. Lets see some examples.


 There are diffrent way to execute or submit the task with ExecutorService.
  1. submit(Runnable)
  2. submit(Callable)
  3. execute(Runnable)
  4. invokeAny(...)
  5. invokeAll(...)
Lets go through with the example to run multiple treads with ExecutorService.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HTMLUnitMultipleThreads {

	public static void main(String[] args) {

		int threadSize = 5;
		ExecutorService executor = Executors.newFixedThreadPool(threadSize);
		for (int i = 0; i < threadSize; i++) {
			executor.submit(new MultiThreadingService());
		}
	}
}

public class MultiThreadingService implements Runnable {

	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			System.out.println("Thread Name = " + Thread.currentThread().getName());
		}

	}

}

Getting Started with Angular

We have setup the development setup of angular in angular-installation blog. Now in this blog, lets start a new project and lets see how we can create a new project in Angular.

How we can create a new project in Angular?

To create a new project, open Angular CLI and type below mentioned command and press enter. This will take some time to create an ready to build application for you.


ng new angular-project

To create a new project, open Angular CLI and type below mentioned command and press enter. This will take some time to create an ready to build application for you.


Now this will create a full ready to build angular application. In below image you can see the full folder structure of angular application.

full folder structure of angular application
We'll be mainly working in the src folder.

Run or Serve application

You can build and run the application by using below CLI command. The default port for angular application is 4200.

Go to angular-project folder and then run the application.

cd angular-project
ng serve
build and run the application by using below CLI command



We can open this application on our browser at http://localhost:4200/

We can open this application on our browser at http://localhost:4200/


So this application is working fine. If you are facing some problem while running your application , let me know in comments section.