Form a tree or nodes from a raw string - javascript

I have the following as a string
var string = "#anno1[ data1 xyz #anno2[data2 #anno3[data3] data4] data5 #anno4[data6] data7]"
And I would like to convert it an object as follows:
var childs = [
{
name : '#anno1',
text : 'data1 xyz data2 data3 data4 data5 data6 data7',
},
{
name : '#anno2',
text : 'data2 data3 data4'
},
{
name : '#anno3',
text : 'data3'
},
{
name : '#anno4',
text : 'data6'
}
]
I've tried out many ways but I was not successful, thanks in advance.
Here is the java code which i have tried
import java.util.HashMap;
import java.util.Map;
public class ExpressionTree {
static Map <String, String> resultMap = new HashMap<String, String>(16);
public static void main(String args[]) {
// String exp = "[data1 xyz #anno2[data2 #anno3[data3] data4] data5 #anno4[data6] data7]";
String exp = "#anno1[ data1 xyz #anno2[data2 #anno3[data3] data4] data5 #anno4[data6] data7 ]";
parseRecursively(exp);
}
private static void parseRecursively(String exp) {
String annotation = null;
String annotationValue = null;
if (exp.startsWith("#")) {
int dataStartIndex = exp.indexOf("[");
annotation = exp.substring(0, dataStartIndex);
annotationValue = exp.substring(0 + dataStartIndex, exp.lastIndexOf("]")+1).trim();
System.out.println(annotation);
System.out.println(annotationValue);
resultMap.put(annotation, annotationValue);
parseRecursively(annotationValue);
} else {
int annotationStartIndex = exp.indexOf("#");
int dataStartIndex = exp.substring(1).indexOf("[");
if( -1 != annotationStartIndex || -1 != dataStartIndex)
{
annotation = exp.substring(annotationStartIndex, dataStartIndex+1).trim();
String nextData = exp.substring(0 + dataStartIndex + 1).trim();
String tmpNextData = nextData;
int countOfOpenBrackets = 0;
for (int i = 0; tmpNextData.charAt(i) != ']'; i++) {
// System.out.println(tmpNextData.charAt(i));
if (tmpNextData.charAt(i) == '[') {
countOfOpenBrackets++;
}
// tmpNextData = tmpNextData.substring(1);
}
tmpNextData = nextData;
int endIndexOfCurrentData = 0;
for (int i = 0; i < tmpNextData.length() && endIndexOfCurrentData == 0; i++) {
// System.out.println(tmpNextData.charAt(i));
if (tmpNextData.charAt(i) == ']') {
countOfOpenBrackets--;
}
if (countOfOpenBrackets == 0) {
endIndexOfCurrentData = i + 1;
}
// tmpNextData = tmpNextData.substring(1);
}
annotationValue = nextData.substring(0, endIndexOfCurrentData).trim();
System.out.println(annotation);
System.out.println(annotationValue);
resultMap.put(annotation, annotationValue);
parseRecursively(annotationValue);
}
}
System.out.println(resultMap);
}
}

Here is a JavaScript (ES6) solution:
function toObject(string) {
"use strict";
const tokens = string.match(/[\[\]]|[^\s\[\]]+/g),
result = [];
let i = 0;
function recurse() {
const words = [];
let obj;
while (i < tokens.length) {
let token = tokens[i];
if (token[0] === '#') {
obj = {name: token};
result.push(obj);
} else if (token === '[') {
i++;
obj.text = recurse();
words.push(obj.text);
} else if (token === ']') {
break;
} else {
words.push(token);
}
i++;
}
return words.join(' ');
}
recurse();
return result;
}
const string = "#anno1[ data1 xyz #anno2[data2 #anno3[data3] data4] data5 #anno4[data6] data7]";
const result = toObject(string);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

how to count two string common character

*** i am try to this count two string match character ***
var s1 = "abcd";
var s2 = "aad";
function match(s1,s2){
var obj = {}
var spilt1 = s1.split("")
var spilt2 = s2.split("")
for(let i =0;i<spilt1.length;i++){
let th = spilt2.includes(spilt1[i])
if(!obj[th[i]]){
obj[th[i]] = 0
}else{
obj[th[i]]++
}
}
return obj
}
console.log(match(s1,s2))
*** output like this ***
{
a:1,
d:1
}
function match(str1, str2) {
const str1Obj = {};
const resultObj = {};
for (let i = 0; i < str1.length; i++) {
str1Obj[str1[i]] = str1Obj.hasOwnProperty(str1[i])
? str1Obj[str1[i]] + 1
: 1;
}
for (let i = 0; i < str2.length; i++) {
if (str1Obj.hasOwnProperty(str2[i]) && str1Obj[str2[i]] >= 1) {
resultObj[str2[i]] = resultObj.hasOwnProperty(str2[i])
? resultObj[str2[i]] + 1
: 1;
str1Obj[str2[i]] -= 1;
}
}
return resultObj;
}

Append array value to string

How can an array value (could be any number less than 20K) be appended to a string?
I'm trying to imitate :
if (form1.EActQ20 === undefined) { Q2B0 = 0; }
else (Q2B0 = document.form1.EActQ20.value);
var und = x < 20000;
var less1 = form1.EActQ1.und.toString();
var less2 = form1.EActQ2.und.toString();
var less3 = form1.EActQ3.und.toString();
var less4 = form1.EActQ4.und.toString();
if (less1 === undefined) { Q1B.und.toString() = 0; }
else (Q1B.und.toString() = document.less1.value); /// is now a value to get added in an equation
if (less2 === undefined) { Q2B.und.toString() = 0; }
else (Q2B.und.toString() = document.less2.value);
if (less3 === undefined) { Q3B.und.toString() = 0; }
else (Q3B.und.toString() = document.less3.value);
if (less4 === undefined) { Q4B.und.toString() = 0; }
else (Q4B.und.toString() = document.less4.value);
/// Revised Code Below
arr = [];
var und = 0; // some number below 2000
var less = form1["EActQ1" + und];
if (less1 === undefined) {
arr[und] = 0;
} else {
arr[und] = document["less1" + und].value;
}
if (less2 === undefined) {
arr[und] = 0;
} else {
arr[und] = document["less2" + und].value;
}
if (less3 === undefined) {
arr[und] = 0;
} else {
arr[und] = document["less3" + und].value;
}
if (less1 === undefined) {
arr[und] = 0;
} else {
arr[und] = document["less1" + und].value;
}
add = (["Q1B"+ und] * 1)+(["Q2B"+ und] * 1)+(["Q3B"+ und] * 1)+(["Q4B"+ und] * 1);
Returns NaN. I'm defining cells based on their values and trying to add them up.
You seem to be looking for bracket notation:
var und = 0; // some number below 2000
var less = form1["EActQ" + und];
Also use an object to collect all those values, not a set of Q2B… variables. Or even better, just an array:
arr = [];
…
if (less === undefined) {
arr[und] = 0;
} else {
arr[und] = document["less" + und].value;
}

implementing split() method for exercise 4 in Object Oriented Javascript 2n edition

here is the question:
Imagine the String() constructor didn't exist. Create a constructor
function, MyString(), that acts like String() as closely as possible.
You're not allowed to use any built-in string methods or properties,
and remember that String() doesn't exist. You can use this code to
test your constructor:
I created constructor however I have no clue how to re-create split method, how to implement that functionality.
If you could give an idea how to implement split method, I would be grateful
function MyString(str) {
var thisObj = this;
var innerLength = 0;
this.length;
function updateLength() {
innerLength = 0;
for (var i = 0; str[i] != undefined; i++) {
innerLength++;
thisObj[i] = str[i];
}
thisObj.length = innerLength;
}
updateLength();
this.toString = function() {
return str;
}
this.charAt = function(i) {
if (isNaN(parseInt(i))) {
return this[0]
} else {
return this[i]
}
}
this.concat = function(string) {
str += string;
updateLength();
}
this.slice = function(start, end) {
var slicedString = "";
if (start >= 0 && end >= 00) {
for (start; start < end; start++) {
slicedString += str[start];
}
}
return slicedString;
}
this.reverse = function() {
var arr = str.split("");
arr.reverse();
var reversedString = "",
i;
for (i = 0; i < arr.length; i++) {
reversedString += arr[i];
}
return reversedString;
}
}
var ms = new MyString("Hello, I am a string")
console.log(ms.reverse())
You can convert the string to an array and use Array.prototype and RegExp.prototype methods.
this.split = function(re) {
var arr = Array.prototype.slice.call(this.toString());
if (re === "") {
return arr
}
if (re === " ") {
return arr.filter(function(el) {
return /[^\s]/.test(el)
})
}
if (/RegExp/.test(Object.getPrototypeOf(re).constructor)) {
var regexp = re.source;
return arr.filter(function(el) {
return regexp.indexOf(el) === -1
})
}
}
function MyString(str) {
var thisObj = this;
var innerLength = 0;
this.length;
function updateLength() {
innerLength = 0;
for (var i = 0; str[i] != undefined; i++) {
innerLength++;
thisObj[i] = str[i];
}
thisObj.length = innerLength;
}
updateLength();
this.toString = function() {
return str;
}
this.split = function(re) {
var arr = Array.prototype.slice.call(this.toString());
if (re === "") {
return arr
}
if (re === " ") {
return arr.filter(function(el) {
return /[^\s]/.test(el)
})
}
if (/RegExp/.test(Object.getPrototypeOf(re).constructor)) {
var regexp = re.source;
return arr.filter(function(el) {
return regexp.indexOf(el) === -1
})
}
}
this.charAt = function(i) {
if (isNaN(parseInt(i))) {
return this[0]
} else {
return this[i]
}
}
this.concat = function(string) {
str += string;
updateLength();
}
this.slice = function(start, end) {
var slicedString = "";
if (start >= 0 && end >= 00) {
for (start; start < end; start++) {
slicedString += str[start];
}
}
return slicedString;
}
this.reverse = function() {
var arr = str.split("");
arr.reverse();
var reversedString = "",
i;
for (i = 0; i < arr.length; i++) {
reversedString += arr[i];
}
return reversedString;
}
}
var ms = new MyString("Hello, I am a string")
console.log(ms.split(""), ms.split(" "), ms.split(/l/))
Iterate and search:
MyString.prototype.split = function(splitter){
var tmp="", result = [];
for(var i = 0; i < this.length; i++){
for(var offset = 0; offset < this.length && offset < splitter.length;offset++){
if(this[i+offset] !== splitter[offset]) break;
}
if(offset === splitter.length){
result.push( tmp );
tmp="";
i += offset -1;
}else{
tmp+=this[i];
}
}
result.push(tmp);
return result;
};
So now you can do:
new MyString("testtest").split("t") //['','es','','','es','']
In action

Problems with searching arrays

I wrote my code to search string for keywords and extracting needed data, but I have problems when I'm trying to search with keywords in arrays named: sort, title and artist. When I'm doing it I get an error about potential infinite loop.
var type = ['track','tracks','song','songs','album','albums'];
var artist = ['created by', 'made by'];
var genre = ['genre'];
var limit = ['set limit'];
var title = ['title','name'];
var sort = ['sort by', 'classificate by', 'separate by'];
var sortBy = ['popularity'];
// function changeWordsToNumbers(words) {
// if (msg.numbers[words])
// return msg.numbers[words];
// }
function searchForIndex(instruction, keywords) {
for (i = 0; i < keywords.length; i++) {
let search = instruction.search(keywords[i]);
if (search)
return search;
}
return false;
}
function getSearchResult(wanted) {
var searchResult = {
artist : searchForIndex(wanted, artist),
genre : searchForIndex(wanted, genre),
limit : searchForIndex(wanted, limit),
type : searchForIndex(wanted, type),
title : searchForIndex(wanted, title),
sort : searchForIndex(wanted, sort),
sortBy : searchForIndex(wanted, sortBy)
};
return searchResult;
}
function removeJunkKeyword(searchResult,instruction) {
for(var property in searchResult) {
if(searchResult.hasOwnProperty(property)) {
if(searchResult[property] != - 1) {
instruction = instruction.slice(0, searchResult[property] - 1);
}
}
}
return instruction;
}
function checkExist(searchResult) {
for(var property in searchResult) {
if(searchResult.hasOwnProperty(property)) {
if(searchResult[property] != -1)
return false;
}
}
return true;
}
function findAndCleanQuery(instruction, keywords) {
var exist = instruction.search(keywords);
var result = instruction.slice(exist + keywords.length + 1, instruction.length);
var searchResult = getSearchResult(result);
if (exist != -1) {
if (checkExist(searchResult)) {
return result;
} else {
result = removeJunkKeyword(searchResult,result);
return result;
}
}
return false;
}
function searchFor(instruction, keywords) {
for (i = 0; i < keywords.length; i++) {
let result = findAndCleanQuery(instruction,keywords[i]);
if (result)
return result;
}
return false;
}
function searchForType(instruction) {
for (i = 0; i < type.length; i++) {
let search = instruction.search(type[i])
if(search)
return type[i];
}
return false;
}
function searchForKeywords(instruction) {
msg.artist = searchFor(instruction, artist);
msg.type = searchForType(instruction, type);
msg.genre = searchFor(instruction, genre);
msg.limit = searchFor(instruction, limit);
msg.title = searchFor(instruction, title);
msg.sort = searchFor(instruction, sortreg);
}
var msg = {}
msg.instruction = 'Search for me';
searchForKeywords(msg.instruction);
console.log(msg.artist);
console.log(msg.type);
console.log(msg.genre);
console.log(msg.limit);
console.log(msg.title);
console.log(msg.sort);
Link for code: https://repl.it/J4Mc/9
PS. The object msg is used by node-red to communicate between nodes.
The issue is that you're doing this on several of your loops:
for (i = 0; i < keywords.length; i++) {
...where you should be doing this instead:
for (let i = 0; i < keywords.length; i++) {
Without using let, the variable i is effectively global. Each time you went into a new loop it got reset to 0, so it was never able to increase, which created the infinite loop.
As a side note, you'll also notice sortreg is undefined when it's used on line 98.

Replace Java Applet with GWT

Hi I have the following class which would like to replace with stjs, but it seems it does not work for me, as stjs does not cover all applet libraries, any though if this is can be done thru stjs or any other technology? Thanks in advance
package org.stjs.examples.hello;
import java.applet.Applet;
import java.awt.Button;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.Rectangle;
import java.awt.TextArea;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.text.BreakIterator;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
import java.util.StringTokenizer;
public class DataCache
extends Applet
implements ActionListener
{
private static final String APPLET_VERSION = "1.6.0";
private static final int MSG_WIN_HEIGHT = 179;
private static final int MSG_WIN_WIDTH = 288;
private static final String MSG_WIN_ETITLE = "Error Message";
private static final String MSG_WIN_MTITLE = "Information Message";
public String m_error = "";
public String m_message = "";
public String m_currCacheString = "";
public StringBuffer m_currXMLCache = null;
public Hashtable m_currHashCache = null;
private String m_commandKey;
private Hashtable m_XMLCache = new Hashtable();
private Hashtable m_hashCache = new Hashtable();
private String m_key = "";
private String m_keyList = "";
private String m_file = "";
private String m_dataDir = "";
private String m_autoLoad = "TRUE";
private String m_servletURL = "";
private String m_debugApplet = "";
private Frame m_msgWindow;
private TextArea m_msgText;
private Button m_msgButton;
private FontMetrics m_msgMetrics;
private int m_msgTextHeight;
public void destroy()
{
this.m_msgWindow.dispose();
}
public void init()
{
createErrorWindow();
alertStatus("applet version: 1.6.0", 'D');
this.m_debugApplet = getAppParam("debugApplet");
this.m_autoLoad = getAppParam("autoLoad");
this.m_commandKey = getAppParam("commandKey");
String ls = getAppParam("loadStatic");
String dataDir = getAppParam("dataDir");
this.m_servletURL = getAppParam("servletURL");
URL url = getCodeBase();
int port = url.getPort();
if (this.m_debugApplet.equals("TRUE")) {
System.out.println("url: " + this.m_servletURL);
} else if (port != -1) {
this.m_servletURL = ("http://" + url.getHost() + ":" + port + this.m_servletURL);
} else {
this.m_servletURL = ("http://" + url.getHost() + this.m_servletURL);
}
setDataDir(dataDir);
if (!this.m_autoLoad.toUpperCase().equals("FALSE")) {
if ((ls.equals("")) || (ls.toUpperCase().equals("FALSE")))
{
alertStatus("loading non-static...", 'D');
loadAllData(false);
}
else if (ls.toUpperCase().equals("TRUE"))
{
alertStatus("loading static...", 'D');
openAllData(false);
}
}
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if (s.equals("OK")) {
this.m_msgWindow.hide();
}
}
private void createErrorWindow()
{
this.m_msgWindow = new Frame("New Title");
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3 = new Panel();
p1.setLayout(new GridLayout(2, 1));
this.m_msgText = new TextArea("New Message", 3, 40, 1);
this.m_msgText.setEditable(false);
this.m_msgText.setFont(new Font("Dialog", 0, 8));
this.m_msgMetrics = this.m_msgText.getFontMetrics(this.m_msgText.getFont());
p2.add(this.m_msgText);
p1.add(p2);
this.m_msgButton = new Button(" OK ");
this.m_msgButton.addActionListener(this);
this.m_msgButton.setActionCommand("OK");
p3.add(this.m_msgButton);
p1.add(p3);
this.m_msgWindow.add(p1);
this.m_msgWindow.pack();
Toolkit t = this.m_msgWindow.getToolkit();
this.m_msgTextHeight = this.m_msgMetrics.getHeight();
this.m_msgWindow.setBounds(new Rectangle(
t.getScreenSize().width / 2 - 144,
t.getScreenSize().height / 2 - 89,
288,
179));
}
public void setDataDir(String s)
{
try
{
if ((s != null) && (s.length() > 0))
{
if (s.charAt(s.length() - 1) != '\\') {
s = s + "\\";
}
this.m_dataDir = s;
}
}
catch (Exception e)
{
e.printStackTrace();
alertStatus(e.getMessage(), 'E');
alertStatus(s, 'E');
}
}
private String getAppParam(String s)
{
String param = getParameter(s);
if (param == null) {
return "";
}
return param;
}
private String alertStatus(String source, Exception e, char status)
{
e.printStackTrace(System.out);
return alertStatus(source + " -- " + e.getMessage(), status);
}
private String alertStatus(String s, char status)
{
switch (status)
{
case 'E':
this.m_error = s;
System.out.println(s);
showStatus(s);
this.m_msgWindow.setTitle("Error Message");
setWrapText(s);
this.m_msgButton.setEnabled(true);
this.m_msgWindow.show();
return s;
case 'M':
this.m_message = s;
System.out.println(s);
showStatus(s);
this.m_msgWindow.setTitle("Information Message");
setWrapText(s);
this.m_msgButton.setEnabled(true);
this.m_msgWindow.show();
return s;
case 'S':
this.m_message = s;
System.out.println(s);
showStatus(s);
this.m_msgWindow.setTitle("Information Message");
setWrapText(s);
this.m_msgButton.setEnabled(false);
this.m_msgWindow.show();
return s;
case 'D':
System.out.println(s);
return s;
}
return "";
}
private void setWrapText(String s)
{
BreakIterator boundary = BreakIterator.getWordInstance(Locale.US);
String line = "";
int maxWidth = this.m_msgText.getSize().width;
this.m_msgText.setText("");
boundary.setText(s);
int start = boundary.first();
int end = boundary.next();
while (end != -1)
{
String tmp = s.substring(start, end);
if (this.m_msgMetrics.stringWidth(line + tmp) > maxWidth)
{
this.m_msgText.append(line + "\n");
line = tmp;
}
else
{
line = line + tmp;
}
start = end;
end = boundary.next();
if (end == -1) {
this.m_msgText.append(line);
}
}
this.m_msgText.append(s.substring(start));
}
private void makeDirectories(String dir)
{
String fdir = dir;
AccessController.doPrivileged(new PrivilegedAction()
{
private final String val$fdir="";
public Object run()
{
String subdir = "";
int i = this.val$fdir.indexOf('\\');
while (i != -1)
{
subdir = this.val$fdir.substring(0, i);
File f = new File(subdir);
if (!f.isDirectory()) {
f.mkdir();
}
i = this.val$fdir.indexOf('\\', i + 1);
}
return null;
}
});
}
private boolean verifyDataFile(String s)
{
String fs = s;
Boolean retVal =
(Boolean)AccessController.doPrivileged(new PrivilegedAction()
{
private final String val$fs="";
public Object run()
{
File f = new File(this.val$fs);
if (!f.isFile()) {
return new Boolean(false);
}
return new Boolean(true);
}
});
return retVal.booleanValue();
}
private String verifyDataFilesInternal()
{
try
{
AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
File dir = new File(DataCache.this.m_dataDir);
if (!dir.isDirectory()) {
dir.mkdirs();
}
return dir;
}
});
StringTokenizer st = new StringTokenizer(this.m_commandKey, ";");
while (st.hasMoreElements())
{
String key = (String)st.nextElement();
if (!verifyDataFile(this.m_dataDir + key + ".data")) {
return "Data cache file " + this.m_dataDir + key + ".data could not be found.";
}
if (!verifyDataFile(this.m_dataDir + key + ".hash")) {
return "Data cache file " + this.m_dataDir + key + ".hash could not be found.";
}
}
return "";
}
catch (Exception e)
{
e.printStackTrace();
return e.getMessage();
}
}
private String loadAllDataInternal()
{
String status = "";
String key = "";
StringBuffer data = new StringBuffer("");
Hashtable hash = null;
alertStatus("loading data internal", 'D');
URLConnection connection;
ObjectInputStream in;
try
{
if (this.m_servletURL.equals("")) {
return alertStatus("Servlet URL not specified!", 'E');
}
try
{
URL inURL = new URL(this.m_servletURL);
connection = inURL.openConnection();
}
catch (Exception e)
{
e.printStackTrace();
return alertStatus("Error opening server connection: " + e.getMessage(), 'E');
}
try
{
// URLConnection connection;
URL inURL;
in = new ObjectInputStream(connection.getInputStream());
}
catch (Exception e)
{
e.printStackTrace();
return alertStatus("Error opening input stream: " + e.getMessage(), 'E');
}
int count;
try
{
count = Integer.parseInt((String)in.readObject());
}
catch (Exception e)
{
e.printStackTrace();
return alertStatus("Error getting object count: " + e.getMessage(), 'E');
}
this.m_XMLCache = new Hashtable(count, 1.0F);
this.m_hashCache = new Hashtable(count, 1.0F);
for (int i = 0; i < count; i++)
{
key = "";
data = new StringBuffer("");
status = (String)in.readObject();
alertStatus("read status", 'D');
key = (String)in.readObject();
alertStatus("read key", 'D');
data = (StringBuffer)in.readObject();
alertStatus("read data", 'D');
hash = (Hashtable)in.readObject();
alertStatus("read cache", 'D');
if (status.equals("connection closed")) {
return alertStatus("Error communicating with servlet: Connection is closed. Please re-login.", 'E');
}
if (status.equals("execution error")) {
return alertStatus("Error in servlet: Error during execution of query. Please notify Data Management.", 'E');
}
if (data == null) {
return alertStatus("Error communicating with servlet: There was a data transmission error. Please notify Data Management.", 'E');
}
alertStatus("got cache: " + key, 'D');
this.m_XMLCache.put(key, data);
this.m_hashCache.put(key, hash);
}
alertStatus("closing stream", 'D');
in.close();
return "";
}
catch (Exception e)
{
e.printStackTrace();
return "Error in loadAllDataInternal: " + e.getMessage();
}
}
private String openAllDataInternal(String path)
{
ObjectInputStream in = null;
String file = "";
StringBuffer data = new StringBuffer("");
Hashtable hash = null;
String status = "";
try
{
status = verifyDataFilesInternal();
if (!status.equals("")) {
return status;
}
StringTokenizer st = new StringTokenizer(this.m_commandKey, ";");
int len = st.countTokens();
this.m_XMLCache = new Hashtable(len, 1.0F);
this.m_hashCache = new Hashtable(len, 1.0F);
while (st.hasMoreElements())
{
String key = (String)st.nextElement();
file = path + key + ".data";
in = new ObjectInputStream(new FileInputStream(file));
data = (StringBuffer)in.readObject();
in.close();
file = path + key + ".hash";
in = new ObjectInputStream(new FileInputStream(file));
hash = (Hashtable)in.readObject();
in.close();
this.m_XMLCache.put(key, data);
this.m_hashCache.put(key, hash);
}
return "";
}
catch (Exception e)
{
e.printStackTrace();
return "Error in openAllDataInternal: " + e.getMessage();
}
}
private String saveAllDataInternal(String s)
{
Enumeration keys = null;
String file = "";
StringBuffer data = new StringBuffer("");
Hashtable hash = null;
ObjectOutputStream out = null;
if (s.equals("")) {
return alertStatus("Data file path is '': " + s, 'E');
}
try
{
keys = this.m_XMLCache.keys();
makeDirectories(s);
while (keys.hasMoreElements())
{
this.m_key = ((String)keys.nextElement());
file = s + this.m_key;
data = (StringBuffer)this.m_XMLCache.get(this.m_key);
hash = (Hashtable)this.m_hashCache.get(this.m_key);
out = new ObjectOutputStream(new FileOutputStream(file + ".data"));
out.writeObject(data);
out.close();
out = new ObjectOutputStream(new FileOutputStream(file + ".hash"));
out.writeObject(hash);
out.close();
}
return "";
}
catch (Exception e)
{
e.printStackTrace();
return "Error in saveAllDataInternal: " + e.getMessage();
}
}
public String loadAllData(boolean verbose)
{
String s =
(String)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return DataCache.this.loadAllDataInternal();
}
});
if (verbose) {
if (s.equals("")) {
alertStatus("Loaded all data!", 'M');
} else {
alertStatus(s, 'E');
}
}
return s;
}
public String saveAllData(boolean verbose, String path)
{
String fpath = path;
String s =
(String)AccessController.doPrivileged(new PrivilegedAction()
{
private final String val$fpath="";
public Object run()
{
return DataCache.this.saveAllDataInternal(this.val$fpath);
}
});
if (verbose) {
if (s.equals("")) {
alertStatus("Saved all data files!", 'M');
} else {
alertStatus(s, 'E');
}
}
return s;
}
public String saveAllData(boolean verbose)
{
String s =
(String)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return DataCache.this.saveAllDataInternal(DataCache.this.m_dataDir);
}
});
if (verbose) {
if (s.equals("")) {
alertStatus("Saved all data files!", 'M');
} else {
alertStatus(s, 'E');
}
}
return s;
}
public String openAllData(boolean verbose)
{
String s =
(String)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return DataCache.this.openAllDataInternal(DataCache.this.m_dataDir);
}
});
if ((s.equals("")) && (verbose)) {
alertStatus("Opened all data files!", 'M');
}
return s;
}
public String verifyAllDataFiles(boolean verbose)
{
String s = verifyDataFilesInternal();
if ((s.equals("")) && (verbose)) {
alertStatus("Verified all data files!", 'M');
}
return s;
}
public void setCache(String key, boolean verbose)
{
this.m_currXMLCache = ((StringBuffer)this.m_XMLCache.get(key));
this.m_currHashCache = ((Hashtable)this.m_hashCache.get(key));
this.m_currCacheString = key;
if (((this.m_currXMLCache == null) || (this.m_currHashCache == null)) &&
(verbose)) {
alertStatus("Requested cache (" + this.m_currCacheString + ") is null!", 'E');
}
}
public String getXML(String key)
{
this.m_currXMLCache = ((StringBuffer)this.m_XMLCache.get(key));
this.m_currHashCache = ((Hashtable)this.m_hashCache.get(key));
this.m_currCacheString = key;
return getXML();
}
public String getXML()
{
if (this.m_currXMLCache == null)
{
alertStatus("Current cache (" + this.m_currCacheString + ") is null!", 'E');
return "";
}
return this.m_currXMLCache.toString();
}
public String lookupCacheValue(String code)
{
String[] values = (String[])this.m_currHashCache.get(code);
return values[1];
}
private void printData(String[][] data)
{
alertStatus("printing data", 'D');
for (int i = 0; i < data[0].length; i++) {
System.out.println("key: " + data[0][i] + "\tvalue: " + data[1][i]);
}
}
}

Categories