Meteor hello world example

In this tutorial, we will show you how to create a website with Meteor framework. Tools used : Meteor 1.2.1 Tested with Linux (Debian, Ubuntu or Mint) Tested with Mac OSX 1. Install Meteor Issue curl https://install.meteor.com | sh, everything will be installed and configured. $ curl https://install.meteor.com | sh % Total % Received % …

Read more

Python – How to split a String

Few examples to show you how to split a String into a List in Python. 1. Split by whitespace By default, split() takes whitespace as the delimiter. alphabet = "a b c d e f g" data = alphabet.split() #split string into a list for temp in data: print temp Output a b c d …

Read more

Python – How to loop a List

In this tutorial, we will show you how to use for-in-loop to loop a List in Python. #example 1 frameworks = [‘flask’, ‘pyramid’, ‘django’] #list for temp in frameworks: print temp print "Python framework : %s" %temp #example 2 numbers = [2,4,6,8,10] #list for num in numbers: print num print "Number : %d" %num Output …

Read more

Spring MVC – Refactoring a jQuery Ajax Post example

Reviewing a jQuery Ajax form POST and Spring MVC example, find out the following patterns : <script> jQuery(document).ready( function($) { $("#btn-save").click(function(event) { var id = $(‘#id’).val(); var domain = $(‘#domain’).val(); var name = $(‘#name’).val(); var desc = $(‘#desc’).val(); var tags = $(‘#tags’).val(); var afflink = $(‘#afflink’).val(); var cdn = $("#cdn").prop("checked") ? true : false; var …

Read more

Spring – Inject value into static variables

Spring doesn’t allow to inject value into static variables, for example: import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class GlobalValue { @Value("${mongodb.db}") public static String DATABASE; } If you print out the GlobalValue.DATABASE, a null will be displayed. GlobalValue.DATABASE = null Solution To fix it, create a “none static setter” to assign the injected value for …

Read more

Java 8 Stream – Read a file line by line

In Java 8, you can use Files.lines to read file as Stream. c://lines.txt – A simple text file for testing line1 line2 line3 line4 line5 1. Java 8 Read File + Stream TestReadFile.java package com.mkyong.java8; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Stream; public class TestReadFile { public static void main(String args[]) { String fileName …

Read more

How to get the environment variables in Java

In Java, the System.getenv() returns an unmodifiable string Map view of the current system environment. Map<String, String> env = System.getenv(); // get PATH environment variable String path = System.getenv("PATH"); Table of contents. 1. Get a specified environment variable 2. UnsupportedOperationException 3. Display all environment variables 4. Sort the environment variables 5. Download Source Code 6. …

Read more

Jackson 2 – Convert Java Object to / from JSON

In this tutorial, we will show you how to use Jackson 2.x to convert Java objects to / from a JSON. 1. Basic 1.1 Convert a Staff object to from JSON. writeValue(…) – Java Objects to JSON ObjectMapper mapper = new ObjectMapper(); // Java object to JSON file mapper.writeValue(new File("c:\\test\\staff.json"), new Staff()); // Java object …

Read more

MongoDB : Sort exceeded memory limit of 104857600 bytes

Performs a large sort operation (Aggregation) in a collection, and hits the following error message : MongoDB Console > db.bigdata.aggregate( {$group : {_id : "$range", total : { $sum : 1 }}}, {$sort : {total : -1}} ); #… aggregate failed at Error (<anonymous>) at doassert (src/mongo/shell/assert.js:11:14) #… Error: command failed: { "errmsg" : "exception: …

Read more

How to split a string in Java

In Java, we can use String#split() to split a string. String phone = "012-3456789"; // String#split(string regex) accepts regex as the argument String[] output = phone.split("-"); String part1 = output[0]; // 012 String part2 = output[1]; // 3456789 Table of contents 1. Split a string (default) 2. Split a string and retain the delimiter 3. …

Read more

Java – How to delay few seconds

In Java, we can use TimeUnit.SECONDS.sleep() or Thread.sleep() to delay few seconds. 1. TimeUnit JavaDelayExample.java package com.mkyong; import java.util.Date; import java.util.concurrent.TimeUnit; public class JavaDelayExample { public static void main(String[] args) { try { System.out.println("Start…" + new Date()); // delay 5 seconds TimeUnit.SECONDS.sleep(5); System.out.println("End…" + new Date()); // delay 0.5 second //TimeUnit.MICROSECONDS.sleep(500); // delay 1 minute …

Read more

Python – How to delay few seconds

In Python, you can use time.sleep(seconds) to make the current executing Python program to sleep or delay a few seconds. import time time.sleep(1) # delays for 1 seconds time.sleep(10) # delays for 10 seconds time.sleep(60) # delays for 1 minute time.sleep(3600) # delays for 1 hour Full example. test_delay.py import time def main(): while True: …

Read more

Python – How to loop a dictionary

In this tutorial, we will show you how to loop a dictionary in Python. 1. for key in dict: 1.1 To loop all the keys from a dictionary – for k in dict: for k in dict: print(k) 1.2 To loop every key and value from a dictionary – for k, v in dict.items(): for …

Read more

Java – Check if key exists in HashMap

In Java, you can use Map.containsKey() to check if a key exists in a Map. TestMap.java package com.mkyong.examples; import java.util.HashMap; import java.util.Map; public class TestMap { public static void main(String[] args) { Map<String, Integer> fruits = new HashMap<>(); fruits.put("apple", 1); fruits.put("orange", 2); fruits.put("banana", 3); fruits.put("watermelon", null); System.out.println("1. Is key ‘apple’ exists?"); if (fruits.containsKey("apple")) { //key …

Read more

Python Whois client example

In this article, we will show you how to create a simple Whois client both in Python 2 and Python 3. Tested Python 2.7.10 Python 3.4.3 1. Python 3 Whois example In Python 3, the socket accepts bytes, so you need to encode() and decode() manually. whois3.py import sys import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) …

Read more

How to check Debian version

On Debian, type cat /etc/debian_version to display the Debian version. Terminal $ cat /etc/debian_version 9.5 Alternatively, cat /etc/issue Terminal $ cat /etc/issue Debian GNU/Linux 9 \n \l The last one, lsb-release -a, it will display the Debian detail. Terminal $ lsb-release -a -bash: lsb-release: command not found $ sudo apt-get install lsb-release $ lsb_release -a …

Read more

Python – Check if key exists in dictionary

In Python, you can use the in operator to check if a key exists in a dictionary. test.py def main(): fruits = { ‘apple’:1, ‘orange’:2, ‘banana’:3 } #if key ‘apple’ exists in fruits? if ‘apple’ in fruits: print(fruits[‘apple’]) if __name__ == ‘__main__’: main() Output 1 P.S Tested with Python 3.4.3 Note has_key() is deprecated in …

Read more

Java – Generate random integers in a range

In this article, we will show you three ways to generate random integers in a range. java.util.Random.nextInt Math.random java.util.Random.ints (Java 8) 1. java.util.Random This Random().nextInt(int bound) generates a random integer from 0 (inclusive) to bound (exclusive). 1.1 Code snippet. For getRandomNumberInRange(5, 10), this will generates a random integer between 5 (inclusive) and 10 (inclusive). private …

Read more

Java 8 Lambda : Comparator example

In this example, we will show you how to use Java 8 Lambda expression to write a Comparator to sort a List. 1. Classic Comparator example. Comparator<Developer> byName = new Comparator<Developer>() { @Override public int compare(Developer o1, Developer o2) { return o1.getName().compareTo(o2.getName()); } }; 2. Lambda expression equivalent. Comparator<Developer> byName = (Developer o1, Developer o2)->o1.getName().compareTo(o2.getName()); …

Read more

Tomcat 7 + Java 8 : Invalid byte tag in constant pool: 15

Just upgraded to Java 8, and the Tomcat 7 keeps prompting the following exceptions: Jul 20, 2015 4:06:36 PM org.apache.catalina.startup.ContextConfig processAnnotationsJar SEVERE: Unable to process Jar entry [jdk/nashorn/internal/objects/NativeURIError.class] from Jar [jar:file:/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/jre/lib/ext/nashorn.jar!/] for annotations org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15 at org.apache.tomcat.util.bcel.classfile.Constant.readConstant(Constant.java:131) at org.apache.tomcat.util.bcel.classfile.ConstantPool.<init>(ConstantPool.java:60) at org.apache.tomcat.util.bcel.classfile.ClassParser.readConstantPool(ClassParser.java:209) at org.apache.tomcat.util.bcel.classfile.ClassParser.parse(ClassParser.java:119) at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2066) at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:1942) at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1908) …

Read more

Python 3 TypeError: ‘str’ does not support the buffer interface

Review a Python 2 socket example whois.py import sys import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("whois.arin.net", 43)) s.send(sys.argv[1] + "\r\n") #Python 2.7 send signature #socket.send(string[, flags]) If compile with Python 3, it prompts the following error? Traceback (most recent call last): File "C:\repos\hc\whois\python\whois.py", line 6, in <module> s.send(sys.argv[1] + "\r\n") TypeError: ‘str’ does not support …

Read more

HSQL identify auto increase ID

In HSQLDB you can use IDENTITY keyword to define an auto-increment column, normally, this is the primary key. Review below examples : 1. IDENTITY – Default By default, the IDENTITY value is start with zero. CREATE TABLE users ( id INTEGER IDENTITY PRIMARY KEY, name VARCHAR(30), email VARCHAR(50) ); INSERT INTO users (name, email) VALUES …

Read more

Spring MVC – Catch the exceptions thrown by view page

Here’s the scenario, the controller returns a ModelAndView, and an exception is thrown while rendering the JSP view page, reason behind is one of message code is not found. org.apache.jasper.JasperException: org.springframework.context.NoSuchMessageException: No message found under code ‘Diff.userform.password’ for locale ‘en_US’. org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334) javax.servlet.http.HttpServlet.service(HttpServlet.java:722) An exception is thrown and render an HTTP 500 error …

Read more

How to register a servlet filter in Spring MVC

In a nutshell, a servlet filter lets you intercepts requests and responses on your web application. This article shows you how to register a servlet filter in Spring XML and JavaConfig. 1. Servlet Filter Review the following custom filter, it will catch any exceptions and redirect to an error page. package com.mkyong.form.web; import java.io.IOException; import …

Read more

Spring – Mixing XML and JavaConfig

Spring examples to show you how to mix both Spring XML and JavaConfig together. 1. Load JavaConfig From Spring XML A Spring MVC example, uses @Configuration to load everything, and you want integrate with web.xml SpringWebConfig.java package com.mkyong.form.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @EnableWebMvc …

Read more

Combine Spring validator and Hibernate validator

In this article, we will show you how to validate the submitted form values with Spring validator and Hibernate Validator (bean validation). Technologies used : Spring 4.1.6.RELEASE Hibernate Validator 5.1.3.Final 1. Hibernate Validator The Hibernate validator will be fired if @Valid is provided. import org.hibernate.validator.constraints.NotEmpty; public class User { @NotEmpty String name; //… } @RequestMapping(value …

Read more

Spring MVC Form – Check if a field has an error

In this article, we will show you few Spring form tag examples to check if a field has an error message. Review the following Spring MVC bean validation example : Technologies used : Spring 4 JSTL 1.2 //Bean validation import org.hibernate.validator.constraints.NotEmpty; public class User { @NotEmpty String name; //… } //Controller class @RequestMapping(value = "/users", …

Read more

Python 3 TypeError: Can’t convert ‘bytes’ object to str implicitly

Converting a Python 2 socket example to Python 3 whois.py import sys import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("whois.arin.net", 43)) s.send((sys.argv[1] + "\r\n").encode()) response = "" while True: data = s.recv(4096) response += data if not data: break s.close() print(response) If compile with Python 3, it prompts the following error? Traceback (most recent call last): …

Read more

Spring embedded database examples

In this tutorial, we will show you a few examples to configure the embedded database engines like HSQL, H2 and Derby in Spring framework. Technologies used : Spring 4.1.6.RELEASE jUnit 4.1.2 Maven 3 Embedded databases tested : HSQLDB 2.3.2 H2 1.4.187 Derby 10.11.1.1 The embedded database concept is very helpful during the development phase, because …

Read more

Spring MethodInvokingFactoryBean Example

In Spring, you can use MethodInvokingFactoryBean to run a method, get the result and inject the result into another bean. This method invoker is very useful in XML configuration, but less use now in favor of annotation and Spring expression. 1. MethodInvokingFactoryBean 1.1 Example to get the current Java version. Spring XML Configuration <!– 1. …

Read more

Spring MVC – How to set active profile

In this example, we will show you how to set active @Profile in a Spring MVC web application. @Profile Examples @Configuration public class AppConfig { @Profile("dev") @Bean public CacheManager cacheManager() { //… } @Profile("live") @Bean public EhCacheManagerFactoryBean ehCacheCacheManager() { //… } @Profile("testdb") @Bean public DataSource dataSource() { //… } } To set active @Profile in …

Read more

Spring – View content of HSQLDB embedded database

A Spring @Configuration example to start an HSQLDB embedded database or in-memory database. DataSourceConfig.java package com.mkyong.config.db; import javax.sql.DataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; @Configuration public class DataSourceConfig { @Bean public DataSource dataSource(){ //jdbc:hsqldb:mem:testdb EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.HSQL) .addScript("db/hsqldb/db.sql") .build(); return db; } } Review the …

Read more

Spring MVC + Logback SLF4j example

In this tutorial, we will show you how to setup slf4j and logback in a Spring MVC web application. Technologies used : Spring 4.1.6.RELEASE Logback 1.1.3 Maven 3 or Gradle 2.0 Tomcat 7 Eclipse 4.4 Note By default, Spring is using the Jakarta Commons Logging API (JCL), read this. To setup logback framework you need …

Read more

Gradle – Display project dependency

In this tutorial, we will show you how to display project dependencies with the Gradle build tool. Review a simple Spring MVC project dependencies. build.gradle dependencies { compile ‘org.slf4j:jcl-over-slf4j:1.7.12’ compile ‘ch.qos.logback:logback-classic:1.1.3’ compile(‘org.springframework:spring-webmvc:4.1.6.RELEASE’){ exclude group: ‘commons-logging’, module: ‘commons-logging’ } compile ‘org.hsqldb:hsqldb:2.3.2’ providedCompile ‘javax.servlet:servlet-api:2.5’ } P.S Tested with Gradle 2.4 1. gradle dependencies Display project dependencies (direct …

Read more