Guava Enum Mapper

by GarciaPL on Monday, 23 May 2016

Have you ever wondered how to map enums from one to another ? Did you use switch statement to make it work ? Now you can use method immutableEnumMap from class Maps which is part of Guava. Below you can find an example.


public class EnumSourceMapper {

    static ImmutableMap<EnumSource, EnumDestination> mapper;

    static {
        mapper = Maps.immutableEnumMap(ImmutableMap.<EnumSource, EnumDestination>builder()
                .put(EnumSource.SUCCESS,                  EnumDestination.SUCCESS)
                .put(EnumSource.INCOMPLETE,               EnumDestination.ERROR)
                .put(EnumSource.FAIL,                     EnumDestination.ERROR)
                .build());
    }

    public EnumDestination getEnumDestination(EnumSource enumSource) {
        return mapper.get(enumSource);
    }
}



Reference:

EuroMonitor - get email notification about currency

by GarciaPL on Monday, 9 May 2016

Recently I was trying to convert some cash in EUR currency, but I did not have time to watch currency graph all the time. So, I have created small tool which will let me know via email when currency will get more expensive above some concrete level. You can put below script in cron to execute it with some time interval. I used Sparkpost as a email provider.

import urllib2
import json
from sparkpost import SparkPost

sp = SparkPost('YOUR_API_KEY')

def currencyConverter(currency_from,currency_to):
    yql_base_url = "https://query.yahooapis.com/v1/public/yql"
    yql_query = 'select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20("'+currency_from+currency_to+'")'
    yql_query_url = yql_base_url + "?q=" + yql_query + "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"
    try:
        yql_response = urllib2.urlopen(yql_query_url)
        try:
            yql_json = json.loads(yql_response.read())
            currency_output = 1 * float(yql_json['query']['results']['rate']['Rate'])
            return currency_output
        except (ValueError, KeyError, TypeError):
            return "JSON format error"

    except IOError, e:
        if hasattr(e, 'code'):
            return e.code
        elif hasattr(e, 'reason'):
            return e.reason

currency_from = "EUR" # currency codes : http://en.wikipedia.org/wiki/ISO_4217
currency_to = "PLN"
direction_rate = 4.44

rate = currencyConverter(currency_from,currency_to)
print rate

if rate > direction_rate:
 response = sp.transmissions.send(
     recipients=['YOUR_EMAIL@gmail.com'],
     html='Rate of ' + currency_from + currency_to + ' equals ' + str(round(rate, 2)) + '
', from_email='test@sparkpostbox.com', subject='EuroMonitor' ) print(response) else: print "Rate too low"

Reference :
[1] EuroMonitor Source Code

Spring Test DBUnit - Table already exists

by GarciaPL on Saturday, 16 April 2016

I had a chance to work with Spring Test DBUnit [1] (integration between Spring testing framework and DBUnit) with few tests related with Spring Integration. Most of them use the same common text context which contains embedded database H2. Funny thing was that some tests failed, because of some tables already exist. The issue is that embedded database is not cleared between tests and it is reused within the same context. That's why you should use @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) with @TestExecutionListeners({DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class}) like below :

@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class})
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class YourTest {

}




Reference :
[1] Spring Test DBUnit

[2] Spring Framework - DirtiesContext

PerlJobs

by GarciaPL on Thursday, 31 March 2016

I would like to announce that new Android app has been released recently times by me. This time application is called PerlJobs. This application helps you as a Perl developer to find new job opportunities across the globe. Job offers are divided into sections : Standard, Mod, Catalyst, Mason, Telecommute and By Country. The main source of all jobs is website : https://jobs.perl.org

Google Play Developer Page

by GarciaPL on Sunday, 6 March 2016

Yes! I finally managed to create it. Obviously it is not so pretty as it might be, but.. never mind :) If you would like to create your own Google Play Developer Page where you can add some promotion text and graphics (icon and background), just go to your Developer Console and then click Settings and then Developer Page. If you are looking for let's say 'inspiration', you can have a look on my Developer Page which link you can find below :





Pack CSV files in ZIP Archive

by GarciaPL on Saturday, 5 March 2016

This time I would like to share with small snippet of code written in Java and Spring MVC which might allow you to pack and download some files (in this case .csv file) in ZIP archive. So, if you will hit URL http://localhost:8090/yourApp/download/zip, Zip archive will be downloaded with name 'download.zip'.

    @ResponseBody
    @RequestMapping(value = {"/download/zip"}, method = RequestMethod.GET)
    public void downloadZipArchive(HttpServletResponse response) throws IOException {

        List<MyClass> list; //should contains some records!
        if (list != null && !list.isEmpty()) {
            if (list.size() > 200000) {

                response.setContentType("application/zip");
                response.addHeader("Content-Disposition", "attachment; filename=\"download.zip\"");
                response.addHeader("Content-Transfer-Encoding", "binary");

                OutputStream servletOutputStream = response.getOutputStream();
                ZipOutputStream zos = new ZipOutputStream(servletOutputStream);

                int counter = 0;
                List<List<MyClass>> dividedlist = Lists.partition(list, 200000);
                for (List<MyClass> partition : dividedlist) {
                    zos.putNextEntry(new ZipEntry("file_" + counter + ".csv"));
                    CSVWriter writer = new CSVWriter(new OutputStreamWriter(zos));
                    writer.writeNext(new String[]{"HEADER"});
                    for (MyClass item : partition) {
                        writer.writeNext(new String[]{item.getText()});
                    }
                    writer.flush();
                    zos.closeEntry();
                    counter++;
                }
                zos.close();
                response.getOutputStream().flush();
                response.getOutputStream().close();
            }
        }
    }