how to export Hbase data to elastic search using nutch? - nutch
i have followed https://gist.github.com/xrstf/b48a970098a8e76943b9 to integrate nutch and elastic-search. everything is working fine data is stored in Hbase 'webpage' table but i am not able to fetch data in elastic search.i want to know how to fetch data in elastic search.
below is my code
package com.process;
/*
import package will be here
*/
public class HbaseToElastic extends Configured implements
org.apache.hadoop.util.Tool {
static class Mapper extends TableMapper<Text, IndexWritable> {
public static String CLUSTER;
public static String SEARCH_HOST;
public static String SEARCH_PORT;
public static String SEARCH_INDEX_NAME;
public static String SEARCHtYPE;
public static int BULKSIZE;
public static String TABLENAME;
public static String FAMILY;
private static List<String> SPORTS_KEYWORDS;
private static List<String> BUSINESS_KEYWORDS;
private static List<String> GOSSIP_KEYWORDS;
private static List<String> CRIME_KEYWORDS;
private static Map<String, Map<String, String>> STATE_MAP = new HashMap<String, Map<String, String>>();
private static Map<String, String> CITY_MAP = new HashMap<String, String>();
private static Mapper mapper = new Mapper();
static {
try {
System.out.println("done1");
DetectorFactory.loadProfile("./profiles");
System.out.println("done2");
} catch (final LangDetectException e) {
System.out.println("done3");
e.printStackTrace();
}
}
Configuration hbaseConf = null;
HTable table = null;
List<Put> hbasePutErrorList = new ArrayList<Put>();
/**
* Clean up the hbase table object
*/
#Override
protected void cleanup(final Context context) throws IOException,
InterruptedException {
super.cleanup(context);
table.put(hbasePutErrorList);
table.close();
hbasePutErrorList.clear();
}
/**
* Initialize various variables
*/
#Override
protected void setup(
final org.apache.hadoop.mapreduce.Mapper<ImmutableBytesWritable, Result, Text, IndexWritable>.Context context)
throws IOException, InterruptedException {
final Configuration conf = context.getConfiguration();
CLUSTER = conf.get("cluster");
SEARCH_HOST = conf.get("search_host");
SEARCH_PORT = conf.get("search_port");
SEARCH_INDEX_NAME = conf.get("search_index_name");
SEARCHtYPE = conf.get("search_type");
BULKSIZE = conf.getInt("search_bulk_size", 500);
TABLENAME = conf.get("table_name");
FAMILY = conf.get("family");
hbaseConf = HBaseConfiguration.create();
hbaseConf.set("hbase.zookeeper.quorum",
conf.get("hbase.zookeeper.quorum"));
hbaseConf.set("hbase.zookeeper.property.clientPort",
conf.get("hbase.zookeeper.property.clientPort"));
hbaseConf.set("hbase.rpc.timeout", conf.get("hbase.rpc.timeout"));
hbaseConf.set("hbase.regionserver.lease.period",
conf.get("hbase.regionserver.lease.period"));
hbaseConf.set("hbase.master", conf.get("hbase.master"));
table = new HTable(hbaseConf, conf.get("table_name"));
SPORTS_KEYWORDS = new ArrayList<String>();
BUSINESS_KEYWORDS = new ArrayList<String>();
GOSSIP_KEYWORDS = new ArrayList<String>();
CRIME_KEYWORDS = new ArrayList<String>();
String keywrods = conf.get("sportskeywords");
String[] keyarr = keywrods.split(",");
for (final String key : keyarr) {
SPORTS_KEYWORDS.add(key.trim());
}
keywrods = conf.get("businesskeywords");
keyarr = keywrods.split(",");
for (final String key : keyarr) {
BUSINESS_KEYWORDS.add(key.trim());
}
keywrods = conf.get("gossipkeywords");
keyarr = keywrods.split(",");
for (final String key : keyarr) {
GOSSIP_KEYWORDS.add(key.trim());
}
keywrods = conf.get("crimekeywords");
keyarr = keywrods.split(",");
for (final String key : keyarr) {
CRIME_KEYWORDS.add(key.trim());
}
final String stateMap = conf.get("statemap");
final Gson g = new Gson();
STATE_MAP = g.fromJson(stateMap, Map.class);
}
/**
* map function
*/
#Override
public void map(final ImmutableBytesWritable row, final Result result,
final Context context) throws IOException, InterruptedException {
try {
final byte b = 0;
int deleteFlag = 0;
final String keyString = Bytes.toString(row.get());
final Map<String, Object> mapobject = new HashMap<String, Object>();
for (final KeyValue kv : result.raw()) {
final String key = (new String(kv.getQualifier()));
final String value = (new String(kv.getValue()));
mapobject.put(key, value);
}
final Gson g = new Gson();
if (checkValidType(mapobject)) {
refineMetaTags(mapobject);
if (refineDescription(mapobject)) {
assignCity(mapobject);
if (checkTitleImage(mapobject)) {
if (setLang(mapobject)) {
setCorrectCategory(mapobject);
correctDuplicateTitle(mapobject);
final String json = g.toJson(mapobject);
context.write(new Text(keyString),
new IndexWritable(json, b));
deleteFlag = 1;
}
}
}
}
if (deleteFlag == 0) {
final Put put = new Put(Bytes.toBytes(keyString));
put.add(Bytes.toBytes("cf"), Bytes.toBytes("ErrorFlag"),
Bytes.toBytes("1"));
hbasePutErrorList.add(put);
}
} catch (final Exception e) {
e.printStackTrace();
}
}
/**
* Remove duplicate statement in the title
*
* #param mapobject
*/
private void correctDuplicateTitle(final Map<String, Object> mapobject) {
final String duplicateTitle = mapobject.get("title").toString();
final String stripedTitleArr[] = duplicateTitle.split(" ", 4);
if (stripedTitleArr.length == 4) {
final String subString = stripedTitleArr[0] + " "
+ stripedTitleArr[1] + " " + stripedTitleArr[2];
if (stripedTitleArr[3].contains(subString)) {
mapobject.put("title", duplicateTitle
.substring(duplicateTitle.indexOf(subString,
subString.length() - 1)));
mapobject.put("title", stripedTitleArr[3]
.substring(stripedTitleArr[3].indexOf(subString)));
}
}
}
/**
* Set category based on the various category specific keyword
*
* #param mapobject
*/
private void setCorrectCategory(final Map<String, Object> mapobject) {
final String url = mapobject.get("url") + "";
final String cat = mapobject.get("tags") + "";
if ("sports".equalsIgnoreCase(cat)
|| "cricket".equalsIgnoreCase(cat)) {
if (!(url.toLowerCase().contains("sport")
|| url.toLowerCase().contains("खेल")
|| url.toLowerCase().contains("cric") || url
.toLowerCase().contains("क्रिकेट"))) {
final String desc = mapobject.get("description").toString();
boolean isSports = false;
int count = 0;
for (final String keyword : SPORTS_KEYWORDS) {
if (desc.contains(keyword)) {
count++;
}
}
if (count > 1) {
isSports = true;
}
if (!isSports) {
mapobject.put("tags", "national");
}
if (isSports
&& (desc.contains("क्रिकेट")
|| url.toLowerCase().contains("cric")
|| desc.contains("टॉस")
|| desc.contains("वनडे") || desc
.contains("बल्लेबाज"))) {
mapobject.put("tags", "cricket");
}
}
} else if ("business".equalsIgnoreCase(cat)) {
if ((url.toLowerCase().contains("sport") || url.toLowerCase()
.contains("खेल"))) {
mapobject.put("tags", "sports");
} else if (url.toLowerCase().contains("cric")
|| url.toLowerCase().contains("क्रिकेट")) {
mapobject.put("tags", "cricket");
} else if (!(url.toLowerCase().contains("busines")
|| url.toLowerCase().contains("व्यापार")
|| url.toLowerCase().contains("economy")
|| url.toLowerCase().contains("finance")
|| url.toLowerCase().contains("बिजनेस")
|| url.toLowerCase().contains("market")
|| url.toLowerCase().contains("karobar") || url
.contains("कारोबार"))) {
final String desc = mapobject.get("description").toString();
int count = 0;
for (final String keyword : BUSINESS_KEYWORDS) {
if (desc.contains(keyword)) {
count++;
}
}
if (count < 2) {
mapobject.put("tags", "national");
}
}
} else if ("gossip".equalsIgnoreCase(cat)) {
if ((url.toLowerCase().contains("sport") || url.toLowerCase()
.contains("खेल"))) {
mapobject.put("tags", "sports");
} else if (url.toLowerCase().contains("cric")
|| url.toLowerCase().contains("क्रिकेट")) {
mapobject.put("tags", "cricket");
} else if (url.toLowerCase().contains("busines")) {
mapobject.put("tags", "business");
} else if (!(url.toLowerCase().contains("masala")
|| url.toLowerCase().contains("gossip")
|| url.toLowerCase().contains("gupshup") || url
.toLowerCase().contains("garam"))) {
final String desc = mapobject.get("description").toString();
int count = 0;
for (final String keyword : GOSSIP_KEYWORDS) {
if (desc.contains(keyword)) {
count++;
}
}
if (count < 2) {
mapobject.put("tags", "national");
}
}
} else if ("crime".equalsIgnoreCase(cat)) {
if ((url.toLowerCase().contains("sport") || url.toLowerCase()
.contains("खेल"))) {
mapobject.put("tags", "sports");
} else if (url.toLowerCase().contains("cric")
|| url.toLowerCase().contains("क्रिकेट")) {
mapobject.put("tags", "cricket");
} else if (url.toLowerCase().contains("busines")) {
mapobject.put("tags", "business");
} else if (!(url.toLowerCase().contains("crime")
|| url.toLowerCase().contains("terrorist")
|| url.toLowerCase().contains("abuse")
|| url.toLowerCase().contains("forgery")
|| url.toLowerCase().contains("assault")
|| url.toLowerCase().contains("violence")
|| url.toLowerCase().contains("rape")
|| url.toLowerCase().contains("teasing")
|| url.toLowerCase().contains("molestation")
|| url.toLowerCase().contains("scandal") || url
.toLowerCase().contains("murder"))) {
final String desc = mapobject.get("description").toString();
int count = 0;
for (final String keyword : CRIME_KEYWORDS) {
if (desc.contains(keyword)) {
count++;
}
}
if (count < 2) {
mapobject.put("tags", "national");
}
}
} else if (cat != null && cat.startsWith("local")) {
}
}
/**
* Check valid type of the HTML pages
*
* #param mapobject
* #return
*/
private boolean checkValidType(final Map<String, Object> mapobject) {
if (mapobject.containsKey("type")
&& !(mapobject.get("type").toString().contains("image") || mapobject
.get("type").toString().contains("rss"))) {
return true;
}
return false;
}
/**
* refine the description according to its length and must starting with
* english and it the description is not present get the description
* from the metatags description
*
* #param mapobject
* #return {#link Boolean}
*/
private boolean refineDescription(final Map<String, Object> mapobject) {
if (mapobject.containsKey("description")
&& mapobject.get("description").toString().length() > 75
&& !mapobject.get("description").toString().contains(";}")
&& !mapobject.get("description").toString()
.contains("<cite>")
&& !mapobject.get("description").toString()
.contains("href=")
&& !mapobject.get("description").toString()
.contains("All rights reserved")) {
return true;
} else if (mapobject.containsKey("metatag.description")
&& mapobject.get("metatag.description").toString().length() > 75
&& !mapobject.get("metatag.description").toString()
.contains(";}")
&& !mapobject.get("metatag.description").toString()
.contains("<cite>")) {
mapobject.put("description",
mapobject.get("metatag.description"));
return true;
}
return false;
}
/**
* refine metatags by refining meta keyword to only include the English
* keyword only that has at most three keyword and if not present then
* create the keyword with title field of the html and if none of the
* keyword found then form it using the help of the url and exclude the
* number from the keywords
*
* #param mapobject
*/
private void refineMetaTags(final Map<String, Object> mapobject) {
String metaTag = "";
int tagFlag = 0;
if (mapobject.containsKey("metatag.keywords")) {
final String metaTags[] = mapobject.get("metatag.keywords")
.toString().replaceAll("\\|", ",").split(",");
String domain = null;
StringBuilder temp = null;
for (final String metaTag2 : metaTags) {
if (mapobject.containsKey("host")) {
domain = mapobject.get("host") + "";
if (domain.split("\\.").length > 1
&& (metaTag2
.contains(domain.split("\\.")[domain
.split("\\.").length - 2]) || metaTag2
.contains(domain.split("\\.")[0])))
{
continue;
}
}
String[] arr = metaTag2.split(" ");
arr = removeUnicodeWords(arr);
if (arr.length > 0 && arr.length < 5) {
temp = new StringBuilder();
for (final String str : arr) {
temp.append(str);
temp.append(" ");
}
if (metaTag.length() + temp.length() < 70) {
metaTag = metaTag + "," + temp.toString();
}
}
}
if (metaTag.startsWith(",")) {
metaTag = metaTag.trim();
metaTag = metaTag.substring(1, metaTag.length());
}
}
if (metaTag.length() < 1 && mapobject.containsKey("title")) {
/**
* Extracting tags from the title tag if the length of the
* keyword is greater than 4
*/
final String title = (String) mapobject.get("title");
final String splitTitle[] = title.split(" ");
int count = 0;
for (int i = 0; i < splitTitle.length; i++) {
if (splitTitle[i].length() > 4
&& !splitTitle[i].matches("^[\\u0900-\\u097F].*")) {
metaTag = metaTag + splitTitle[i] + ",";
count++;
if (count == 5) {
break;
}
}
}
if (metaTag.split(",").length > 3) {
if (metaTag.endsWith(",")) {
metaTag = metaTag.trim();
metaTag = metaTag.substring(0, metaTag.length() - 1);
}
} else {
metaTag = "";
}
}
if (metaTag.length() < 1) {
/**
* Extracting the tags from the url if the length of the keyword
* is greater than 4
*/
final String splitUrl[] = mapobject.get("url").toString()
.split("/");
final String lastSplitValue = splitUrl[splitUrl.length - 1];
final String tagList[] = generateTokens(lastSplitValue);
if (tagList != null) {
int count = 0;
for (int i = 0; i < tagList.length; i++) {
if (tagList[i].length() > 4
&& !tagList[i].matches("^[\\u0900-\\u097F].*")) {
metaTag = metaTag + tagList[i] + ",";
count++;
if (count == 5) {
break;
}
}
}
}
if (metaTag.endsWith(",")) {
metaTag = metaTag.trim();
metaTag = metaTag.substring(0, metaTag.length() - 1);
}
}
if (metaTag.length() > 0) {
metaTag = metaTag.replaceAll("\\[", "");
metaTag = metaTag.replaceAll("\"", "");
metaTag = metaTag.replaceAll(";", "");
metaTag = metaTag.replaceAll(":", "");
metaTag = metaTag.replaceAll("\u0027", "");
metaTag = metaTag.replaceAll("\u003d", "");
metaTag = metaTag.replaceAll("\u0026", "");
tagFlag = 1;
}
mapobject.put("TagFlag", tagFlag);
mapobject.put("metatag.keywords", metaTag);
}
/**
* Remove unicode character
*
* #param arr
* #return
*/
private String[] removeUnicodeWords(final String[] arr) {
final List<String> returnArr = new ArrayList<String>();
for (final String str : arr) {
if (str != null && str.trim().length() > 3
&& !str.matches("^[\\u0900-\\u097F].*")
&& !(str.matches("^[0-9].*"))) {
returnArr.add(str.trim());
}
}
final String[] retrnArr = new String[returnArr.size()];
returnArr.toArray(retrnArr);
return retrnArr;
}
/**
* Generate Token list with the help of the lucene analyzer
*
* #param lastSplitValue
* #return {#link ArrayIndexOutOfBoundsException} of the list of the
* keywords
*/
private String[] generateTokens(String lastSplitValue) {
final List<String> list = new ArrayList<String>();
lastSplitValue = lastSplitValue.replace("\\.", " ").replace("%20",
" ");
try {
final Version matchVersion = Version.LUCENE_45;
final Analyzer analyzer = new HindiAnalyzer(matchVersion);
final TokenStream ts = analyzer.tokenStream("field",
new StringReader(lastSplitValue));
ts.reset();
while (ts.incrementToken()) {
final CharTermAttribute cta = ts
.getAttribute(CharTermAttribute.class);
if (cta.toString().length() > 4
&& !cta.toString().matches("^[0-9].*")) {
list.add(cta.toString());
}
}
ts.end();
ts.close();
analyzer.close();
} catch (final Exception e) {
e.printStackTrace();
}
if (list.size() > 3) {
return list.toArray(new String[list.size()]);
} else {
return null;
}
}
/**
* Checks title and assign their language based on their first character
* of the title
*
* #param mapobject
* #return {#link Map}
*/
private boolean setLang(final Map<String, Object> mapobject) {
final String title = mapobject.get("title").toString();
final String description = mapobject.get("title").toString();
String language = "";
try {
language = mapper.detect(title);
mapper.detect(description);
} catch (final LangDetectException e) {
System.out.println("\n title with error is - " + title);
System.out.println("\n description with error is - "
+ description);
e.printStackTrace();
/*
* String title = mapobject.get("title").toString(); language =
* mapobject.get("lang") + ""; language = language.trim(); if
* (language.trim().equalsIgnoreCase("hi") ||
* language.trim().startsWith("en") ||
* language.trim().equalsIgnoreCase("lt")) { String[] titleArr =
* title.trim().split(" "); int i = 0; for (String titlePart :
* titleArr) { if
* (titlePart.trim().matches("^[\\u0900-\\u097F].*")) { i++; } }
* if (i >= titleArr.length * 0.5) { mapobject.put("lang",
* "hi"); } else { mapobject.put("lang", "lt"); } return true; }
*/
return false;
}
if (language.trim().equalsIgnoreCase("hi")
|| language.trim().startsWith("en")
|| language.trim().equalsIgnoreCase("lt")) {
mapobject.put("lang", language);
return true;
}
return false;
}
private String detect(final String text) throws LangDetectException {
final Detector detector = DetectorFactory.create();
detector.append(text);
return detector.detect();
}
/**
* Checks whether to include the doc based on their title and get the
* title from anchor tag title to choose the title that has largest
* number of the words and in hindi and it also gets the image from
* anchor tag href attribute
*
* #param mapobject
* of the key value pair
* #return {#link Boolean}
*/
private boolean checkTitleImage(final Map<String, Object> mapobject) {
final TreeSet<String> set = new TreeSet<String>(new SetSort());
final Gson gson = new Gson();
JsonArray array = null;
JsonObject object2 = null;
if (mapobject.containsKey("anchor")
&& mapobject.get("anchor") != null) {
final String arr = (String) mapobject.get("anchor");
try {
array = gson.fromJson(arr, JsonArray.class);
for (final JsonElement jsonElement : array) {
try {
object2 = gson.fromJson(jsonElement.getAsString(),
JsonObject.class);
} catch (final Exception e) {
if (object2 == null) {
object2 = new JsonObject();
object2.addProperty("title",
jsonElement.getAsString());
object2.addProperty("href", "");
object2.addProperty("alt", "");
}
}
if (object2 != null) {
assignTitleImage(mapobject, set, object2);
}
object2 = null;
}
} catch (final ClassCastException e) {
object2 = gson.fromJson(arr, JsonObject.class);
assignTitleImage(mapobject, set, object2);
} catch (final Exception e) {
e.printStackTrace();
}
if (!set.isEmpty()) {
int loop = 0;
final List<String> tempList = new LinkedList<String>();
for (final String string : set) {
final String title = string;
tempList.add(title.trim());
loop++;
if (loop == 2) {
break;
}
}
if (!tempList.isEmpty()) {
if (tempList.get(0).matches("^[\\u0900-\\u097F].*")) {
mapobject.put("title", tempList.get(0));
} else if (tempList.size() > 1
&& !(tempList.get(0)
.matches("^[\\u0900-\\u097F].*"))
&& tempList.get(1).matches(
"^[\\u0900-\\u097F].*")) {
mapobject.put("title", tempList.get(1));
} else {
mapobject.put("title", tempList.get(0));
}
}
}
}
if (mapobject.containsKey("title")
&& mapobject.get("title").toString().length() > 0
&& mapobject.get("title").toString().split(" ").length > 2
&& mapobject.get("title").toString().split(" ").length < 20
&& !mapobject.get("title").toString().contains("<")) {
if (set.isEmpty()) {
mapobject.put("title",
getTitleRefined(mapobject.get("title") + ""));
}
return true;
}
return false;
}
/**
* #param mapobject
* #param set
* #param object2
*/
private void assignTitleImage(final Map<String, Object> mapobject,
final TreeSet<String> set, final JsonObject object2) {
if (!mapobject.containsKey("ImgH1")
&& !mapobject.containsKey("ImgH2")) {
if (object2.get("href") != null
&& object2.get("href").getAsString().length() > 0
&& (object2.get("href").getAsString().toLowerCase()
.contains(".jpg")
|| object2.get("href").getAsString()
.toLowerCase().contains(".jpeg") || object2
.get("href").getAsString().toLowerCase()
.contains(".gif"))) {
putImages(mapobject, object2.get("href").getAsString()
.trim(), mapobject.get("tags").toString().trim()
.toLowerCase());
}
}
if (object2.get("title") != null
&& object2.get("title").getAsString().length() > 0
&& object2.get("title").getAsString().split(" ").length > 2
&& object2.get("title").getAsString().split(" ").length < 20
&& !object2.get("title").getAsString().contains("<")) {
final String newTitle = getTitleRefined(object2.get("title")
.getAsString());
set.add(newTitle.trim());
}
}
/**
* This function used to refine the title based on specific bad keyword
* during observation
*
* #param title
* #return refined title
*/
private String getTitleRefined(String title) {
title = title.replaceAll("\u0027", "");
title = title.replaceAll("\u0026", "");
title = title.replaceAll("\u003d", "");
if (title.contains("-")) {
if (title.trim().split("-").length > 1
&& !title.trim().split("-")[1].trim().matches(
"^[\\u0900-\\u097F].*")) {
return title.trim().split("-")[0].trim();
}
} else if (title.contains(":")) {
if (!title.trim().split(":")[0].trim().matches(
"^[\\u0900-\\u097F].*")
&& title.trim().split(":").length > 1) {
return title.trim().split(":")[1].trim();
}
}
return title;
}
/**
* Creates the path for the images
*
* #param map
* of the key value pair
* #param imageUrl
* #param category
*/
private void putImages(final Map<String, Object> map2,
final String imageUrl, final String category) {
try {
map2.put("ImgSrc", StringEscapeUtils.unescapeHtml(imageUrl)
.trim());
if (map2.containsKey("ImgSrc") && map2.get("ImgSrc") != null
&& map2.get("ImgSrc").toString().length() > 0) {
map2.put(
"ImgSrc",
StringEscapeUtils.unescapeHtml(map2.get("ImgSrc")
.toString())
+ "##RAFTAAR##"
+ imageUrl.trim());
} else {
return;
}
String imgNamearr[] = null;
try {
imgNamearr = imageUrl.split("/");
} catch (final Exception e) {
e.printStackTrace();
}
String imgName = null;
try {
imgName = imgNamearr[imgNamearr.length - 1];
} catch (final Exception e) {
e.printStackTrace();
}
final String imagePath = "/"
+ String.valueOf(imgName.charAt(0));
imgName = imgName.replaceAll(" ", "_").replaceAll("%20", "_");
if (imgName.split(".jpg").length > 0) {
imgName = imgName.split(".jpg")[0];
imgName = imgName + ".jpg";
}
map2.put("ImgH1", "h1/" + category + imagePath + "/" + imgName);
map2.put("ImgH2", "h2/" + category + imagePath + "/" + imgName);
} catch (final Exception e) {
e.printStackTrace();
}
}
/**
* Inserts the data to the elasticsearch
*
* #param mapobject
* #param key
* unique id generally it is the unique url
*/
public static void insertToElastic(final Map<String, Object> mapobject,
final String key) {
final Settings settings = ImmutableSettings.settingsBuilder()
.put("cluster.name", CLUSTER).build();/*
* change ccluster.name
* to cluster
*/
final Client client = new TransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(
SEARCH_HOST, Integer.parseInt(SEARCH_PORT)));
client.prepareIndex(SEARCH_INDEX_NAME, SEARCHtYPE, key)
.setSource(mapobject).execute().actionGet();
client.close();
}
/**
* Assign the city to the news without city
*
* #param category
* #param description
* #return update category with city
*/
private static void assignCity(final Map<String, Object> mapobject) {
String category = mapobject.get("tags").toString();
if (category.endsWith("/")) {
boolean flag = true;
final String catArr[] = category.split("/");
if (catArr.length == 2) {
final String state = catArr[1];
CITY_MAP = STATE_MAP.get(state);
for (final Entry<String, String> e : CITY_MAP.entrySet()) {
final String description = mapobject.get("description")
.toString();
if (description.contains(e.getValue())) {
category = category + e.getKey();
mapobject.put("tags", category);
flag = false;
break;
}
}
}
if (flag) {
mapobject.put("tags", "national");
}
}
}
}
/**
* Update the data to hbase
*
* #param tableName
* #param rowKey
* #param family
* #param qualifier
* #param value
* #param conf
*/
public static void updateIntoHbase(final String tableName,
final String rowKey, final String family, final String qualifier,
final String value, final Configuration conf) {
HTable table = null;
try {
table = new HTable(conf, tableName);
} catch (final IOException e) {
e.printStackTrace();
}
final Put put = new Put(Bytes.toBytes(rowKey));
put.add(Bytes.toBytes(family), Bytes.toBytes(qualifier),
Bytes.toBytes(value));
try {
table.put(put);
table.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
/**
* Return the map of the all states and city
*
* #param fileName
* #return
*/
private static Map<String, Map<String, String>> returnMap(
final String fileName) {
final Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileName));
String line;
while ((line = br.readLine()) != null) {
final String arr[] = line.split("\t", 3);
if (arr.length == 3) {
if (map.containsKey(arr[0])) {
Map<String, String> m = new HashMap<String, String>();
m = map.get(arr[0]);
m.put(arr[1], arr[2]);
} else {
final Map<String, String> m = new HashMap<String, String>();
m.put(arr[1], arr[2]);
map.put(arr[0], m);
}
}
}
} catch (final FileNotFoundException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (final Exception e) {
e.printStackTrace();
}
}
}
return map;
}
public static void main(final String[] args) throws Exception {
int c = 0;
c = ToolRunner.run(new Configuration(), new HbaseToElastic(), args);
System.exit(c);
}
}
Related
Get posted file over HTTP Listener in c#
I have make a simple http server using c#. And I know how to get posted data and output them. Here is my c# code public static void start(){ HttpListener listener = new HttpListener(); listener.Prefixes.Add(new Uri("http://localhost:8080").ToString()); istener.Start(); while(true){ HttpListenerContext con = listener.GetContext(); showPostedData(con.Request); con.Response.StatusCode = (int)HttpStatusCode.NotFound; string data = "Uploaded successful"; byte[] output = Encoding.ASCII.GetBytes(data); con.Response.ContentType = "text/html"; con.Response.ContentLength64 = output.Length; con.Response.OutputStream.Write(output , 0, output.Length ); } } public static void showPostedData(HttpListenerRequest request){ if (!request.HasEntityBody) { return; } System.IO.Stream body = request.InputStream; System.Text.Encoding encoding = request.ContentEncoding; System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding); string text; if (request.ContentType != null) { text = reader.ReadToEnd(); } Console.WriteLine( text ); } My client html form has input box named file: <input type="file" name"file"> In the console output is like that : file='Path of Choosed file not a file' So How i get POSTED files and copy them to upload directory..? Sorry for my english and thanks in advance...
public static void start(){ HttpListener listener = new HttpListener(); listener.Prefixes.Add(new Uri("http://localhost:80").ToString()); istener.Start(); while(true){ HttpListenerContext con = listener.GetContext(); var values = new HttpNameValueCollection(ref con); try { Console.WriteLine(values.Files["file"].FileName); File.WriteAllText(values.Files["file"].FileName, values.Files["file"].FileData, Encoding.Default); } catch (Exception tr) { } } } class HTTPFormData { public class File { private string _fileName; public string FileName { get { return _fileName ?? (_fileName = ""); } set { _fileName = value; } } private string _fileData; public string FileData { get { return _fileData ?? (_fileName = ""); } set { _fileData = value; } } private string _contentType; public string ContentType { get { return _contentType ?? (_contentType = ""); } set { _contentType = value; } } } private NameValueCollection _post; private Dictionary<string, File> _files; private readonly HttpListenerContext _ctx; public NameValueCollection Post { get { return _post ?? (_post = new NameValueCollection()); } set { _post = value; } } public NameValueCollection Get { get { return _ctx.Request.QueryString; } } public Dictionary<string, File> Files { get { return _files ?? (_files = new Dictionary<string, File>()); } set { _files = value; } } private void PopulatePostMultiPart(string post_string) { var boundary_index = _ctx.Request.ContentType.IndexOf("boundary=") + 9; var boundary = _ctx.Request.ContentType.Substring(boundary_index, _ctx.Request.ContentType.Length - boundary_index); var upper_bound = post_string.Length - 4; if (post_string.Substring(2, boundary.Length) != boundary) throw (new InvalidDataException()); var current_string = new StringBuilder(); for (var x = 4 + boundary.Length; x < upper_bound; ++x) { if (post_string.Substring(x, boundary.Length) == boundary) { x += boundary.Length + 1; var post_variable_string = current_string.Remove(current_string.Length - 4, 4).ToString(); var end_of_header = post_variable_string.IndexOf("\r\n\r\n"); if (end_of_header == -1) throw (new InvalidDataException()); var filename_index = post_variable_string.IndexOf("filename=\"", 0, end_of_header); var filename_starts = filename_index + 10; var content_type_starts = post_variable_string.IndexOf("Content-Type: ", 0, end_of_header) + 14; var name_starts = post_variable_string.IndexOf("name=\"") + 6; var data_starts = end_of_header + 4; if (filename_index != -1) { var filename = post_variable_string.Substring(filename_starts, post_variable_string.IndexOf("\"", filename_starts) - filename_starts); var content_type = post_variable_string.Substring(content_type_starts, post_variable_string.IndexOf("\r\n", content_type_starts) - content_type_starts); var file_data = post_variable_string.Substring(data_starts, post_variable_string.Length - data_starts); var name = post_variable_string.Substring(name_starts, post_variable_string.IndexOf("\"", name_starts) - name_starts); Files.Add(name, new File() { FileName = filename, ContentType = content_type, FileData = file_data }); } else { var name = post_variable_string.Substring(name_starts, post_variable_string.IndexOf("\"", name_starts) - name_starts); var value = post_variable_string.Substring(data_starts, post_variable_string.Length - data_starts); Post.Add(name, value); } current_string.Clear(); continue; } current_string.Append(post_string[x]); } } private void PopulatePost() { if (_ctx.Request.HttpMethod != "POST" || _ctx.Request.ContentType == null) return; var post_string = new StreamReader(_ctx.Request.InputStream, _ctx.Request.ContentEncoding).ReadToEnd(); if (_ctx.Request.ContentType.StartsWith("multipart/form-data")) PopulatePostMultiPart(post_string); } public HTTPFormData(ref HttpListenerContext ctx) { _ctx = ctx; PopulatePost(); } }
Accessing Map Value
static void getRecommendations(Map<User, HashMap<Item, Double>> map, User to) { scores = sortMapByScore(scores, to); TreeMap<User, Double> scores1 = (TreeMap<User, Double>) scores.get(to); Set<User> user = (Set<User>) scores1.keySet(); Iterator<User> itr = user.iterator(); Map<Item, Double> rec = new HashMap<Item, Double>(); int i = 0; while (itr.hasNext() && i < 5) { User u = itr.next(); /* for(Item e:map.get(to).keySet()){ */ for (Item e1 : map.get(u).keySet()) { if (!map.get(to).containsKey(e1)) { if (rec.containsKey(e1)) { double sc = rec.get(e1); rec.put(e1, sc + map.get(u).get(e1) * scores.get(to).get(u)); } else { // System.out.println(scores); rec.put(e1, map.get(u).get(e1) * scores.get(to).get(u)); } // } } } i++; } TreeMap<Item, Double> res = new TreeMap<Item, Double>( new ValueComparator(rec)); res.putAll(rec); int k=0; for(Item d:res.keySet()){ System.out.println(d.getmTitle()); k++; if(k==5){break;} } } I am using nested HashMap and TreeMap in this example.But I am facing the below problem. In the code above in the line rec.put(e1, map.get(u).get(e1) * scores.get(u).get(to)); I am getting a NullPointerException, even though I am using the same HashMap's keyset to get the Values.
NullPointerException in working with JButtons
public class Node extends JButton { private Node rightConnection ; private Node downConnection ; private Node rightNode ,downNode, leftNode ,upNode; private ArrayList<String> buttonImages = new ArrayList<String>(); public static void connectNodes(ArrayList<Node> nodes) { for (int i = 0; i < nodes.size(); i++) { nodes.get(i).setRightNode((nodes.get(i).getLocation().x / 150 < Integer.parseInt(SetMap.getMapSize()) - 1) ? nodes.get(i + 1) : null); nodes.get(i).setDownNode((nodes.get(i).getLocation().y / 150 < Integer.parseInt(SetMap.getMapSize()) - 1) ? nodes.get(i + Integer.parseInt(SetMap.getMapSize())) : null); nodes.get(i).setLeftNode((nodes.get(i).getLocation().x / 150 > 0) ? nodes.get(i - 1) : null); nodes.get(i).setUpNode((nodes.get(i).getLocation().y / 150 > 0) ? nodes.get(i - Integer.parseInt(SetMap.getMapSize())) : null); } } public class SetContent { private JPanel contentPanel; private int imgNum; public SetContent() { contentPanel = new JPanel(null); contentPanel.setLocation(1166, 0); contentPanel.setSize(200, 768); makeOptionNodes(); } private void makeOptionNodes() { MouseListener mouseListener = new DragMouseAdapter(); for (int row = 0; row < 13; row++) { for (int col = 0; col < 2; col++) { Node button = new Node(); button.setSize(100, 50); button.setLocation(col * 100, row * 50); ImageIcon img = new ImageIcon("src/com/company/" + this.imgNum++ + ".png"); button.setIcon(new ImageIcon(String.valueOf(img))); // to remote the spacing between the image and button's borders //button.setMargin(new Insets(0, 0, 0, 0)); // to add a different background //button.setBackground( ... ); button.setTransferHandler(new TransferHandler("icon")); button.addMouseListener(mouseListener); contentPanel.add(button); } } } } public class DragMouseAdapter extends MouseAdapter{ String name= new String(); public void mousePressed(MouseEvent e) { JComponent c = (JComponent) e.getSource(); TransferHandler handler = c.getTransferHandler(); handler.exportAsDrag(c, e, TransferHandler.COPY); name = handler.getDragImage().toString();// here is another nullpointerException for(int i = 0 ; i< Integer.parseInt(SetMap.getMapSize()) ; i++) { if (c.getName().equals(String.valueOf(i))) { ((Node) c).getButtonImages().add(name); } } } } public class SetMap { private static String mapSize; private JPanel nodesPanel; private ArrayList<Node> nodes; public SetMap() { nodes = new ArrayList<Node>(); for (Node node : nodes) { node = new Node(); } nodesPanel = new JPanel(null); nodesPanel.setLocation(0, 0); nodesPanel.setSize(1166, 768); this.mapSize = JOptionPane.showInputDialog(null, "enter map size:"); makeMapNodes(); Node.connectNodes(this.nodes); makeConnections(); } private void makeMapNodes() { for (int row = 0; row < Integer.parseInt(this.mapSize); row++) { for (int col = 0; col < Integer.parseInt(this.mapSize); col++) { final Node button = new Node(); button.setRightNode(null); button.setDownNode(null); button.setLeftNode(null); button.setUpNode(null); button.setRightConnection(null); button.setDownConnection(null); button.setTransferHandler(new TransferHandler("icon")); button.setSize(100, 100); button.setLocation(col * 150, row * 150); this.nodes.add(button); nodesPanel.add(button); Node.setNodeName(this.nodes, this.nodes.indexOf(button)); button.addActionListener(new AbstractAction() { #Override public void actionPerformed(ActionEvent e) { int index = nodes.indexOf(button); nodes.remove(button); Node.setNodeName(nodes, index); button.invalidate(); button.setVisible(false); if (button.getLocation().x / 150 < Integer.parseInt(SetMap.getMapSize()) - 1) { button.getRightConnection().invalidate(); button.getRightConnection().setVisible(false); } if (button.getLocation().y / 150 < Integer.parseInt(SetMap.getMapSize()) - 1) { button.getDownConnection().invalidate(); button.getDownConnection().setVisible(false); } if (button.getLocation().x / 150 > 0) { button.getLeftNode().getRightConnection().invalidate(); button.getLeftNode().getRightConnection().setVisible(false); } if (button.getLocation().y / 150 > 0) { button.getUpNode().getDownConnection().invalidate(); button.getUpNode().getDownConnection().setVisible(false); } } }); } } } private void makeConnections() { for (Node button : this.nodes){ final Node rightConnection = new Node(); final Node downConnection = new Node(); rightConnection.setSize(50, 35); downConnection.setSize(35, 50); rightConnection.setLocation(button.getLocation().x + 100, button.getLocation().y + 35); downConnection.setLocation(button.getLocation().x + 35, button.getLocation().y + 100); button.setRightConnection(rightConnection); button.setDownConnection(downConnection); ImageIcon imgH = new ImageIcon("src/com/company/horizontal.png"); rightConnection.setIcon(new ImageIcon(String.valueOf(imgH))); ImageIcon imgV = new ImageIcon("src/com/company/vertical.png"); downConnection.setContentAreaFilled(false); downConnection.setIcon(new ImageIcon(String.valueOf(imgV))); if(button.getLocation().x / 150 != Integer.parseInt(this.mapSize)-1) { nodesPanel.add(rightConnection); } if(button.getLocation().y / 150 != Integer.parseInt(this.mapSize)-1) { nodesPanel.add(downConnection); } rightConnection.addActionListener(new AbstractAction() { #Override public void actionPerformed(ActionEvent e) { rightConnection.invalidate(); rightConnection.setVisible(false); } }); downConnection.addActionListener(new AbstractAction() { #Override public void actionPerformed(ActionEvent e) { downConnection.invalidate(); downConnection.setVisible(false); } }); } } } public class File { public static void writeInFile(ArrayList<Node> nodes) { try { FileWriter fileWriter = new FileWriter("G:\\file.txt"); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write("[" + SetMap.getMapSize() + "]" + "[" + SetMap.getMapSize() + "]"); bufferedWriter.newLine(); Iterator itr = nodes.iterator(); while (itr.hasNext()) { Node node = (Node) itr.next(); if (node != null) { bufferedWriter.write(node.getText()); bufferedWriter.newLine(); bufferedWriter.write("R" + ((node.getRightConnection() != null) ? node.getRightNode().getText() : null) + " D" + ((node.getDownConnection() != null) ? node.getDownNode().getText() : null) + " L" + ((node.getLeftNode().getRightConnection() != null) ? node.getLeftNode().getText() : null) + " U" + ((node.getUpNode().getDownConnection() != null) ? node.getUpNode().getText() : null));//here is the NullPOinterException bufferedWriter.newLine(); bufferedWriter.write("image"); bufferedWriter.newLine(); Iterator it = node.getButtonImages().iterator(); while (it.hasNext()){ String images = (String) it.next(); bufferedWriter.write(" " + images); } } } bufferedWriter.close(); fileWriter.close(); } catch (IOException e) { System.out.println(e); } } } public class Main { public static void main(String[] args) { JFrame mainFrame = new JFrame(); mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.setLayout(null); final SetMap map = new SetMap(); SetContent options = new SetContent(); mainFrame.add(map.getNodesPanel()); mainFrame.add(options.getContentPanel()); JButton saveButton = new JButton("save"); saveButton.setSize(100, 25); saveButton.setLocation(1050, 10); saveButton.addActionListener(new AbstractAction() { #Override public void actionPerformed(ActionEvent e) { File.writeInFile(map.getNodes()); } }); map.getNodesPanel().add(saveButton); mainFrame.setVisible(true); JOptionPane.showMessageDialog(null, "choose nodes and connections you want to remove"); } } I'm trying to write the changes that are made on some nodes I added in mapPanel but in the File class the line (which is commented), I get NullPointerException and also for another line in class DragMouseAdapter I get this exception again. I've omitted some unimportant part of code. I know it's a lot to check code but I would be thankful for any simple help in this case cause I'm a real noob in programming.
how to upload audio to server: Blackberry
I'm trying to upload an .amr file to the server. My Code as follows: private static void uploadRecording(byte[] data) { byte[] response=null; String currentFile = getFileName(); //the .amr file to upload StringBuffer connectionStr=new StringBuffer("http://www.myserver/bb/upload.php"); connectionStr.append(getString()); PostFile req; try { req = new PostFile(connectionStr.toString(), "uploadedfile", currentFile, "audio/AMR", data ); response = req.send(data); } catch (Exception e) { System.out.println("====Exception: "+e.getMessage()); } System.out.println("Server Response : "+new String(response)); } public class PostFile { static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy"; byte[] postBytes = null; String url = null; public PostFile(String url, String fileField, String fileName, String fileType, byte[] fileBytes) throws Exception { this.url = url; String boundary = getBoundaryString(); String boundaryMessage = getBoundaryMessage(boundary, fileField, fileName, fileType); String endBoundary = "\r\n--" + boundary + "--\r\n"; ByteArrayOutputStream bos = new ByteArrayOutputStream(); bos.write(boundaryMessage.getBytes()); bos.write(fileBytes); bos.write(endBoundary.getBytes()); this.postBytes = bos.toByteArray(); bos.close(); } String getBoundaryString() { return BOUNDARY; } String getBoundaryMessage(String boundary, String fileField, String fileName, String fileType) { StringBuffer res = new StringBuffer("--").append(boundary).append("\r\n"); res.append("Content-Disposition: form-data; name=\"").append(fileField).append("\"; filename=\"").append(fileName).append("\"\r\n") .append("Content-Type: ").append(fileType).append("\r\n\r\n"); return res.toString(); } public byte[] send(byte[] fileBytes) throws Exception { HttpConnection hc = null; InputStream is = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] res = null; try { hc = (HttpConnection) Connector.open(url); hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + getBoundaryString()); hc.setRequestMethod(HttpConnection.POST); hc.setRequestProperty(HttpProtocolConstants.HEADER_ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); hc.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH ,Integer.toString(fileBytes.length)); OutputStream dout = hc.openOutputStream(); dout.write(postBytes); dout.close(); int ch; is = hc.openInputStream(); // <<< EXCEPTION HERE!!! if(hc.getResponseCode()== HttpConnection.HTTP_OK) { while ((ch = is.read()) != -1) { bos.write(ch); } res = bos.toByteArray(); System.out.println("res loaded.."); } else { System.out.println("Unexpected response code: " + hc.getResponseCode()); hc.close(); return null; } } catch(IOException e) { System.out.println("====IOException : "+e.getMessage()); } catch(Exception e1) { e1.printStackTrace(); System.out.println("====Exception : "+e1.getMessage()); } finally { try { if(bos != null) bos.close(); if(is != null) is.close(); if(hc != null) hc.close(); } catch(Exception e2) { System.out.println("====Exception : "+e2.getMessage()); } } return res; } } Highlighted above is the code line which throws the exception: Not Connected. Can somebody tell me what can be done to correct this? Thanks a lot. Updated: public static String getString() { String connectionString = null; String uid = null; // Wifi if(WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) { connectionString = ";interface=wifi"; } else { ServiceBook sb = ServiceBook.getSB(); net.rim.device.api.servicebook.ServiceRecord[] records = sb.findRecordsByCid("WPTCP"); for (int i = 0; i < records.length; i++) { if (records[i].isValid() && !records[i].isDisabled()) { if (records[i].getUid() != null && records[i].getUid().length() != 0) { if ((records[i].getCid().toLowerCase().indexOf("wptcp") != -1) && (records[i].getUid().toLowerCase().indexOf("wifi") == -1) && (records[i].getUid().toLowerCase().indexOf("mms") == -1) ) { uid = records[i].getUid(); break; } } } } if (uid != null) { connectionString = ";deviceside=true;ConnectionUID="+uid; } else { // the carrier network if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) { String carrierUid = getCarrierBIBSUid(); if (carrierUid == null) { // Has carrier coverage, but not BIBS. So use the // carrier's // TCP network System.out.println("No Uid"); connectionString = ";deviceside=true"; } else { // otherwise, use the Uid to construct a valid carrier // BIBS // request System.out.println("uid is: " + carrierUid); connectionString = ";deviceside=false;connectionUID=" + carrierUid + ";ConnectionType=mds-public"; } } //(BlackBerry Enterprise Server) else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) { connectionString = ";deviceside=false"; } // If there is no connection available abort to avoid bugging // the user unnecessarily. else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) { System.out.println("There is no available connection."); } // In theory, all bases are covered so this shouldn't be // reachable. else { System.out.println("no other options found, assuming device."); connectionString = ";deviceside=true"; } } } return connectionString; } /** * Looks through the phone's service book for a carrier provided BIBS * network * * #return The uid used to connect to that network. */ private static String getCarrierBIBSUid() { try { net.rim.device.api.servicebook.ServiceRecord[] records = ServiceBook.getSB().getRecords(); int currentRecord; for (currentRecord = 0; currentRecord < records.length; currentRecord++) { if (records[currentRecord].getCid().toLowerCase().equals( "ippp")) { if (records[currentRecord].getName().toLowerCase() .indexOf("bibs") >= 0) { return records[currentRecord].getUid(); } } } } catch (Exception e) { System.out.println("====Exception : "+e.toString()); } return null; }
How to sort search dictionary result based on frequency in j2me
This is my dictionary format: word Frequency Gone 60 Goes 10 Go 30 So far the system returns words eg starting with 'g' as go30, goes10, gone60 as a list. (alphabetically). I want to increase the accuracy of the system so that the search result is based on frequency. Words with high frequencies appear first. kindly help. Here is the Text midlet class that reads the dictionary line by line. public class Text extends MIDlet { // Fields private static final String[] DEFAULT_KEY_CODES = { // 1 ".,?!'\"1-()#/:_", // 2 "ABC2", // 3 "DEF3", // 4 "GHI4", // 5 "JKL5", // 6 "MNO6", // 7 "PQRS7", // 8 "TUV8", // 9 "WXYZ9", }; //Initializing inner Classes public ComposeText() { cmdHandler = new CommandHandler(); lineVector = new Vector(); } //Calling All InitMethods, setting Theme, Show MainForm public void startApp() { Display.init(this); setTheme(); initCmd(); initMainGui(); mainFrm.show(); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } //Initializing all the Commands public void initCmd() { exitCmd = new Command("Exit"); selectCmd = new Command("Ok"); cancelCmd = new Command("Cancel"); predCmd = new Command("Prediction"); sendCmd = new Command("Send"); tfPredArea = new TextField(); //check dictionary try { readFile(); } catch (IOException ex) { ex.printStackTrace(); } } //Initiating MainScreen public void initMainGui() { mainFrm = new Form("Compose Text"); mainFrm.setLayout(new BorderLayout()); mainFrm.setLayout(new CoordinateLayout(150, 150)); mainFrm.addCommand(exitCmd); mainFrm.addCommand(predCmd); mainFrm.addCommand(sendCmd); mainFrm.addCommandListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { if(ae.getSource() == predCmd){ initPredGui(); } else if(ae.getSource() == exitCmd){ destroyApp(true); notifyDestroyed(); } } }); // To : 07xxxxxxxxxx Dimension d1 = new Dimension(130, 20); lbTo = new Label("To:"); lbTo.setX(10); lbTo.setY(10); tfTo = new TextField(); tfTo.setReplaceMenu(false); tfTo.setConstraint(TextField.NUMERIC); tfTo.setInputModeOrder(new String[]{"123"}); tfTo.setMaxSize(13); tfTo.setX(40); tfTo.setY(10); tfTo.setPreferredSize(d1); //Message : Compose Text Dimension d2 = new Dimension(135, 135); lbSms = new Label("Message:"); lbSms.setX(5); lbSms.setY(40); tfSms = new TextField(); tfSms.setReplaceMenu(false); tfSms.setX(40); tfSms.setY(40); tfSms.setPreferredSize(d2); //add stuff mainFrm.addComponent(lbTo); mainFrm.addComponent(lbSms); mainFrm.addComponent(tfTo); mainFrm.addComponent(tfSms); } //Initiating FilterSelection Screen public void initPredGui() { predForm = new Form("Prediction on"); predForm.setLayout(new CoordinateLayout(150, 150)); predForm.addCommand(cancelCmd); predForm.addCommand(selectCmd); //textfied in prediction form final Dimension d5 = new Dimension(200, 200); tfPredArea = new TextField(); tfPredArea.setReplaceMenu(false); tfPredArea.setX(10); tfPredArea.setY(10); tfPredArea.setPreferredSize(d5); predForm.addComponent(tfPredArea); final ListModel underlyingModel = new DefaultListModel(lineVector); // final ListModel underlyingModel = new DefaultListModel(tree.getAllPrefixMatches(avail)); // this is a list model that can narrow down the underlying model final SortListModel proxyModel = new SortListModel(underlyingModel); final List suggestion = new List(proxyModel); tfPredArea.addDataChangeListener(new DataChangedListener() { public void dataChanged(int type, int index) { int len = 0; int i = 0; String input = tfPredArea.getText(); len = tfPredArea.getText().length(); //ensure start search character is set for each word if (!(len == 0)) { for (i = 0; i < len; i++) { if (input.charAt(i) == ' ') { k = i; } } String currentInput = input.substring(k + 1, len); proxyModel.filter(currentInput); } } }); Dimension d3 = new Dimension(110, 120); suggestion.setX(80); suggestion.setY(80); suggestion.setPreferredSize(d3); predForm.addComponent(suggestion); suggestion.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { String string = suggestion.getSelectedItem().toString(); if (tfPredArea.getText().charAt(0) == 0) { tfPredArea.setText(string); } else if (tfPredArea.getText().length() == 0) { tfPredArea.setText(string); } else { tfPredArea.setText(tfPredArea.getText() + string); } } }); predForm.addCommandListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { if (ae.getSource() == addCmd) { newDictionaryFrm.show(); } else { mainFrm.show(); } } }); predForm.show(); } //Setting Theme for All Forms public void setTheme() { try { Resources r = Resources.open("/theme.res"); UIManager.getInstance().setThemeProps(r.getTheme( r.getThemeResourceNames()[0])); } catch (java.io.IOException e) { System.err.println("Couldn't load the theme"); } } //Inner class CommandHandler public class CommandHandler implements ActionListener { public void actionPerformed(ActionEvent ae) { //cancelCommand from predictionForm if (ae.getSource() == cancelCmd) { if (edit) { mainFrm.show(); // clearFields(); } else if (ae.getSource() == selectCmd){ tfPredList.addDataChangeListener(model); predForm.show(); } else{} } } } // method that reads dictionary line by line public void readFile() throws IOException { tree = new Trie(); InputStreamReader reader = new InputStreamReader( getClass().getResourceAsStream("/Maa Corpus.txt-01-ngrams-Alpha.txt")); String line = null; // Read a single line from the file. null represents the EOF. while ((line = readLine(reader)) != null) { // Append to a vector to be used as a list lineVector.addElement(line); } } public String readLine(InputStreamReader reader) throws IOException { // Test whether the end of file has been reached. If so, return null. int readChar = reader.read(); if (readChar == -1) { return null; } StringBuffer string = new StringBuffer(""); // Read until end of file or new line while (readChar != -1 && readChar != '\n') { // Append the read character to the string. // This is part of the newline character if (readChar != '\r') { string.append((char) readChar); } // Read the next character readChar = reader.read(); } return string.toString(); } } } The SortListModel Class has a filter method that gets prefix from the textfield datachangeLister class SortListModel implements ListModel, DataChangedListener { private ListModel underlying; private Vector filter; private Vector listeners = new Vector(); public SortListModel(ListModel underlying) { this.underlying = underlying; underlying.addDataChangedListener(this); } private int getFilterOffset(int index) { if(filter == null) { return index; } if(filter.size() > index) { return ((Integer)filter.elementAt(index)).intValue(); } return -1; } private int getUnderlyingOffset(int index) { if(filter == null) { return index; } return filter.indexOf(new Integer(index)); } public void filter(String str) { filter = new Vector(); str = str.toUpperCase(); for(int iter = 0 ; iter < underlying.getSize() ; iter++) { String element = (String)underlying.getItemAt(iter); if(element.toUpperCase().startsWith(str)) // suggest only if smthing { filter.addElement(new Integer(iter)); } } dataChanged(DataChangedListener.CHANGED, -1); } public Object getItemAt(int index) { return underlying.getItemAt(getFilterOffset(index)); } public int getSize() { if(filter == null) { return underlying.getSize(); } return filter.size(); } public int getSelectedIndex() { return Math.max(0, getUnderlyingOffset(underlying.getSelectedIndex())); } public void setSelectedIndex(int index) { underlying.setSelectedIndex(getFilterOffset(index)); } public void addDataChangedListener(DataChangedListener l) { listeners.addElement(l); } public void removeDataChangedListener(DataChangedListener l) { listeners.removeElement(l); } public void addSelectionListener(SelectionListener l) { underlying.addSelectionListener(l); } public void removeSelectionListener(SelectionListener l) { underlying.removeSelectionListener(l); } public void addItem(Object item) { underlying.addItem(item); } public void removeItem(int index) { underlying.removeItem(index); } public void dataChanged(int type, int index) { if(index > -1) { index = getUnderlyingOffset(index); if(index < 0) { return; } } for(int iter = 0 ; iter < listeners.size() ; iter++) { ((DataChangedListener)listeners.elementAt(iter)).dataChanged(type, index); } } }