Tuesday, October 20, 2015

Convert String to Date in DD/MM/YYYY from Java scripts

If you try to convert DD/MM/YYYY String to date it will give you Invalid Date Error

  new Date("31/05/2015")
 Invalid Date

Solution is to convert it to correct format using REGEX

Some samples are shown below

new Date("31/05/2015".replace(/(\d{2})\/(\d{2})\/(\d{4})/, "$2/$1/$3"))
Sun May 31 2015 00:00:00 GMT+1000 (AUS Eastern Standard Time)


new Date("31/05/2015 03:24 PM".replace(/(\d{2})\/(\d{2})\/(\d{4})/, "$2/$1/$3"))
Sun May 31 2015 15:24:00 GMT+1000 (AUS Eastern Standard Time)

Sunday, July 12, 2015

How to get enum description from enum C# using Dictionaries



using System;
using System.Linq;
using System.Reflection;
using Constants.EnumHelpers;

namespace EnumDescription
{
public enum OrderEnum
{
        [Description("Buy Market")]
        OT_buyMarket = 0,

        [Description("Sell Market")]
        OT_sellMarket,

        [Description("Buy Limit")]
        OT_buyLimit,

        [Description("Sell Limit")]
        OT_sellLimit,
}

public HowToGetEnumDescription
        {

        private static Dictionary<int, string> GetDictionaryFromEnum<T>()
        {
            var myDictionary = new Dictionary<int, string>();
            foreach (T code in Enum.GetValues(typeof(T)).Cast<T>())
            {
                if ((code as Enum).Lookup())
                {
                    myDictionary.Add(int.Parse((code as Enum).GetValue()), (code as Enum).GetDescription());
                }
            }

            return myDictionary;
        }

        private static string getEnumDescription(int roleKey) {
            Dictionary<int, string> defaultDictinary = GetDictionaryFromEnum<EnumDescription.OrderEnum>();
            string value;
            defaultDictinary.TryGetValue(roleKey, out value);
            return value;
        }
[TestMethod]
        public void TestingHowToGetEnumDescription()
        {
       Dictionary<int, string> selectedDictinary = GetDictionaryFromEnum<EnumDescription.OrderEnum>();
                Assert.IsNotNull(selectedDictinary);
                Assert.IsTrue(selectedDictinary.ContainsValue(getEnumDescription((int)EnumDescription.OrderEnum.OT_buyMarket)));
}
}

    public static class EnumHelper
    {
        public static string GetDescription(this Enum value)
        {
            FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
            Description attribute = Attribute.GetCustomAttribute(fieldInfo, typeof(Description)) as Description;
            return attribute == null ? value.ToString() : attribute.Text;
        }

        public static bool Lookup(this Enum value)
        {
            FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
            Include attribute = Attribute.GetCustomAttribute(fieldInfo, typeof(Include)) as Include;
            return attribute == null ? true : attribute.IncludeInLookup;
        }

        public static string GetValue(this Enum value)
        {
            FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
            Value attribute = Attribute.GetCustomAttribute(fieldInfo, typeof(Value)) as Value;
            return attribute == null ? Convert.ToInt32(value).ToString() : attribute.Text;
        }
    }


}

Sunday, February 8, 2015

Spring Boot - REST Controller and Scheduler in same application

Keeping REST Controller and Scheduler in same spring boot application little bit tricky as it might generate unexpected errors

Here is a way to do that

Maven dependencies
....
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.0.1.RELEASE</version>
</parent>


....

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

Main Application
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableAutoConfiguration
@EnableScheduling
@Configuration
@ComponentScan
public class ServiceApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(ServiceApplication.class);
}

}

Controller
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ClientController {
    @RequestMapping("/greeting")
    @ResponseBody
    public String greeting() {
        return "Greetings!";
    }
}

Scheduler
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


@Component
public class MyScheduler {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        System.out.println("The time is now " + dateFormat.format(new Date()));
    }
}

Tuesday, January 6, 2015

Custom Property Placeholder With Spring 4 and AWS S3 or RDBMS or NoSQL Database

Traditionally we use property files to load properties like 

<context:property-placeholder location="/WEB-INF/database.properties" ignore-unresolvable="true" ignore-resource-not-found="true"/>
So if you place the property file inside the server you need to re- deploy every time we did a change in the property values
The work around is place a property file in a remote location like Amazon S3 or a database

import java.io.IOException;
import java.io.StringWriter;
import java.util.Properties;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;

public class CustomPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

@Override
    protected void loadProperties(final Properties props) throws IOException {
props.putAll(getProperties("database.properties"));
}

private Properties getProperties(String key) throws IOException{
String accessKey = "XXXXXX";
String secretKey = "YYYYYYYYYYY";
String bucketName = "ZZZZZZZZZ";
 
AWSCredentials awsCredentials =  new BasicAWSCredentials(accessKey,secretKey);
AmazonS3  client=new AmazonS3Client(awsCredentials);
S3Object object = client.getObject(bucketName, key);  
S3ObjectInputStream objectContent = object.getObjectContent();
StringWriter writer=new StringWriter();
IOUtils.copy(objectContent, writer);  
return PropertiesConverter.stringToProperties(writer.toString());
}
}



import java.io.IOException;
import java.io.StringReader;
import java.util.Properties;

import org.springframework.util.DefaultPropertiesPersister;
import org.springframework.util.PropertiesPersister;
import org.springframework.util.StringUtils;


public final class PropertiesConverter {
private static final PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();
// prevents the class from being instantiated
private PropertiesConverter() {
};

public static Properties stringToProperties(String stringToParse) {
if (stringToParse == null) {
return new Properties();
}
if (!contains(stringToParse, "\n")) {
return StringUtils.splitArrayElementsIntoProperties(StringUtils
.commaDelimitedListToStringArray(stringToParse), "=");
}
StringReader stringReader = new StringReader(stringToParse);
Properties properties = new Properties();

try {
propertiesPersister.load(properties, stringReader);
}
catch (IOException ex) {
throw new IllegalStateException("Error while trying to parse String to java.util.Properties,"
+ " given String: " + properties);
}
return properties;
}

private static boolean contains(String str, String searchStr) {
return str.indexOf(searchStr) != -1;
}
}


You can invoke from spring config like

<bean id="placeholderPropertiesDatabase" class="xxx.xxxxxxxxxx.CustomPropertyPlaceholderConfigurer" >
<property name="order" value="1" />

    </bean>

Also you can edit the CustomPropertyPlaceholderConfigurer.java loadProperties method to load properties from RDBMS or NoSQL Database

Set JSON View Resolver with Spring 4

<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
       <property name="favorPathExtension" value="false" />
       <property name="favorParameter" value="true" />
       <property name="parameterName" value="mediaType" />
       <property name="ignoreAcceptHeader" value="false"/>
       <property name="useJaf" value="false"/>
       <property name="defaultContentType" value="application/json" />

       <property name="mediaTypes">
            <map>
                <entry key="json"  value="application/json" />
            </map>
        </property>
</bean>

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver" p:order="1">

<property name="contentNegotiationManager" ref="contentNegotiationManager" />
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />
</list>
</property>
</bean>