Execute the command ‘cls’ to clear the screen in mongo shell.
Previous Next HomeThis blog is primarily focus on Java fundamentals and the libraries built on top of Java programming language. Most of the post are example oriented, hope you have fun in reading my blog....:)
Friday, 4 June 2021
Setup MongoDB on MAC
Approach 1: Download the executable and install
Step 1: Go to the location ‘https://www.mongodb.com/’ and downliad mongodDB community server edition.
Step 2: Set MondoDB binaries path to system path.
Open terminal and update ~/.bash_profile with following statement.
export PATH=$PATH:{Mongo DB bin folder path}
Load the settings from bash_profile by executing below command.
source ~/.bash_profile
Approach 2: Install Mongodb using brew.
brew tap mongodb/brew
brew install mongodb-community@4.4
Create a folder to store mongodb documents
Create a folder to store the documents. For example, I am using the folder /Users/Shared/data/db to store the documents.
Start mongodb server
Execute below command to start mongodb server
mongod --dbpath /Users/Shared/data/db
Start mongo client
Execute the command ‘mongo’ to connect to the mongoDB server.
$ mongo
MongoDB shell version v4.4.5
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("87ae317a-fe6a-4075-a275-31793d433371") }
MongoDB server version: 4.4.5
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
https://docs.mongodb.com/
Questions? Try the MongoDB Developer Community Forums
https://community.mongodb.com
---
The server generated these startup warnings when booting:
2021-06-04T16:25:12.045+05:30: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
2021-06-04T16:25:12.045+05:30: This server is bound to localhost. Remote systems will be unable to connect to this server. Start the server with --bind_ip <address> to specify which IP addresses it should serve responses from, or with --bind_ip_all to bind to all interfaces. If this behavior is desired, start the server with --bind_ip 127.0.0.1 to disable this warning
2021-06-04T16:25:12.045+05:30: Soft rlimits too low
2021-06-04T16:25:12.045+05:30: currentValue: 2560
2021-06-04T16:25:12.045+05:30: recommendedMinimum: 64000
---
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).
The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.
To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
To get list of commands use ‘db.help()’.
> db.help()
DB methods:
db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [just calls db.runCommand(...)]
db.aggregate([pipeline], {options}) - performs a collectionless aggregation on this database; returns a cursor
db.auth(username, password)
db.cloneDatabase(fromhost) - will only function with MongoDB 4.0 and below
db.commandHelp(name) returns the help for the command
db.copyDatabase(fromdb, todb, fromhost) - will only function with MongoDB 4.0 and below
db.createCollection(name, {size: ..., capped: ..., max: ...})
db.createUser(userDocument)
db.createView(name, viewOn, [{$operator: {...}}, ...], {viewOptions})
db.currentOp() displays currently executing operations in the db
db.dropDatabase(writeConcern)
db.dropUser(username)
db.eval() - deprecated
db.fsyncLock() flush data to disk and lock server for backups
db.fsyncUnlock() unlocks server following a db.fsyncLock()
db.getCollection(cname) same as db['cname'] or db.cname
db.getCollectionInfos([filter]) - returns a list that contains the names and options of the db's collections
db.getCollectionNames()
db.getLastError() - just returns the err msg string
db.getLastErrorObj() - return full status object
db.getLogComponents()
db.getMongo() get the server connection object
db.getMongo().setSecondaryOk() allow queries on a replication secondary server
db.getName()
db.getProfilingLevel() - deprecated
db.getProfilingStatus() - returns if profiling is on and slow threshold
db.getReplicationInfo()
db.getSiblingDB(name) get the db at the same server as this one
db.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set
db.hostInfo() get details about the server's host
db.isMaster() check replica primary status
db.hello() check replica primary status
db.killOp(opid) kills the current operation in the db
db.listCommands() lists all the db commands
db.loadServerScripts() loads all the scripts in db.system.js
db.logout()
db.printCollectionStats()
db.printReplicationInfo()
db.printShardingStatus()
db.printSecondaryReplicationInfo()
db.resetError()
db.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into {cmdObj: 1}
db.serverStatus()
db.setLogLevel(level,<component>)
db.setProfilingLevel(level,slowms) 0=off 1=slow 2=all
db.setVerboseShell(flag) display extra information in shell output
db.setWriteConcern(<write concern doc>) - sets the write concern for writes to the db
db.shutdownServer()
db.stats()
db.unsetWriteConcern(<write concern doc>) - unsets the write concern for writes to the db
db.version() current version of the server
db.watch() - opens a change stream cursor for a database to report on all changes to its non-system collections.
That’s it you are done….:)
Thursday, 3 June 2021
Php: class implement multiple interfaces
In Php, a class can implement multiple interfaces.
Syntax
class ClassName implements interface1, interface2....interfaceN{
//Provide definition to all the method signatures of interface.
}
Example
class MyCircle implements Circle{
public const PI = 3.14;
public function area_of_circle($radius){
return self::PI * $radius * $radius;
}
public function perimeter_of_circle($radius){
return 2 * self::PI * $radius;
}
public function info($msg){
echo $msg;
}
public function debug($msg){
$this->info($msg);
}
public function error($msg){
$this->info($msg);
}
}
Class implementing the interfaces must provide definition of all the methods signatures.
class_implement_multiple_interfaces.php
#!/usr/bin/php
<?php
interface Circle{
public function area_of_circle($radius);
public function perimeter_of_circle($radius);
}
interface Logger{
public function info($msg);
public function debug($msg);
public function error($msg);
}
class MyCircle implements Circle{
public const PI = 3.14;
public function area_of_circle($radius){
return self::PI * $radius * $radius;
}
public function perimeter_of_circle($radius){
return 2 * self::PI * $radius;
}
public function info($msg){
echo $msg;
}
public function debug($msg){
$this->info($msg);
}
public function error($msg){
$this->info($msg);
}
}
$circle1 = new MyCircle();
$radius = 12;
$area = $circle1->area_of_circle($radius);
$perimeter = $circle1->perimeter_of_circle($radius);
echo "Radius of Circle : $radius\n";
echo "Area of Circle : $area\n";
echo "Perimeter of Circle : $perimeter\n";
$circle1->debug("\nI am debug message\n");
$circle1->info("I am information message\n");
$circle1->error("I am error message\n");
?>
Output
$./class_implement_multiple_interfaces.php
Radius of Circle : 12
Area of Circle : 452.16
Perimeter of Circle : 75.36
I am debug message
I am information message
I am error message
Previous Next Home
Php: Interfaces
Interface is an abstract type that contain method signatures(It do not contain method definitions). Since interface describes the contract, it contains only public functions.
How to create an interface?
‘interface’ keyword is used to create an interface.
Syntax
interface InterfaceName{
public function function_1(args);
public function function_2(args);
.....
.....
.....
}
Example
interface Circle{
public function area_of_circle($radius);
public function perimeter_of_circle($radius);
}
How to implement an interface?
Once an interface is defined, a class can implement this interface and provide definition of all the signatures declared interface.
Syntax
class ClassName implements InterfaceName{
//Provide definition to all the method signatures of interface.
}
Example
class MyCircle implements Circle{
public const PI = 3.14;
public function area_of_circle($radius){
return self::PI * $radius * $radius;
}
public function perimeter_of_circle($radius){
return 2 * self::PI * $radius;
}
}
Find the below working application.
interfaces.php
#!/usr/bin/php
<?php
interface Circle{
public function area_of_circle($radius);
public function perimeter_of_circle($radius);
}
class MyCircle implements Circle{
public const PI = 3.14;
public function area_of_circle($radius){
return self::PI * $radius * $radius;
}
public function perimeter_of_circle($radius){
return 2 * self::PI * $radius;
}
}
$circle1 = new MyCircle();
$radius = 12;
$area = $circle1->area_of_circle($radius);
$perimeter = $circle1->perimeter_of_circle($radius);
echo "Radius of Circle : $radius\n";
echo "Area of Circle : $area\n";
echo "Perimeter of Circle : $perimeter\n";
?>
Output
$./interfaces.php
Radius of Circle : 12
Area of Circle : 452.16
Perimeter of Circle : 75.36
Previous Next Home
Java: Read information from EAN-13 1D format code
Below snippet reads information from EAN-13 1d format code.
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.
EAN131DFormatUtil.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 EAN131DFormatUtil {
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_13, 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();
}
}
EAN131DCodeDemo.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.EAN131DFormatUtil;
public class EAN131DCodeDemo {
public static void main(String args[]) throws FileNotFoundException, NotFoundException, IOException {
String filePath = "/Users/Shared/secret.png";
boolean isQRCodeGenerated = EAN131DFormatUtil.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 : 101110011105
Generated secret.png
Java: Generate EAN-13 1D format code
Below snippet generate EAN-13 1d format 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_13, imageWidth, imageHeight);
String fileFormat = filePath.substring(filePath.lastIndexOf('.') + 1);
MatrixToImageWriter.writeToPath(bitMatrix, fileFormat, Paths.get(filePath));
Find the below working application.
EAN131DFormatUtil.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 EAN131DFormatUtil {
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_13, 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();
}
}
EAN131DCodeDemo.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.EAN131DFormatUtil;
public class EAN131DCodeDemo {
public static void main(String args[]) throws FileNotFoundException, NotFoundException, IOException {
String filePath = "/Users/Shared/secret.png";
boolean isQRCodeGenerated = EAN131DFormatUtil.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 : 101110011105
Generated secret.png

