Pages

Showing posts with label file. Show all posts
Showing posts with label file. Show all posts

Friday, 26 July 2013

Java Multi-Threaded Recursive File & Folder Crawler

This is a multi-threaded java program that takes a filepath and recursively goes through each folder and displays the contents of each 

package FileName;
import java.util.*;
import java.io.*;
 
public class fileCrawler {
 
  private WorkQueue workQ;
  static int i = 0;
 
 private class Worker implements Runnable {
 
  private WorkQueue queue;
 
  public Worker(WorkQueue q) {
   queue = q;
  }
 
//  since main thread has placed all directories into the workQ, we
//  know that all of them are legal directories; therefore, do not need
//  to try ... catch in the while loop below
 
  public void run() {
   String name;
   while ((name = queue.remove()) != null) {
    File file = new File(name);
    String entries[] = file.list();
    if (entries == null)
     continue;
    for (String entry : entries) {
     if (entry.compareTo(".") == 0)
      continue;
     if (entry.compareTo("..") == 0)
      continue;
     String fn = name + "\\" + entry;
     System.out.println(fn);
    }
   }
  }
 }
 
 public fileCrawler() {
  workQ = new WorkQueue();
 }
 
 public Worker createWorker() {
  return new Worker(workQ);
 }
 
 
// need try ... catch below in case the directory is not legal
 
 public void processDirectory(String dir) {
   try{
   File file = new File(dir);
   if (file.isDirectory()) {
    String entries[] = file.list();
    if (entries != null)
     workQ.add(dir);
 
    for (String entry : entries) {
     String subdir;
     if (entry.compareTo(".") == 0)
      continue;
     if (entry.compareTo("..") == 0)
      continue;
     if (dir.endsWith("\\"))
      subdir = dir+entry;
     else
      subdir = dir+"\\"+entry;
     processDirectory(subdir);
    }
   }}catch(Exception e){}
 }
 
 public static void main(String Args[]) {
 
  fileCrawler fc = new fileCrawler();
 
//  now start all of the worker threads
 
  int N = 5;
  ArrayList<Thread> thread = new ArrayList<Thread>(N);
  for (int i = 0; i < N; i++) {
   Thread t = new Thread(fc.createWorker());
   thread.add(t);
   t.start();
  }
 
//  now place each directory into the workQ
 
  fc.processDirectory(Args[0]);
 
//  indicate that there are no more directories to add
 
  fc.workQ.finish();
 
  for (int i = 0; i < N; i++){
   try {
    thread.get(i).join();
   } catch (Exception e) {};
  }
 }
}



package FileName;
import java.util.*;
 
public class WorkQueue {
 
//
// since we are providing the concurrency control, can use non-thread-safe
// linked list
//
  private LinkedList<String> workQ;
 private boolean done;  // no more directories to be added
 private int size;  // number of directories in the queue
 
 public WorkQueue() {
  workQ = new LinkedList<String>();
  done = false;
  size = 0;
 }
 
 public synchronized void add(String s) {
  workQ.add(s);
  size++;
  notifyAll();
 }
 
 public synchronized String remove() {
  String s;
  while (!done && size == 0) {
   try {
    wait();
   } catch (Exception e) {};
  }
  if (size > 0) {
   s = workQ.remove();
   size--;
   notifyAll();
  } else
   s = null;
  return s;
 }
 
 public synchronized void finish() {
  done = true;
  notifyAll();
 }
}

Monday, 22 July 2013

Syntax Highlighting on Blogger


  1. In the design menu hit Template
  2. Under Live on Blog  heading hit Edit HTML
  3. Find the </head> tag and insert the following above it

    <!-- Syntax Highlighter Additions START -->
    <link href="http://alexgorbatchev.com/pub/sh/current/styles/shCore.css" rel="stylesheet" type="text/css" />
    <link href="http://alexgorbatchev.com/pub/sh/current/styles/shThemeEmacs.css" rel="stylesheet" type="text/css" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushAS3.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushBash.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushColdFusion.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCSharp.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCss.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushDelphi.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushDiff.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushErlang.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushGroovy.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJavaFX.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPerl.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPhp.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPlain.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPowerShell.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPython.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushRuby.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushScala.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushVb.js" type="text/javascript" />
    <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js" type="text/javascript" />
    <script language="javascript" type="text/javascript">
    SyntaxHighlighter.config.bloggerMode = true;
    SyntaxHighlighter.all();
    </script>
    <!-- Syntax Highlighter Additions END -->
  4. Delete any extensions you do not wish to use as it may affect performance
  5. Click Save Template and click Close
  6. When writing your new post hit HTML in the top left corner
  7. When you wish to insert some code insert it after a <span...> tag in this manner:
    <pre class = "brush:[enter language e.g (Java)];>
            [Enter code here]
    </pre>
  8. Publish your post and voila


Installation Guide To Set Up Nutch To Crawl A Filesystem Or Intranet (Windows)

Preparation

At this point you should have Solr and Tika set-up as well as having Nutch ready to crawl the web. The guides can be found here:    http://amac4.blogspot.co.uk/2013/07/setting-up-solr-with-apache-tomcat-be.html         http://amac4.blogspot.co.uk/2013/07/setting-up-tika-extracting-request.html       http://amac4.blogspot.co.uk/2013/07/configuring-nutch-to-crawl-urls.html     
The required changes that need to be done to make Nutch crawl a file-system require that Nutch is set-up to crawl the web so please ensure you have read the post.

URLs/nutch.txt Format

This is where you specify where you would like to crawl, so add your locations with a new line after each one. If you wish to crawl a fileshare then it must be in a similar format to :
file:////189.189.1.42/test

Or if you wish to crawl the local filesystem it must be in this format:
file:/C:/Users/alamil/test/

Required Changes

Change 1 (regex-urlfilter.txt)

The default setting for Nutch is to skip anything that begins with "file" so our first change is to get Nutch to parse files. Nutch is currently set-up to parse anything that it finds via http so we need to change this line:
# skip file: ftp: and mailto: urls
-^(file|ftp|mailto):
to say
# skip http: ftp: and mailto: urls
-^(http|ftp|mailto):

Change 2 (regex-urlfilter.txt)

This change is not necessary but may make your life easier.  Any file types you do not want to index need to be added to the list otherwise Nutch will often try to parse them and fail in doing so as it doesnt know how to deal with a lot of binary file types.:
# skip image and other suffixes we can't yet parse
# for a more extensive coverage use the urlfilter-suffix plugin

-\.(gif|GIF|jpg|JPG|png|PNG|ico|ICO|css|CSS|sit|SIT|eps|EPS
|wmf|WMF|zip|ZIP|ppt|PPT|mpg|MPG|gz|GZ|rpm|RPM|tgz|TGZ|mov
|MOV|exe|EXE|jpeg|JPEG|bmp|BMP|js|JS|asp|ASP|xxx|XXX|yyy|YYY
|cs|CS|dll|DLL|refresh|REFRESH)$

Change 3 (regex-urlfilter.txt)

Our final change to Nutch is to filter out unwanted files from being parsed.  Often you will only want the subdirectories and files of the initial directory you supplied to be indexed. For example, if I supply Nutch with the file:////189.189.1.42/test In the nutch.txt file then I only want the files within any of its subdirectories to be indexed so I would filter by:
# accept anything else
+^file:////189.189.1.42/test

Change 4 (nutch-site.xml)

To allow Nutch to recognise that it is dealing with files it needs a plugin to be activated. So adding the protocol-file plugin to the list of plugins that are used allows Nutch to know how to deal with files:
<property>
<name>plugin.includes</name>
<value>protocol-file|protocol-httpclient|urlfilter-regex|parse-(html|tika)|index-(basic|anchor)|
  scoring-opic|urlnormalizer-(pass|regex|basic)|index-more</value>
  <description>Regular expression naming plugin directory names to 
    include.  Any plugin not matching this expression is excluded. 
    In any case you need at least include the nutch-extensionpoints plugin.
  </description>
</property>

Change 5 (nutch-site.xml)

We encountered the problem of file size earlier when doing the web crawler, if you set a limit on the content size it can cause the read to fail and the same applies here, so not matter how big the file is we want it to be parsed.
<property>
 <name>file.content.limit</name>
 <value>-1</value>
 <description> Needed to stop buffer overflow errors - Unable to read.....</description>
</property>

Change 6 (regex-normalise.xml)

We do not want duplicate slashes to be replaced by single slashes other the filenames we specify will not be valid. Therefore we need to comment out the code that does the replacement:
<!-- removes duplicate slashes 
<regex>
  <pattern>(?&lt;!:)/{2,}</pattern>
  <substitution>/</substitution>
</regex>
-->

Running the Crawl

Ensure you add the location you wish to crawl to the nutch.txt file 

To run the crawl, like before, you issue the command:
./nutch crawl urls -dir [dir_name] -solr http://localhost:8080/solr/ -depth [depth] -topN [topN]
Be sure to set a depth and a topN number of files to index otherwise nutch will use its default setting of depth 3 which will mean that you may have a lot of files that are untouched.

Next Steps

An issue I have noticed that occurs is with files that contain an apostrophe in the filepath.  Nutch was designed to run on Unix, which is why in this tutorial you are required to download cygwin, but this also has its complications.  Unix by default does not allow any filepaths to contain an apostrophe, but Windows filepaths do.  This means that when Nutch comes across an apostrophe, it thinks that is the end of the file.  I have written a Java program that will solve the problem and it can be found here:

http://amac4.blogspot.co.uk/2013/07/nutch-apostrophesingle-quotes-issue_23.html 

You should now have everything set-up to work now and the next step is to integrate your crawler and search server into your web application.  I have written a C# Web Service that makes calls to the Solr server and returns the xml response, have a look, copy and tweak it to your own liking to create your own search engine:

http://amac4.blogspot.co.uk/2013/07/web-service-to-query-solr-rest.html



Installation Guide To Set Up Solr 4.3 With Apache Tomcat (Windows & Cygwin)

Installation Guide to Set Up Solr 4 With Apache Tomcat On Windows

This is a short guide on how to set up Apache Solr on Windows 7 running on Apache Tomcat. Be aware that Solr-4.3.0 and Apache-tomcat-7.0.40. Older versions of Solr use different folder structure and therefore this guide will not adequately cover its requirements.

Preparation

First of all we need an Apache Tomcat servlet container. It can be found at the Apache Tomcat website:Apache Website Any version beyond 7.0.0 is considered stable with sufficient support and documentation available. Please Download Tomcat & Solr in preparation to starting this guide. You will also require the Java Runtime Environment to be downloaded and set up. Its location will be referred to as $JAVA.

  • Solr 4.3.0
  • Tomcat 7 or Tomcat 8
  • Cygwin
  • JRE 7

Set-up

  • Firstly, choose the location you wish to install Tomcat and copy the files from your downloads to your chosen directory. This will be referred to as $TOMCAT_HOME. Do the same for your Solr download, copy the files to your chosen location and this will be referred to as which will be referred to as $SOLR.
  • Edit the server.xml file in $TOMCAT_HOME/conf to look like the following code snippet:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UTF-8" />
  • Now copy the [$SOLR]/example/solr directory somewhere else and rename it solr_home. This will be your main Solr installation to run your Solr server and will be referred to as $SOLR_HOME.
  • The next thing is setting up the Solr deployment. To do that we need the apache-solr-4.0.0.war (found in $SOLR/example/webapps) file that contains the necessary files and libraries to run Solr to be copied to the $TOMCAT_HOME/webapps directory and renamed solr.war.
  • Create a proper context file by creating a solr.xml file in the $TOMCAT_HOME/conf/Catalina/localhost directory. If the Catalina/localhost/ directory does not exist then you will need to make it yourself. The contents of the file should look like the following code:
<Context docBase="/solr.war"debug="0" crossContext="true">
<Environment name="solr/home" type="java.lang.String" value="$SOLR_HOME" override="true"/>
</Context>
  • Modify solr_home/collection1/conf/solrconfig.xml to set the absolute directory:
<lib dir="$SOLR/contrib/extraction/lib" regex=".*\.jar" />
  • Also set the data directory like:
<dataDir>${solr.data.dir:$SOLR_HOME/data}</dataDir>
  • Now we can start the servlet container. Navigate to the $TOMCAT_HOME/bin and double click: startup.bat. Using command prompt:
cd $TOMCAT_HOME/bin
startup.bat run
  • Copy the jar files from $SOLR\example\lib\ext into the $TOMCAT_HOME/lib folder and also copy the $SOLR/example/solr/example/resources/log4j.properties into the same location.
  • Runtimes may need to be set in the startup.bat file. Add set JAVA_HOME=$JAVA or equivalent location to the second line of the file catalina.bat if it fails to run.
  • Your Solr server is now running and to ensure that Solr is running properly, you can open a browser and navigate to:http://localhost:8080/solr/. The Solr administration screen should appear and there are a variety of options to choose from. 

Next Steps

The next step is to ensure that Tika's extracting request handler is configured correctly so that it can deal with pdf, doc, xls etc files:
http://amac4.blogspot.co.uk/2013/07/setting-up-tika-extracting-request.html

You will also want to set-up de-duplication and potentially Solr's Highlighting functionality:http://amac4.blogspot.co.uk/2013/08/setting-up-highlighting-for-solr-4.htmlhttp://amac4.blogspot.co.uk/2013/08/solr-deduplication.html

Tomcat Options

When running Tomcat you have various options which are availible to you here:

  • stop: This stops Apache Tomcat
  • restart: This restarts Apache Tomcat
  • debug: This start Apache Tomcat in debug mode
  • run: This runs Apache Tomcat in the current window, so you can see the output on the console from which you run Tomcat.