Posted by Editor | 4/24/2015 01:01:00 p.m. | 0 comments »

If you are a programmer, you would have faced this kind of issue at least once in your programming life, a long folder structure got created and you are not able to delete it using Windows delete option nor with DOS commands.

Normally you can delete folders recursively using command "rmdir", for example, "rmdir delete_me /s /q" but if it is really large rmdir simply returns an error "File name too large...".

Root cause: In Windows and DOS, there is a flag "MAX_PATH" which has value 260, means a file path can have only a maximum of 260 characters including the drive and null character("D:\256-character path string"). So, files created by other programs which has more than 260 characters cannot be deleted using Windows or DOS commands.

There are multiple ways to delete these files/folders, like moving few set of folders into the root folder, or writing a script which will recursively delete folders etc. If you don't want to spend time on these try the command "robocopy". Robocopy is a Windows command to copy files from one location to another.

Syntax: robocopy <Source> <Destination> [<File>[ ...]] [<Options>]

There is an optional flag MIR which can be used to mirror a directory tree. We will use this flag to delete the folders recursively, how?

First we will create an empty directory say "c:\empty". Say the folder we want to delete is "c:\delete_me", then issue the command:

robocopy "c:\empty" "c:\delete_me" /MIR
The trick is, robocopy tries to mirror the empty folder; since there are no files or folders in the source directory, it simply deletes the files and folders under target directory recursively! Nice trick, isn't it?

Hope we saved your day! Feel free to drop your comments below.

Continue reading...

Posted by Editor | 2/27/2015 02:31:00 p.m. | 3 comments »
By default, Jackson JSON processor does not wrap the JSON object with the root name when used with JaxB Introspection(@JsonRootName will work for non-JaxB implementation). You can enable this feature by setting the property SerializationConfig.Feature.WRAP_ROOT_VALUE and DeserializationConfig.Feature.UNWRAP_ROOT_VALUE to true.

Domain Object - User.java

@XmlType(name = "user")
public class User implements Serializable {

    @XmlElement(name = "first_name")
    protected String firstName;

    @XmlElement(name = "last_name")
    protected String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String value) {
        this.firstName = value;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String value) {
        this.lastName = value;
    }
}
Default Jackson generated JSON Output
{"first_name": "James", "last_name": "Gosling"}
With WRAP_ROOT_VALUE=true
{"User": {"first_name": "James", "last_name": "Gosling"} }
All good? Not yet. Noticed the naming convention used in the root node? It came out in Pascal case(begins with a capital letter), how? By default Jackson uses class name as the root name. This makes our JSON output ugly. Let us find a way to make this root name inline with our naming convention.

JaxbAnnotationIntrospector for your rescue

We can tell Jackson ObjectMapper to use JAXB annotations to map objects with name and change the behavior of name generation by providing a customized version of JaxbAnnotationIntrospector. We can use this class to change the root name or even the property names; change to lower case, change to upper case, suffix or prefix names with custom string or even give new name to the elements.

Name root element as defined in JaxB

Below class overrides findRootName() of JaxbAnnotationIntrospector and returns the XmlType as root name.
public class MyAnnotationIntrospector extends JaxbAnnotationIntrospector {
 @Override
 public String findRootName(AnnotatedClass ac) {

  return ac.getAnnotations().get(XmlType.class).name();
 }
}
If you want to do it for only specific domain objects, you can add the below condition:
 if(ac.getAnnotated().getName().equalsIgnoreCase("com.texient.domain.User")) {...}
Now you can use this introspector in the mapper object:
public class MyObjectMapperFactory {

    public static ObjectMapper createMapper() {

        final ObjectMapper mapper = new ObjectMapper(); 
        final JaxbAnnotationIntrospector myAnnotationIntrospector = new MyAnnotationIntrospector();

        final DeserializationConfig deserializeConf = mapper.getDeserializationConfig()  
                .with(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE)
                .withAnnotationIntrospector(myAnnotationIntrospector);

        mapper.setDeserializationConfig(deserializeConf);

        final SerializationConfig serializeConf = mapper.getSerializationConfig()
                .with(SerializationConfig.Feature.WRAP_ROOT_VALUE)
                .withSerializationInclusion(JsonSerialize.Inclusion.NON_NULL)
                .withAnnotationIntrospector(myAnnotationIntrospector);

        mapper.setSerializationConfig(serializeConf);

        return mapper;
    }
}

Conclusion

So, with a custom Annotation Introspector you can customize the way the JSON serialization and de-serialization are done. Feel free to drop your feedback below.
Continue reading...

Posted by Editor | 12/26/2014 02:04:00 p.m. | 0 comments »
In some cases you may need to get nextval of a sequence in your Spring bean, say for example you need to generate a CSV file with a unique id column.
 
In this tutorial, we are explaining how to create a sequence in PostgreSQL and how to get the next value from the sequence in a Spring bean.

Creating a sequence in PostgreSQL

First we will create a sequence named texient_uuid_seq in PostgreSQL. For this, execute the following command in the terminal:
-- Sequence: texient_uuid_seq

-- DROP SEQUENCE texient_uuid_seq;

CREATE SEQUENCE texient_uuid_seq
  INCREMENT 1
  MINVALUE 1
  MAXVALUE 9223372036854775807
  START 100000
  CACHE 1;
ALTER TABLE texient_uuid_seq
  OWNER TO postgres;
A sequence named texient_uuid_seq is created.

Defining the Beans

A straight forward approach would be to use plain sql as given below:
 
Query q = entityManager.createNativeQuery(
                "SELECT texient_uuid_seq.nextval from DUAL");
BigDecimal result = (BigDecimal)q.getSingleResult();   
return result.longValue();
Spring has some in-built classes to deal with sequences, those are:
  • DB2SequenceMaxValueIncrementer
  • OracleSequenceMaxValueIncrementer
  • PostgreSQLSequenceMaxValueIncrementer
All these classes implements DataFieldMaxValueIncrementer, so this can be used in your DAO classes without worrying about the implementation.
 
In this tutorial, we will use PostgreSQLSequenceMaxValueIncrementer to get the next value from the sequence texient_uuid_seq. Define the following beans in your application context:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
  destroy-method="close">
 <property name="driverClassName" value="${texient.jdbc.driver}" />
 <property name="url" value="${texient.jdbc.url}" />
 <property name="username" value="${texient.jdbc.user}" />
 <property name="password" value="${texient.jdbc.password}" />
 <property name="maxActive" value="${texient.jdbc.pool.size}"/>
 <property name="validationQuery" value="${texient.jdbc.validationQuery}"/>
 <property name="testWhileIdle" value="${texient.jdbc.testWhileIdle}"/>
</bean>

<bean id="transactionManager" 
  class="org.springframework.jdbc.datasource.DataSourceTransactionManager" 
  lazy-init="true">
 <property name="dataSource" ref="dataSource" />
</bean>

<bean id="uidIncrementer" 
 class="org.springframework.jdbc.support.incrementer.PostgreSQLSequenceMaxValueIncrementer">
 <property name="dataSource" ref="dataSource" />
 <property name="incrementerName" value="texient_uuid_seq" />
</bean>

First, we defined a dataSource bean, then a transactionManager and finally a uidIncrementer bean. Let us concentrate on the uidIncrementer bean, there are two properties set, first the dataSource and the second, the incrementerName. incrementerName is nothing but the PostgreSQL sequence we created in the first step.

Getting the next value in a Spring Bean

Now let us write a utility bean named UidGenerator which returns the next value from the sequence.
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.jdbc.support.incrementer.
          PostgreSQLSequenceMaxValueIncrementer;
import org.springframework.stereotype.Component;

@Component
public class UidGenerator implements ApplicationContextAware {
 
 private static ApplicationContext context;

 public Long getUid() {
  PostgreSQLSequenceMaxValueIncrementer uidIncrementer = 
      (PostgreSQLSequenceMaxValueIncrementer)context.getBean("uidIncrementer");
  return uidIncrementer .nextLongValue();
 }

 public void setApplicationContext(ApplicationContext ac) {
  context = ac;
 }

}
Now you can inherit other classes from UidGenerator to get the next value from the sequence.

Conclusion

In this tutorial, we learnt how to get the next value of a sequence in a Spring bean. A detailed tutorial will be published soon on how to use a CSV file generator using Spring batch, stay tuned.
Continue reading...

Posted by Editor | 12/22/2014 03:46:00 p.m. | 5 comments »

As you know Redmi Note comes pre-loaded with MIUI launcher. There are no other launchers pre-installed on this device, you may install and activate other launchers like Nova launcher from Google Play Store but not the Android default Google Now Launcher.

Even-though MIUI is a smart and popular launcher, those who are already an Android user would find it difficult to familiarize with this launcher, especially lack of App drawer feature.

This guide is for those who want to make Google Now as the default launcher.

MIUI Launcher   Google Now Launcher

Even if you download Google Now launcher it will not appear in the available launchers list. Follow the below steps carefully in order to install and enable Google Now Launcher on your Redmi Note.

  1. First, uninstall Google Now Launcher if already installed
  2. Now open Google folder and select Google Settings
  3. Select Search & Now and enable Google Now


  4. Then go to Google Play Store and install Google Search
  5. Now install Google Now Launcher
  6. Now we need to select Google Launcher as the default launcher
  7. Go to Settings->General Settings->Display->Default Launcher
  8. Click on the arrow on the right side of Google Search option


  9. Select Replace as option
  10. Now press the Home button, you will see Google Now Launcher set as the default launcher

Let us know if you are facing issues setting up Google Launcher as the default launcher in your Redmi Note. You may follow the same instructions for Redmi 1s as well.

Continue reading...

Posted by Editor | 12/19/2014 04:27:00 p.m. | 31 comments »

Everyone knows buying a house is not only an investment but also a smart way to save tax. There are various sections under income tax act to save tax in terms of principal repaid and the interest.

Section 80C

Under this section, an individual can save tax on the principal repaid in the current financial year. The overall deduction is limited to 1.5 Lakhs which also includes employee provident fund, public provident fund, national savings certificates, life insurance premiums, tax saving fixed deposits etc.

Section 24(b)

This section allows you to deduct the interest paid during the financial year from the taxable income. For self occupied property the limit is 2 Lakhs where for let-out property there is no limit.

How to avail tax benefits?

To avail tax benefits, declare your investments in the beginning of the financial year itself so that the TDS(tax deducted at source) would be same throughout the year. You need to submit the investment proofs to your employer at the end of the financial year, otherwise all tax benefits already availed would be deducted from your last month salary(some employers starts this activity in December and the difference is deducted from the salary for the month of Jan, Feb and Mar).

What kind of proofs need to be submitted for home loan?

You need to submit provisional certificate of your home loan account to avail income tax benefits under Section 24(b) and Section 80c. It should contain breakup of the principal and interest paid in the current financial year, otherwise your employer may reject your claim.

How to get provisional certificate for my SBI MaxGain loan account?

One of the most popular home loan product from State Bank of India named MaxGain did not have an option to generate provisional certificate online but few weeks back SBI introduced this option in their online banking portal.

Earlier, to get the provisional certificate, one had to personally visit the home branch. With the online option, by sitting at home, you can generate principal and interest paid certificate against your loan account, which can be submitted as an investment proof.

How to generate MaxGain Provisional Certificate?

First, log into your SBI online account by going to http://www.onlinesbi.com

Now click on the Enquiries tab

On the left side you will see a link named Home Loan Int. Cert.(Prov). This link will take you to the home loan interest paid certificate generation screen. Click the link.

Now select your home loan account(account type will be OD account - Over Draft account) and click the submit button.

This will generate the interest paid certificate on the screen. Scroll down to the bottom and click on View/Download certificate in PDF Format and download the certificate in pdf format.

This certificate contains the following information:

  • Name and address of the borrower
  • Loan account number
  • Date of sanction
  • Loan limit
  • Actual repayment
  • Expected repayment
  • Total paid, principal and interest

That's it. Take a printout and submit it to your finance team along with other income tax savings proofs. Now in the comfort of your home or office you can generate the provisional certificate.

Conclusion

Let us know your feedback, feel free to post your comments below, we will get back as soon as possible.

Continue reading...

Posted by Editor | 10/15/2014 02:31:00 p.m. | 0 comments »

Have you got a javax.net.ssl.SSLHandshakeException while trying to connect to a URL which is SSL encrypted? You want to connect to a web page or a SOAP Web Service from your Java application but it is throwing the below exception:

Exception in thread "main" javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

The error says the connection could not be established due to a certificate validation error. You might be wondering why some urls are working while some not. To understand this you need to know what is SSL and how SSL works.

What is Secure Socket Layer?

SSL stands for Secure Socket Layer which is a protocol in which the data transfer between a Web Client(e.g. web browser) and a Web Server takes place in an encrypted format. Content encrypted by the server is decrypted by the client using a public-private key pair.

Key pairs contains a public key and a private key, content encrypted with one key can be decrypted with the other. All modern browsers includes a set of well known certificates issued by certificate authorities(CA), which makes the encryption-decryption possible for HTTPS sites.

Why Java throwing javax.net.ssl.SSLHandshakeException for some SSL sites?

As in browser, JRE also contains a trustsore where all trusted CA certificates are stored. This truststore is stored in a file named cacerts located at <JRE_HOME>/lib/security/. You can connect to all HTTPS sites which are having certificates trusted by Java truststore but a SSLHandshakeException is thrown for sites with untrusted certificates(including self signed certificates).

How to avoid SSLHandshakeException?

There are many ways to overcome SSLHandshakeException, some are given below:

  1. Adding certificate to Java trust store manually
  2. Adding certificate to Java trust store programmatically
  3. Use custom trust store
  4. Turn off certificate validation

Safest option is to add the certificate to Java trust store manually to avoid any security issues.

How to add SSL certificate to the Java Truststore?

It is a two step process, first download the certificate, then add the certificate to the truststore.

1. Downloading the certificate

First, open the url in your browser(steps may vary depends on the browser), then click on the lock icon on the navigation bar, then click on Certificate Information. Now go to Details tab, there you will see a Copy to File button. Clicking on this will give you a certificate export wizard where you need to select certificate format as DER encoded binary X.509. Give a file name say mycertificate.cer and save the file.

2. Adding certificate to the Java truststore

This is a simple step, go to <JRE_HOME>/bin and execute the below command:

keytool -import -alias alias -keystore ../lib/security/cacerts 
      -file mycertificate.cer
Enter the default keystore password 'changeit'(changeme on Mac) for the prompt 'Enter keystore password:'.

Then enter 'yes' for the prompt 'Trust this certificate? [no]:' and press enter key.

If everything goes well, you will get a message 'Certificate was added to keystore' which confirms your certificate is added to the Java truststore successfylly!

Connecting to a HTTPS site with URLConnection

Below program will now work without any SSL handshake exception:

 URL url = new URL("https://secure.skunkworks.net.au");
 URLConnection con = url.openConnection();
 con.connect();
  
 InputStream in = con.getInputStream();
 InputStreamReader inputstreamreader = new InputStreamReader(in);
 BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

 String string = null;
 while ((string = bufferedreader.readLine()) != null) {
  System.out.println(string);
 } 

That's it, now you learnt how to connect to a SSL secured url from a Java application!

Those who want to connect to a mail server over SSL using Java Mail API, use the below property to authenticate over SSL:

 props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

Continue reading...




Recommended products for you

 
texient.com