Thursday, July 30, 2015

Exclude specific tasks of a sub-project in Gradle

To exclude specific tasks of a sub-project in Gradle,

do as follows:

gradle build -x :test-common:startScripts -x :test-common:bootRepackage

Run a specific task of a sub-project in Gradle

To run a specific task of a sub-project in Gradle,

do as follows:

gradle :test-common:startScripts

Wednesday, July 29, 2015

No signature of method: build_59tj2ra5d1mn9tk0vrfinvo79c$_run_closure2.id() is applicable for argument types: (java.lang.String) values: [org.asciidoctor.convert]

You might encounter the following exception:

FAILURE: Build failed with an exception.

* Where:
Build file '/home/izeye/applications/test/build.gradle' line: 9

* What went wrong:
A problem occurred evaluating root project 'test'.
> No signature of method: build_59tj2ra5d1mn9tk0vrfinvo79c$_run_closure2.id() is applicable for argument types: (java.lang.String) values: [org.asciidoctor.convert]
  Possible solutions: is(java.lang.Object), is(java.lang.Object), find(), find(), find(groovy.lang.Closure), find(groovy.lang.Closure)

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Gradle version was 1.12.

Just upgrading to 2.5 fixed the problem.

Tuesday, July 28, 2015

Error: Invalid value for attribute d="MNaN,82.5LNaN,41.25LNaN,0LNaN,123.75LNaN,330"

You might encounter the following error in D3.js:

Error: Invalid value for <path> attribute d="MNaN,82.5LNaN,41.25LNaN,0LNaN,123.75LNaN,330"

If you get the following date and time format:

"collectedTime" : "2015-05-19 14:48:40",

you need to parse it as follows:

        svg.x.domain(d3.extent(data, function (d) {
//            return d.collectedTime;
            var parsedTime = d3.time.format("%Y-%m-%d %H:%M:%S").parse(d.collectedTime);
            return parsedTime;
        }));

        svg.line = d3.svg.line()
                .x(function (d) {
                    //return svg.x(d.timestamp);
                    //return svg.x(d.collectedTime);
                    var parsedTime = d3.time.format("%Y-%m-%d %H:%M:%S").parse(d.collectedTime);
                    return svg.x(parsedTime);
                })
                .y(function (d) {
                    return svg.y(valueFunction(d));
                });

References:
http://stackoverflow.com/questions/26070783/invalid-value-for-path-attribute
https://github.com/mbostock/d3/wiki/Time-Formatting

Monday, July 27, 2015

Get the latest commid ID in Get

To get the latest commid ID in Get,

use the following command:

$ git log --format="%H" -n 1

Reference:
http://stackoverflow.com/questions/19176359/how-to-get-the-last-commit-id-of-a-remote-repo-using-curl-like-command

Git rebase and squash commits

* Check commit logs as follows:

$ git log

commit da274bb605a962fa02ae8fba2da27b934b59d68d
Author: izeye <izeye@naver.com>
Date:   Tue Jul 28 11:55:38 2015 +0900

    Fix typos.

commit 0e5f855954a69dd05128442bf9c996efc8d35f0d
Author: izeye <izeye@naver.com>
Date:   Tue Jul 28 11:47:52 2015 +0900

    Fix typos.

commit 32128a6ac2390250d9e0b933618177846fb7bef0
Author: Stephane Nicoll <snicoll@pivotal.io>
Date:   Mon Jul 27 16:02:03 2015 +0200

    Polish
...

* `git rebase` with the base commit as follows:

$ git rebase -i 32128a6ac2390250d9e0b933618177846fb7bef0

pick 0e5f855 Fix typos.
squash da274bb Fix typos.

* Type `:wq` and change commit messages as follows:

# This is a combination of 2 commits.
# The first commit's message is:

Fix typos.

# This is the 2nd commit message:

#Fix typos.

* Type `:wq` again.

* Check commit logs again as follows:

$ git log

commit d51d6b7e8d21c60a6ac9e6e6e60847c112514998
Author: izeye <izeye@naver.com>
Date:   Tue Jul 28 11:47:52 2015 +0900

    Fix typos.

commit 32128a6ac2390250d9e0b933618177846fb7bef0
Author: Stephane Nicoll <snicoll@pivotal.io>
Date:   Mon Jul 27 16:02:03 2015 +0200

    Polish

If you want to push it to the remote repository,

do as follows:

$ git push -f

Reference:
https://github.com/edx/edx-platform/wiki/How-to-Rebase-a-Pull-Request

Sunday, July 26, 2015

only buildscript {} and other plugins {} script blocks are allowed before plugins {} blocks, no other statements are allowed

You might encounter the following error:

only buildscript {} and other plugins {} script blocks are allowed before plugins {} blocks, no other statements are allowed

Just do the instruction in the error message.

In order words, move `plugin {}` script block on top of the script

except `buildscript {}` and other `plugins {}` script blocks.

Change Gradle version in IntelliJ

To change Gradle version in IntelliJ,

do as follows:

File -> Settings -> Gradle -> Gradle home

Format `yyyy-MM-dd HH:mm:ss` in Bash

To format `yyyy-MM-dd HH:mm:ss` in Bash,

do as follows:

date +"%F %T"

Saturday, July 25, 2015

Uncaught RangeError: Maximum call stack size exceeded

I got the following error suddenly in Windows Chrome Canary:

Uncaught RangeError: Maximum call stack size exceeded

It didn't happen in Windows Chrome, Mac Chrome, and Mac Chrome Canary.

I guess it's a bug of Windows Chrome Canary.

I'm wondering why this kind of bug is happening.

I guess they have tons of tests.

Although it's quite easily reproducible, why did they miss it?

Friday, July 24, 2015

java.lang.NoClassDefFoundError: org/codehaus/groovy/runtime/typehandling/ShortTypeHandling

When I used the following command:

gradle build

I got the following exception:

FAILURE: Build failed with an exception.
             
* Where:    
Build file 'C:\Users\nbp\IdeaProjects\impression-neo\build.gradle' line: 101
             
* What went wrong:
Execution failed for task ':generateGitProperties'.
> java.lang.NoClassDefFoundError: org/codehaus/groovy/runtime/typehandling/ShortTypeHandling
             
* Try:      
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
             
BUILD FAILED

When I checked the Gradle version with the following command:

gradle -v

the result was as follows:

------------------------------------------------------------
Gradle 1.11
------------------------------------------------------------

Build time:   2014-02-11 11:34:39 UTC
Build number: none
Revision:     a831fa866d46cbee94e61a09af15f9dd95987421

Groovy:       1.8.6
Ant:          Apache Ant(TM) version 1.9.2 compiled on July 8 2013
Ivy:          2.2.0
JVM:          1.8.0_05 (Oracle Corporation 25.5-b02)
OS:           Windows 7 6.1 amd64

When I upgraded Gradle to 2.5 as follows:

------------------------------------------------------------
Gradle 2.5
------------------------------------------------------------

Build time:   2015-07-08 07:38:37 UTC
Build number: none
Revision:     093765bccd3ee722ed5310583e5ed140688a8c2b

Groovy:       2.3.10
Ant:          Apache Ant(TM) version 1.9.3 compiled on December 23 2013
JVM:          1.8.0_05 (Oracle Corporation 25.5-b02)
OS:           Windows 7 6.1 amd64

the problem was solved.

I guess the problem was caused by the old version of Groovy.

Thursday, July 23, 2015

Use Swagger in Spring Boot

To use Swagger in Spring Boot,

add the following dependencies to `build.gradle`:

    compile("io.springfox:springfox-swagger2:2.1.1")
    compile("io.springfox:springfox-swagger-ui:2.1.1")

and add `@EnableSwagger2` as follows:

@SpringBootApplication
@EnableSwagger2
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}

Open the following URL in your browser:

http://localhost:8080/swagger-ui.html

Reference:
http://springfox.github.io/springfox/docs/current/

Monday, July 20, 2015

Spring Data JPA `IN` clause with Spring Data REST

You can do as follows:

http://localhost:8080/api/events/search/findByLevelIn?level=ERROR,WARN

See the following link for the details on Spring Data JPA `IN` clause:

http://izeye.blogspot.kr/2015/07/use-in-caluse-with-spring-data-jpa.html

Use `IN` clause with Spring Data JPA

To use `IN` clause with Spring Data JPA,

you can do as follows:

public interface EventRepository extends JpaRepository<Event, Long> {

  Page<Event> findByLevelIn(@Param("level") Set<EventLevel> levels, Pageable pageable);

}

You can test as follows:

  @Test
  public void testFindByLevelIn() {
    Set<EventLevel> levels = new HashSet<>();
    levels.add(EventLevel.ERROR);
    levels.add(EventLevel.WARN);
    levels.add(EventLevel.INFO);

    Page<Event> events = eventRepository.findByLevelIn(levels, new PageRequest(0, 100));
    events.forEach(System.out::println);
  }

Reference:
http://stackoverflow.com/questions/18987292/spring-crudrepository-findbyinventoryidslistlong-inventoryidlist-equivalen

sun.net.util.IPAddressUtil vs. org.apache.commons.validator.routines.InetAddressValidator

There are two IP address validation utils:

sun.net.util.IPAddressUtil
org.apache.commons.validator.routines.InetAddressValidator

I made some tests for both.

`IPAddressUtil` tests:

// NOTE:
// Got the following warning in Travis:
// warning: IPAddressUtil is internal proprietary API and may be removed in a future release
public class IPAddressUtilTests {

@Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void testIsIPv4LiteralAddress() {
assertTrue(IPAddressUtil.isIPv4LiteralAddress("1.2.3.0"));
assertTrue(IPAddressUtil.isIPv4LiteralAddress("1.2.3.4"));
assertTrue(IPAddressUtil.isIPv4LiteralAddress("1.2.3.255"));
assertFalse(IPAddressUtil.isIPv4LiteralAddress("1.2.3.256"));
assertFalse(IPAddressUtil.isIPv4LiteralAddress("1.2.3."));

// NOTE: They look weird but valid.
// See http://stackoverflow.com/questions/7550806/check-valid-ipv4-address-in-java
assertTrue(IPAddressUtil.isIPv4LiteralAddress("1.2.3"));
assertTrue(IPAddressUtil.isIPv4LiteralAddress("1.2"));
assertTrue(IPAddressUtil.isIPv4LiteralAddress("1"));

assertFalse(IPAddressUtil.isIPv4LiteralAddress(""));
assertFalse(IPAddressUtil.isIPv4LiteralAddress("::1"));

thrown.expect(NullPointerException.class);
IPAddressUtil.isIPv4LiteralAddress(null);
}

@Test
public void testIsIPv6LiteralAddress() {
assertTrue(IPAddressUtil.isIPv6LiteralAddress("::1"));
assertFalse(IPAddressUtil.isIPv6LiteralAddress("1.2.3.4"));
}

}

`InetAddressValidator` tests:

public class InetAddressValidatorTests {

InetAddressValidator validator = InetAddressValidator.getInstance();

@Test
public void testIsValidInet4Address() {
assertTrue(validator.isValidInet4Address("1.2.3.0"));
assertTrue(validator.isValidInet4Address("1.2.3.4"));
assertTrue(validator.isValidInet4Address("1.2.3.255"));
assertFalse(validator.isValidInet4Address("1.2.3.256"));
assertFalse(validator.isValidInet4Address("1.2.3."));
assertFalse(validator.isValidInet4Address("1.2.3"));
assertFalse(validator.isValidInet4Address("1.2"));
assertFalse(validator.isValidInet4Address("1"));
assertFalse(validator.isValidInet4Address(""));
assertFalse(validator.isValidInet4Address("::1"));
assertFalse(validator.isValidInet4Address(null));
}

@Test
public void testIsValidInet6Address() {
assertTrue(validator.isValidInet6Address("::1"));
assertFalse(validator.isValidInet6Address("1.2.3.4"));
}

}

As you can see the above tests,

they work differently.

Don't use `IPAddressUtil`.

I got the following warning from Travis builds when I used it:

warning: IPAddressUtil is internal proprietary API and may be removed in a future release

Saturday, July 18, 2015

Reference AngularJS's `$scope` in Chrome's Console

To reference AngularJS's `$scope.events` in Chrome's Console,

select the target element in `Elements` tab and use the following in `Console` tab:

angular.element($0).scope().events

Reference:
http://stackoverflow.com/questions/13743058/how-to-access-the-angular-scope-variable-in-browsers-console

Friday, July 17, 2015

Run a specifc test in Gradle

To run a specific test in Gradle,

you can use the following command:

gradle test --tests *SomeTests.test

Reference:
http://stackoverflow.com/questions/22505533/how-to-run-a-one-test-class-only-on-gradle

Spring Data REST max page size 1000

When I tried to fetch 2000 entries in Spring Data REST,

I got only 1000 entries.

I didn't know the reason until I saw the following source:

https://github.com/spring-projects/spring-data-rest/blob/master/spring-data-rest-core/src/main/java/org/springframework/data/rest/core/config/RepositoryRestConfiguration.java

It is used in `HateoasPageableHandlerMethodArgumentResolver.enhance()` as follows:

builder.replaceQueryParam(sizePropertyName, pageable.getPageSize() <= getMaxPageSize() ? pageable.getPageSize()
: getMaxPageSize());

If you use Spring Boot and want to change the default value,

you can add the following property to `application.properties`:

spring.data.rest.max-page-size=10000

I didn't find any related documentation except the source.

In my case, it would be nice to have a warning when exceeding the max page size,

but in some cases, it could be irritating, I guess.

Thursday, July 16, 2015

Apply `WebJarsResourceResolver` in Spring Boot

To apply `WebJarsResourceResolver` in Spring Boot,

add the following property to `application.properties`:

spring.resources.chain.enabled:true

and add the following dependency to `build.gradle`:

    compile("org.webjars:webjars-locator:0.26")
    compile("org.webjars:jquery:2.1.4")

Now you can use jQuery as follows in Thymeleaf templates:

    <script src="/webjars/jquery/jquery.min.js"></script>

How to exclude a file when publishing an artifact to Maven repository in Gradle

To exclude a `logback.xml` file when publishing an artifact to Maven repository in Gradle,

you can use the following configuration:

ext {
    artifactId = project.name
    artifactVersion = project.version
}

jar {
    baseName = artifactId
    version = artifactVersion
}

task commonJar(type: Jar) {
    baseName "test-common"
    from sourceSets.main.output
    exclude 'logback.xml'
}

publishing {
    repositories {
        maven {
            credentials {
                username "admin"
                password "1234"
            }
            url "http://repo.test.com:8080/repository/internal"
        }
    }

    publications {
        maven(MavenPublication) {
            groupId 'com.test'
            artifactId artifactId
            version artifactVersion

            artifact commonJar
        }
    }
}

Reference:
https://docs.gradle.org/current/userguide/publishing_maven.html

Tuesday, July 14, 2015

Check an environment variable having Spring profiles if a specific Spring profile is activated by a Bash script

When an environment variable having Spring profiles is as follows:

SPRING_PROFILE=test,something-else

you can check if `test` Spring profile is activated by using the following Bash script:

spring_active_profiles=(${SPRING_PROFILE//,/ })

spring_profile_test_activated=false
for spring_active_profile in ${spring_active_profiles[@]}
do
  if [ $spring_active_profile == "test" ]
  then
    spring_profile_test_activated=true
  fi
done

echo $spring_profile_test_activated
if [ "$spring_profile_test_activated" = true ]
then
  echo "Spring profile 'test' is activated."
fi

Saturday, July 4, 2015

Configure Graphite with Dropwizard Metrics in Spring Boot

To configure Graphite with Dropwizard Metrics in Spring Boot,

add the following Java Config:

@Configuration
public class GraphiteConfig {

  @Autowired
  private MetricRegistry metricRegistry;

  @Value("${graphite.host}")
  private String graphiteHost;

  @Value("${graphite.port}")
  private int graphitePort;

  @PostConstruct
  public void initialize() {
    Graphite graphite = new Graphite(this.graphiteHost, this.graphitePort);
    GraphiteReporter reporter = GraphiteReporter.forRegistry(this.metricRegistry)
        .prefixedWith(NetworkUtils.HOSTNAME.replace(".", "_"))
        .convertRatesTo(TimeUnit.SECONDS)
        .convertDurationsTo(TimeUnit.MILLISECONDS)
        .filter(MetricFilter.ALL).build(graphite);
    reporter.start(1, TimeUnit.MINUTES);
  }

}

and add the following properties:

graphite.host=1.2.3.4
graphite.port=2003

Reference:
https://dropwizard.github.io/metrics/3.1.0/manual/graphite/

Install Graphite with Python 2.6.6 on CentOS 6.6

If you don't have pip, install it as follows:

sudo yum install python-pip

# Install Django
sudo pip install 'https://www.djangoproject.com/download/1.4.20/tarball/'

# Install django-tagging
sudo easy_install django-tagging==0.3.1

# Install Twisted
sudo pip install twisted

# Install pytz
sudo pip install pytz

# Install bitmap-fonts-compat
sudo yum install bitmap-fonts-compat

# Install Apache
sudo yum install httpd

# Install mod_wsgi
sudo yum install mod_wsgi

sudo vi /etc/httpd/conf.d/wsgi.conf

#LoadModule wsgi_module modules/mod_wsgi.so

# Install Graphite
sudo pip install https://github.com/graphite-project/ceres/tarball/master
sudo pip install whisper
sudo pip install carbon
sudo pip install graphite-web

# Configure Carbon
cd /opt/graphite/conf
sudo cp carbon.conf.example carbon.conf
sudo cp storage-schemas.conf.example storage-schemas.conf

# Run Carbon
sudo /opt/graphite/bin/carbon-cache.py start

tail -F /opt/graphite/storage/log/carbon-cache/carbon-cache-a/console.log

# Test Carbon
echo "local.random.diceroll 4 `date +%s`" | nc localhost 2003

tail -F /opt/graphite/storage/log/carbon-cache/carbon-cache-a/creates.log

05/07/2015 14:22:22 :: new metric local.random.diceroll matched schema default_1min_for_1day
05/07/2015 14:22:22 :: new metric local.random.diceroll matched aggregation schema default
05/07/2015 14:22:22 :: creating database file /opt/graphite/storage/whisper/local/random/diceroll.wsp (archive=[(60, 1440)] xff=None agg=None)

# Configure Graphite Webapp
sudo cp /opt/graphite/examples/example-graphite-vhost.conf /etc/httpd/conf.d/graphite.conf
sudo cp /opt/graphite/conf/graphite.wsgi.example /opt/graphite/conf/graphite.wsgi
sudo cp /opt/graphite/webapp/graphite/local_settings.py.example /opt/graphite/webapp/graphite/local_settings.py

sudo chown apache:apache /opt/graphite/storage/
sudo chown apache:apache /opt/graphite/storage/log/webapp/

sudo python /opt/graphite/webapp/graphite/manage.py syncdb

# Start Apache
sudo /sbin/service httpd start

tail -F /opt/graphite/storage/log/webapp/error.log

# Visit Graphite Webapp Using Web Browser
http://your-ip-address/

References:
http://graphite.readthedocs.org/en/latest/install.html
http://graphite.readthedocs.org/en/latest/install-pip.html
http://graphite.readthedocs.org/en/latest/config-carbon.html
http://graphite.readthedocs.org/en/latest/admin-carbon.html
https://gist.github.com/ashrithr/9224450

Friday, July 3, 2015

Install a specific version of package by easy_install

To install a specific version of package by easy_install,

you can use the following command:

sudo easy_install django-tagging==0.3.1

Reference:
https://gist.github.com/ashrithr/9224450

Show installed packages by pip

If you want to know whether `tagging` package is installed,

you can use the following command:

$ pip freeze | grep tagging                                                            
django-tagging==0.4
tagging==0.2.1
$

Reference:
https://pip.pypa.io/en/latest/reference/pip_freeze.html

Show the version of an installed package by pip

If you want to know the version of an installed package (say, `django-tagging`) by pip,

use the following command:

$ pip show django-tagging
---
Name: django-tagging
Version: 0.4
Location: /usr/lib/python2.6/site-packages
Requires:
$

Reference:
http://stackoverflow.com/questions/10214827/find-which-version-of-package-is-installed-with-pip

Show installed packages by yum

If you want to know whether `python-devel` package is installed,

you can use the following command:

$ yum list installed | grep python-devel
python-devel.x86_64                2.6.6-52.el6                      @update
$

Reference:
http://www.electrictoolbox.com/yum-list-installed-packages/

Install Django with Python 2.6.6

If you try the following command:

sudo pip install django

you might get some error.

With Python 2.6.6, you can use only 1.4 version of Django.

So you have to use the following command to install:

sudo pip install 'https://www.djangoproject.com/download/1.4.20/tarball/'

You can check if it's working as follows:

$ python
...
>>> import django
>>> print(django.get_version())                                                                                    
1.4.20
>>>

If you want to use greater than 1.4 version,

you should upgrade Python to at least 2.7.

References:
https://docs.djangoproject.com/en/1.8/intro/install/
https://docs.djangoproject.com/en/1.8/faq/install/
https://www.djangoproject.com/download/

[warn] module wsgi_module is already loaded, skipping

When you did the following for Graphite,

sudo cp /opt/graphite/examples/example-graphite-vhost.conf /etc/httpd/conf.d/graphite.conf

you will get the following warning:

httpd ()  : [Fri Jul 03 19:16:29 2015] [warn] module wsgi_module is already loaded, skipping

You should comment out the original WSGI configuration as follows:

sudo vi /etc/httpd/conf.d/wsgi.conf

#LoadModule wsgi_module modules/mod_wsgi.so

Reference:
http://stackoverflow.com/questions/12120057/module-wsgi-module-is-already-loaded-skipping

Apache error log location in CentOS

In CentOS, you can find Apache error log in the following location:

/var/log/httpd/error_log

Reference:
http://lists.centos.org/pipermail/centos/2008-January/049950.html

Install pip in CentOS

To install pip in CentOS, use the following command:

sudo yum install python-pip

Reference:
https://pip.pypa.io/en/latest/installing.html

Wednesday, July 1, 2015

Read `Map` by `ObjectMapper.readValue()`

If you try to do the following:

Map<String, String> metricsMap = objectMapper.readValue(response, Map.class);

you might encounter the following exception:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

You can solve the problem by using `TypeReference` as follows:

  private final TypeReference<Map<String, String>> metricsType
      = new TypeReference<Map<String, String>>() {};

Map<String, String> metricsMap = objectMapper.readValue(response, metricsType);