Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Thiti V. Sintopchai http://thitiv.blogspot.com

« Newer Snippets
Older Snippets »
Showing 1-10 of 21 total  RSS 

Jena: Listing all Classes and Instances in a Jena Ontology Model

// Listing all classes and instances in a Jena ontology model

    OntModel model = ModelFactory.createOntologyModel();
    model.read(ONT_URL);
    
    ExtendedIterator classes = model.listClasses();

    while (classes.hasNext())
    {
      OntClass thisClass = (OntClass) classes.next();
      _logger.info("Found class: " + thisClass.toString());

      ExtendedIterator instances = thisClass.listInstances();

      while (instances.hasNext())
      {
        Individual thisInstance = (Individual) instances.next();
        _logger.info("  Found instance: " + thisInstance.toString());
      }
    }

Java: RegEx: Splitting a space-, comma-, and semi-colon separated list

// Greedy RegEx quantifier used
// X+ = X, one or more times
// [\\s,;]+ = one or more times of either \s , or ;

    String test_data = "hello world, this is a test, ;again";
    _logger.debug("Source: " + test_data);
    
    for (String tag : test_data.split("[\\s,;]+"))
    {
      _logger.debug("Received tag: [" + tag + "]");
    }

C#: Inserting New Line in Multiline Textbox

// Ref: http://www.geekpedia.com/Question19_How-can-I-insert-a-new-line-in-a-TextBox.html
// Make sure MultiLine property is true and use "\r\n"

  TextBox1.Text = "First line\r\nSecond line";

Java: Getting the Name of a Class Object

// Ref: http://www.exampledepot.com/egs/java.lang/GetClassName.html

    // Get the fully-qualified name of a class
    Class cls = java.lang.String.class;
    String name = cls.getName();        // java.lang.String
    
    // Get the fully-qualified name of a inner class
    cls = java.util.Map.Entry.class;
    name = cls.getName();               // java.util.Map$Entry
    
    // Get the unqualified name of a class
    cls = java.util.Map.Entry.class;
    name = cls.getName();
    if (name.lastIndexOf('.') > 0) {
        name = name.substring(name.lastIndexOf('.')+1);  // Map$Entry
    }
    // The $ can be converted to a .
    name = name.replace('$', '.');      // Map.Entry
    
    
    // Get the name of a primitive type
    name = int.class.getName();         // int
    
    // Get the name of an array
    name = boolean[].class.getName();   // [Z
    name = byte[].class.getName();      // [B
    name = char[].class.getName();      // [C
    name = short[].class.getName();     // [S
    name = int[].class.getName();       // [I
    name = long[].class.getName();      // [J
    name = float[].class.getName();     // [F
    name = double[].class.getName();    // [D
    name = String[].class.getName();    // [Ljava.lang.String;
    name = int[][].class.getName();     // [[I
    
    // Get the name of void
    cls = Void.TYPE;
    name = cls.getName();               // void

Java: File System: Getting the path of TMP directory from Environmental Variable

public static String INDEX_FILE_LOCATION = System.getenv("TMP") + File.separator + "dl-index.tmp";

Java: Listing the Files or Subdirectories in a Directory

// Ref: Java Developers Almanac
// http://www.exampledepot.com/egs/java.io/GetFiles.html


    //
    // Example 1
    //

    File dir = new File("directoryName");
    
    String[] children = dir.list();
    if (children == null) {
        // Either dir does not exist or is not a directory
    } else {
        for (int i=0; i<children.length; i++) {
            // Get filename of file or directory
            String filename = children[i];
        }
    }

    //
    // Example 2
    //
    
    // It is also possible to filter the list of returned files.
    // This example does not return any files that start with '.'
    FilenameFilter filter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return !name.startsWith(".");
        }
    };
    children = dir.list(filter);
    
    //
    // Example 3
    //

    
    // The list of files can also be retrieved as File objects
    File[] files = dir.listFiles();

    //
    // Example 4
    //
    
    // This filter only returns directories
    FileFilter fileFilter = new FileFilter() {
        public boolean accept(File file) {
            return file.isDirectory();
        }
    };
    files = dir.listFiles(fileFilter);

Java: Lucene: Simple Indexing and Searching Example (from javadoc)

public void simpleLucene()
{
    Analyzer analyzer = new StandardAnalyzer();

    // Store the index in memory:
    Directory directory = new RAMDirectory();

    // To store an index on disk, use this instead (note that the 
    // parameter true will overwrite the index in that directory
    // if one exists):
    // Directory directory = FSDirectory.getDirectory("/tmp/testindex", true);

    IndexWriter iwriter = new IndexWriter(directory, analyzer, true);
    iwriter.setMaxFieldLength(25000);

    Document doc = new Document();
    String text = "This is the text to be indexed.";
    doc.add(new Field("fieldname", text, Field.Store.YES,
        Field.Index.TOKENIZED));
    iwriter.addDocument(doc);
    iwriter.close();
    
    // Now search the index:
    IndexSearcher isearcher = new IndexSearcher(directory);

    // Parse a simple query that searches for "text":
    QueryParser parser = new QueryParser("fieldname", analyzer);
    Query query = parser.parse("text");
    Hits hits = isearcher.search(query);
    assertEquals(1, hits.length());

    // Iterate through the results:
    for (int i = 0; i < hits.length(); i++)
    {
      Document hitDoc = hits.doc(i);
      assertEquals("This is the text to be indexed.", hitDoc.get("fieldname"));
    }

    isearcher.close();
    directory.close();
}

Java: Lucene: Simple In-Memory Search Example

// Adapted from http://javatechniques.com/blog/lucene-in-memory-text-search-example
// Works with present APIs in Lucene 2.1.0

/**
 * A simple example of an in-memory search using Lucene.
 */
import java.io.IOException;
import java.io.StringReader;

import org.apache.lucene.search.Hits;
import org.apache.lucene.search.Query;
import org.apache.lucene.document.Field;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.document.Document;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;

public class InMemoryExample
{

  public static void main(String[] args)
  {
    // Construct a RAMDirectory to hold the in-memory representation
    // of the index.
    RAMDirectory idx = new RAMDirectory();

    try
    {
      // Make an writer to create the index
      IndexWriter writer = new IndexWriter(idx, new StandardAnalyzer(), true);

      // Add some Document objects containing quotes
      writer.addDocument(createDocument("Theodore Roosevelt",
          "It behooves every man to remember that the work of the "
              + "critic, is of altogether secondary importance, and that, "
              + "in the end, progress is accomplished by the man who does "
              + "things."));
      writer.addDocument(createDocument("Friedrich Hayek",
          "The case for individual freedom rests largely on the "
              + "recognition of the inevitable and universal ignorance "
              + "of all of us concerning a great many of the factors on "
              + "which the achievements of our ends and welfare depend."));
      writer.addDocument(createDocument("Ayn Rand",
          "There is nothing to take a man’s freedom away from "
              + "him, save other men. To be free, a man must be free "
              + "of his brothers."));
      writer.addDocument(createDocument("Mohandas Gandhi",
          "Freedom is not worth having if it does not connote "
              + "freedom to err."));

      // Optimize and close the writer to finish building the index
      writer.optimize();
      writer.close();

      // Build an IndexSearcher using the in-memory index
      Searcher searcher = new IndexSearcher(idx);

      // Run some queries
      search(searcher, "freedom");
      search(searcher, "free");
      search(searcher, "progress or achievements");

      searcher.close();
    }
    catch (IOException ioe)
    {
      // In this example we aren’t really doing an I/O, so this
      // exception should never actually be thrown.
      ioe.printStackTrace();
    }
    catch (ParseException pe)
    {
      pe.printStackTrace();
    }
  }

  /**
   * Make a Document object with an un-indexed title field and an indexed
   * content field.
   */
  private static Document createDocument(String title, String content)
  {
    Document doc = new Document();

    // Add the title as an unindexed field…
    doc.add(new Field("title", title, Field.Store.YES, Field.Index.NO));

    //and the content as an indexed field. Note that indexed
    // Text fields are constructed using a Reader. Lucene can read
    // and index very large chunks of text, without storing the
    // entire content verbatim in the index. In this example we
    // can just wrap the content string in a StringReader.
    doc.add(new Field("content", new StringReader(content)));

    return doc;
  }

  /**
   * Searches for the given string in the "content" field
   */
  private static void search(Searcher searcher, String queryString)
      throws ParseException, IOException
  {

    // Build a Query object
    QueryParser parser = new QueryParser("content", new StandardAnalyzer());
    Query query = parser.parse(queryString);

    // Search for the query
    Hits hits = searcher.search(query);

    // Examine the Hits object to see if there were any matches
    int hitCount = hits.length();
    if (hitCount == 0)
    {
      System.out.println("No matches were found for \"" + queryString + "\"");
    }
    else
    {
      System.out.println("Hits for \"" + queryString
          + "\" were found in quotes by:");

      // Iterate over the Documents in the Hits object
      for (int i = 0; i < hitCount; i++)
      {
        Document doc = hits.doc(i);

        // Print the value that we stored in the "title" field. Note
        // that this Field was not indexed, but (unlike the
        // "contents" field) was stored verbatim and can be
        // retrieved.
        System.out.println(" " + (i + 1) + ". " + doc.get("title"));
      }
    }
    System.out.println();
  }
}

Java: RegEx to Remove HTML Tags

// Ref: https://jalbum.net/forum/thread.jspa?forumID=7&threadID=971&messageID=6907

String noHTMLString = htmlString.replaceAll("\\<.*?\\>", "");

Java: log4j Initialization Example

// Initialization for Basic Console Output
// Ref: http://logging.apache.org/log4j/docs/manual.html

 import com.foo.Bar;

 // Import log4j classes.
 import org.apache.log4j.Logger;
 import org.apache.log4j.BasicConfigurator;

 public class MyApp {

   // Define a static logger variable so that it references the
   // Logger instance named "MyApp".
   static Logger logger = Logger.getLogger(MyApp.class);

   public static void main(String[] args) {

     // Set up a simple configuration that logs on the console.
     BasicConfigurator.configure();

     logger.setLevel(Level.DEBUG); // optional if log4j.properties file not used
     // Possible levels: TRACE, DEBUG, INFO, WARN, ERROR, and FATAL

     logger.info("Entering application.");
     Bar bar = new Bar();
     bar.doIt();
     logger.info("Exiting application.");
   }
 }
« Newer Snippets
Older Snippets »
Showing 1-10 of 21 total  RSS