Search This Blog

Showing posts with label sample. Show all posts
Showing posts with label sample. Show all posts

Monday, April 24, 2023

Java Sample - Copy any object into any object including sub object fields generic

 Steps 1:

Source

Person.java(list address)

Address.java(User.java)


public class Person implements Serializable

{

private String firstName;

private String lastName;

private int age;

private List <AddressaddressList;

}

public class Address implements Serializable

{

private int id;

private String address1;

private String address2;

private String city;

private String state;

private String country;

private String pincode;

private String contactNumber;

private String email;

private User user;

}




Target

PersonDTO.java (list addressDTO)

AddressDTO.java (User.java)

public class PersonDTO implements Serializable

{

private String firstName;

private int age;

private String lastName;

private List <AddressDTO> addressList;

}

public class AddressDTO implements Serializable

{

private int id;

private String address1;

private String address2;

private String city;

private String state;

private String country;

private String pincode;

private String contactNumber;

private String email;

private User user;

}


Step 2: Sample java class

package com.drvijay;

import java.lang.reflect.Field;

import java.lang.reflect.Modifier;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.HashMap;

import java.util.List;

import org.apache.commons.lang3.RandomStringUtils;

import com.product.base.utils.ObjectUtils;

import com.product.base.utils.ProductConstants;

/**

* @author drvijay

* @date Apr-20-2023 10:30 AM

*/

@SuppressWarnings ( "unused" )

public class UtilHelper

{

private static final long serialVersionUID = 1L;

public static void copy ( Object source, Object target ) throws IllegalArgumentException, IllegalAccessException

{

Class <?> sourceClass = source.getClass ();

Class <?> targetClass = target.getClass ();

Field [] sourceFields = sourceClass.getDeclaredFields ();

Field [] targetFields = targetClass.getDeclaredFields ();

for ( Field sourceField : sourceFields )

{

for ( Field targetField : targetFields )

{

// If the source and target fields have the same name and type

if ( sourceField.getName ().equals ( targetField.getName () ) && sourceField.getType ().equals ( targetField.getType () ) )

{

// Make the source and target field accessible

sourceField.setAccessible ( true );

targetField.setAccessible ( true );

// Copy the value from the source field to the target field

targetField.set ( target, sourceField.get ( source ) );

// Stop looping through the target fields

break;

}

}

}

}

public static void main ( String [] args ) throws Exception

{

// Create a source object

Person sourcePerson = new Person ();

sourcePerson.setFirstName ( "vijay" );

sourcePerson.setLastName ( "kumar" );

sourcePerson.setAge ( 30 );

User u = new User ();

u.setUA ( "ua" );

u.setUB ( "ub" );

List<Address> aList = new ArrayList();

Address address = new Address ();

address.setAddress1 ( "add 1" );

address.setAddress2 ( "add 2" );

address.setPincode ( "54534" );

address.setUser ( u );

aList.add ( address );

address = new Address ();

address.setAddress1 ( "add 11" );

address.setAddress2 ( "add 22" );

address.setPincode ( "545341" );

aList.add ( address );

sourcePerson.setAddressList ( aList );

// Create a target object with similar properties

PersonDTO targetPersonDTO = new PersonDTO ();

// Copy the properties from the source object to the target object

UtilHelper.copy ( sourcePerson, targetPersonDTO );

// Print the values of the target object

System.out.println ( targetPersonDTO.getFirstName () );

System.out.println ( targetPersonDTO.getAge () );

System.out.println ( sourcePerson.toString () );

System.out.println ( targetPersonDTO.toString () );

System.out.println ( targetPersonDTO.getAddressList ().toString () );

}

}



Output


vijay

30

Person(firstName=vijay, lastName=kumar, age=30, addressList=[Address(id=0, address1=add 1, address2=add 2, city=null, state=null, country=null, pincode=54534, contactNumber=null, email=null, user=User(uA=ua, uB=ub)), Address(id=0, address1=add 11, address2=add 22, city=null, state=null, country=null, pincode=545341, contactNumber=null, email=null, user=null)])

PersonDTO(firstName=vijay, age=30, lastName=kumar, addressList=[Address(id=0, address1=add 1, address2=add 2, city=null, state=null, country=null, pincode=54534, contactNumber=null, email=null, user=User(uA=ua, uB=ub)), Address(id=0, address1=add 11, address2=add 22, city=null, state=null, country=null, pincode=545341, contactNumber=null, email=null, user=null)])

[Address(id=0, address1=add 1, address2=add 2, city=null, state=null, country=null, pincode=54534, contactNumber=null, email=null, user=User(uA=ua, uB=ub)), Address(id=0, address1=add 11, address2=add 22, city=null, state=null, country=null, pincode=545341, contactNumber=null, email=null, user=null)]


Monday, October 11, 2021

Java to Do ImageMagick Call

 package com.product.zilly;


import java.io.File;

import java.util.Map;


import org.slf4j.Logger;

import org.slf4j.LoggerFactory;


/**

 * @author drvijay

 * @description img class

 * @version 1.0

 */


@SuppressWarnings ("all")

public class TestModules implements Constants

{

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


public static void main ( String args[] )

{

ImageHelper imageHelper = new ImageHelper ();

String renditionPath = "/home/drvijay/images"; 

String rendtionPathCategory = "/home/drvijay/images"; 

String startingMainPath = renditionPath + PATH_SEPARATOR + SkuRendition.main;

String startingCategoryMainPath = rendtionPathCategory + PATH_SEPARATOR + SkuRendition.main; // for category images main path

imageHelper.loadSkuImageProperties ();

boolean imageOverride = false; 

File rotated = null;

File file = new File ( startingMainPath + PATH_SEPARATOR + "sample.png" );

if ( file.isFile () && file.exists () )

{

Map <SkuRendition, Map <Resolution, DimInfo>> dimensions = imageHelper.getAllDimensions ();

logger.debug ( dimensions.toString () );

for ( SkuRendition skuRendition : dimensions.keySet () )

{

try

{

Map <Resolution, DimInfo> resolutions = dimensions.get ( skuRendition );

for ( Resolution resolution : resolutions.keySet () )

{

DimInfo dimInfo = resolutions.get ( resolution );


File isExist = new File ( renditionPath + PATH_SEPARATOR + skuRendition.name () + PATH_SEPARATOR + resolution.name () + UNDER_SCORE + file.getName () );

if ( ( imageOverride && isExist.isFile () && isExist.exists () ) || ( !isExist.isFile () && !isExist.exists () ) )

{

rotated = imageHelper.processImage ( file, imageHelper.getOutputDir ( renditionPath, skuRendition.name () ), dimInfo, resolution.name () );

logger.debug ( "Generated : " + rotated.getAbsolutePath () );

}


}

}

catch ( Exception e )

{

logger.error ( "Error : " + e );

}

finally

{


/*

* if ( rotated != null )

* {

* rotated.delete ();

* }

*/


}

}

}

}

}


//Iamge Process

public File processImage ( File inFile, File outputDir, DimInfo dimInfo, String resolution ) throws Exception

{

String fileName = resolution + UNDER_SCORE + inFile.getName ();

// String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);

// String fileNameExt = FilenameUtils.getExtension ( fileName );


// check for windows and set the image magick home manually to avoid error.

String OS = System.getProperty ( "os.name" ).toLowerCase ();

if ( ( OS.indexOf ( "win" ) >= 0 ) )

{

// linux - "/usr/lib/mime/packages/imagemagick-6.q16";

String myPath = "C:/Program Files/ImageMagick-6.9.2-Q16"; // globalMaster.getSystemProperties ().get ( KEY_PATH_HOME_IMAGE_MAGICK ).getValue ();

ProcessStarter.setGlobalSearchPath ( myPath );

}

ConvertCmd convert = new ConvertCmd ();

IMOperation operation = new IMOperation ();

String input = inFile.getAbsolutePath ();

int tmbWidth = dimInfo.getWidth ();

int tmbHeight = dimInfo.getHeight ();


operation.addImage ( input );

operation.gravity ( LocalProperties.getPropertyValue ( "render.image.gravity" ) );

operation.thumbnail ( tmbHeight, tmbWidth );

operation.units ( LocalProperties.getPropertyValue ( "render.image.units" ) );

operation.density ( Integer.parseInt ( LocalProperties.getPropertyValue ( "render.image.density" ) ) );

operation.strip ();

operation.interlace ( LocalProperties.getPropertyValue ( "render.image.interlace" ) );

operation.gaussianBlur ( Double.parseDouble ( LocalProperties.getPropertyValue ( "render.image.gaussian.blur" ) ) );

operation.quality ( Double.parseDouble ( LocalProperties.getPropertyValue ( "render.image.quality" ) ) );


File retVal = new File ( outputDir, fileName );

operation.addImage ( retVal.getAbsolutePath () );

convert.run ( operation );


logger.debug ( "Preview file: " + retVal.getAbsolutePath () );

return retVal;

}


Tuesday, December 10, 2019

Python Google Speech Setup and Example (WINDOWS)

1. Download SOX latest version - https://sourceforge.net/projects/sox/files/sox/

2. Install it (ex: C:\Program Files (x86)\sox-14-4-2 )
     2.1 download 2 (libmad-0.dll, libmp3lame-0.dll) DLLs and copy to C:\Program Files (x86)\sox-14-4-2;

                 https://app.box.com/s/tzn5ohyh90viedu3u90w2l2pmp2bl41t


3. Set environment path in system variable

4. Restart the IDE or CMD prompt

5. in cmd prompt
        set path=%path%;C:\Program Files (x86)\sox-14-4-2;
       echo %path%

6. pip install google_speech
    pip install sox

7. create a sample test.py


from google_speech import Speech

# say "Hello World"
text = "Hello This is Vijay DR";
lang = "en";
speech = Speech(text, lang);
speech.play();

# you can also apply audio effects while playing (using SoX)
# see http://sox.sourceforge.net/sox.html#EFFECTS for full effect documentation
sox_effects = ("speed", "1.5");
speech.play(sox_effects);

# save the speech to an MP3 file (no effect is applied)
speech.save("output.mp3");


8. cmp prompt py test.py



enjoy !
vijay

Thursday, July 18, 2019

Java RabbitMQ - Sample Send Receiver

//path lib setting
set CLASSPATH=.;lib\amqp-client-5.4.1.jar;lib\*.jar;lib\slf4j-api-1.7.26.jar;

//compile
javac TestSender.java

//run
java TestSender


TestSender.java

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class TestSender
{

private final static String QUEUE_NAME = "rmq";

public static void main ( String [] argv ) throws Exception
{
ConnectionFactory factory = new ConnectionFactory ();
factory.setHost ( "192.168.7.11" );
factory.setPort ( 8890 ); //always give HA port to test if you want to do HA testing. else give queue port
factory.setUsername ( "test" );
factory.setPassword ( "test" );
try (Connection connection = factory.newConnection ();
Channel channel = connection.createChannel ())
{
channel.queueDeclare (QUEUE_NAME, true, false, false, null );
String message = "Hello World111!";
channel.basicPublish ( "", QUEUE_NAME, null, message.getBytes ( "UTF-8" ) );
System.out.println ( " [x] Sent '" + message + "'" );
}
}
}


TestReceiver.java

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

public class TestReceiver
{

private final static String QUEUE_NAME = "rmq";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost ( "192.168.7.13" );
factory.setPort ( 5672 ); //always receive with your default queue port and not HA port
factory.setUsername ( "test" );
factory.setPassword ( "test" );

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
        };
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
    }
}



NOTE: channel.queueDeclare (QUEUE_NAME, true, false, false, null ); //if durable else give false instead of true.

Monday, September 10, 2012

What is RPC [ Remote Procedure Call ] ?

Remote procedure call (RPC) is an inter-process communication that allows a computer program to cause a subroutine or procedure to execute in another address space (commonly on another computer on a shared network) without the programmer explicitly coding the details for this remote interaction.

 

Sequence of events during a RPC

  1. The client calls the client stub. The call is a local procedure call, with parameters pushed on to the stack in the normal way.
  2. The client stub packs the parameters into a message and makes a system call to send the message. Packing the parameters is called marshaling.
  3. The client's local operating system sends the message from the client machine to the server machine.
  4. The local operating system on the server machine passes the incoming packets to the server stub.
  5. The server stub unpacks the parameters from the message . Unpacking the parameters is called unmarshaling.
  6. Finally, the server stub calls the server procedure. The reply traces the same steps in the reverse direction.

Hit Counter


View My Stats