Showing posts with label J2SE. Show all posts
Showing posts with label J2SE. Show all posts

Using Apache Commons Lang ExceptionUtils


Apache Commons Lang ExceptionUtils provides some utility methods to manipulate and examine Throwable, such as getRootCause, getStackTrace, getFullStackTrace etc.

The following would introduce some common usage of ExceptionUtils.

Check the Root Cause
Sometimes, we need check the root cause of one exception or whether the exception stack trace contains one specific exception. 
For example, when Lucene commit, it may fail due to OutOfMemoryError. But the returned exception maybe IllegalStateException like blow: We need check whether OutOfMemoryError happened.
auto commit error...:java.lang.IllegalStateException: this writer hit 
an OutOfMemoryError; cannot commit 
        at org.apache.lucene.index.IndexWriter.prepareCommit(IndexWriter.java:2650) 
        at org.apache.lucene.index.IndexWriter.commitInternal(IndexWriter.java:2804) 

We can use code like below:
Throwable th= ExceptionUtils.getRootCause();
boolean causedByOOM = th instanceof OutOfMemoryError;

Or if we want to check whether it contains the exception in any position in the exception chaining. Use code like below:
String fullTrace = ExceptionUtils.getFullStackTrace(th);
boolean isOOM = fullTrace.contains("OutOfMemoryError");
Or:
java.io.Writer result = new java.io.StringWriter();
java.io.PrintWriter printWriter = new java.io.PrintWriter(result);
e.printStackTrace(printWriter);
result.toString();
Check Caller or Code Branch
We may want to log some debug message when methodA is called by ClassX.MethodY -either directly or indirectly. We can use code like below:
if (logger.isDebugEnabled()) {
String fullStack = ExceptionUtils.getFullStackTrace(new Throwable());
boolean isXY = fullStack.contains("ClassX.MethodY");
if(isXY) {
logger.debug("some debug message");
}
Resource
Exception Utils Javadoc

Using Guava Stopwatch


When read this post, TRIM, LTRIM and RTRIM in Java

I have a doubt about the performance difference between the one uses regular expression ltrim and the straightforward ltrim3. So I use Guava topwatch
to test their performance. 
Guava Usage
1. Use Stopwatch static factory method to create one instance.
Stopwatch stopwatch = Stopwatch.createStarted()
2. Use stopwatch.elapsed(TimeUnit) to get elapsed time.
3. We can reuse same stopwatch instance to measures another operation, but we have to first call reset(), and start().
reset() method would reset internal variable: elapsedNanos=0, isRunning=false. Calling start() would start again to measure time elapsed.
Conclusion
The test result is as what I expected, the straightforward one gives the best performance.
458 for ltrim3(the straightforward one)
3967 for ltrim(using regular expression)

The code looks like below:
import com.google.common.base.Stopwatch;

public class LTrimTester {
  private final static Pattern LTRIM = Pattern.compile("^\\s+");
  private final static Pattern RTRIM = Pattern.compile("\\s+$");

  public static void main(String[] args) {
    int times = 10000000;
    Stopwatch stopwatch = Stopwatch.createStarted();
    for (int i = 0; i < times; i++) {
      String str = "  hello world  ";
      ltrim(str);
    }
    System.out.println(stopwatch.elapsed(TimeUnit.MILLISECONDS)
        + " for ltrim(using regular expression)");

    stopwatch.reset();
    stopwatch.start();
    for (int i = 0; i < times; i++) {
      String str = "  hello world  ";
      ltrim3(str);
    }
    System.out.println(stopwatch.elapsed(TimeUnit.MILLISECONDS)
        + " for ltrim3(the straightforward one)");
    stopwatch.stop();
  }

  public static String ltrim(String s) {
    return LTRIM.matcher(s).replaceAll("");
  }

  public static String ltrim3(String s) {
    int i = 0;
    while (i < s.length() && Character.isWhitespace(s.charAt(i))) {
      i++;
    }
    return s.substring(i);
  }
}
Resources
TRIM, LTRIM and RTRIM in Java
Guava Stopwatch Javadoc
Guava Stopwatch

Be Sure to Reuse SolrServer and Apache HttpClient Instance


The Problem
In one solr-related application, we use SolrJ HttpSolrServer to push data into remote Solr server. In one load testing machine, we see SocketConnection Exception intermittently in remote Solr Server. 
Caused by: org.apache.solr.client.solrj.SolrServerException: java.net.SocketException: Connection reset
at org.apache.solr.client.solrj.impl.HttpSolrServer.request (HttpSolrServer.java:340)
Although for each request, we will retry several times. But we are still wondering what caused this exception and the network usage in the remote Solr server.
Use TCPView in Windows to Monitor Network
In linux, we can use lsof -i -p pid to list all port a process opens. In Windows, we can use TCPView
from Windows Sysinternals to monitor tcp connections. 

We see there are a thousands of connections in TIME_WAIT, CLOSE_WAIT, FIN_WAIT2 status in client and remote Solr server. This looks suspicious.
HttpSolrServer Usage Pattern
As the main logic in client is to use HttpSolrServer to send requests to Solr server. So we suspect there is something wrong when use HttpSolrServer.
Checked the code, the client program uses java Threadpool to send request, in each thread, it creates a HttpSolrServer, send a requests, then shutdown the SolServer.

Looked at wike page in SolrJ
HttpSolrServer is thread-safe and if you are using the following constructor, you *MUST* re-use the same instance for all requests.  If instances are created on the fly, it can cause a connection leak. The recommended practice is to keep a static instance of HttpSolrServer per solr server url and share it for all requests.

We changed the code to use a global static HttpSolrServer instance. Then use TCPView to monitor network usage after the change. Now there are only less than 20 connections open. 

Same logic applies when we use Apache HttpClient: Use one single HttpClient instance for each remote host.
Lesson Learned
Use tools in Windows Sysinternals and TCPView 
Reuse HttpSolrServer and Apache HttpClient instance.
Test Program
If you run the following test program, and monitor with TCPView, you can immediately notice the difference.
@Test
public void correctUsageSolrServer() throws InterruptedException {
 final String baseURL = "SOLRURL";
 final HttpSolrServer solrServer = new HttpSolrServer(baseURL);
 
 int i = 0;
 while (i++ < 1000) {
  Thread thread = new Thread() {
   @Override
   public void run() {
    SolrQuery query = new SolrQuery("*:*");
    try {
     QueryResponse rsp = solrServer.query(query);
     System.out.println(rsp);
    } catch (Exception e) {
     e.printStackTrace();
     throw new RuntimeException(e);
    }
   }
  };
  
  thread.start();
  Thread.sleep(10);
 }
 // be sure to shutdown solrServer at the end.
 solrServer.shutdown();
}

@Test
public void wrongUsageSolrServer() throws InterruptedException {
 final String baseURL = "SOLRURL";
 
 int i = 0;
 while (i++ < 1000) {
  Thread thread = new Thread() {
   @Override
   public void run() {
    final HttpSolrServer solrServer = new HttpSolrServer(baseURL);
    
    SolrQuery query = new SolrQuery("*:*");
    try {
     QueryResponse rsp = solrServer.query(query);
     System.out.println(rsp);
    } catch (Exception e) {
     e.printStackTrace();
     throw new RuntimeException(e);
    } finally {
     solrServer.shutdown();
    }
   }
  };
  
  thread.start();
  Thread.sleep(10);
 }
}
Resources
SolrJ Wiki
Connection Close in HttpClient
HttpClient Connection Management FAQ and Explanation of TIME_WAIT status
TCP Connection Termination Order

Trouble Shooting Apache Procrun Unable to Start Service Problem


Today, I am debugging the batch script that wraps the embedded jetty+solr application as windows service. The script looks like:
Windows BAT: Using Apache Procrun to Install Java Application As Windows Service

Then I run installService.bat -service_name service1 -start_params "start;-port;9753" -stop_params shutdown, it installs the service successfully. But when I click service1.exe and try to start the service, it fails silently. No any (error) message logged in commons-daemon.log or service1.stderr/stdout.log. But when I run prunsrv //TS//service1 to debug the service, it runs well.

Looks weird. If procrun logged error message in some place, it would be much easier to find the root cause of the problem.
View Procrun Error Message in Event Viewer
To view the error log, we have to view Windows Event Log: Go to Control Panel, and search Event Viewer, open it. Select "Windows Log" -> "System", reproduce the problem by starting the service in service1 service GUI, we can see one new error log:
The service1 service failed to start due to the following error: 
The system cannot find the file specified.

Root Cause of The system cannot find the file specified
Google search "The system cannot find the file specified". Find post Build windows service from java application with procrun:
If you use (correct) relative paths to files(especially for prunmgr.exe) in the installation script, the service will install correctly and it will run fine in debugging mode. It will however fail when run normally with any administrative tooling you have.
Generally, you should use absolute paths with procrun.

Check the service1 GUI, in general tab. it indeed uses prunsrv //RS//service1.
Check the script, I use:
"%PRUNSRV%" //IS//%SERVICE_JAVA% --Install="%MYPATH%prunsrv"
But somehow I removed the definition of MYPATH in the script. Update the script:
set "PRUNSRV=%%~dp0/%prunsrv.exe"
"%PRUNSRV%" //IS//%SERVICE_JAVA% --Install="%PRUNSRV%"
Now it works.
Lesson Learned
Use absolute path in installation script.
Don't use white spaces in the service name.
Use System Event Log to view prunsrv error message.

Resources
Build windows service from java application with procrun
https://github.com/lenhard/procrun-sample
Windows BAT: Using Apache Procrun to Install Java Application As Windows Service
http://commons.apache.org/proper/commons-daemon/procrun.html

Creating Custom Solr Type to Stream Large Text Field


The Problem
In my project, we run some queries in Solr server, and return combined response back to client(we can't use SolrJ as the request goes through some proxy applications which add extra functions). But some text fields are too large, we would like to reduce their size, so the transfer content would be much less.
Steps We Have Done
To reduce the content size,  at remote Solr server we use GZipOutputStream and Bse64OutputStream to zip the string, this can reduce the size by more than 85%: Original 134 mb String is compressed to 16mb.
Read more: Java: Use ZIP Stream and Base64 Stream to Compress Large String Data
Java: Use Zip Stream and Base64 Encoder to Compress Large String Data 
At client side, when it receives the zipped base64 string, it first Base64 decodes it, uncompress it, then add it as a field into Solr. 

But If we do all this in memory, it will load the huge original unzipped string 134mb into memory. It will cause the application OutOfMemoryError. Obviously this is not desired.

We want to first use stream(Base64InputStream and GZipInputStream) to unzip it, and write original string into a temp file. When Solr add this field into Solr, it can use Reader to read from the temp file, after it’s done, it can delete the temp file.

In Lucene, we can provide a Reader as a parameter to Field constructor, Lucene will consume the reader and close it after it’s done. 
The field can only indexed, not stored. But this is fine for us, as this field is only used for search.

Solr doesn't expose this function, but we can easily extend Solr to define a custom field which accepts a Reader.

The Solution
Custom Solr Field Type: FileTextField
FileTextField extends solr.schema.TextField. When add value to FileTextField, the value can be a string, or a reader. If it's a reader, createField will create a Lucene Field with Reader as parameter: Field f = new Field(name, fr, type); Lucene will consume the reader, and close it after it's done.
FileTextField has one configuration parameter: deleteFile. If true, it will delete the file after Lucene has read the file and written it to index. If false, it will keep this file. We have to set encoding in its constructors: this can avoid the problem: different encodings are used when write and read the file.
public class FileTextField extends TextField {
  private boolean deleteFile;
  protected void init(IndexSchema schema, Map<String,String> args) {
    String str = args.remove("deleteFile");
    if (str != null) {
      deleteFile = Boolean.parseBoolean(str);
    }
    super.init(schema, args);
  }

  public IndexableField createField(SchemaField field, Object value, float boost) {
    if (!field.indexed() && !field.stored()) {
      if (log.isTraceEnabled()) log.trace("Ignoring unindexed/unstored field: "
          + field);
      return null;
    }
    if (value instanceof FileHolder) {
      FileHolder fileHolder = (FileHolder) value;
      fileHolder.setDeleteFile(deleteFile);
      Reader reader;
      try {
        reader = fileHolder.getReader();
        return createFileTextField(field.getName(), reader, boost);
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    } else {
      return super.createField(field, value, boost);
    }
  }
  
  public Field createFileTextField(String name, Reader fr,
      float boost) {
    Field f = new org.apache.lucene.document.TextField(name, fr);
    f.setBoost(boost);
    return f;
  }
}
FileHolder 
In order to get the file path, we create a wrapper FileHolder, it's get reader method return an InputStreamReader. If deleteFile is true, its close method will delete the file after close the stream.
public static class FileHolder {
 private String filePath;
 private boolean deleteFile;
 private String encoding;
 public FileHolder(File file, String encoding)
   throws FileNotFoundException, UnsupportedEncodingException {
  this.filePath = file.getAbsolutePath();
  this.encoding = encoding;
 }
 public void setDeleteFile(boolean deleteFile) {
  this.deleteFile = deleteFile;
 }
  // @return  an InputStreamReader, if deleteFile is true, it will delete the file when the reader is closed.
 public Reader getReader() throws IOException {
  InputStreamReader reader = new InputStreamReader(new FileInputStream(
    filePath), encoding) {
   @Override
   public void close() throws IOException {
    super.close();
    if (deleteFile) {
     boolean deleted = new File(filePath).delete();
     if (!deleted) {
      log.error("Unable to delete " + filePath);
     }
    }
   }
  };
  return reader;
 }
}
Define FileTextField field in schema FileTextField is similar as Solr Text Field, we can define tokenizer and filters for index and query. It accepts an additional parameter: deleteFile. The value of stored can't be true. Read Document from Stream and add FileTextField into Solr The following code uses GSon's streaming JsonReader to read one document. We can determine size of zippedcontent by size field. If it's too large, we will write the uncompressed string into a temporary file and add a FleHodler instance to content field. 
private static Future<Void> readOneDoc(JsonReader reader, SolrQueryRequest request)
  throws IOException {
String str;
reader.beginObject();
long size = 0;
Object unzippedcontent = null;
boolean useFileText = false;
SolrInputDocument solrDoc = new SolrInputDocument();
while (reader.hasNext()) {
  str = reader.nextName();
  if ("size".equals(str)) {
 size = Long.parseLong(reader.nextString());
 if (size > size_LIMIT_FILETEXT) {
   useFileText = true;
 }
  } else if ("zippedcontent".equals(str) && reader.peek() != JsonToken.NULL) {
 if (useFileText) {
   // unzippedcontent is a FleHodler
   unzippedcontent = unzipValueToTmpFile(reader);
 } else {
   // decoded and uncompressed string
   unzippedcontent = unzipValueDirectly(reader);
 }
  } else {
 // in case, we change server side code.
 reader.skipValue();
  }
}
reader.endObject();
// add it to solr
UpdateRequestProcessorChain updateChian = request.getCore()
   .getUpdateProcessingChain("/update");
AddUpdateCommand command = new AddUpdateCommand(request);
command.solrDoc = solrDoc;
UpdateRequestProcessor processor = updateChian.createProcessor(request, new SolrQueryResponse());
processor.processAdd(command); 
}

private static String unzipValueDirectly(JsonReader reader)
  throws IOException {
String value = reader.nextString();
ZipInputStream zi = null;
try {
  Base64InputStream base64is = new Base64InputStream(new ByteArrayInputStream(
   value.getBytes("UTF-8")));
  zi = new ZipInputStream(base64is);
  zi.getNextEntry();
  return IOUtils.toString(zi);
} finally {
  IOUtils.closeQuietly(zi);
}
}

private static FileHolder unzipValueToTmpFile(JsonReader reader) throws IOException {
File tmpFile = File.createTempFile(TMP_FILE_PREFIX_ZIPPEDCONTENT, TMP_FILE_PREFIX_SUFFIX);
String value = reader.nextString();
ZipInputStream zi = null;
OutputStreamWriter osw = null;

try {
 Base64InputStream base64is = new Base64InputStream(new ByteArrayInputStream(
   value.getBytes("UTF-8")));
  zi = new ZipInputStream(base64is);
  zi.getNextEntry();
  osw = new OutputStreamWriter(new FileOutputStream(tmpFile), "UTF-8");
  IOUtils.copy(zi, osw);
  zi.closeEntry();
} finally {
  IOUtils.closeQuietly(osw);
  IOUtils.closeQuietly(base64is);
}
return new FileHolder(tmpFile.getAbsolutePath(), "UTF-8");
}
Conclusion
  • Use GZipOutput/InputStream and Bse64Output/InputStream to compress the large text. This can reduce size of text about 85%, this can reduce the time to transfer the request/response.
  • To reduce memory usage at client side:
  •   We use stream api(GSon stream or XML Stax) to read doc one by one.
  •   Define a custom Solr Field Type: FileTextField which accepts FileHolder as value. FileTextField will eventually pass a reader to Lucene. Lucene will use the reader to read content and add to index.
  •   When the text field is too big, first uncompress it to a temp file, create a FileHolder instance, then set the FileHolder instance as field value.

Java: Use ZIP Stream and Base64 Stream to Compress Large String Data


In the last post, we introduced how to use common codec library Base64 class: Base64.encodeBase64String and Base64.decodeBase64 and Zip Stream to compress large string data and encode it as Base64 string, then pass it via network to remote client; then decode it and uncompress to get the original string at remote side.

It works, but it has one drawback: it has to load the whole byte array or string into memory. If the string is too large, application may hit OutOfMemoryError.  
To solve this problem, we can use apache common codec Bse64OutputStream and Java GZipOutputStream to write base64 endode string; use Base64InputStream and GZipInputStream to decode to get the original string.
Apache Common Codec Base64InputStream and Base64OutputStream
The default behaviour of the Base64InputStream is to DECODE base64 string, whereas the default behaviour of the Base64OutputStream is to ENCODE, but this behaviour can be overridden by using a different constructor.
Stream Chaining Order
When zipped the string, the order would be GZIPOutputStream -> Base64OutputStream -> FileOutputStream.
First GZIPOutputStream compresses the string, Base64OutputStream converts it to base64 encoded string, FileOutputStream writes result to a file.


When unzip the base64 encoded string, the order would be GZIPInputStream -> Base64InputStream -> FileInputStream
FileInputStream reads from the file, Base64InputStream decode the base64-encoded string, GZIPInputStream then uncompress to get the original string.
Stream Chaining close
When closing chained streams, we should (and need only) close the outermost stream.
Compress String and Encode It
public static void zipAndEncode(File originalFile, File outFile) throws IOException {
    FileInputStream fis = null;
    GZIPOutputStream zos = null;
    try {
      fis = new FileInputStream(originalFile);
      FileOutputStream fos = new FileOutputStream(outFile);
      Base64OutputStream base64Out = new Base64OutputStream(fos);
      zos = new GZIPOutputStream(base64Out);
      IOUtils.copy(fis, zos);
    } finally {
      IOUtils.closeQuietly(fis);
      IOUtils.closeQuietly(zos);
    }
  }
Decode Base64 String and Uncompress It
public static void decodeAndUnzip(File inZippedFile, File outUnzippedFile) throws IOException {
    GZIPInputStream zis = null;
    OutputStreamWriter osw = null;
    try {
      FileInputStream fis = new FileInputStream(inZippedFile);
      Base64InputStream base64In = new Base64InputStream(fis);
      zis = new GZIPInputStream(base64In);
      
      FileOutputStream fos = new FileOutputStream(outUnzippedFile);
      osw = new OutputStreamWriter(fos, "UTF-8");
      IOUtils.copy(zis, osw);
    } finally {
      IOUtils.closeQuietly(zis);
      IOUtils.closeQuietly(osw);
    }
  }
Test Result:
Original file is about 131,328kb(131mb), base64 encode zipped string is 15,756kb(15mb).
We can see that the size reduces 88%. The benefit is huge and it's worth.
Resource
Commons Base64OutputStream - Principle of least surprise?

How To Encode A URL String in Java


Recently, I am using Apache Http Client and HttpURLConnection to send the following request to remote Solr server:
http://localhost:8080/solr/select?q=extractingat:[2012-11-14T04:08:54.000Z TO 2013-11-14T04:11:05.000Z]&start=0&rows=100
It got IllegalArgumentException like below:
java.lang.IllegalArgumentException: Illegal character in query at index 74: http://localhost:8080/solr/select?q=extractingat:[2012-11-14T04:08:54.000Z TO 2013-11-14T04:11:05.000Z]&start=0&rows=100
 at java.net.URI.create(URI.java:859)
 at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:69)
Caused by: java.net.URISyntaxException: Illegal character in query at index 74: http://localhost:8080/solr/select?q=extractingat:[2012-11-14T04:08:54.000Z TO 2013-11-14T04:11:05.000Z]&start=0&rows=100
 at java.net.URI$Parser.fail(URI.java:2829)
 at java.net.URI$Parser.checkChars(URI.java:3002)
 at java.net.URI$Parser.parseHierarchical(URI.java:3092)
The problem is because url special characters which should be encoded. Please read URL Encoding about what characters need to be encoded and why?

In Java, we can use URLEncoder to encode special characters. 
To use URLEncoder, we just need pay attention to one thing: which parts should be encoded.
Basic rule is that if these special characters are used for special use, then don't encode them.

In url: <scheme name> : <hierarchical part> [ ? <query> ] [ # <fragment> ], we usually need encode the <query> and <fragment> part. 

For the 2 formats of query string: 
Semicolon format: key1=value1;key2=value2;key3=value3
Ampersand format: key1=value1&key2=value2&key3=value3
We should not encode the ? =, & or ; which is used to separate multiple key value pairs. We should just encode the key and value field.

Resource
URL Encoding
URLEncoder Javadoc
URI scheme

Java: Use Zip Stream and Base64 Encoder to Compress Large String Data


Problem

In my project, we run some queries in Solr server, and return combined response back to client. But some text fields are too large, we would like to reduce their size.

Use GZIPOutputStream or ZipOutputStream?

To compress data, Java provides two streams GZIPOutputStream and ZipOutputStream. What’s the difference and which we should use? The compression algorithm and performance is almost same (Lempel-Ziv Welch), the difference is that GZIP format is used to compress a single file, and ZIP is a archive format: to compress many files in a single archive: using putNextEntry and closeEntry to add a new entry into the archive file.

In this case, we use GZIPOutputStream, because we don’t add and compress multiple file in a single archive, so no need to use ZipOutputStream, also the code to use ZipOutputStream si a little simpler.

Use GZIPOutputStream and Base64 Encoder to Compress String At server side, we can use GZIPOutputStream to compress a string to a byte array stored in ByteArrayOutputStream. But we can’t transfer the byte array as text in http response. We have to use a Base64 encoder to encode the byte array as Base64. We can use org.apache.commons.codec.binary.Base64.encodeBase64String(). Then we add the compressed text as a field in Solr Document field - not shown in the code below.

/**
   * At server side, use ZipOutputStream to zip text to byte array, then convert
   * byte array to base64 string, so it can be trasnfered via http request.
   */
  public static String compressString(String srcTxt)
      throws IOException {
    ByteArrayOutputStream rstBao = new ByteArrayOutputStream();
    GZIPOutputStream zos = new GZIPOutputStream(rstBao);
    zos.write(srcTxt.getBytes());
    IOUtils.closeQuietly(zos);

    byte[] bytes = rstBao.toByteArray();
    // In my solr project, I use org.apache.solr.co mmon.util.Base64.
    // return = org.apache.solr.common.util.Base64.byteArrayToBase64(bytes, 0,
    // bytes.length);
    return Base64.encodeBase64String(bytes);
  }

Test Data:

Original text in memory is about 134,479,520(134mb), its zipped byte array is about 9,001,240(9mb), base 64 string is 16,198,528(16mb). We can see that the size reduces 88%. This is huge and it’s worth. Use Base64 Decoder and GZIPInputStream to Uncompress String At remote client side, we first read the text response from stream, about how to read one Solr document using stream API, please read: Solr: Use STAX Parser to Read XML Response to Reduce Memory Usage Solr: Use SAX Parser to Read XML Response to Reduce Memory Usage Solr: Use JSON(GSon) Streaming to Reduce Memory Usage

Then use org.apache.commons.codec.binary.Base64.decodeBase64() to decode the Base64 string to byte array, and then use ZipInputStream to read the zipped byte array to get original unzipped string, then add it to Solr Document as a field.

/**
   * When client receives the zipped base64 string, it first decode base64
   * String to byte array, then use ZipInputStream to revert the byte array to a
   * string.
   */
  public static String uncompressString(String zippedBase64Str)
      throws IOException {
    String result = null;

    // In my solr project, I use org.apache.solr.common.util.Base64.
    // byte[] bytes =
    // org.apache.solr.common.util.Base64.base64ToByteArray(zippedBase64Str);
    byte[] bytes = Base64.decodeBase64(zippedBase64Str);
    GZIPInputStream zi = null;
    try {
      zi = new GZIPInputStream(new ByteArrayInputStream(bytes));
      result = IOUtils.toString(zi);
    } finally {
      IOUtils.closeQuietly(zi);
    }
    return result;
  }

Test Code

public static void main(String... args) throws IOException {
    String source = "-original-file-path;
    String zippedFile = "-base-64-zip-file-path-";
    FileInputStream fis = new FileInputStream(source);
    String srcTxt = IOUtils.toString(fis, "UTF-8");
    IOUtils.closeQuietly(fis);

    String str = compressString(srcTxt);
    FileWriter fw = new FileWriter(zippedFile);
    IOUtils.write(str, fw);
    IOUtils.closeQuietly(fw);

    fis = new FileInputStream(zippedFile);
    String zippedBase64Str = IOUtils.toString(fis, "UTF-8");
    IOUtils.closeQuietly(fis);

    String originalStr = uncompressString(zippedBase64Str);
    fw = new FileWriter("-revertedt-file-path");
    IOUtils.write(originalStr, fw);
    IOUtils.closeQuietly(fw);
  }

Resource

Use Json(Gson) to Serialize/Deserialize Collection of Object to Java Properties File


It's common and easy to store application configuration information like key=value in java properties file.
But how to store object or collection of object type into java properties file.

For example, I want to store a list of failed to fetch items in java properties file: including item id, failed times, and some other properties of this item, then I need deserialize it to list of UnableToFetchItem.
unableToFetchList={"id_1"\:{"id"\:"id_1, "extracting"\:a_long_millseconds,"failedTimes"\:a_int}, "id_x":{}, }

If we have to write our own code, it gets troublesome: when serialize the item lists, we have to put delimiter to separate items, serialize key/value pairs; when ddeserialize it back, we have to parse the delimiter, construct item object and set field value.

As my application already uses the java Json library:Gson, so I decide to serialize the list of UnableToFetchItem as a Json string, and then deserialize the Json string to a list of UnableToFetchItem. The code is much simpler and easy to read and maintain.
Implementation
The code is simple, the only trick part is how to serialize and deserialize a list of object: 
Look at GSon User Guide: Collections Examples
The key is to define a TypeToken with correct parameterized type:
private static Type objType = new TypeToken<Map<String,UnableToFetch>>() {}.getType();
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class AppConfig {
  private Map<String,UnableToFetch> unableToFetchMap = new HashMap<String,UnableToFetch>();
  private static Type objType = new TypeToken<Map<String,UnableToFetch>>() {}
      .getType();
  
  public static Map<String,UnableToFetch> fromJson(String jsonStr) {
    Map<String,UnableToFetch> result = null;
    if (StringUtils.isNotBlank(jsonStr)) {
      result = new Gson().fromJson(jsonStr, objType);
    }
    if (result == null) {
      result = new HashMap<String,UnableToFetch>();
    }
    return result;
  }
  
  public static String toJson(Map<String,UnableToFetch> map) {
    return new Gson().toJson(map, objType);
  }
  
  public AppConfig readFromPropertiesFile() {
    File proppertiesFile = new File("PROPERTIES_FILE_NAME");
    if (!proppertiesFile.exists()) {
      return this;
    }
    Properties properties = new Properties();
    FileInputStream fis = null;
    try {
      fis = new FileInputStream(proppertiesFile);
      properties.load(fis);
      String str = properties.getProperty("unableToFetchList");
      unableToFetchMap = fromJson(str);
    } catch (Exception e) {
      throw new RuntimeException(e);
    } finally {
      IOUtils.closeQuietly(fis);
    }
    return this;
  }

  public void saveProperties() {
    File proppertiesFile = new File("PROPERTIES_FILE_NAME");
    
    Properties properties = new Properties();
    FileOutputStream fos = null;
    try {
      fos = new FileOutputStream(proppertiesFile);
      if (unableToFetchMap != null) {
        properties.setProperty("unableToFetchList", toJson(unableToFetchMap));
      }
      properties.store(fos, null);
    } catch (Exception e) {
      throw new RuntimeException(e);
    } finally {
      IOUtils.closeQuietly(fos);
    }
  }
  
  public static void main(String[] args) {
    Map<String,UnableToFetch> unableToFetchMap = new HashMap<String,UnableToFetch>();
    
    unableToFetchMap.put("id1", new UnableToFetch("id1", 1, 11111));
    String jsonStr = AppConfig.toJson(unableToFetchMap);
    System.out.println(jsonStr);
    
    unableToFetchMap = AppConfig.fromJson(jsonStr);
    jsonStr = AppConfig.toJson(unableToFetchMap);
    System.out.println(jsonStr);
  }
  
  public static class UnableToFetch {
    private String id;
    private long along;
    private int failedTimes;
    public UnableToFetch() {}
    public String toString() {
      return ToStringBuilder.reflectionToString(this);
    }
  }
}

Analyze and Fix One Java System.exit Hang Problem


My Solr application is designed to be running at user's laptop, it will fetch content from remote Solr server via proxy application. To reduce the impact to user, we limit the max memory size to 512mb: -Xmx512.
We take several approaches to reduce memory usage: for example use JSON(GSon) Streaming to read Solr document one by one from response.
Please see more details at:
Solr: Use JSON(GSon) Streaming to Reduce Memory Usage
Solr: Use STAX Parser to Read XML Response to Reduce Memory Usage
Solr: Use SAX Parser to Read XML Response to Reduce Memory Usage

But the Solr application may still throw OutOfMemoryError, when this happens, I have to kill the embedded jetty server, another application will detect the jetty server is down (by sending http request to /solr/admin/ping) and will restart it.

But I found that at some point, there are 2 embedded jetty application running: the first one hit OutOfMemoryError, and tried to kill itself, but hang, another was starting but failed with followingerror:
org.apache.solr.common.SolrException: 
Index locked for write for core collection1.
EVERE: Unable to create core: collection1
org.apache.solr.common.SolrException: Index locked for write for core collection1
 at org.apache.solr.core.SolrCore.$lt;init$gt;(SolrCore.java:806)
 at org.apache.solr.core.SolrCore.$lt;init$gt;(SolrCore.java:619)
Caused by: org.apache.lucene.store.LockObtainFailedException: Index locked for write for core collection1
 at org.apache.solr.core.SolrCore.initIndex(SolrCore.java:484)
 at org.apache.solr.core.SolrCore.$lt;init$gt;(SolrCore.java:730)
This is because the first jetty application didn't actually be killed, so it's still holding the lock to write.lock file. This problem can be fixed by fixing the first issue: why the first jetty application didn't kill itself.
Why System.exit hang?
I reproduced the problem, and get the heap dump and use IBM Java Thread and Dump Analyzer to analyze it.
Quick Conclusion
Don't call System.ext in ServletContextListener.contextDestroyed.

MyTaskThread
This happens first: when the application code detects OutOfMemoryError, it will do some clean up jobs and then call System.exit to kill itself. System.exit will call Shutdown.runHooks, which will run all ShutdownHook threads - added by Runtime.addShutdownHook(Thread hook).
Now it owns the lock of Shutdown instance and wait for jetty ShutdownThread finish.
MyTaskThread State: in Object.wait()
Monitor: Owns Monitor Lock on 0x00000000f0051870
at java.lang.Object.wait(Native Method) 
- waiting on [0x00000000f00a7000] (a org.eclipse.jetty.util.thread.ShutdownThread) 
at java.lang.Thread.join(Unknown Source) 
- locked [0x00000000f00a7000] (a org.eclipse.jetty.util.thread.ShutdownThread) 
at java.lang.Thread.join(Unknown Source) 
at java.lang.ApplicationShutdownHooks.runHooks(Unknown Source) 
at java.lang.ApplicationShutdownHooks$1.run(Unknown Source) 
at java.lang.Shutdown.runHooks(Unknown Source) 
at java.lang.Shutdown.sequence(Unknown Source) 
at java.lang.Shutdown.exit(Unknown Source) 
- locked [0x00000000f0051870] (a java.lang.Class for java.lang.Shutdown) 
at java.lang.Runtime.exit(Unknown Source) 
at java.lang.System.exit(Unknown Source) 
at MyAppUtilUtil.hardCommitLocalCache(MyAppUtilUtil.java:152) 
at MyAppUtilUtil.synchronizeP1Index(MyAppUtilUtil.java:372) 
at MyAppUtil$MyAppUtilUtilTask$MyTaskThread.doRun(MyAppUtilUtil.java:352) 
at MyAppUtil$MyAppUtilUtilTask$MyTaskThread.run(MyAppUtilUtil.java:324
Look at jetty ShutdownThread, it's a ShutdownHook added by jetty.server.Server. It calls MyServletContextListener.contextDestroyed, which will call same method MyAppUtil.shutdown to do clean up which will call System.exit.
Now the cause of the hang is obvious.
ShutdownThread tries to call Shutdown.exit, and tries to get the lock of Shutdown instance to enter synchronized (lock) block. But it can't as the lock is already owned by MyTaskThread thread, so ShutdownThread will wait for ever.

MyTaskThread thread owns the lock of Shutdown instance and wait for jetty ShutdownThread finish. It will also wait for ever. This cause the System.ext hang.
ShutdownThread
Look at jetty ShutdownThread, it's a ShutdownHook added by jetty.server.Server. It calls MyServletContextListener.contextDestroyed, which will call same method MyAppUtil.shutdown to do clean up which will call System.exit.
Now the cause of the hang is obvious.
ShutdownThread tries to call Shutdown.exit, and tries to get the lock of Shutdown instance to enter synchronized (lock) block. But it can't as the lock is already owned by MyTaskThread thread, so ShutdownThread will wait for ever.

MyTaskThread thread owns the lock of Shutdown instance and wait for jetty ShutdownThread finish. It will also wait for ever. This cause the System.ext hang.

State: Waiting on monitor
Monitor: Waiting for Monitor Lock on 0x00000000f0051870
at java.lang.Shutdown.exit(Unknown Source) 
- waiting to lock [0x00000000f0051870] (a java.lang.Class for java.lang.Shutdown) 
at java.lang.Runtime.exit(Unknown Source) 
at java.lang.System.exit(Unknown Source) 
at MyAppUtilUtil.hardCommitLocalCache(MyAppUtilUtil.java:152) 
at MyAppUtil$MyAppUtilUtilTask.shutdown(MyAppUtilUtil.java:126) 
at MyAppUtil.shutdown(MyAppUtilUtil.java:64) 
- locked [0x00000000f04cbfc0] (a MyAppUtil) 
at MyServletContextListener.contextDestroyed(MyServletContextListener.java:18) 
at org.eclipse.jetty.server.handler.ContextHandler.doStop(ContextHandler.java:813) 
at org.eclipse.jetty.servlet.ServletContextHandler.doStop(ServletContextHandler.java:158) 
at org.eclipse.jetty.webapp.WebAppContext.doStop(WebAppContext.java:504) 
at org.eclipse.jetty.util.component.AbstractLifeCycle.stop(AbstractLifeCycle.java:89) 
- locked [0x00000000f010ce40] (a java.lang.Object) 
at org.eclipse.jetty.server.handler.HandlerCollection.doStop(HandlerCollection.java:250) 
at org.eclipse.jetty.util.component.AbstractLifeCycle.stop(AbstractLifeCycle.java:89) 
- locked [0x00000000f00430c8] (a java.lang.Object) 
at org.eclipse.jetty.server.handler.HandlerWrapper.doStop(HandlerWrapper.java:107) 
at org.eclipse.jetty.server.Server.doStop(Server.java:338) 
at org.eclipse.jetty.util.component.AbstractLifeCycle.stop(AbstractLifeCycle.java:89) 
- locked [0x00000000f00404d8] (a java.lang.Object) 
at org.eclipse.jetty.util.thread.ShutdownThread.run(ShutdownThread.java:131)
To fix the problem, In MyServletContextListener.contextDestroyed, I do all nedded cleanup but don't call System.exit.

Resource

Windows BAT: Using Apache Procrun to Install Java Application As Windows Service


I have a java application which combines embedded jetty and Solr in one application, and wrap it as a windows service.

This embedded jetty and Solr application should be able to be installed at different locations, and run as a different services.

To do this: I use Apache procrun, put prunsrv.exe and prunmgr.exe in bin folder, create several windowshowAdsenses bat files to install it as a widows service, to uninstall it, start and stop the services.
installService.bat
We can install the application with specified service name, service display name, service description, we can use start_params to specify parameters to the application like port number.

The script will first use %PRUNSRV% //IS, %PRUNSRV% //US  to install it as a service, then copy prunmgr.exe to %service_name%.exe, so we can use %service_name%.exe to monitor, edit and manage the service.

installService.bat -service_name service1 -service_display_name display_name1 -service_description service_description1 -start_params "start;-port;9753" -stop_params shutdown

@echo off
@echo off
@setlocal enableextensions enabledelayedexpansion
goto install

:parseParams
set key=%~1
set value=%~2
if "%key%" == "" goto :eof
if "%key%" == "-PR_JAVA_OPTIONS" (   
 shift
 shift
 if "%value%" == "" (
        echo Empty value for -PR_JAVA_OPTIONS
        goto end
    )
 SET PR_JAVA_OPTIONS=%value%
) else if "%key%" == "-remotedebug" (  
 shift
 SET remotedebug=true
) else if "%key%" == "-action" (  
 shift
 shift
 if "%value%" == "" (
        echo Empty value for -action
        goto end
    )
 SET ACTION=%value%
) else if "%key%" == "-service_name" (  
 shift
 shift
 if "%value%" == "" (
        echo Empty value for -service_name
        goto end
    )
 SET SERVICE_JAVA=%value%
) else if "%key%" == "-service_display_name" (  
 shift
 shift
 if "%value%" == "" (
        echo Empty value for -service_display_name
        goto end
    )
 SET PR_DESPLAYNAME=%value%
) else if "%key%" == "-service_description" (  
 shift
 shift
 if "%value%" == "" (
        echo Empty value for -service_description
        goto end
    )
 SET PR_DESCRIPTION=%value%
) else if "%key%" == "-start_params" (  
 shift
 shift
 if "%value%" == "" (
        echo Empty value for -start_params
        goto end
    )
 SET START_PARAMS=%value%
) else if "%key%" == "-stop_params" (  
 shift
 shift
 if "%value%" == "" (
        echo Empty value for -stop_params
        goto end
    )
 SET STOP_PARAMS=%value%
) else if "%key%" == "-pr_jvm" (  
  shift
 shift
 if "%value%" == "" (
        echo Empty value for -pr_jvm
        goto end
    )
 SET PR_JVM=%value%
) else if "%key%" == "-uninstallIfExsit" (  
 shift
 SET UNINSTALL_IF_EXSIT=true
) else (
 shift
)
goto parseParams %*
goto :eof

:install
set SERVICE_JAVA=MyApp
set PR_DESPLAYNAME=MyApp
set PR_DESCRIPTION="MyApp Service"
set START_PARAMS=start
set STOP_PARAMS=shutdown
set PR_JVM=auto
SET PR_JAVA_OPTIONS="-Xms512m;"
SET CMD_OPTS=%*
set APP_RUNNING_HOME=
set "APP_HOME=%~dp0/../"
set "PATH_PRUNSRV=%~dp0"
set "PR_LOGPATH=%APP_HOME%/logs"
set UNINSTALL_IF_EXSIT=false
SET MYCLASSPATH=
rem set PR_INSTALL=%PATH_PRUNSRV%prunsrv.exe

call :parseParams %*
set PRUNSRV=%PATH_PRUNSRV%%SERVICE_JAVA%.exe
if "%PR_DESPLAYNAME%" == "" (
 set PR_DESPLAYNAME=%SERVICE_JAVA%
)

REM check whether service already exists
echo Installing %SERVICE_JAVA%
SC QUERY %SERVICE_JAVA% > NUL
REM if ERRORLEVEL 1060 means it doesn't exists
IF not ERRORLEVEL 1060 (
 if "%UNINSTALL_IF_EXSIT%" == "true" (
  "%PRUNSRV%" //DS//%SERVICE_JAVA%
 ) else  (
  echo %SERVICE_JAVA% already exists, and uninstallIfExsit is false. Do nothing
  goto end
 )
)

"%PRUNSRV%" //IS//%SERVICE_JAVA% --Install="%PRUNSRV%"

if not errorlevel 1 goto installed
echo Failed to install '%SERVICE_JAVA%' service
goto end
:installed
echo The service '%SERVICE_JAVA%' has been installed.
set libDir=%APP_HOME%\lib
set MYCLASSPATH="%libDir%\*;%libDir%\ext\*;%libDir%\shared-libs\*;%APP_HOME%\etc"
if "%remotedebug%" == "true" (
 SET PR_JAVA_OPTIONS="%PR_JAVA_OPTIONS%;-agentlib:jdwp=transport=dt_socket,address=9999,server=y,suspend=n"
)

echo Setting the parameters for %SERVICE_JAVA%
echo "%PRUNSRV%" //US//%SERVICE_JAVA% --DisplayName "%PR_DESPLAYNAME%" --Description "%PR_DESCRIPTION%" --StdOutput auto --StdError auto ^
--Classpath=%MYCLASSPATH% --Jvm="%PR_JVM%" --JvmOptions="%PR_JAVA_OPTIONS%" --Startup=auto ^
--StartMode=jvm --StartClass=MainClass --StartParams="%START_PARAMS%" ^
--StopMode=jvm  --StopClass=MainClass  --StopParams="%STOP_PARAMS%"

"%PRUNSRV%" //US//%SERVICE_JAVA% --DisplayName "%PR_DESPLAYNAME%" --Description "%PR_DESCRIPTION%" --StdOutput auto --StdError auto ^
--Classpath=%MYCLASSPATH% --Jvm="%PR_JVM%" --JvmOptions="%PR_JAVA_OPTIONS%" --StartPath %APP_HOME% --Startup=auto ^
--StartMode=jvm --StartClass=MainClass --StartParams="%START_PARAMS%" ^
--StopMode=jvm  --StopClass=MainClass  --StopParams="%STOP_PARAMS%"

if not errorlevel 1 goto updated
echo Failed updating '%SERVICE_JAVA%' service
goto end
:updated

If NOT exist %SERVICE_JAVA%w.exe (
 copy /B prunmgr.exe %SERVICE_JAVA%w.exe
)
echo The service '%SERVICE_JAVA%' has been updated.
echo Installation of %SERVICE_JAVA% is complete
goto end

:end
endlocal 
@echo on
uninstallService.bat
To uninstall the service, we just need specify service name:
uninstallService.bat -service_name service1
It will use "%PRUNSRV%" //DS to uninstall the service.
@echo off
setlocal
goto uninstall

:parseParams
set key=%~1
set value=%~2
if "%key%" == "" goto :eof
if "%key%" == "-service_name" (  
  shift
 shift
 if "%value%" == "" (
        echo Empty value for -service_name
        goto end
    )
 SET SERVICE_JAVA=%value%
) else if "%key%" == "-delete_exe" (  
 shift
 SET DELETE_EXE=true
) else (
 shift
)
goto parseParams %*
goto :eof

:uninstall
set MYPATH=%~dp0
set PATH_PRUNSRV=%MYPATH%
set "PR_LOGPATH=%MYPATH%/../logs"
set SERVICE_JAVA=MyApp
set DELETE_EXE=false

call :parseParams %*
set PRUNSRV=%PATH_PRUNSRV%%SERVICE_JAVA%.exe
echo Removing %SERVICE_JAVA%

cmd /c stopService.bat -service_name %SERVICE_JAVA%
"%PRUNSRV%" //DS//%SERVICE_JAVA%

if "%DELETE_EXE%" == "true" (
  del /Q %SERVICE_JAVA%.exe
 echo %SERVICE_JAVA%.exe deleted
)
if not errorlevel 1 goto removed
echo.
echo Failed uninstalling '%SERVICE_JAVA%' service
goto :eof
:removed
echo The service '%SERVICE_JAVA%' has been removed

endlocal
@echo on
startService.bat/stopService.bat
It's very easy to implement: just get service name, then use %PRUNSRV% //ES to start the service, use %PRUNSRV% //SS to stop the service.
startService.bat/stopService.bat -service_name service1
startService.bat
@echo off
setlocal

goto run
:parseParams
set key=%~1
set value=%~2
echo %key% %value%
if "%key%" == "" goto :eof
if "%key%" == "-service_name" (  
  shift
 shift
 if "%value%" == "" (
        echo Empty value for -service_name
        goto end
    )
 SET SERVICE_JAVA=%value%
) else if "%key%" == "-install_if_not_exist" (  
  shift
 SET INSTALL_IF_NOT_EXIST=true
) else if "%key%" == "-service_description" (  
  shift
 shift
 if "%value%" == "" (
        echo Empty value for -service_description
        goto end
    )
 SET service_description=%value%
) else if "%key%" == "-service_display_name" (  
  shift
 shift
 if "%value%" == "" (
        echo Empty value for -service_display_name
        goto end
    )
 SET service_display_name=%value%
) else if "%key%" == "-start_params" (  
  shift
 shift
 if "%value%" == "" (
        echo Empty value for -start_params
        goto end
    )
 SET start_params=%value%
) else (
 shift
)
goto parseParams %*
goto :eof

:run
set "PATH_PRUNSRV=%~dp0"
set SERVICE_JAVA=MyApp
set INSTALL_IF_NOT_EXIST=true
set service_display_name=MyApp
set service_description="MyApp Service"
set start_params=""
call :parseParams %*

set PRUNSRV=%PATH_PRUNSRV%%SERVICE_JAVA%.exe
REM if INSTALL_IF_NOT_EXIST is true, check whether the service exists, if false, install the service if needed.
SC QUERY %SERVICE_JAVA% > NUL 2>&1
REM if ERRORLEVEL 1060 means it doesn't exists
IF ERRORLEVEL 1060 (
  echo %SERVICE_JAVA% doesn't exists
 if "%INSTALL_IF_NOT_EXIST%" == "true" (
   echo install_if_not_exist is true, install the service %SERVICE_JAVA%.
  cmd /c installEmbededJettyService.bat -service_name %SERVICE_JAVA% -service_display_name "%service_display_name%" -service_description "MyApp Service" -start_params "%start_params%"
  echo service %SERVICE_JAVA% is installed.
 ) else (
  echo install_if_not_exist is false, exit with error.
  exit -1
 )
)

%PRUNSRV% //ES//%SERVICE_JAVA%
if %ERRORLEVEL% == 0 (
 echo %SERVICE_JAVA% is started.
) else (
 echo Failed starting '%SERVICE_JAVA%' service
)

:end
endlocal 
@echo on
StopService.bat
@echo off
setlocal

goto run
:parseParams
set key=%~1
set value=%~2
echo %key% %value%
if "%key%" == "" goto :eof
if "%key%" == "-service_name" (  
    shift
 shift
 if "%value%" == "" (
        echo Empty value for -service_name
        goto end
    )
 SET SERVICE_JAVA=%value%
) else (
 shift
)
goto parseParams %*
goto :eof

:run

set PATH_PRUNSRV=%~dp0
set SERVICE_JAVA=MyApp
call :parseParams %*

set PRUNSRV=%PATH_PRUNSRV%%SERVICE_JAVA%.exe
"%PRUNSRV%"  //SS//%SERVICE_JAVA%
rem force kill the service as a safety bet
Taskkill /F /FI "SERVICES eq %SERVICE_JAVA%"
rem recheck service exists
Tasklist /FI "SERVICES eq %SERVICE_JAVA%" 2>NUL | find /I /N "%SERVICE_JAVA%">NUL 2>&1
if %ERRORLEVEL% == 0 (
 echo Failed stopping '%SERVICE_JAVA%' service
) else (
  echo %SERVICE_JAVA% is stopped.
)
:end
endlocal 
@echo on
Resource
http://commons.apache.org/proper/commons-daemon/procrun.html
Commons Daemon Procrun as a Java Service Wrapper for ActiveMQ

Labels

ANT (6) Algorithm (69) Algorithm Series (35) Android (7) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) JSON (7) Java (186) JavaScript (27) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) adsense (5) bat (8) regex (5) xml (5)