Count IP address in Nginx access logs

Recently, many referer spam hit on my server, below is the command I used to find and count the IP Address from a Nginx access log file. $ sudo awk ‘{print $1}’ /var/log/nginx/access.log | sort | uniq -c | sort -nr Full example. $ sudo awk ‘{print $1}’ /var/log/nginx/access.log | sort | uniq -c | …

Read more

jsoup : Send search query to Google

This example shows you how to use jsoup to send a search query to Google. Document doc = Jsoup .connect("https://www.google.com/search?q=mario"); .userAgent("Mozilla/5.0") .timeout(5000).get(); Unusual traffic from your computer network Don’t use this example to spam Google, you will get above message from Google, read this Google answer. 1. jsoup example Example to send a “mario” search …

Read more

Java – Read a file from resources folder

In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream. // the stream holding the file content InputStream is = getClass().getClassLoader().getResourceAsStream("file.txt"); // for static access, uses the class name directly InputStream is = JavaClassName.class.getClassLoader().getResourceAsStream("file.txt"); The …

Read more

How to change Tomcat manager default path ?

By default, Tomcat’s manager webapp is able to access via yourapp:8080/manager. It is a good practice to change the default /manager to something else, to avoid potential brute force attack. Environment Tomcat 7 (apt-get install) Debian 7.5 1. Solution This article show you how to change / rename the default manager webapp path from “/manager” …

Read more

How to change Tomcat to use JDK 7

The current environment is using Tomcat 7 + JDK 6. How to configure Tomcat to use JDK 7? Environment Tomcat 7 (apt-get install) Debian 7.5 JDK 6 and JDK 7 P.S Tomcat 7 is installed via apt-get Note You may interest at this tutorial – Apache Tomcat 8 + JDK 8 on Debian 1. Solution …

Read more

Eclipse – red-x icon didn’t display on project explorer

In Eclipse IDE, If a project contains errors, a small “red-x” icon will be displayed in the files that are causing the error. This useful feature is supported in Java related perspectives only, for example, “Package Explorer”. 1. Problem Personally, I prefer to use the “Project Explorer” perspective (pure folder structure), but the “red-x” icon …

Read more

Linux : How to gzip a folder

On Linux, gzip is unable to compress a folder, it used to compress a single file only. To compress a folder, you should use tar + gzip, which is tar -z. Note $ tar –help -z, -j, -J, –lzma Compress archive with gzip/bzip2/xz/lzma For example, tar -zcvf outputFileName folderToCompress 1. Tar + Gzip a folder …

Read more

mongoimport unable to import $numberLong

A collection with NumberLong type data as follows : > db.hc_whois.findOne(); { "_id" : NumberLong(3000001), "startIpInLong" : NumberLong(1543503872), "endIpInLong" : NumberLong(1544552447), "name" : "ap-net-1", //… } Export it with mongoexport : server1 $ mongoexport -d mydb -c hc_whois -o whois.json whois.json { "_id" : { "$numberLong" : "3000001" }, "startIpInLong" : { "$numberLong" : "1543503872" …

Read more

servlet-api-2.5.jar – jar not loaded

Deployed a “war” file on Tomcat, and hits following error messages : Jul 17, 2014 7:59:55 PM org.apache.catalina.loader.WebappClassLoader validateJarFile INFO: validateJarFile(D:\apache-tomcat-7.0.53\webapps\hc\WEB-INF\lib\servlet-api-2.5.jar) – jar not loaded. See Servlet Spec 3.0, section 10.7.2. Offending class: javax/servlet/Servlet.class Tools used : JDK1.7 Maven 3 Tomcat 7 1. Reason The Tomcat’s container comes with own version of servlet-api.jar, and the …

Read more

JSF 2 + Log4j Integration Example

In this tutorial, we will show you how to integrate the log4j framework with the JSF 2.x web application. JSF is using java.util.logging, you need extra works to redirect the logging from JSF’s java.util.logging to log4j, with a serious penalty of performance, make sure use this trick only during local development or debugging environment. Review …

Read more

Log4j hello world example

In this tutorial, we will show you how to use the classic log4j 1.2.x to log a debug or error message in a Java application. 1. Project Directory Review the final project structure, a standard Maven style Java project. 2. Get Log4j Declares the following dependencies : pom.xml <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> For non-Maven …

Read more

Download file from server using SSH

Normally, you use Secure copy or SCP to download a file from another server via SSH connection. For example, scp username@remotehost:remoteFileToDownload localFolderNameToSaveTheFile 1. SCP Examples 1.1 Download File From Server Example to download a log file (hc.audit.log) from server (198.58.x.x), into your current local folder. scp [email protected]:/var/log/tomcat7/hc.audit.log . 1.2 Upload File To Server Example to …

Read more

Debian : Change default Java version

Deployed a Debian 7.5 on Linode server, the default is using OpenJDK 1.6. How to upgrade to OpenJDK 1.7? $ java -version java version "1.6.0_31" OpenJDK Runtime Environment (IcedTea6 1.13.3) (6b31-1.13.3-1~deb7u1) OpenJDK 64-Bit Server VM (build 23.25-b01, mixed mode) Tracing the java, it’s using the Debian’s alternative settings : $ ls -lsa /usr/bin/ | grep …

Read more

log4j.xml Example

Here’s an XML version of log4j properties file, just for sharing. 1. Output to Console Redirect the logging to console. log4j.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration debug="true" xmlns:log4j=’http://jakarta.apache.org/log4j/’> <appender name="console" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L – %m%n" /> </layout> </appender> <root> <level value="DEBUG" /> <appender-ref ref="console" /> …

Read more

Spring Security + Hibernate Annotation Example

In this tutorial, previous Spring Security + Hibernate4 XML example will be reused, and convert it to a annotation-based example. Technologies used : Spring 3.2.8.RELEASE Spring Security 3.2.3.RELEASE Hibernate 4.2.11.Final MySQL Server 5.6 Tomcat 7 (Servlet 3.x container) Quick Note : Create a session factory with LocalSessionFactoryBuilder Inject session factory into a UserDao Integrate UserDao …

Read more

Spring Security + Hibernate XML Example

In this tutorial, we will show you how to integrate Hibernate 4 in Spring Security, XML configuration example. Note For annotation version, please read this Spring Security + Hibernate Annotation Example. Technologies used : Spring 3.2.8.RELEASE Spring Security 3.2.3.RELEASE Hibernate 4.2.11.Final MySQL Server 5.6 JDK 1.6 Maven 3 Eclipse 4.3 Quick Notes Create a session …

Read more

java.lang.ClassNotFoundException: org.hibernate.service.jta.platform.spi.JtaPlatform

Spring 3.2.x + Hibernate 4.3.x integration, hits JtaPlatform ClassNotFoundException, search the project classpath, find out that JtaPlatform is at different package? hibernate-core.4.3.5.Final.jar org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform Error message shows org.hibernate.service.jta.platform.spi.JtaPlatform Caused by: java.lang.NoClassDefFoundError: org/hibernate/service/jta/platform/spi/JtaPlatform at org.springframework.orm.hibernate4.SpringSessionContext.<init>(SpringSessionContext.java:56) ~[spring-orm-3.2.8.RELEASE.jar:3.2.8.RELEASE] … 40 common frames omitted Caused by: java.lang.ClassNotFoundException: org.hibernate.service.jta.platform.spi.JtaPlatform //… pom.xml <!– Hibernate ORM –> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.5.Final</version> </dependency> <!– …

Read more

Spring Security : Encoded password does not look like BCrypt

In Spring Security, database authentication with bcrypt password hashing. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; //… String password = “123456”; PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String hashedPassword = passwordEncoder.encode(password); spring-security.xml <authentication-manager> <authentication-provider> <password-encoder hash="bcrypt" /> //… </authentication-provider> </authentication-manager> CREATE TABLE users ( username VARCHAR(45) NOT NULL , password VARCHAR(45) NOT NULL , enabled TINYINT NOT NULL DEFAULT …

Read more

Google Chrome displays pink color screen

Problem After upgrading from Windows 8 Enterprise to Windows 8.1, Google Chrome displays pink color screen like this : Windows Environment Chrome 34.0.1847.137 m Windows 8.1 NVIDIA 331.58 Chrome GPU : NVIDIA 9.18.13.3158 To get the Chrome GPU, type chrome://gpu in the browser URL, refer to the driver version. Driver vendor NVIDIA Driver version 9.18.13.3523 …

Read more

ClassNotFoundException: org.aspectj.weaver.reflect.ReflectionWorld$ReflectionWorldException

Spring + Hibernate4 integration, and transaction are managed by Spring AOP, example : spring-hibernate.xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="get*" read-only="true" /> <tx:method name="*" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="userDaoPointCut" expression="execution(* com.mkyong.users.service.*Dao.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="userDaoPointCut" /> …

Read more

Spring Security : Check if user is from remember me cookie

This Spring Security example shows you how to check if a user is login from a “remember me” cookie. private boolean isRememberMeAuthenticated() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) { return false; } return RememberMeAuthenticationToken.class.isAssignableFrom(authentication.getClass()); } @RequestMapping(value = "/admin/update**", method = RequestMethod.GET) public ModelAndView updatePage() { ModelAndView model = new ModelAndView(); if (isRememberMeAuthenticated()) …

Read more

Spring + Hibernate : No Session found for current thread

Integrates Spring 3 and Hibernate 4, the system shows the following message while performing database operation : org.hibernate.HibernateException: No Session found for current thread The sessionFactory is injected like this : spring-hibernate4.xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test" /> <property name="username" value="root" /> <property name="password" …

Read more

How to autowire DataSource in JdbcDaoSupport

A Simple DAO class extends JdbcDaoSupport, but, unable to inject or @autowired a “dataSource”, the method setDataSource is final, can’t override. UserDetailsDaoImpl.java package com.mkyong.users.dao; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.stereotype.Repository; @Repository public class UserDetailsDaoImpl extends JdbcDaoSupport implements UserDetailsDao { //Error, cannot override the final method from JdbcDaoSupport @Autowired public void setDataSource(DataSource dataSource) { …

Read more

Can’t delete records in MySQL Workbench

In MySQL workbench, issue a simple delete all commands delete FROM users; But it shows me following error message : Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable safe mode, toggle the option in Preferences -> SQL …

Read more

JdbcTemplate queryForInt() is Deprecated

Upgrading Spring version and noticed that queryForInt() is deprecated, what should be replaced by? private boolean isUserExists(String username) { String sql = "SELECT count(*) FROM USERS WHERE username = ?"; boolean result = false; //The method queryForInt(String, Object…) from the type JdbcTemplate is deprecated int count = getJdbcTemplate().queryForInt(sql, new Object[] { username }); if (count …

Read more

Python – Read XML file (DOM Example)

In this example, we will show you how to read an XML file and print out its values, via Python xml.dom.minidom. 1. XML File A simple XML file, later parse it with Python minidom. staff.xml <?xml version="1.0"?> <company> <name>Mkyong Enterprise</name> <staff id="1001"> <nickname>mkyong</nickname> <salary>100,000</salary> </staff> <staff id="1002"> <nickname>yflow</nickname> <salary>200,000</salary> </staff> <staff id="1003"> <nickname>alex</nickname> <salary>20,000</salary> </staff> …

Read more

queryForObject() throws EmptyResultDataAccessException when record not found

Reviewing a legacy project, and found this Spring JDBC code snippets : public User getUser(String username) { String sql = "SELECT * FROM USER WHERE username = ?"; return getJdbcTemplate().queryForObject( sql, new Object[] { username }, new RowMapper<UserAttempts>() { public UserAttempts mapRow(ResultSet rs, int rowNum) throws SQLException { User user = new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); …

Read more

How to install a Vim color scheme

In this tutorial, we will show you how to install a Vim editor color scheme named “distinguished“. 1. Default Color Scheme Default syntax highlight in the “homebrew” profile terminal. 2. Install a new Vim Color Scheme 2.1 Download a new Vim color scheme – “distinguished“. Extracts and move the downloaded *.vim file to this folder …

Read more

The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved

Developing a Spring MVC, using a JSP file as a View resource. example.jsp <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <body> <h1>Spring MVC web application</h1> </body> </html> Above is a simple JSP page, but hits the following jstl error? SEVERE: Servlet.service() for servlet mvc-dispatcher threw exception org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either …

Read more

Spring Security Hello World Annotation Example

In preview post, we are using XML files to configure the Spring Security in a Spring MVC environment. In this tutorial, we are going to show you how to convert the previous XML-base Spring Security project into a pure Spring annotation project. Technologies used : Spring 3.2.8.RELEASE Spring Security 3.2.3.RELEASE Eclipse 4.2 JDK 1.6 Maven …

Read more

Eclipse – SimpleTagSupport was not found on the Java Build Path

Here is the development environment Eclipse 4.3 Kepler Java 1.7 Spring 3.2, a MVC project using JSP view. 1. Problem Recently, Eclipse IDE is prompting following error message on top of all of the .tag file. The superclass "javax.servlet.jsp.tagext.SimpleTagSupport" was not found on the Java Build Path. See figure : P.S The SimpleTagSupport class is …

Read more

Java – Get nameservers of a website

In this tutorial, we will show you how to get the nameservers of a website using Java + dig command. 1. Using Dig Command 1.1 On Linux, we can use dig command to query a DNS lookup of a website, for example : $ dig any mkyong.com //… mkyong.com. 299 IN A 162.159.x.x mkyong.com. 299 …

Read more