Friday, 4 June 2021

Java: Generate ITF (Interleaved Two of Five) 1D format code

Below snippet generates ITF 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.ITF, imageWidth, imageHeight);

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

 

Find the below working application.

 

ITFFormatUtil.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 ITFFormatUtil {
	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.ITF, 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();
	}
}

 

ITFFormatDemo.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.ITFFormatUtil;

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

		boolean isQRCodeGenerated = ITFFormatUtil.generateCode("010111001110", 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 : 010111001110

 

Generated secret.png

 


 

 

 

 

Previous                                                    Next                                                    Home

Php: Traits

Traits allow developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

 

Unlike interfaces, traits can have methods with any visibility level.

 

Syntax

trait TraitName{

   

}

 

Example

trait Logger{

   

}

 

How to use a trait?

Syntax

use Trait_name;

 

Example

use Logger;

 

Find the below working application.

 

traits.php

#!/usr/bin/php

<?php

trait Logger{
    public function info($msg){
        $this->log($msg);
    }

    public function debug($msg){
        $this->log($msg);
    }

    public function error($msg){
        $this->log($msg);
    }

    private function log($msg){
        echo $msg;
    }
}

class MyClass{
    use Logger;
}

$obj = new MyClass();

$obj->debug("\nI am debug message\n");
$obj->info("I am information message\n");
$obj->error("I am error message\n");
?>

 

Output

$./traits.php 


I am debug message
I am information message
I am error message

 

 

 

 

 

Previous                                                    Next                                                    Home

Spring integration: PayloadTypeRouter: Route based on content type

PayloadTypeRouter resolves the message channel based on the message content type.

 

Example

@ServiceActivator(inputChannel = "payloadTypeRoutingChannel")
@Bean
public PayloadTypeRouter router() {
	PayloadTypeRouter router = new PayloadTypeRouter();
	router.setChannelMapping(String.class.getName(), "stringChannel");
	router.setChannelMapping(Integer.class.getName(), "integerChannel");
	return router;
}

 As per above definition, if the content type is string, then message is routed to stringChannel. If the content type is Integer, then message is routed to integerChannel.



Find the below working application.

 

Step 1: Create new maven project ‘payload-type-router-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>payload-type-router-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 custom gateway.

 

CustomGateway.java

package com.sample.app.gateway;

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

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

	@Gateway(requestChannel = "payloadTypeRoutingChannel")
	public void print(Message<?> message);

}
 

Step 4: Define endpoints.

 

ConsumerEndpoint1.java

 

package com.sample.app.endpoints;

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

@Component
public class ConsumerEndpoint1 {

	@ServiceActivator(inputChannel = "stringChannel")
	public void consumeStringMessage(Message<String> message) {
		System.out.println("ConsumerEndpoint1 -> Received message from stringChannel : " + message.getPayload());
	}

	@ServiceActivator(inputChannel = "integerChannel")
	public void consumeIntegerMessage(Message<String> message) {
		System.out.println("ConsumerEndpoint1 -> Received message from integerChannel : " + message.getPayload());
	}

}

 

Step 5: Define main application class.

 

App.java

 

package com.sample.app;

import org.springframework.beans.factory.annotation.Autowired;
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.annotation.ServiceActivator;
import org.springframework.integration.router.PayloadTypeRouter;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;

import com.sample.app.gateway.CustomGateway;

@SpringBootApplication
@Configuration
public class App {
	@ServiceActivator(inputChannel = "payloadTypeRoutingChannel")
	@Bean
	public PayloadTypeRouter router() {
		PayloadTypeRouter router = new PayloadTypeRouter();
		router.setChannelMapping(String.class.getName(), "stringChannel");
		router.setChannelMapping(Integer.class.getName(), "integerChannel");
		return router;
	}

	@Autowired
	private CustomGateway customGateway;

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

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

			for (int i = 0; i < 5; i++) {
				Message<?> message = MessageBuilder.withPayload(i).build();
				customGateway.print(message);
			}

			for (int i = 0; i < 5; i++) {
				Message<?> message = MessageBuilder.withPayload("Secret message : " + i).build();
				customGateway.print(message);
			}

		};
	}

}

Total project structure looks like below.



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

 

ConsumerEndpoint1 -> Received message from integerChannel : 0
ConsumerEndpoint1 -> Received message from integerChannel : 1
ConsumerEndpoint1 -> Received message from integerChannel : 2
ConsumerEndpoint1 -> Received message from integerChannel : 3
ConsumerEndpoint1 -> Received message from integerChannel : 4

ConsumerEndpoint1 -> Received message from stringChannel : Secret message : 0
ConsumerEndpoint1 -> Received message from stringChannel : Secret message : 1
ConsumerEndpoint1 -> Received message from stringChannel : Secret message : 2
ConsumerEndpoint1 -> Received message from stringChannel : Secret message : 3
ConsumerEndpoint1 -> Received message from stringChannel : Secret message : 4

 

You can download complete working application from below link.

https://github.com/harikrishna553/springboot/tree/master/spring-integration/payload-type-router-demo

 

 

 

 

 

 

  

Previous                                                    Next                                                    Home

Spring integration: Routing the messages

Router is used to route the messages to specific endpoints.

 


There are multiple ways to route a message.

a.   Based on message type

b.   Based on header value

c.    Based on recipient list

d.   Based on XPath


Previous                                                    Next                                                    Home

Mongo shell: Connect to MongoDB server running on specific port

Using –port option, you can connect to MongoDB server running on specific port.

 

Example

mongo --port 8888

 

Previous                                                    Next                                                    Home

Run MongoDB server on specific port

While starting the MongoDB server, you can explicitly specify the port using --port option.

 

Example

mongod --port 8888 --dbpath /Users/Shared/data/db

Previous                                                    Next                                                    Home

MongoDB: Databases, collections, documents

A MongoDB server can host one or more databases. Each database can have one or more collections. A collection can store documents.


If you are from SQL world, collection is like a table and document is like a row.



Previous                                                    Next                                                    Home