Wednesday, 2 June 2021

Php: include_once, require_once

require_once

The require_once expression is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again.

 

include_once

The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again, and include_once returns true. As the name suggests, the file will be included just once.

 

Why to use require_once, include_once statements?

If the same file is included more than once during the execution of particular php file, it leads to.

a.   Function redefinitions

b.   Variable value reassignments etc.,

 

Let’s see it with an example.

 

a.php

<?php
    $my_org_name = 'ABC Corp'
?>

 

b.php

#!/usr/bin/php

<?php
    include 'a.php';

    echo "my_org_name : $my_org_name\n";

    echo "\nSetting my_org_name to XYZ Corp\n";
    $my_org_name = 'XYZ Corp';

    echo "Reincluding the file a.php\n";
    include 'a.php';

    echo "my_org_name : $my_org_name\n";

?>

 

Output

$./b.php 


my_org_name : ABC Corp

Setting my_org_name to XYZ Corp
Reincluding the file a.php

my_org_name : ABC Corp

 

As you see b.php application, I set the value of ‘my_org_name’ to ‘XYZ Corp’ and re included the file a.php. Since a.php has assigned the value of of ‘my_org_name’ to ‘ABC Corp’, whatever the changes we have done in a.php are reassigned. In case of functions, they will be redefined, to avoid these problems, use include_once or require_once.

 

Let’s update include statement with include_once statement in b.php file and rerun the application.

 

b.php

 

#!/usr/bin/php

<?php
    include 'a.php';

    echo "my_org_name : $my_org_name\n";

    echo "\nSetting my_org_name to XYZ Corp\n";
    $my_org_name = 'XYZ Corp';

    echo "Reincluding the file a.php\n";
    //include 'a.php';
    include_once 'a.php';

    echo "my_org_name : $my_org_name\n";

?>

 

Output

$./b.php 


my_org_name : ABC Corp

Setting my_org_name to XYZ Corp
Reincluding the file a.php
my_org_name : XYZ Corp

 

 

 

 

 

 

 

 

  

Previous                                                    Next                                                    Home

Spring integration: PublishSubscribeChannel: Deliver the messages parallelly

We can deliver the messages parallely, by attaching the executor to the PublishSubscribeChannel instance.

 

Example

Executor exec = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

PublishSubscribeChannel channel = new PublishSubscribeChannel(exec);

 

Find the below working application.

 

Step 1: Create new maven project ‘pub-sub-channel-parallel-delivery-demo’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>pub-sub-channel-parallel-delivery-demo</artifactId>
	<version>1</version>

	<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.0</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-integration</artifactId>
		</dependency>

	</dependencies>

</project>

 

Step 3: Define consumer endpoints.

 

ConsumerEndpoint1.java

package com.sample.app.endpoints;

import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

@Component
public class ConsumerEndpoint1 {

	@ServiceActivator(inputChannel = "pubSubChannel")
	public Message<String> consumeMessage(Message<String> message) {
		System.out.println("ConsumerEndpoint1 -> Received message from gateway : " + message.getPayload());
		return MessageBuilder.withPayload("Message '" + message.getPayload() + "' received by ConsumerEndpoint1")
				.build();
	}

}

 

ConsumerEndpoint2.java

package com.sample.app.endpoints;

import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

@Component
public class ConsumerEndpoint2 {

	@ServiceActivator(inputChannel = "pubSubChannel")
	public Message<String> consumeMessage(Message<String> message) {
		System.out.println("ConsumerEndpoint2 -> Received message from gateway : " + message.getPayload());
		return MessageBuilder.withPayload("Message '" + message.getPayload() + "' received by ConsumerEndpoint2")
				.build();
	}

}

 

ConsumerEndpoint3.java

package com.sample.app.endpoints;

import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

@Component
public class ConsumerEndpoint3 {

	@ServiceActivator(inputChannel = "pubSubChannel")
	public Message<String> consumeMessage(Message<String> message) {
		System.out.println("ConsumerEndpoint3 -> Received message from gateway : " + message.getPayload());
		return MessageBuilder.withPayload("Message '" + message.getPayload() + "' received by ConsumerEndpoint3")
				.build();
	}

}

Step 4: Define custom gateway.

 

CustomGateway.java

package com.sample.app.endpoints;

import org.springframework.integration.annotation.Gateway;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.messaging.Message;

@MessagingGateway(name = "myGateway", defaultRequestChannel = "pubSubChannel")
public interface CustomGateway {

	@Gateway(requestChannel = "pubSubChannel")
	public void print(Message<String> message);

}


Step 5: Define App class.

 

App.java

package com.sample.app;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.channel.PublishSubscribeChannel;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;

import com.sample.app.endpoints.CustomGateway;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@SpringBootApplication
@Configuration
public class App {

	@Autowired
	@Qualifier("pubSubChannel")
	private PublishSubscribeChannel pubSubChannel;

	@Autowired
	private CustomGateway customGateway;

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

	@Bean(name = "pubSubChannel")
	public PublishSubscribeChannel channel1() {
		Executor exec = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

		PublishSubscribeChannel channel = new PublishSubscribeChannel(exec);
		return channel;
	}

	@Bean
	public CommandLineRunner demo() {
		return (args) -> {

			for (int i = 0; i < 10; i++) {
				Message<String> message = MessageBuilder.withPayload("Msg " + i).build();
				customGateway.print(message);
			}

		};
	}

}


Total project structure looks like below.


Run App.java, you will see below messages in console.

ConsumerEndpoint3 -> Received message from gateway : Msg 0
ConsumerEndpoint2 -> Received message from gateway : Msg 1
ConsumerEndpoint1 -> Received message from gateway : Msg 0
ConsumerEndpoint1 -> Received message from gateway : Msg 1
ConsumerEndpoint2 -> Received message from gateway : Msg 0
ConsumerEndpoint3 -> Received message from gateway : Msg 1
ConsumerEndpoint1 -> Received message from gateway : Msg 2
ConsumerEndpoint2 -> Received message from gateway : Msg 2
ConsumerEndpoint1 -> Received message from gateway : Msg 3
ConsumerEndpoint3 -> Received message from gateway : Msg 2
ConsumerEndpoint1 -> Received message from gateway : Msg 4
ConsumerEndpoint3 -> Received message from gateway : Msg 3
ConsumerEndpoint2 -> Received message from gateway : Msg 3
ConsumerEndpoint1 -> Received message from gateway : Msg 5
ConsumerEndpoint3 -> Received message from gateway : Msg 4
ConsumerEndpoint3 -> Received message from gateway : Msg 5
ConsumerEndpoint2 -> Received message from gateway : Msg 4
ConsumerEndpoint2 -> Received message from gateway : Msg 6
ConsumerEndpoint3 -> Received message from gateway : Msg 6
ConsumerEndpoint1 -> Received message from gateway : Msg 6
ConsumerEndpoint2 -> Received message from gateway : Msg 7
ConsumerEndpoint3 -> Received message from gateway : Msg 7
ConsumerEndpoint2 -> Received message from gateway : Msg 5
ConsumerEndpoint2 -> Received message from gateway : Msg 8
ConsumerEndpoint1 -> Received message from gateway : Msg 8
ConsumerEndpoint1 -> Received message from gateway : Msg 7
ConsumerEndpoint1 -> Received message from gateway : Msg 9
ConsumerEndpoint3 -> Received message from gateway : Msg 8
ConsumerEndpoint3 -> Received message from gateway : Msg 9
ConsumerEndpoint2 -> Received message from gateway : Msg 9

You can download source code from below link.

https://github.com/harikrishna553/springboot/tree/master/spring-integration/pub-sub-channel-parallel-delivery-demo



 

Previous                                                    Next                                                    Home

Monday, 31 May 2021

Java: Generate EAN-8 1D format code

Below snippet generates EAN-8 1D code.

Map<EncodeHintType, ErrorCorrectionLevel> hashMap = new HashMap<EncodeHintType, ErrorCorrectionLevel>();
hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

BitMatrix bitMatrix = new MultiFormatWriter().encode(new String(message.getBytes(encodingFormat)),BarcodeFormat.EAN_8, imageWidth, imageHeight);

String fileFormat = filePath.substring(filePath.lastIndexOf('.') + 1);
MatrixToImageWriter.writeToPath(bitMatrix, fileFormat, Paths.get(filePath));

 

Find the below working application.

 

EAN81DFormatUtil.java

package com.sample.app.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class EAN81DFormatUtil {
	public static boolean generateCode(String message, String filePath, Charset encodingFormat, int imageWidth,
			int imageHeight) {

		try {
			Map<EncodeHintType, ErrorCorrectionLevel> hashMap = new HashMap<EncodeHintType, ErrorCorrectionLevel>();
			hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

			BitMatrix bitMatrix = new MultiFormatWriter().encode(new String(message.getBytes(encodingFormat)),
					BarcodeFormat.EAN_8, imageWidth, imageHeight);

			String fileFormat = filePath.substring(filePath.lastIndexOf('.') + 1);
			MatrixToImageWriter.writeToPath(bitMatrix, fileFormat, Paths.get(filePath));
			return true;

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

	public static String getInfoFromCode(String filePath, Charset encodingFormat)
			throws FileNotFoundException, IOException, NotFoundException {
		BinaryBitmap binaryBitmap = new BinaryBitmap(
				new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(new FileInputStream(filePath)))));
		Result result = new MultiFormatReader().decode(binaryBitmap);
		return result.getText();
	}
}

 

EAN81DCodeDemo.java

package com.sample.app;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import com.google.zxing.NotFoundException;
import com.sample.app.util.Aztec2DBarcodeUtil;
import com.sample.app.util.EAN81DFormatUtil;

public class EAN81DCodeDemo {
	public static void main(String args[]) throws FileNotFoundException, NotFoundException, IOException {
		String filePath = "/Users/Shared/secret.png";

		boolean isQRCodeGenerated = EAN81DFormatUtil.generateCode("0101010", filePath, StandardCharsets.UTF_8,
				400, 100);

		if (isQRCodeGenerated) {
			System.out.println("code generated successfully");
		} else {
			System.out.println("code generation failed");
		}

		String information = Aztec2DBarcodeUtil.getInfoFromCode(filePath, StandardCharsets.UTF_8);
		System.out.println("Retrieved message is : " + information);

	}
}

 

Output

code generated successfully

Retrieved message is : 01010107

 

Generated secret.png file

 

 

Previous                                                    Next                                                    Home

Java: Read information from Data Matrix 2D barcode

Below snippet read information from Data matrix 2D barcode.

BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(new FileInputStream(filePath)))));
Result result = new MultiFormatReader().decode(binaryBitmap);
String info = result.getText();

 

Find the below working application.

 

DataMatrix2DBarcodeUtil.java

package com.sample.app.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class DataMatrix2DBarcodeUtil {
	public static boolean generateCode(String message, String filePath, Charset encodingFormat, int imageWidth,
			int imageHeight) {

		try {
			Map<EncodeHintType, ErrorCorrectionLevel> hashMap = new HashMap<EncodeHintType, ErrorCorrectionLevel>();
			hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

			BitMatrix bitMatrix = new MultiFormatWriter().encode(new String(message.getBytes(encodingFormat)),
					BarcodeFormat.DATA_MATRIX, imageWidth, imageHeight);

			String fileFormat = filePath.substring(filePath.lastIndexOf('.') + 1);
			MatrixToImageWriter.writeToPath(bitMatrix, fileFormat, Paths.get(filePath));
			return true;

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

	public static String getInfoFromCode(String filePath, Charset encodingFormat)
			throws FileNotFoundException, IOException, NotFoundException {
		BinaryBitmap binaryBitmap = new BinaryBitmap(
				new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(new FileInputStream(filePath)))));
		Result result = new MultiFormatReader().decode(binaryBitmap);
		return result.getText();
	}
}

 

DataMatrix2DBarcodeDemo.java

package com.sample.app;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import com.google.zxing.NotFoundException;
import com.sample.app.util.Aztec2DBarcodeUtil;
import com.sample.app.util.DataMatrix2DBarcodeUtil;

public class DataMatrix2DBarcodeDemo {
	public static void main(String args[]) throws FileNotFoundException, NotFoundException, IOException {
		String filePath = "/Users/Shared/secret.png";

		boolean isQRCodeGenerated = DataMatrix2DBarcodeUtil.generateCode("123456789", filePath, StandardCharsets.UTF_8,
				400, 100);

		if (isQRCodeGenerated) {
			System.out.println("code generated successfully");
		} else {
			System.out.println("code generation failed");
		}

		String information = Aztec2DBarcodeUtil.getInfoFromCode(filePath, StandardCharsets.UTF_8);
		System.out.println("Retrieved message is : " + information);

	}
}

Output

code generated successfully

Retrieved message is : 123456789

 

Generated secret.png file



 

 

Previous                                                    Next                                                    Home