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

Maven Jetty Plugin Examples

Few Maven Jetty 8.x and 9.x plugin examples, just for quick reference. 1. Maven Jetty Plugin 9.x Note You need to use Maven 3 and Java 1.7 for Maven Jetty 9.x plugin. 1.1 The ‘groupId’ is org.eclipse.jetty, by default, it runs on port 8080, in root context ‘/’. pom.xml <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.2.11.v20150529</version> </plugin> To …

Read more

Python 3 : Convert string to bytes

Code snippets to show you how to convert string to bytes and vice versa. 1. To convert a string to bytes. data = "" #string data = "".encode() #bytes data = b"" #bytes 2. To convert bytes to a String. data = b"" #bytes data = b"".decode() #string data = str(b"") #string P.S Tested with …

Read more

How to convert String to int in Java

In Java, we can use Integer.parseInt(String) to convert a String to an int; For unparsable String, it throws NumberFormatException. Integer.parseInt("1"); // ok Integer.parseInt("+1"); // ok, result = 1 Integer.parseInt("-1"); // ok, result = -1 Integer.parseInt("100"); // ok Integer.parseInt(" 1"); // NumberFormatException (contains space) Integer.parseInt("1 "); // NumberFormatException (contains space) Integer.parseInt("2147483648"); // NumberFormatException (Integer max 2,147,483,647) …

Read more

Maven – Display project dependency

In Maven, you can use mvn dependency:tree to display the project dependencies in tree format. 1. Maven Project Review a simple Maven project, declared Spring and logback dependencies. pom.xml <properties> <spring.version>4.1.6.RELEASE</spring.version> <logback.version>1.1.3</logback.version> <jcl.slf4j.version>1.7.12</jcl.slf4j.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${jcl.slf4j.version}</version> …

Read more

Java – Display double in 2 decimal places

In Java, there are few ways to display double in 2 decimal places. Table of contents. 1. DecimalFormat("0.00") 2. String.format("%.2f") 3. BigDecimal 4. References Possible Duplicate How to round double / float value to 2 decimal places 1. DecimalFormat(“0.00”) We can use DecimalFormat("0.00") to ensure the number is round to 2 decimal places. DecimalExample.java package …

Read more

Java – Math.pow example

A simple Math.pow example, display 2 to the power of 8. In Math 2^8 = 2x2x2x2x2x2x2x2 =256 In Java Math.pow(2, 8) Note In Java, the symbol ^ is a XOR operator, DON’T use this for the power calculation. TestPower.java package com.mkyong.test; import java.text.DecimalFormat; public class TestPower { static DecimalFormat df = new DecimalFormat(".00"); public static …

Read more

Gradle – Create Java project structure automatically

To quick start a new Gradle Java project, type gradle init –type java-library $ gradle init –type java-library :wrapper :init BUILD SUCCESSFUL Total time: 4.866 secs The following files and folders will be created automatically. P.S Tested with Gradle 2.0 1. Java Project Structure Both src/main/java and src/test/java folders are created. The Library*.java is a …

Read more

Spring Data MongoDB – Aggregation Grouping Example

In this tutorial, we will show you how to do the data grouping with Spring Data + MongoDB aggregation framework. 1. Test Data domain.json { "_id" : 1, "domainName" : "test1.com", "hosting" : "hostgator.com" } { "_id" : 2, "domainName" : "test2.com", "hosting" : "aws.amazon.com"} { "_id" : 3, "domainName" : "test3.com", "hosting" : "aws.amazon.com" …

Read more

Gradle Application Plugin – APP_HOME in applicationDefaultJvmArgs

In Gardle, the application plugin, you can pass the system properties via applicationDefaultJvmArgs : gradle.build apply plugin:’application’ mainClassName = "com.mkyong.analyzer.engine.hydra.entryPointForJar" applicationName = ‘analyzer’ distZip { archiveName ‘analyzer-‘ + version + ‘.zip’ } applicationDefaultJvmArgs = ["-Dlogback.configurationFile=logback.xml"] The problem is how to get the APP_HOME for logback.xml? gradle.build applicationDefaultJvmArgs = ["-Dlogback.configurationFile=APP_HOME/logback.xml"] You can hard code the APP_HOME, …

Read more

Spring MVC – Beans loaded twice

A Spring MVC web application, noticed all the Spring’s beans are loaded twice!? package com.mkyong.config.db; @Configuration public class MongoDevConfig { private final static Logger logger = LoggerFactory.getLogger(MongoDevConfig.class); @Bean MongoDbFactory mongoDbFactory() throws Exception { logger.debug("Init…… MongoDbFactory() in production mode!"); //… return new new SimpleMongoDbFactory(mongo, "db");; } } During Application startup : 2015-03-05 17:52:32 DEBUG c.m.config.MongoLiveConfig – …

Read more

Spring Data MongoDB – Select fields to return

In MongoDB console, you can use field:1 to select the fields to return from a query : > db.hosting.find({},{domain:1, count:1}); In Spring Data for MongoDB, you use query.fields().include : HostingDaoImpl.java package com.mkyong.core.hosting.dao; import java.util.List; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Repository; import com.hostingcompass.core.db.dao.MongoDaoImpl; @Repository public class HostingDaoImpl extends MongoDaoImpl<Hosting> implements HostingDao { …

Read more

Gradle War Plugin – Change output WAR filename

In Gradle, the WAR plugin will generate the final WAR file with the following pattern: ${baseName}-${appendix}-${version}-${classifier}.${extension} Example : hello.1.0.war To change the default WAR filename, update war.archiveName. For example : build.gradle project(‘:web’) { apply plugin: ‘war’ war { archiveName ‘hello-gradle.war’ } dependencies { compile project(‘:core’) providedCompile ‘javax.servlet:servlet-api:2.5’ providedCompile ‘org.apache.tomcat:tomcat-jsp-api:7.0.55’ //… } } Build it… $ …

Read more

How to pass System Properties in web.xml

In Java standalone application, you can use -D option to pass in the system properties : $ java -Dgeoip.file="/home/mkyong/geoip/test.db" test.jar In Java web application, you can pass the system properties via context-param in web.xml : web.xml <web-app> <context-param> <param-name>geoip.file</param-name> <param-value>/home/mkyong/geoip/test.db</param-value> </context-param> </web-app>

Spring @Value – Import a list from properties file

In this tutorial, we will show you how to import a “List” from a properties file, via Spring EL @Value Tested with : Spring 4.0.6 JDK 1.7 Spring @Value and List In Spring @Value, you can use the split() method to inject the ‘List” in one line. config.properties server.name=hydra,zeus server.id=100,102,103 AppConfigTest.java package com.mkyong.analyzer.test; import java.util.List; …

Read more

Spring @PropertySource example

Spring default loads application.properties into the application’s environment, and we can use @PropertySource to load custom .properties files. file.properties file.path=/server1/file/path Application.java @Configuration @PropertySource("classpath:file.properties") public class Application { @Value("${file.path}") private String path; //… } Table of contents: 1. Project Structure 2. Properties Files 3. @PropertySource and @Value 4. Loads property files from multiple sources 5. Placeholder …

Read more

Spring @Value default value

This article shows how to provide a default value for the @Value annotation. In the below code, if the property.name doesn’t exist in the application properties or environment, defaultValue will be assigned to the propertyName field. SimpleComponent.java import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class SimpleComponent { @Value("${property.name:defaultValue}") private String propertyName; // getters, setters, etc } …

Read more

Multiple SSH private keys Examples

To allow multiple private keys connect to different servers, edit ~/.ssh/config : ~/.ssh/config Host 10.10.10.1 IdentityFile ~/.ssh/linode_rsa Host 200.20.20.2 IdentityFile ~/.ssh/id_rsa If you SSH to 10.10.10.1, private key ~/.ssh/linode_rsa will be used. If you SSH to 200.20.20.2, private key ~/.ssh/id_rsa will be used. 1. Single Private Key for Multiple Servers 1.1 You have following public …

Read more