I want to run SQL query in Java and the result of the query is in xml. The query result is as follows -
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Rows>
<Unique_id>6124</Unique_id>
<DoorNo>12</DoorNo>
<StreetNo>1</StreetNo>
<SiteNo>84904</SiteNo>
</Rows>
<Rows>
<Unique_id>6125</Unique_id>
<DoorNo>12</DoorNo>
<StreetNo>2</StreetNo>
<SiteNo>84904</SiteNo>
</Rows>
</Root>
Now I want to export the above xml into an external file called QueryResult.xml using java.
I have tried using the below java script but unable to save the file.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con=DriverManager.getConnection("jdbc:sqlserver://sqldatabase:1009;
databaseName=DatabaseName;user=UserName;password=1234");
PreparedStatement ps=con.prepareStatement(QueryName);
ResultSet rs=ps.executeQuery();
SQLXML xmlVal1= rs.getSQLXML(1);
String val = xmlVal1.getString();
try (PrintWriter out = new PrintWriter(new File("Output.xml"))) {
out.println(val);
}
Query Name:
select Distinct Unique_id, DoorNo, StreetNo, Siteno from Table Name where
Unqiue_id IN ( '6124','6125') FOR XML RAW ('Rows'), ROOT ('Root'), ELEMENTS XSINIL;
SQLXML xmlVal= rs.getSQLXML(1);
String val = xmlVal.getString();
try (PrintWriter out = new PrintWriter("out.xml")) {
out.println(val);
}
Here is the Oracle Tutorial with code examples.
Regarding your code,
1. you forgot to make next() on result set;
2. you don't need SQLXML here at all.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con=DriverManager.getConnection("jdbc:sqlserver://sqldatabase:1009;
databaseName=DatabaseName;user=UserName;password=1234");
PreparedStatement ps=con.prepareStatement(QueryName);
ResultSet rs=ps.executeQuery();
rs.next();
String val = rs.getString(1);
try (PrintWriter out = new PrintWriter(new File("Output.xml"))) {
out.println(val);
}
I know it's a bit silly to load a js into VBA, but I need to load the libphonenumber library by Google to perform an analysis of a big bunch of phone numbers.
I tried to adapt the following code borrowed from here, but the compiled library is to big to be inserted into the Vba code.
Is there any way to load the .js library from a file instead?
Thanks!
Function encodeURL(str As String)
Dim ScriptEngine As ScriptControl
Set ScriptEngine = New ScriptControl
ScriptEngine.Language = "JScript"
ScriptEngine.AddCode "function encode(str) {return encodeURIComponent(str);}"
Dim encoded As String
encoded = ScriptEngine.Run("encode", str)
encodeURL = encoded
End Function
UPDATE.
This should be a working code, but for some reason doesn't works:
Function loabdjs(x As String)
Dim fso As Scripting.FileSystemObject
Set fso = New Scripting.FileSystemObject
Dim script As String
Dim fs As Scripting.TextStream
''' CODE : "function encode(str) {return encodeURIComponent(str);}"
Set fs = fso.OpenTextFile("test.js", ForReading, False)
MsgBox ("Never reached this point")
script = fs.ReadAll
fs.Close
Dim ScriptEngine As ScriptControl
Set ScriptEngine = New ScriptControl
Dim output As String
ScriptEngine.Language = "JScript"
ScriptEngine.AddCode script
output = ScriptEngine.Run("encode", x)
loadjs = output
End Function
Any ideas?
Read the library from the filesystem into a string:
Dim fso As Scripting.FileSystemObject
Set fso = New Scripting.FileSystemObject
Dim fs As Scripting.TextStream
Set fs = fso.OpenTextFile( "libphonenumber.js", ForReading, False )
Dim script As String
script = fs.ReadAll
fs.Close()
scriptEngine.AddCode script
may be this:
Function loabdjs(x As String)
...
...
loadjs = output
End Function
I know this question is old but for anyone looking for an answer, this is a working example
Sub loadFile()
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
Dim fs, f, ts, script
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile("C:\test.js")
Set ts = f.OpenAsTextStream(ForReading, TristateUseDefault)
script = ts.ReadAll
Debug.Print script
ts.Close
End Sub
I am facing issue with alerting Database value fetching in code behind C# and alerting them at client side. Issue is for string value.
E.g - Suppose any user has set their password as integer, then the code is easily alerting the value, but if the password is string then it's not alerting any thing. Even it not alerting as 'undefined', while value is there with variable.
See the below example
Code Behind C#
public string strPassword = string.Empty;
public string strEmailPassword = string.Empty;
var objData = UserBusiness.GetUserByID(strUserID);
if (objData != null)
{
strPassword = objData.Password;
strEmailPassword = objData.EmailPwd;
}
At JavaScript
$(document).ready(function () {
var strPwd = <%= strPassword %> ;
$('#<%= txtLoginPassword.ClientID%>').val(strPwd);
var strEmailPwd = <%= strEmailPassword %> ;
$('#<%= txtEmailPwd.ClientID%>').val(strEmailPwd);
});
Change your JavaScript code like this.
$(document).ready(function () {
var strPwd = '<%= strPassword %>' ;
$('#<%= txtLoginPassword.ClientID%>').val(strPwd);
var strEmailPwd = "<%= strEmailPassword %>" ;
$('#<%= txtEmailPwd.ClientID%>').val(strEmailPwd);
});
Reason: Strings must be place inside quotes ' or " and integers doesn't need quotes
I have a JSP page, where an editor (ACE editor) is based on a DIV tag.
1. User upload a file (ex: my.txt)
2. This file is saved in the servlet (WEB-INF/my.txt)
Now, I want to open this file, copy it's contents to a variable in Java Script and populate the DIV tag.
How do I do this?
Based on an answer below, I've understood that once I get the contents of the file I can populate my DIV tag by using
var MyDiv1 = document.getElementById('DIV1');
MyDiv1.innerHTML = yourFileContent;
This solves the second part of the problem, now how to I open that file and copy its contents to a var in JS?
====================================EDIT==========================================
From the answers below, I've done the following steps
Step1: Getting the file contents, I take 4 input files so I've included a file counter to identify which file is being uploaded and when the 4th inpiut file is uploaded its contents are being stored to a string variable.
Servlet.java
response.setContentType("text/html");
String LINE = "<br>";
String filename = "/WEB-INF/myfile.txt";
fileTxt = "";
ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream(filename);
if (is != null)
{
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
PrintWriter writer = response.getWriter();
String text = "";
while ((text = reader.readLine()) != null) {
fileTxt = text + LINE;
writer.print(fileTxt);
HttpSession session = request.getSession(true);
session.setAttribute("FileText", "fileTxt");
}
}
Step2 : Submitting the forms for upload and right after submitting accessing the variable to populate ,
my.jsp
document.myform.submit();
var name = '<%= session.getAttribute("FileText") %>';
var div = document.getElementById("editor");
div.innerHTML = name;
PS: This still displays a null value, working on it and waiting fr answers.
I'm currently using .resx files to manage my server side resources for .NET.
the application that I am dealing with also allows developers to plugin JavaScript into various event handlers for client side validation, etc.. What is the best way for me to localize my JavaScript messages and strings?
Ideally, I would like to store the strings in the .resx files to keep them with the rest of the localized resources.
I'm open to suggestions.
A basic JavaScript object is an associative array, so it can easily be used to store key/value pairs. So using JSON, you could create an object for each string to be localized like this:
var localizedStrings={
confirmMessage:{
'en/US':'Are you sure?',
'fr/FR':'Est-ce que vous ĂȘtes certain?',
...
},
...
}
Then you could get the locale version of each string like this:
var locale='en/US';
var confirm=localizedStrings['confirmMessage'][locale];
Inspired by SproutCore You can set properties of
strings:
'Hello'.fr = 'Bonjour';
'Hello'.es = 'Hola';
and then simply spit out the proper localization based on your locale:
var locale = 'en';
alert( message[locale] );
After Googling a lot and not satisfied with the majority of solutions presented, I have just found an amazing/generic solution that uses T4 templates. The complete post by Jochen van Wylick you can read here:
Using T4 for localizing JavaScript resources based on .resx files
Main advantages are:
Having only 1 place where resources are managed ( namely the .resx
files )
Support for multiple cultures
Leverage IntelliSense - allow for code completion
Disadvantages:
The shortcomings of this solution are of course that the size of the
.js file might become quite large. However, since it's cached by the
browser, we don't consider this a problem for our application. However
- this caching can also result in the browser not finding the resource called from code.
How this works?
Basically he defined a T4 template that points to your .resx files. With some C# code he traverses each and every resource string and add it to JavaScript pure key value properties that then are output in a single JavaScript file called Resources.js (you can tweak the names if you wish).
T4 template [ change accordingly to point to your .resx files location ]
<## template language="C#" debug="false" hostspecific="true"#>
<## assembly name="System.Windows.Forms" #>
<## import namespace="System.Resources" #>
<## import namespace="System.Collections" #>
<## import namespace="System.IO" #>
<## output extension=".js"#>
<#
var path = Path.GetDirectoryName(Host.TemplateFile) + "/../App_GlobalResources/";
var resourceNames = new string[1]
{
"Common"
};
#>
/**
* Resources
* ---------
* This file is auto-generated by a tool
* 2012 Jochen van Wylick
**/
var Resources = {
<# foreach (var name in resourceNames) { #>
<#=name #>: {},
<# } #>
};
<# foreach (var name in resourceNames) {
var nlFile = Host.ResolvePath(path + name + ".nl.resx" );
var enFile = Host.ResolvePath(path + name + ".resx" );
ResXResourceSet nlResxSet = new ResXResourceSet(nlFile);
ResXResourceSet enResxSet = new ResXResourceSet(enFile);
#>
<# foreach (DictionaryEntry item in nlResxSet) { #>
Resources.<#=name#>.<#=item.Key.ToString()#> = {
'nl-NL': '<#= ("" + item.Value).Replace("\r\n", string.Empty).Replace("'","\\'")#>',
'en-GB': '<#= ("" + enResxSet.GetString(item.Key.ToString())).Replace("\r\n", string.Empty).Replace("'","\\'")#>'
};
<# } #>
<# } #>
In the Form/View side
To have the correct translation picked up, add this in your master if you're using WebForms:
<script type="text/javascript">
var locale = '<%= System.Threading.Thread.CurrentThread.CurrentCulture.Name %>';
</script>
<script type="text/javascript" src="/Scripts/Resources.js"></script>
If you're using ASP.NET MVC (like me), you can do this:
<script type="text/javascript">
// Setting Locale that will be used by JavaScript translations
var locale = $("meta[name='accept-language']").attr("content");
</script>
<script type="text/javascript" src="/Scripts/Resources.js"></script>
The MetaAcceptLanguage helper I got from this awesome post by Scott Hanselman:
Globalization, Internationalization and Localization in ASP.NET MVC 3, JavaScript and jQuery - Part 1
public static IHtmlString MetaAcceptLanguage<T>(this HtmlHelper<T> html)
{
var acceptLanguage =
HttpUtility.HtmlAttributeEncode(
Thread.CurrentThread.CurrentUICulture.ToString());
return new HtmlString(
String.Format("<meta name=\"{0}\" content=\"{1}\">", "accept-language",
acceptLanguage));
}
Use it
var msg = Resources.Common.Greeting[locale];
alert(msg);
With a satellite assembly (instead of a resx file) you can enumerate all strings on the server, where you know the language, thus generating a Javascript object with only the strings for the correct language.
Something like this works for us (VB.NET code):
Dim rm As New ResourceManager([resource name], [your assembly])
Dim rs As ResourceSet =
rm.GetResourceSet(Thread.CurrentThread.CurrentCulture, True, True)
For Each kvp As DictionaryEntry In rs
[Write out kvp.Key and kvp.Value]
Next
However, we haven't found a way to do this for .resx files yet, sadly.
JSGettext does an excellent job -- dynamic loading of GNU Gettext .po files using pretty much any language on the backend. Google for "Dynamic Javascript localization with Gettext and PHP" to find a walkthrough for JSGettext with PHP (I'd post the link, but this silly site won't let me, sigh...)
Edit: this should be the link
I would use an object/array notation:
var phrases={};
phrases['fatalError'] ='On no!';
Then you can just swap the JS file, or use an Ajax call to redefine your phrase list.
There's a library for localizing JavaScript applications:
https://github.com/wikimedia/jquery.i18n
It can do parameter replacement, supports gender (clever he/she handling), number (clever plural handling, including languages that have more than one plural form), and custom grammar rules that some languages need.
The strings are stored in JSON files.
The only requirement is jQuery.
I did the following to localize JavaScript for a mobile app running HTML5:
1.Created a set of resource files for each language calling them like "en.js" for English. Each contained the different strings the app as follows:
var localString = {
appName: "your app name",
message1: "blah blah"
};
2.Used Lazyload to load the proper resource file based on the locale language of the app: https://github.com/rgrove/lazyload
3.Pass the language code via a Query String (As I am launching the html file from Android using PhoneGap)
4.Then I wrote the following code to load dynamically the proper resource file:
var lang = getQueryString("language");
localization(lang);
function localization(languageCode) {
try {
var defaultLang = "en";
var resourcesFolder = "values/";
if(!languageCode || languageCode.length == 0)
languageCode = defaultLang;
// var LOCALIZATION = null;
LazyLoad.js(resourcesFolder + languageCode + ".js", function() {
if( typeof LOCALIZATION == 'undefined') {
LazyLoad.js(resourcesFolder + defaultLang + ".js", function() {
for(var propertyName in LOCALIZATION) {
$("#" + propertyName).html(LOCALIZATION[propertyName]);
}
});
} else {
for(var propertyName in LOCALIZATION) {
$("#" + propertyName).html(LOCALIZATION[propertyName]);
}
}
});
} catch (e) {
errorEvent(e);
}
}
function getQueryString(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
5.From the html file I refer to the strings as follows:
span id="appName"
Well, I think that you can consider this. English-Spanish example:
Write 2 Js Scripts, like that:
en-GB.js
lang = {
date_message: 'The start date is incorrect',
...
};
es-ES.js
lang = {
date_message: 'Fecha de inicio incorrecta',
...
};
Server side - code behind:
Protected Overrides Sub InitializeCulture()
Dim sLang As String
sLang = "es-ES"
Me.Culture = sLang
Me.UICulture = sLang
Page.ClientScript.RegisterClientScriptInclude(sLang & ".js", "../Scripts/" & sLang & ".js")
MyBase.InitializeCulture()
End Sub
Where sLang could be "en-GB", you know, depending on current user's selection ...
Javascript calls:
alert (lang.date_message);
And it works, very easy, I think.
Expanding on diodeus.myopenid.com's answer: Have your code write out a file containing a JS array with all the required strings, then load the appropriate file/script before the other JS code.
The MSDN way of doing it, basically is:
You create a separate script file for each supported language and culture. In each script file, you include an object in JSON format that contains the localized resources values for that language and culture.
I can't tell you the best solution for your question, but IMHO this is the worst way of doing it. At least now you know how NOT to do it.
We use MVC and have simply created a controller action to return a localized string. We maintain the user's culture in session and set the thread culture before any call to retrieve a language string, AJAX or otherwise. This means we always return a localized string.
I'll admit, it isn't the most efficient method but getting a localised string in javascript is seldom required as most localization is done in our partial views.
Global.asax.cs
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)
{
// Set the current thread's culture
var culture = (CultureInfo)Session["CultureInfo"];
if (culture != null)
{
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
}
}
Controller Action
public string GetString(string key)
{
return Language.ResourceManager.GetString(key);
}
Javascript
/*
Retrieve a localized language string given a lookup key.
Example use:
var str = language.getString('MyString');
*/
var language = new function () {
this.getString = function (key) {
var retVal = '';
$.ajax({
url: rootUrl + 'Language/GetString?key=' + key,
async: false,
success: function (results) {
retVal = results;
}
});
return retVal;
}
};