Category Archives: java

If we want to customize our ids or any other columns of the tables, we can do that in Hibernate without adding the extra tables or columns to the table.

Here we are creating the simple example by using the org.hibernate.usertype.UserType, to generate the customized id.

First we are creating the simple table in MYSQL database:

Following is the Coupon bean:

Coupon.java

We will use following CustomId value object to generate our own type of Id

CustomId.java

So we want to store the data into the COUPON table with the customized id type, for that we need to implement the interface org.hibernate.usertype.UserType. And need to specify which one is the value class to generate the custom id by using one of this interface method returnedClass().

Following is the implementation for CustomIdType class by providing the implementation for the UserType interface.

CustomIdType.java

The brief description about above methods as follows:

sqlTypes: This method returns an array of int, telling Hibernate which SQL column types to use for persisting the entity properties.

returnedClass: This method specifies which Java value type is mapped by this custom type.

assemble: Hibernate calls this method when the instance is fetched from the second-level cache and converted back from binary serialized to the object form.

disassemble: Hibernate may cache any value-type instance in its second-level cache. For this purpose, Hibernate calls this method to convert the value-type instance to the serialized binary form. Return the current instance if the value type implements the java.io.Serializable interface; otherwise, convert it to a Serializable object.

deepCopy: This method creates a copy of the value type if the value type is mutable; otherwise, it returns the current instance. Note that when you create a copy of an object, you should also copy the object associations and collections.

equals: This method compares two instances of the value type mapped by this custom type to check whether they are equal.

hashCode: This method returns a hashcode for the instance, consistent with persistence equality.

isMutable: This method specifies whether the value type is mutable. Since immutable objects cannot be updated or deleted by the application, defining the value type as immutable allows Hibernate to do some minor performance optimization.

nullSafeGet: This method constructs the value-type instance when the instance is retrieved from the database. resultset is the JDBC ResultSet object containing the instance values, names is an array of the column names queried, and owner is the persistent object associated with the value-type instance. Note that you should handle the possibility of null values.

nullSafeSet: This method is called when the value-type instance is written to a prepared statement to be stored or updated in the database. Handle the possibility of null values. A multi-column type should be written to parameters starting from index.

replace: Assume that the application maintains an instance of the value type that its associated session has already closed. Such objects are not tracked and managed by Hibernate, so they are called detached. Hibernate lets you merge the detached object with a session-managed persistent object through the session’s merge() method. Hibernate calls the replace() method when two instances, detached and session-managed, are merged. The first and second arguments of this method are value-type instances associated with a detached and session-managed persistent object, respectively. The third argument represents the owner object, the persistent object that owns the original value type: Coupon in our case. This method replaces the existing (target) value in the persistent object we are merging with a new (original) value from the detached persistent object we are merging. For immutable objects or null values, return the first argument. For mutable objects, return at least a copy of the first argument through the deepCopy() method.

We need to configure the Hibernate configuration file. The example of configuration file as follows,

hibernate.cfg.xml:

We need to write the mapping configuration for the Coupon to COUPON table, so as follows,

coupon.hbm.xml:

And also we need to write the mapping for CustomIdType to tell the hibernate we are using the CustomId as one of the type for our application like as follows,

cutomIdType.hbm.xml:

 

OK, all set. This is the time to test our application, following is the test client program using the Java main method.

CouponCustomIDTest.java:

Output:

Hey, don’t forget to have hibernate cfg file available to classpath.

All The Best 🙂

We should encrypt some sensitive properties like password in real time projects to avoid hacking.

Here we are using  jasypt-spring-boot dependency with spring boot project to encrypt properties and use those properties in code.

Below are the dependencies for different build tools:

Maven:

Gradle:

application.properties:

The example application.properties file in spring boot application look like as following

As you can see, spring.data.mongodb.password value is encrypted. But how was this generated?

We can generate it by using jasypt like below (:

Usage:

We can use spring.data.mongodb.password property in any spring component as like using any other properties.

Example:

Running the Application:

when running the application we should provide the value which is used to generate encrypted password i:e, myEncPwd.

 

Thank You 🙂

In spring Boot applications we can define application.properites file. And in this file we can specify any properties and after that we can access these properties throughout the application.

Spring Boot provided some commonly used application properties. You can look for them here. Spring Common application properties

If we want to define our own custom properties to use in our application, we can define them.

Defining custom property by Java configuration:

  • To define custom properties we need to create one POJO with the annotation @ConfigurationProperties.
  • We can annotate our POJO with the @Component annotation then we no need to create @Bean for our property class explicitly in configuration classes.
  • We can define some prefix for all our properties like @ConfigurationProperties(“machine.config”)

Example property POJO class:

  • To enable the processing of our properties, we need to annotate any of our @Configuration class with @EnableConfigurationProperties(MachineProperties.class) like as following

Example configuration class:

Using of custom property:

Like as any other Spring common properties we can use our custom properties.

  • Specify property name and its value in application.properties file.
  • Access property value with the help of @Value annotation.

Example usage:

 

Note: SpringApplication will load properties from application.properties file by default. If you don’t like application.properties as the configuration file name you can switch to another by specifying a spring.config.name environment property like as following.

 

Thank You 🙂

Here we want to describe and give the example to parse the java objects to xml and xml to java objects using the castor api with the user-defined mapping.

What is Castor XML

Castor XML is an XML data binding framework. Unlike the two main XML APIs, DOM (Document Object Model) and SAX (Simple API for XML) which deal with the structure of an XML document, Castor enables you to deal with the data defined in an XML document through an object model which represents that data.

Castor XML can marshal almost any “bean-like” Java Object to and from XML. In most cases the marshalling framework uses a set of ClassDescriptors and FieldDescriptors to describe how an Object should be marshalled and unmarshalled from XML.

For those not familiar with the terms “marshal” and “unmarshal”, it’s simply the act of converting a stream (sequence of bytes) of data to and from an Object. The act of “marshalling” consists of converting an Object to a stream, and “unmarshalling” from a stream to an Object.

Example:

Following are the Java beans to parse

Company.java

Product.java

Employee.java

→ We should need to specify the default(zero-parameterized) constructor to every bean. Otherwise it will throws the following exception.

“org.exolab.castor.mapping.MappingException: The Java class com.castor.model.Company is not constructable — it does not contain a default public constructor.”

→ We should need to specify setters and getters for fields. Otherwise it will throw the following exception.

“org.exolab.castor.mapping.MappingException: The method getId/isId in class com.castor.model.Company accepting/returning object of type int was not found”.

Following is the service to create the Company instances:

CompanyService.java

CompanyServiceImpl.java

Following is the mapping file to configure the user defined mapping, that allows the (partial) definition of a customized mapping between Java classes (and their properties) and XML.

company_mapping.xml:

→ Here <mapping> is the root tag for Castor mapping file.

<class> is the child for it and this is respect to the java bean.

<map-to> is the child for class and in which we can specify the “xml” attribute value by how we want to see the class tag name.

<field> is the child for <class> which is respect to the field in the java bean.

<bind-xml> is the child for <field>, in which we can provide the “name” attribute value with how we want to see the tag names in generated xml file.

Here we have used some of other attributes for elements, a brief description about those as follows.

ns-uri: To specify the namespace.

ns-prefix: To specify the prefix for namespace.

node: To specify how our field to be generate as attribute or as element.

type: To specify the datatype of the field.

collection: If the datatype is the collection of something we need to specify the collection type.

location: Which is used to specify an element in which we want have some of other related child elements. We can give the name for it. Generally this can be useful for collection of objects.

For more information on the Castor mapping see the Castor Reference.

All set, now we need to test. Here we are providing the test with normal java main method.

CompanyParsingTest.java

→ In this client program we have provided the code, to both marsharlling(java To XML) and UnMarshalling(XML to Java).

→ The Castor will generates the output file with the default XML declaration as

“<?xml version=”1.0″ encoding=”UTF-8″ ?>”

If we want to customize the XML declaration we need to manage in java code like as follows

writer.append(“<?xml version=\”1.0\” encoding=\”UTF-8\” standalone=\”yes\”?>”);

After appending our own XML declaration to writer, we need to suppress Castor not to generate the XML declaration.

marshaller.setSupressXMLDeclaration(true);

→ When we specify the namespace prefix to the <class>, it will generate the prefix to all the child <field> elements which are having the pre-defined data types (it will not generate to the user- defined data types).

→ If we want not to generate namespace prefix we should manage that in java code and we need to configure that in mapping file as like normal fields. Castor is not provided any mapping mechanism for this.

 

Thank You 🙂

In Groovy we can convert the Groovy beans into the XML file and XML file into the Groovy beans.

Here I described and provided the example to convert the Groovy into XML and XML into the Groovy.

Converting the Groovy bean into the XML file:

Groovy provided two techniques to convert the Groovy beans into the XML file. Those are

  • groovy.xml.MarkupBuilder
  • groovy.xml.StreamingMarkupBuilder

There are three key differences between MarkupBuilder and StreamingMarkupBuilder:

  • MarkupBuilder sends its output to System.out by default; StreamingMarkupBuilder is silent until you explicitly hand it off to a Writer.
  • MarkupBuilder is synchronous; StreamingMarkupBuilder is asynchronous. In other words, MarkupBuilder writes the XML document out immediately. StreamingMarkupBuilder allows you to define the closure separately. The document is not generated until the StreamingMarkupBuilder is passed to a Writer.
  • Finally, MarkupBuilder pretty-prints its output, whereas StreamingMarkupBuilder does not.

Example:

Here we have used the StreamingMarkupBuilder to convert Groovy bean into the XML.

Following are the Groovy Beans:

Company.groovy

Product.groovy

Employee.groovy

Following is the service to create the Company instances:

CompanyService.groovy

CompanyServiceImpl.groovy

Now, let’s have trail to generate XML file from the Groovy bean

Here we are given the client with the normal Groovy main method.

CompanyParsingGroovytoXMLTest.groovy

The generated output XML file is looks like as follows,

companyGroovy.xml

We can deal with the Namesapces, XML declarations and also we can change the default encoding value (See the client code above).

Converting the XML file into the Groovy bean:

Groovy provided two techniques to convert the XML file into the Groovy beans. Those are

  • groovy.util.XmlParser
  • groovy.util.XmlSlurper

Difference between XmlParser and XmlSlurper:

Their APIs are almost identical, which is a never-ending source of confusion. (“What is the difference?” “Which one should I use?”) The answer is, of course, that they don’t do exactly the same thing. They are both XML parsing libraries, but each takes a slightly different approach to the problem.

An XmlParser thinks of the document in terms of nodes. When you start dealing with more complex XML documents in just a moment, XmlParser will return a List of nodes as you navigate the tree.

XmlSlurper, on the other hand, treats the document as a groovy.util. slurpersupport.GPathResult. (Since GPathResult is an abstract class, you can see groovy.util.slurpersupport.NodeChild show up as the implementation.) GPath is like XPath,1 only with a “groovier” syntax. XPath uses slash notation to navigate deeply nested XML trees—GPath uses dots to do the same thing.

Example:

Here we have used the groovy.util.XmlParser to convert the XML into the Groovy bean.

For converting the XML into the Groovy bean, we have used the above groovy beans.

→ Following is the XML file which we want to convert to the Groovy bean:

company.xml

→ Following is the client program with main method:

CompanyParsingXMLtoGroovyTest.groovy

The test above will print the Company Object.

→ We can deal with XML namespaces as well by using the class groovy.xml.Namespace.

    We need to create the Namespace instance with the namespace URI like follows

def comp = new groovy.xml.Namespace(“http://uri-of-the-namespace/“)

    And need to invoke the values like follows

company[comp.name.text()]

For more information on Groovy like syntaxes, concepts see reference

For more information on Groovy like classes, methods see Goovy API

 

Thank You 🙂

Java 8 – Lambda Expression: media tableta sildenafil

The biggest language change in Java8 is the introduction of Lambda expressions. Specially we can use it at anonymous inner classes. sildenafil in india online

Syntax :  parameter -> body of the lambda expression.

Here      -> : separates parameter from body.

parameter: name of the parameter same as in anonymous inner class

Overview:

In this place, I’m going to share my understanding on Lambda support in JDK 8 – specifically at how to leverage it to write the Comparator and sort a Collection. where can i get viagra in toronto

Lets have a simple java entity .

Sorting without Lambda:

We can do sort without Lambda to understand current behavior.

sorting a collection would involve creating an anonymous inner class for the Comparator used in the sort:

This would simply be used to sort the List of Member entities:

Sorting with Lambda:

With Lambdas, we can now bypass the anonymous inner class and go achieve the same result with simple, functional semantics:

Similarly – we can now code the behavior just as before:

 

Sorting with no Type Definitions:

We can further simplify the expression by not specifying the type definitions – the compiler is capable of inferring these on its own:

and we can code just as before:

 

What is proxy:
———————-
A proxy server is an intermediary between your PC or device and the Internet. This server makes requests to websites, servers and services on the Internet for you. It is actually a server which helps us maintaining our privacy on the Internet. It is just like a wall between you and the Internet.
When you use a proxy, the webpage on the other side won’t be able to see you, webpage interacts with the proxy and proxy in return shows us the webpage.

A client connects to the proxy server, requesting some service, such as a file, connection, web page, or other resource, available from a different server. The proxy server evaluates the request according to its filtering rules.

A proxy server can be placed in the user’s local computer or at various points between the user and the destination servers on the Internet.

proxy_server1

Advantages:
——————-
Hiding machine or other servers from public. It provides security.
To speed up access to resources (using caching). Web proxies are commonly used to cache web pages from a web server.
To open blocked sites in college schools and some times in offices.
To bypass security/parental controls.
To protect your real identity on internet.

Proxy server settings:
———————————
In twilio client library <7.x old version, we are setting the manually proxy server seetings and add host and port number.
When we are making a twilio api call through proxy server, then we need to configure our proxy host and port number in our customized class.
We are extending the twilio com.twilio.sdk.TwilioRestClient, then set proxy server settings and add host and port number.

In twilio client library (7.1.0) new version, twilio client build every thing for related the proxy server settings,
just we have to add our proxy server host and port number.

When we are making a twilio api call through proxy server, then we need to configure our proxy host and port number in our customized class.
We are extending the twilio NetworkHttpClient, then set our server host and port numbers in customized class constructor.

or

Add the twilio api url into your proxy server configuration file:
——————————————————————————————
And make sure you will add the below url entry in squid filter and restart proxy

Twilio new client version:
————————————–
Twilio new client version 7.x, follow the below code.

Twilio old client version:
———————————–
Twilio old client version <=6.x, then follow the below code.

 

Overview: Get the available twilio phone number from your twilio account configured phone numbers using java, if there is no phone number configured in your twilio account, you can Buy a Number from your twilio account. Your account will be charged when you provision the number, and the number will appear on the Manage Numbers page in your account.

If you want to buy more than one twilio phone numbers, you must upgrade your Twilio account in order to provision additional phone numbers. Once you configured all the twilio phone numbers, then you will get any one number, and that number you will use to send SMS/MMS, make a Voice call.

The following are the types of phone numbers Twilio provides:
— Local numbers
— National numbers
— Toll free numbers
— Mobile numbers

Local numbers: Local numbers are telephone numbers which are assigned to a specific region.
These numbers are typically used by individuals, local businesses and can be considered the most general type of numbers.

use the following maven dependency or set the external jar file for the below version.

Using the below java code snippet for getting the local available twilio phone number.

National numbers: National numbers are telephone numbers which are not region-specific and were designed to be reachable from an entire country at the same cost.

Toll free numbers: Toll free numbers are telephone numbers that are free of charge for the calling party,
and are typically used by businesses when they prefer fully take on the cost of calls for their users. Similar to a geographic area code.

Note: Twilio currently provides toll free numbers in United States, Canada and United Kingdom.
In the United States and Canada, toll-free numbers are enabled for both voice and SMS messaging.
Toll-free numbers in the United Kingdom cannot yet be used to send messages.

Using the below java code snippet for getting the local phone number.

Mobile numbers: Mobile numbers are often the only type of number in the given country that can be used for sending and receiving messages.

Use the following maven dependency or add the external jar file for the below version.

Use the below java code snippet for getting the mobile number from your twilio account. Here using the

<!– [Format Time: 0 le prix du viagra au maroc.0013 seconds] –>

 

1.open the link given below.

2. check the below screenshots,  by default is in decline selected mode change the radio button to accept License agreement.
screen-1

3. for 32-bit OS, below is the link from the above screenshot.

screen-2

4.for 64-bit OS, below is the link .

screen-3

5.extract the tar file manually and open the terminal and check the extracted tar file is in Downloads folder.

6.now check that you have java folder in the specified location.

if you find java folder its okay, otherwise type the below command to create a java folder 

copy

paste the below commands step by step.

7.copy paste the below commands.

8.open the .bashrc file

 now you will see the .bashrc file opened , then copy paste the below statements at last.

save and close this file manually and also close the terminal.

9.check the java version.

now you should get the below screenshot.

screen-5

You have successfully installed JDK1.7.

Building an Android application and launching it into the market might take a lot of time, and if you are a first timer at building an app, it might take even longer. Have you ever wondered if there was a solution simpler and more effective? If you have, we have some news for you! You can quickly set up user registration along with user authentication on your Android app using our pre-built SDK. With WaveLabs IDN(Identity Network), we intend to solve the pain of integrating social logins and the traditional email-password logins.

Even for a pro, it takes around 12 hours or more to integrate Facebook login, and to be honest, half of the time goes into comprehending the documentation. Similarly, for Google, Twitter and other social logins too, it takes the same amount of time. With no proper or reliable results, our turmoil only increases.

We have pre-built SDKs for iOS, Android, Angular, PHP, and Ruby on Rails. Right now, we support the traditional login along with Facebook, Google, Instagram, LinkedIn, AccountKit and all of them in one SDK only. This tutorial is a technical walkthrough to integrate our IDN with your Android app.

Let’s get to building one.

NBOS Android SDK is a client library that can be imported in Android Apps for building an app. Without using the database, you can manage login, registration, authentication, authorization and many more features.

Pre-requisite

Here are a couple of steps that you’ll need to integrate

  1. Import the SDK library
  2. Configure the application
  3. Initialize the SDK
  4. Launch your application

1. Import SDK Library

<img class="aligncenter wp-image-2393 size-full" src="http://blog.nbostech.com/wp-content/uploads/2016/06/^D886E9B1FB3F5D9FB7129D913C53CC73F48F3A856B49D65BA6^pimgpsh_fullsize_distr.png" alt="" width="2560" height="1600" srcset="http://blog.nbostech.com/wp-content/uploads/2016/06/^D886E9B1FB3F5D9FB7129D913C53CC73F48F3A856B49D65BA6^pimgpsh_fullsize_distr.png 2560w, http://blog.nbostech.com/wp-content/uploads/2016/06/^D886E9B1FB3F5D9FB7129D913C53CC73F48F3A856B49D65BA6^pimgpsh_fullsize_distr-300×188.png 300w, http://blog.nbostech.com/wp-content/uploads/2016/06/^D886E9B1FB3F5D9FB7129D913C53CC73F48F3A856B49D65BA6^pimgpsh_fullsize_distr-1024×640.png 1024w, http://blog.nbostech.com/wp-content/uploads/2016/06/^D886E9B1FB3F5D9FB7129D913C53CC73F48F3A856B49D65BA6^pimgpsh_fullsize_distr-624×390 se procurer viagra.png 624w” sizes=”(max-width: 2560px) 100vw, 2560px” />

The SDK is available both in Maven Central and JCenter. To start using it, add the following lines to your build.gradle dependencies file.

2. Configure the Application

Login to nbos.in/app  and get the client id and secret for your app (aka App of Tenant).
Place those credentials in AndroidManifest.xml inside the application tag.

In strings.xml

In Manifest file

3. Initialize the SDK

^377BE3EE33B1E968D82D25F1C8421B086BECFED300D4A9E69F^pimgpsh_fullsize_distr

Add the following code in the Activity or Application class

^0F9C7A26BEFC0FA897E75BB32C05483EB55CF02D646BDDBF99^pimgpsh_fullsize_distr

^EB4441FB5F192557031AC9B3148C36F8FA72E0E6EDA18767CB^pimgpsh_fullsize_distr

Also, our sample code for the starter application is available at https://github.com/nbostech/wavelabs-android-app 

Feel free to play around with it!

That’s it! You are all set to launch your Android app into the market. Attract customers, generate profits, and more importantly, create a space that is uniquely yours. The possibilities are simply endless!

If you have any questions about it, please feel free to get in touch with me.