Total Pageviews

2017/07/11

Utilize AgeFileFilter to filter either newer files or files equal to or older

Scenario
I have an requirement to read a specific directory (including subdirectories) to find five days before log files and delete them.
How to do it?

How-To
Add commons-io to your maven dependency:
1
2
3
4
5
    <dependency>
     <groupId>commons-io</groupId>
     <artifactId>commons-io</artifactId>
     <version>2.5</version>
    </dependency>


Here has code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
    /**
     * 找出某個日期以前的檔案.
     * 
     * @param directory 找出某個目錄下的檔案
     * @param days 找出數天前 (如 -20)
     * @param includeSubdir 是否包含子目錄 (true / false)
     * @return List of File
     */
    public static List<File> getFilesBeforeXDays(File directory, int days, Boolean includeSubdir) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DATE, days);
        cal.set(Calendar.HOUR, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        Date date = cal.getTime();

        IOFileFilter ageFileFilter = FileFilterUtils.ageFileFilter(date);
        IOFileFilter subDirFilter = includeSubdir ? FileFilterUtils.trueFileFilter()
                : FileFilterUtils.falseFileFilter();

        Collection<File> fileCollection = org.apache.commons.io.FileUtils.listFiles(directory, ageFileFilter, subDirFilter);
        if(CollectionUtils.isEmpty(fileCollection)){
            log.info("Cannot find any log files before " + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS").format(date));
        } else{
            log.info("Find " + fileCollection.size() + " log file(s).");
        }
        
        return new ArrayList<File>(fileCollection);
    }




Reference
[1] https://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/filefilter/AgeFileFilter.html    

2017/07/10

How to Clear Code Coverage Highlight in Eclipse

Problem
I am using EclEmma, a free Java code coverage tool for Eclipse, to generate code coverage analysis report. The report looks like:


EclEmma provide source highlighting to show the result of code coverage. If I would like to clear code coverage highlight, how to do it?


How-To
Click "Remove All Sessions" in Coverage tab



2017/07/09

[HttpClient] Fail to Get Response from a Valid URL

Problem
I am using HttpClient Get method to retrieve the response body of the HTTP method, if any.
During the execution, I fail to get response from a valid URL. 

The code snippet is as follows:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package albert.practice.http;

import java.io.IOException;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Charsets;
import com.google.common.base.Strings;

public class HttpSmsClient {

    private final static Logger logger = LoggerFactory.getLogger(HttpSmsClient.class);

    public static String getResponse(String url) throws IOException {
        String responseString = "";
        HttpClient client = new HttpClient();
        
        GetMethod method = new GetMethod(url);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        int statusCode;
        try {
            statusCode = client.executeMethod(method);            
            if (HttpStatus.SC_OK == statusCode) {
                responseString = IOUtils.toString(method.getResponseBodyAsStream(), Charsets.UTF_8);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            method.releaseConnection();
        }
        logger.info("responseString = " + responseString);
        return responseString;
    }

}



How-To
In my office, I need to specify proxy server before I connect to various services.
Therefore, the source code will be modified as follows:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package albert.practice.http;

import java.io.IOException;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Charsets;
import com.google.common.base.Strings;

public class HttpSmsClient {

    private final static Logger logger = LoggerFactory.getLogger(HttpSmsClient.class);

    public static String getResponse(String url, String proxy, String port) throws IOException {
        String responseString = "";
        HttpClient client = new HttpClient();

        HostConfiguration hostConfiguration = client.getHostConfiguration();
        hostConfiguration.setProxy(proxy, Integer.valueOf(port));
        client.setHostConfiguration(hostConfiguration);
        
        GetMethod method = new GetMethod(url);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        int statusCode;
        try {
            statusCode = client.executeMethod(method);            
            if (HttpStatus.SC_OK == statusCode) {
                responseString = IOUtils.toString(method.getResponseBodyAsStream(), Charsets.UTF_8);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            method.releaseConnection();
        }
        logger.info("responseString = " + responseString);
        return responseString;
    }

}


Maven dependencies are as follows:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    <dependencies>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.7</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>20.0</version>
        </dependency>
    </dependencies>




2017/07/08

[HttpClient] Warning: Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.

Problem
I am using HttpClient Get method to retrieve the response body of the HTTP method, if any.
During the execution, the console print this warning message: 
Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.

The code snippet is as follows:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package albert.practice.http;

import java.io.IOException;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Strings;

public class HttpSmsClient {

    private final static Logger logger = LoggerFactory.getLogger(HttpSmsClient.class);
    
    public static String getResponse(String url, String proxy, String port) throws IOException {
        String responseString = "";
        HttpClient client = new HttpClient();

        if (!Strings.isNullOrEmpty(proxy) && !Strings.isNullOrEmpty(proxy)) {
            HostConfiguration hostConfiguration = client.getHostConfiguration();
            hostConfiguration.setProxy(proxy, Integer.valueOf(port));
            client.setHostConfiguration(hostConfiguration);
        }
        
        GetMethod method = new GetMethod(url);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        int statusCode;
        try {
            statusCode = client.executeMethod(method);
            if (HttpStatus.SC_OK == statusCode) {
                responseString = method.getResponseBodyAsString();
            }
        } catch (IOException e) {
            throw e;
        } finally {
            method.releaseConnection();
        }
        logger.info("responseString = " + responseString);
        return responseString;
    }

}


How-To
This warning message results from Line 38
According to its recommendation, the source code will be modified as bellows:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package albert.practice.http;

import java.io.IOException;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Charsets;
import com.google.common.base.Strings;

public class HttpSmsClient {

    private final static Logger logger = LoggerFactory.getLogger(HttpSmsClient.class);

    public static String getResponse(String url, String proxy, String port) throws IOException {
        String responseString = "";
        HttpClient client = new HttpClient();

        if (!Strings.isNullOrEmpty(proxy) && !Strings.isNullOrEmpty(proxy)) {
            HostConfiguration hostConfiguration = client.getHostConfiguration();
            hostConfiguration.setProxy(proxy, Integer.valueOf(port));
            client.setHostConfiguration(hostConfiguration);
        }
        logger.info("url = " + url);
        GetMethod method = new GetMethod(url);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        int statusCode;
        try {
            statusCode = client.executeMethod(method);
            logger.info("[getResponse] statusCode = " + statusCode);
            if (HttpStatus.SC_OK == statusCode) {
                responseString = IOUtils.toString(method.getResponseBodyAsStream(), Charsets.UTF_8);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            method.releaseConnection();
        }
        logger.info("responseString = " + responseString);
        return responseString;
    }

}


Maven dependencies are as bellows:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    <dependencies>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.7</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>20.0</version>
        </dependency>

    </dependencies>




2017/07/07

[webMethods] How to delete threads in webMethods

Problem
假設在 OpcTest 此 package 中會執行以下幾個 flow services

若希望在 package 被 disable 時,能把這幾個 flow services 的 threads 砍掉,該如何做?


How-To
解決方式如下,共有兩個步驟:
Step 1. 建立一個 Java Service,source code 如下:
public static final void terminationService(IData pipeline) throws ServiceException {
        IDataCursor pipelineCursor = pipeline.getCursor();
        String threadNameToKill = IDataUtil.getString(pipelineCursor, "threadNameToKill");
        pipelineCursor.destroy();
        
        if(threadNameToKill == null)
        {
            // Fill in the toppest folder name.
            // Take the OpcTest package for example, it should be "group1".
            threadNameToKill = "group1";
        }
        
        Thread current = Thread.currentThread();
        ThreadGroup root = current.getThreadGroup();
                
        while (root.getParent() != null) {
            root = root.getParent();
        }
        
        Thread [] threads = new Thread[1000];
        int count = root.enumerate(threads, true);
        
        for(int i = 0 ; i < count ; i++)
        {
            if(threads[i] instanceof ServerThread)
            {
                ServerThread temp = (ServerThread) threads[i];
                
                String threadName = temp.getName();
                
                logger( "[ Thread Name ]: " + threadName);
                if(threadName.contains(threadNameToKill))
                {
                    logger( "[ Stopping ]: " + threadName);
                    threads[i].stop();
                }
        
            }
        }       
            
    }

Step 2. 將此 Java Service 設定為 shutdown service,如此一來,當 package 被 disable 或 integration server 被 shutdown 時,都會執行此 shutdown service