javascript function can't find the element - javascript

I need to call some file uploader JavaScript from code behind. The JavaScript is basically customizing the style of the file uploader control. However, the JavaScript function can't find the element. I get this from the inspector:
*o = {element: null,
action: "/Web/UploadHandler.axd?UploadID=55f3930c-6aa9-4201…ccfdfae6c6&ObjectID=145649&RelationshipTypeID=223",
sizeLimit: 209715
when it should look like this:
o = {element: div#uploadContent, action: "/Web/UploadHandler.axd?UploadID=c1829b40-7869-4f19…411e7a542c&ObjectID=151808&RelationshipTypeID=223", sizeLimit: 20971520, acceptTypes: "image/*", onSubmit: ƒ, …}
qq.extend
This is the code:
div = new HtmlGenericControl("div") { ID = ("dlWrapper") };
Literal litScript = new Literal();
litScript.Mode = LiteralMode.PassThrough;
div.Controls.Add(litScript);
var imageUploader = (ImageUpload)CreateImageUploader(ActiveObject, p, litScript);
div.Controls.Add(imageUploader);
controls.Add(div);
private static Control CreateImageUploader(ObjectInstance objectInstance, PropertyType propertyType, Literal litScript)
{
ImageUpload imageUpload = new ImageUpload (objectInstance, litScript) { ID = ControlFactory.GetControlId(ControlFactory.IMAGE_PREFIX, ControlFactory.PROPERTY_TYPE_PREFIX, objectInstance.Id, propertyType.Id), Width = Unit.Pixel(80), Height = Unit.Pixel(30) };
PropertyInstanceValue piv = objectInstance.GetPropertyInstanceValue(propertyType.Id);
return imageUpload;
}
public class ImageUpload : FileUpload
{
public ObjectInstance ActiveObject {get; set; }
public Literal litScript { get; set; }
private string uploadID;
private string accept = "image/*";
public string UploadID
{
get
{
if (string.IsNullOrEmpty(uploadID))
{
uploadID = GetUploadID();
}
return uploadID;
}
set { uploadID = value; }
}
public ImageUpload(ObjectInstance activeObject, Literal literal)
{
ActiveObject = activeObject;
litScript = literal;
}
public string GetUploadID()
{
string uploadID;
if (HttpContext.Current.Session[EDM.Common.Definitions.SessionKey.UPLOAD_ID] != null)
{
uploadID = (string)HttpContext.Current.Session[EDM.Common.Definitions.SessionKey.UPLOAD_ID];
HttpContext.Current.Cache.Remove("cacheFlashSessionID_" + uploadID);
HttpContext.Current.Cache.Remove("cacheFlashAuth_" + uploadID);
}
uploadID = Guid.NewGuid().ToString();
HttpContext.Current.Session[EDM.Common.Definitions.SessionKey.UPLOAD_ID] = uploadID;
HttpContext.Current.Cache.Insert("cacheFlashSessionID_" + uploadID, HttpContext.Current.Session.SessionID, null, DateTime.Now.AddMinutes(20), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);
if (HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
// ReSharper disable PossibleNullReferenceException
HttpContext.Current.Cache.Insert("cacheFlashAuth_" + uploadID, HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value, null, DateTime.Now.AddMinutes(20), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);
// ReSharper restore PossibleNullReferenceException
}
return uploadID;
}
protected override void OnLoad(EventArgs e)
{
Literal litScript = new Literal();
ScriptManager scriptManager = ScriptManager.GetCurrent(Page);
StringBuilder sb = new StringBuilder();
sb.Append("<div id=\"uploadContent\"></div>");
litScript.Text = sb.ToString();
sb.Remove(0, sb.Length);
sb.Append("<script type=\"text/javascript\">");
int maxBytes = ProcessUnity.Common.Utility.GetMaxRequestLength() * 1024;
sb.Append("var uploader = new qq.FileUploader({ element: document.getElementById('uploadContent'), action: '" + Context.Request.ApplicationPath + "/UploadHandler.axd?UploadID=" + UploadID + "&ObjectID=" + ActiveObject.Id + "&RelationshipTypeID=" + EDM.Common.Definitions.RelationshipTypeId.IMAGE_FILE + "', sizeLimit: " + maxBytes + ", acceptTypes:'" + accept + "', onSubmit: uploadStart, onComplete: uploadComplete, onError: uploadError, multiple: false });");
sb.Append("</script>");
if (scriptManager != null)
{
ScriptManager.RegisterClientScriptBlock(this, typeof(ImageUpload), Guid.NewGuid().ToString(), sb.ToString(), false);
}
else
{
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), Guid.NewGuid().ToString(), sb.ToString());
}
base.OnLoad(e);
}
private object GetScriptManager()
{
foreach (DictionaryEntry entry in Page.Items)
{
if (entry.Key.ToString().IndexOf("System.Web.UI.ScriptManager") >= 0)
{
return entry.Value;
}
}
return null;
}
}

It looks like you're expecting litScript here:
Literal litScript = new Literal();
litScript.Mode = LiteralMode.PassThrough;
div.Controls.Add(litScript);
To be modified by the OnLoad event:
protected override void OnLoad(EventArgs e)
{
Literal litScript = new Literal();
// ...
StringBuilder sb = new StringBuilder();
sb.Append("<div id=\"uploadContent\"></div>");
litScript.Text = sb.ToString();
// ...
base.OnLoad(e);
}
But your OnLoad is constructing its own local Literal. Just because it has the same litScript name as the outer Literal doesn't mean that the two are related. In short, nothing is writing that div to the page.

Related

api layer, exchangerate // IOException : Server returned HTTP response code: 403 for URL

control.java
public class control {
public static void main(String[] args) {
boolean success = true;
String timestamp = "1659072666";
String base = "USD";
String date = "2022-07-29";
double GBP = 0.82011;
double JPY = 133.000499;
double EUR = 0.979105;
excJSON vwJson = new excJSON();
exc vw = vwJson.getexc(success, timestamp, base, date, GBP, JPY, EUR);
excDAO vwDao = new excDAO();
vwDao.intertexc(1, vw);
}
}
exc.java
public class exc {
String base;
String date;
String timestamp;
public String getbase() {
return base;
}
public void setbase(String base) {
this.base = base;
}
public String getdate() {
return date;
}
public void setdate(String date) {
this.date = date;
}
public String gettimestamp() {
return timestamp;
}
public void settimestamp(String timestamp) {
this.timestamp = timestamp;
}
}
excDAO.java
import java.sql.Statement;
import java.sql.Connection;
//import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
//import java.util.Enumeration;
public class excDAO {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/test?useSSL=false";
static final String USERNAME = "root"; // DB ID
static final String PASSWORD = "************"; // DB Password
private Connection conn = null;
private Statement stmt = null;
private ResultSet rs = null;
public void intertVillageWeather(int id, exc v) {
String query = "INSERT INTO exchangerate"
+ " VALUE(" + id +",'"+v.gettimestamp() + "','" + v.getbase() + "','" + v.getdate() + "');";
System.out.print("Your Database in : ");
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL,USERNAME,PASSWORD);
if (conn != null){System.out.println("good");}
else{System.out.println("bad");}
System.out.println(query);
stmt = conn.createStatement();
stmt.executeUpdate(query);
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
System.out.println("Class Not Found Exection");
} catch (SQLException e) {
System.out.println("SQL Exception : " + e.getMessage());
}
}
public void intertexc(int i, exc vw) {
}
}
excJSON.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
final static String apiKey = "tUxsDwwjT72GgMLoJRprXlqc34wmOzX4";
public exc getexc(boolean success, String timestamp, String base, String date, double GBP, double JPY, double EUR) {
String urlStr = "https://api.apilayer.com/exchangerates_data/latest?symbols=GBP%2CJPY%2CEUR&base=USD"
+ "&apiKey=" + apiKey + "&success=" + success + "&timestamp=" + timestamp
+ "&base="+ base + "&date=" + date + "&GBP=" + GBP + "&JPY=" + JPY + "&EUR=" + EUR + "&_type=json";
exc vl = new exc(); // 결과 데이터를 저장할 객체를 만듭니다.
try {
URL url = new URL(urlStr);
BufferedReader bf = new BufferedReader(new InputStreamReader(url.openStream()));
String line = "";
String result="";
while((line=bf.readLine())!=null){
result=result.concat(line);
}
//System.out.println(result);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObj = (JSONObject) jsonParser.parse(result);
JSONObject parse_response = (JSONObject) jsonObj.get("response");
JSONObject obj;
String category;
vl.timestamp = timestamp;
vl.base = base;
vl.date = date;
for(int i = 0; i < parse_response.size(); i++) {
obj = (JSONObject) parse_response.get(i);
category = (String)obj.get("category");
switch(category) {
case "timestamp":
vl.timestamp = (obj.get("fcstValue")).toString();
break;
case "base":
vl.base = (obj.get("fcstValue")).toString();
break;
case "date":
vl.date = (obj.get("fcstValue")).toString();
break;
}
}
} catch (MalformedURLException e) {
System.out.println("MalformedURLException : " + e.getMessage());
} catch (IOException e) {
System.out.println("IOException : " + e.getMessage());
} catch (ParseException e) {
System.out.println("ParseException : " + e.getMessage());
}
return vl;
}
}
*Help me please. I think error in excJSON.java. I want make exchangerate program.
I want fix error.
error code : IOException : Server returned HTTP response code: 403 for URL: https://api.apilayer.com/exchangerates_data/latest?symbols=GBP%2CJPY%2CEUR&base=USD&apiKey=tUxsDwwjT72GgMLoJRprXlqc34wmOzX4&success=true&timestamp=1659072666&base=USD&date=2022-07-29&GBP=0.82011&JPY=133.000499&EUR=0.979105&_type=json
I assess "https://api.apilayer.com/exchangerates_data/latest?symbols=GBP%2CJPY%2CEUR&base=USD&apiKey=tUxsDwwjT72GgMLoJRprXlqc34wmOzX4&success=true&timestamp=1659072666&base=USD&date=2022-07-29&GBP=0.82011&JPY=133.000499&EUR=0.979105&_type=json"
but http say {"message":"No API key found in request"}
but i surely receive apikey and api.*

Java Program TextFile Issue

I have a program where a text file is read in and then each word in the file is outputted, followed by the # of times it is repeated throughout the file.
Use the following code.
import java.io.*;
class FileRead {
public static void main(String args[]) {
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C:\\Users\\Desktop\\formate.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println(strLine);
}
//Close the input stream
in.close();
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Try this code:
public static void main(String[] args) throws Throwable
{
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
Scanner scanner = new Scanner(inputFile);
HashMap<String, Integer> count = new HashMap<String, Integer>();
while (scanner.hasNext())
{
String word = scanner.next();
if (count.containsKey(word))
{
count.put(word, count.get(word) + 1);
}
else
{
count.put(word, 1);
}
}
scanner.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
for (Entry<String, Integer> entry : count.entrySet())
{
writer.write("#" + entry.getKey() + " " + entry.getValue()+"\r\n");
}
writer.close();
}
This also, it is a lot simpler if You can't use HashMap or BufferedReader:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Scanner;
public class WordCounter
{
public static void main(String[] args) throws Throwable
{
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
Scanner scanner = new Scanner(inputFile);
LinkedList<Word> words = new LinkedList<Word>();
while (scanner.hasNext())
{
String word = scanner.next();
addWord(words, word);
}
scanner.close();
WriteToFile(outputFile, words);
}
private static void WriteToFile(File outputFile, LinkedList<Word> words) throws IOException
{
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
for (Word word : words)
{
writer.write("#" + word.getWord() + " " + word.getCount() + "\r\n");
}
writer.close();
}
private static void addWord(LinkedList<Word> words, String word)
{
for (Word aWord : words)
{
if (aWord.getWord().equals(word))
{
aWord.incrementCount();
return;
}
}
words.add(new Word(word, 1));
}
}
class Word
{
private String word;
private int count;
public Word(String word, int count)
{
this.word = word;
this.count = count;
}
public String getWord()
{
return word;
}
public void setWord(String word)
{
this.word = word;
}
public int getCount()
{
return count;
}
public void setCount(int count)
{
this.count = count;
}
public void incrementCount()
{
count++;
}
#Override
public String toString()
{
return "Word: " + word + " Count: " + count;
}
}

how to access public methods from a C# class library in javascript(rhino)

I am trying to access public methods from a C# class library (dll) from javascript, specifically a Rhino package for javascript.
Here is what I'm trying to do:
namespace ReturnINT
{
public class ReturnINT
{
public static int RetornaInteiro ()
{
try
{
int number = 2;
return number;
}
catch (Exception)
{
return 1;
}
}
}
}
I created a class library from above code or to be precise a dll file. Now I want to access this dll in my javascript, but I don't want to create any wrappers, which is mentioned in some other threads.
Can someone please guide me here and let me know if I need to perform some setting while creating the dll file?
Here is my sample .net C# app using Rhino over ikvm.
My sample will execute sunspider benchmark script.
class Program
{
public static org.mozilla.javascript.Context con = null;
public static org.mozilla.javascript.Scriptable scope = null;
public static string FILE_PATH = #"C:\sunspider-0.9.1";
public static string JS_Script = "load('run.js');";
static void Main(string[] args)
{
Console.WriteLine("Using .NET Framework " + System.Environment.Version.ToString());
string ___strScriptPath = System.Configuration.ConfigurationManager.AppSettings["script_path"];
if (string.IsNullOrEmpty(___strScriptPath) == false && System.IO.Directory.Exists(___strScriptPath))
{
System.Environment.CurrentDirectory = ___strScriptPath;
FILE_PATH = ___strScriptPath;
}
else
{
System.Environment.CurrentDirectory = FILE_PATH;
}
string ___strOptLevel = System.Configuration.ConfigurationManager.AppSettings["opt"];
int ___optLevel = -1;
if (string.IsNullOrEmpty(___strOptLevel) == false)
{
if (int.TryParse(___strOptLevel, out ___optLevel))
{
if (___optLevel 9)
{
___optLevel = 9;
}
}
}
string ___strScript = System.Configuration.ConfigurationManager.AppSettings["script"];
if (string.IsNullOrEmpty(___strScript) == false)
{
JS_Script = ___strScript;
}
con = org.mozilla.javascript.Context.enter();
con.setLanguageVersion(org.mozilla.javascript.Context.VERSION_ES6);
//con.setGeneratingDebug(false);
con.setOptimizationLevel(___optLevel);
if (___optLevel == -1)
{
con.setGeneratingDebug(true);
con.setGeneratingSource(true);
con.setDebugger(null, null);
}
else
{
con.setGeneratingDebug(false);
con.setGeneratingSource(false);
con.setDebugger(null, null);
}
Console.WriteLine("Starting Rhino Processing OptLevel : {0} Path : {1}", ___optLevel, System.Environment.CurrentDirectory);
scope = con.initSafeStandardObjects();
org.mozilla.javascript.BaseFunction fuc = new org.mozilla.javascript.BaseFunction();
java.lang.Class css = typeof(Program);
java.lang.reflect.Member loadMethod = css.getMethod("load", new java.lang.Class[]{typeof(string)});
org.mozilla.javascript.FunctionObject func = new org.mozilla.javascript.FunctionObject("load", loadMethod, scope);
scope.put("load", scope,func);
java.lang.reflect.Member printMethod = css.getMethod("print", new java.lang.Class[] { typeof(object) });
org.mozilla.javascript.FunctionObject funcPrint = new org.mozilla.javascript.FunctionObject("print", printMethod, scope);
scope.put("print", scope, funcPrint);
java.lang.reflect.Member hogehogeMethod = css.getMethod("hogehoge", new java.lang.Class[] { typeof(object), typeof(object), typeof(object), typeof(object) });
DelegatableFunctionObject.deleHogehoge dele = new DelegatableFunctionObject.deleHogehoge(hogehoge);
//DelegatableFunctionObject funcHogehoge = new DelegatableFunctionObject("hogehoge", hogehogeMethod, scope,dele);
org.mozilla.javascript.FunctionObject funcHogehoge = new org.mozilla.javascript.FunctionObject("hogehoge", hogehogeMethod, scope);
scope.put("hogehoge", scope, funcHogehoge);
try
{
con.evaluateString(scope, JS_Script, "", 1, null);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
DateTime dtStart = DateTime.Now;
/*
org.mozilla.javascript.Script script = con.compileString("", "", 1, null);
for (int i = 0; i cacheFile = new Dictionary();
public static void load(string s)
{
string trace = System.Environment.StackTrace;
string strScript = null;
strScript = System.IO.File.ReadAllText(FILE_PATH + "\\" + s);
// cacheFile[s] = strScript;
con.evaluateString(scope, strScript, "", 1, null);
}
public static void print(object o)
{
Console.WriteLine(string.Format("[Rhino] {0}", o));
}
public static void hogehoge(object o, object o2, object o3, object o4)
{
}
public class DelegatableFunctionObject : org.mozilla.javascript.FunctionObject
{
public delegate void deleHogehoge(object o1, object o2, object o3, object o4);
private deleHogehoge __dele = null;
public DelegatableFunctionObject(string name, java.lang.reflect.Member methodOrContructior, org.mozilla.javascript.Scriptable scope,deleHogehoge dele)
: base(name, methodOrContructior, scope)
{
this.__dele = dele;
}
public override object call(org.mozilla.javascript.Context cx, org.mozilla.javascript.Scriptable scope, org.mozilla.javascript.Scriptable thisObj, object[] args)
{
if (__dele != null)
{
switch (args.Length)
{
case 1:
__dele.Invoke(args[0], null, null, null);
break;
}
}
return null;
}
}
}
I hope this will help you.

The SmartSource Data collector JavaScript Tag, could be inserted from Java?

I'm totally new in Webtrends, I have read that The SmartSource Data collector JavaScript Tag, could be inserted from Java or HTML. does anyone know how to inser it from Java, I found the below class, is this class does the job? please provide some samples. Thanks in advance
public class DC {
public DC() {
super();
}
public String post_url(String connUrl, Map<String, String> bodyref) {
String response = "";
String responseCode = "";
try {
HttpURLConnection conn = null;
// construct data
String data = "";
Iterator<String> i = bodyref.keySet().iterator();
boolean ampersand = false;
while (i.hasNext()) {
if (ampersand) {
data += "&";
} else {
ampersand = true;
}
String b = i.next();
data += b + "=" + bodyref.get(b);
}
System.out.println();
System.out.println("[Request]");
System.out.println("(Url)");
System.out.println(connUrl);
System.out.println("(Body)");
System.out.println(data);
// send data
URL url = new URL(connUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
try {
// get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
response += line;
response += "\n";
}
rd.close();
} catch (IOException e1) {
if (conn != null) {
// get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String line;
while ((line = rd.readLine()) != null) {
response += line;
response += "\n";
}
}
}
System.out.println();
System.out.println("[Response]");
System.out.println("(Status)");
System.out.printf("%s %s\n", conn.getResponseCode(), conn.getResponseMessage());
System.out.println("(Message)");
System.out.println(conn.getResponseMessage());
System.out.println("(Body)");
System.out.println(response);
System.out.flush();
wr.close();
} catch (Exception e) {
System.out.println();
System.out.println("[Response]");
System.out.println("(Status)");
System.out.println(e.toString());
System.out.println("(Message)");
System.out.println(e.getMessage());
System.out.flush();
}
return response;
}
public static void main(String[] args) {
DC dc = new DC();
// customer-specific DCSID
String dcsid = "dcslbiart00000gwngvpqkrcn_2u3z";
// base portion of DC API url
String base_url = "http://dc.webtrends.com/v1/" + dcsid;
// post body
Map<String, String> body1 = new HashMap();
// post query string
String querystring = "";
// compose urls
String id_url = base_url + "/ids.svc" + querystring;
String event_url = base_url + "/events.svc" + querystring;
// get visitor identifier
String id = dc.post_url(id_url, body1);
// post body
Map<String, String> body = new HashMap();
// initialize post body
body.put("dcsuri", "/MyJavaTest");
body.put("dcssip", "localhost");
body.put("WT.ti", "MyJavaTest");
body.put("WT.co_f", id);
body.put("dcsverbose", "true");
// submit event data
dc.post_url(event_url, body);
}

Mustache/handlebars templating: figure out context data structure from template html

In mustache/handlerbars or any templating system in js,
are there any tools to gather all the variables that a template refers to?
for example, given input
templateHTML:
<div class="{{divclass}}">
{#item}}
<h1>{{title}}</h1>
<span>{{text}}</span>
{{/item}}
</div>
would return
{
divclass: "",
item: {
title: "",
text: ""
}
}
when used like MyTemplateTool.getTemplateData(templateHTML)
I tried googling around and checking out handlebars docs but could not find anything suitable
I believe it's just .. See the related docs on paths. Example:
{{#srcs}}
<script src="{{.}}"></script>
{{/srcs}}
I had the same in mind and I thought it was worth while writing something so here you go:
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MustacheSchemaBuilder
{
static String javaIdentifierRegExp = "[a-zA-Z_$0-9]+";
static String tab = " ";
static Format format = Format.java;
enum Format {
json,
java,
;
}
enum TagType {
variable("\\{\\{\\s*" + javaIdentifierRegExp + "\\s*\\}\\}"),
escapedVariable("\\{\\{\\{\\s*" + javaIdentifierRegExp + "\\s*\\}\\}\\}"),
sectionStart("\\{\\{#\\s*" + javaIdentifierRegExp + "\\s*\\}\\}"),
invertedSectionStart("\\{\\{\\^\\s*" + javaIdentifierRegExp + "\\s*\\}\\}"),
sectionEnd("\\{\\{/\\s*" + javaIdentifierRegExp + "\\s*\\}\\}"),
//partial("\\{\\{>\\s*" + javaIdentifierRegExp + "\\s*\\}\\}"),
// no support for set delimiters or partials
;
Pattern pat;
private TagType(String aRegExp) {
pat = Pattern.compile(aRegExp);
}
public Pattern getPattern() { return pat; };
}
class Tag{
public TagType type;
public String identifier;
Tag(TagType aType, String aIdentifier) { type = aType; identifier = aIdentifier;}
public String toString() { return type.name() + " : " + identifier; }
#Override
public boolean equals(Object aOther) {
if(!(aOther instanceof Tag)) return false;
Tag ot = (Tag) aOther;
return ot.type.equals(this.type) && ot.identifier.equals(this.identifier);
}
#Override
public int hashCode() {return identifier.hashCode();}
}
class Node {
public Section parent;
public Tag tag;
Node(Section aParent, Tag aTag){parent = aParent; tag = aTag; if(parent != null) parent.children.put(tag, this);}
#Override
public int hashCode() {return tag.hashCode();}
public int depth() {
int depth = 0;
Node currentNode = this;
while(currentNode.parent != null) {
depth++;
currentNode = currentNode.parent;
}
return depth;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < this.depth(); i++) sb.append(tab);
switch(format) {
case java:
sb.append("public Object ").append(tag.identifier).append(";\n");
break;
case json:
default:
sb.append(tag.identifier).append(": {},\n");
}
return sb.toString();
}
}
class Section extends Node{
public Map<Tag, Node> children = new LinkedHashMap();
Section(Section aParent, Tag aTag) { super(aParent, aTag); };
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < this.depth(); i++) sb.append(tab);
switch(format) {
case java:
sb.append("public Object ").append(tag.identifier).append(" = new Object() {\n");
for(Node child : this.children.values()) sb.append(child);
for(int i = 0; i < this.depth(); i++) sb.append(tab);
sb.append("};\n");
break;
case json:
default:
sb.append(tag.identifier).append(": {\n");
for(Node child : this.children.values()) sb.append(child);
for(int i = 0; i < this.depth(); i++) sb.append(tab);
sb.append("},\n");
}
return sb.toString();
}
}
class MustacheSchemaBuildException extends Exception {
private static final long serialVersionUID = 1L;
MustacheSchemaBuildException(String aMessage) {super(aMessage);}
}
Section rootSection;
public MustacheSchemaBuilder(String aContents) throws Exception
{
TreeMap<Integer, Tag> tagMap = new TreeMap();
for(TagType type : TagType.values()) {
populateMap(tagMap, type, aContents);
}
System.out.println(tagMap);
rootSection = new Section(null, new Tag(TagType.sectionStart, "$root$"));
Section currentSection = rootSection;
for(Tag tag : tagMap.values()) {
if(currentSection.tag.type == TagType.invertedSectionStart) {
if(tag.type == TagType.sectionEnd) {
if(!tag.identifier.equals(currentSection.tag.identifier))
throw new MustacheSchemaBuildException("The end tag: " + tag.identifier + " doesn't match the expected start tag: " + currentSection.tag.identifier + "\n\n" + rootSection);
currentSection = currentSection.parent;
}
continue;
}
switch(tag.type)
{
case variable:
if(!currentSection.children.containsKey(tag))
new Node(currentSection, tag);
break;
case sectionStart:
Tag invertedSectionStartTag = new Tag(TagType.invertedSectionStart, tag.identifier);
if(!(currentSection.children.containsKey(tag) || currentSection.children.containsKey(invertedSectionStartTag)))
new Section(currentSection, tag);
currentSection = (Section)currentSection.children.get(tag);
break;
case invertedSectionStart:
Tag sectionStartTag = new Tag(TagType.sectionStart, tag.identifier);
if(!(currentSection.children.containsKey(tag) || currentSection.children.containsKey(sectionStartTag)))
new Section(currentSection, tag);
currentSection = (Section)currentSection.children.get(sectionStartTag);
break;
case sectionEnd:
if(!tag.identifier.equals(currentSection.tag.identifier))
throw new MustacheSchemaBuildException("The end tag: " + tag.identifier + " doesn't match the expected start tag: " + currentSection.tag.identifier + "\n\n" + rootSection);
currentSection = currentSection.parent;
break;
default:
}
}
}
public void build() {
System.out.println(rootSection);
}
public static void main(String[] args) throws Exception
{
String contents;
try {
contents = readFile(args[0], Charset.defaultCharset());
}catch(Exception e)
{
System.out.println("Unable to open file!");
throw e;
}
MustacheSchemaBuilder builder = new MustacheSchemaBuilder(contents);
builder.build();
}
void populateMap(Map<Integer, Tag> map, TagType aType, String aContents) {
Matcher m = aType.getPattern().matcher(aContents);
while(m.find()) {
int start = m.start() + 3;
if(aType == TagType.variable) start = m.start() + 2;
map.put(m.start(), new Tag(aType, aContents.substring(start, m.end() - 2).trim()));
}
}
static String readFile(String path, Charset encoding) throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
}
Give the template file path at the command line - you need java 7 or higher to open the file, or you can just rewrite the readFile - method. You can produce a json or java 'schema' by changing the format at the top of the class. The 'schema' gets written to stdout, you can copy it from there and paste it into where you need it. Hope this helps. Ah! This doesn't support partials or set delimiters, but if you get round to writing support ping it to me as I might want it :)

Categories

Resources