I need to convert the following Javascript pseudo-class to Java code. I'm googling information about XMLHttpRequest (or equivalent) in Java and i'm confused:
function conexionSOAP(url, uri) {
// Constructor
this.uri = 'urn:' + uri;
this.url = url;
this.cabeceraXML = '<?xml version="1.0" encoding="UTF-8"?>'
+ '<soap:Envelope '
+ 'soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" '
+ 'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" '
+ 'xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" '
+ 'xmlns:xsd="http://www.w3.org/2001/XMLSchema" '
+ 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
+ '<soap:Body>' + '<';
this.sessionKey = null;
// Metodos
var self = this;
(...)
this.llamar_metodo = function(metodo, argumentos, http, loadCallback,
errorCallback) {
// Función que transforma las llamadas a métodos en requests XML
var XMLmsg = self.cabeceraXML + metodo + ' xmlns="' + self.uri + '"';
if (argumentos == null) {
XMLmsg = XMLmsg + ' xsi:nil="true" />';
} else {
var i, I;
XMLmsg = XMLmsg + '>';
for (i = 0, I = argumentos.length; i < I; i++) {
var tipo = typeof argumentos[i];
if (tipo == "number") {
if (argumentos[i] % 1) {
tipo = "float";
} else {
tipo = "int";
}
}
XMLmsg = XMLmsg + '<c-gensym' + (2 * (i + 2))
+ ' xsi:type="xsd:' + tipo + '">' + argumentos[i]
+ '</c-gensym' + (2 * (i + 2)) + '>';
}
XMLmsg = XMLmsg + '</' + metodo + '>';
}
XMLmsg = XMLmsg + '</soap:Body>' + '</soap:Envelope>';
// Una vez preparado el XML preparamos el HttpRequest
http.open("POST", self.url, true);
http.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
http.setRequestHeader('Origin', 'ParkingClientJS');
http
.setRequestHeader('SOAPAction', '"' + self.uri + '#' + metodo
+ '"');
http.timeout = 15000;
http.onload = loadCallback;
http.onerror = errorCallback;
http.ontimeout = errorCallback;
http.send(XMLmsg);
};
function readyState(metodo, http) {
var respuesta = null;
if (http.readyState == 4) {
if (http.status == 200) {
var responseTag = http.responseXML.getElementsByTagName(metodo
+ 'Response');
if (responseTag) {
if (responseTag[0].childNodes.length <= 1) {
respuesta = responseTag[0].childNodes[0].textContent;
} else {
var i, I;
respuesta = [];
for (i = 0, I = responseTag[0].childNodes.length; i < I; i++) {
respuesta
.push(responseTag[0].childNodes[i].textContent);
}
}
}
} else {
respuesta = "--EE--";
}
}
return respuesta;
}
function error_timeOut(http) {
var respuesta = "--EE--";
http.abort();
return respuesta;
}
}
Specifically, How must I implement the method llamar_metodo? Notice that the XMLHttpRequest is passed to this method (http parameter) and the request must be async. There are auxiliar methods like this:
function(method, [param1, param2, ...], responseCallback){
var http = new XMLHttpRequest();
self.llamar_metodo(method, [ param1, param2, ... ], http, function() {
var response = readyState(metodo, http);
responseCallback(response)
}, function() {
var respuesta = error_timeOut(http);
responseCallback(response)
});
}
Finally, the implementation must be android-compatible.
Thanks for your help I'm really confused with the Http stuff.
Sorry for my english
Related
I've written a method to read json and generate data based on different combination.
For example lets say I've 3 json parameter and i wanna pass different permutation of json data.
So combination would be :
1 - F,T,T
2 - T,F,T
3 - T,T,F
4 - T,T,T
I used negativeCaseList to get false data and postitiveCaseList to get true data.
My task is to optimize this code to make it more readable.
Any suggestion is highly appreciated.
for (int i = 0; i < negativeCaseList.size(); i++) {
if (!negativeCaseList.get(i).isEmpty()) {
ArrayList<?> negativeDataAsList = (ArrayList<?>) negativeCaseList.get(i);
for (int j = 0; j < negativeDataAsList.size(); j++) {
ParameterData negativeParameterData = (ParameterData) negativeDataAsList.get(j);
for (int k = 0; k < postitiveCaseList.size(); k++) {
ArrayList<?> positiveDataAsList = (ArrayList<?>) postitiveCaseList.get(k);
for (int l = 0; l < positiveDataAsList.size(); l++) {
ParameterData positiveParameterData = (ParameterData) positiveDataAsList.get(l);
if (Utility.validateString(negativeParameterData.getParameterName())) {
if (!negativeParameterData.getParameterName().equals(positiveParameterData.getParameterName())) {
if (!positiveParameterData.parameterType.startsWith("System")) {
dictionary.put(positiveParameterData.getParameterName(), positiveParameterData.getValue());
} else {
dictionary.put(positiveParameterData.getParameterName(), positiveParameterData.getValue());
}
paramName = positiveParameterData.getParameterName() + "," + paramName;
if (Utility.hasHTMLTags(positiveParameterData.getValue().toString())) {
paramValue = ("<xmp style='padding:0px;margin:0px;white-space:nowrap'>" + positiveParameterData.getValue().toString() + "</xmp>") + "," + paramValue;
} else {
paramValue = positiveParameterData.getValue() + "," + paramValue;
}
} else {
dictionary.put(negativeParameterData.getParameterName(), negativeParameterData.getValue());
paramName = negativeParameterData.getParameterName() + "," + paramName;
if (Utility.hasHTMLTags(negativeParameterData.getValue().toString())) {
paramValue = ("<xmp style='padding:0px;margin:0px;white-space:nowrap'>" + negativeParameterData.getValue().toString() + "</xmp>") + "," + paramValue;
} else {
paramValue = negativeParameterData.getValue() + "," + paramValue;
}
}
} else {
listofParameter = negativeParameterData.getValue();
if (Utility.hasHTMLTags(negativeParameterData.getValue().toString())) {
paramValue = ("<xmp style='padding:0px;margin:0px;white-space:nowrap'>" + negativeParameterData.getValue().toString() + "</xmp>") + "," + paramValue;
} else {
paramValue = negativeParameterData.getValue() + "," + paramValue;
}
}
}
}
//json ="";
if (!dictionary.isEmpty()) {
json = ParameterTransform.ObjectToString(dictionary);
} else {
json = ParameterTransform.ObjectToString(listofParameter);
}
preData.putAll(Utils.fillTestDetailsInPreData(requestRule));
if (requestRule.getiRegistrationNo()) {
JSONObject stringToJson = new JSONObject(json);
json = securityObject.buildMainJson("10401", "f41f9ac6-1090-4851-bc7a-4a2355dd10c4",
stringToJson);
}
jsons.add(json);
app_logs.info("Json " + jsons);
//reportData.add(json+"|"+paramName+"|"+paramValue);
if (Utility.hasHTMLTags(json)) {
reportData.add("<xmp style='padding:0px;margin:0px;white-space:nowrap'>" + json + "</xmp>");
} else {
reportData.add(json);
}
pName.add(paramName.toString());
pValue.add(paramValue.toString());
app_logs.info("data " + reportData);
//app_logs.info("pName : " + pName.toString());
//app_logs.info("pValue : " + pValue.toString());
paramName = "";
paramValue = "";
}
}
}
I have a string:
2 + 2 = ${2 + 2}
This is a ${"string"}
This is an object: ${JSON.stringify({a: "B"})}
This should be "<something>": ${{
abc: "def",
cba: {
arr: [
"<something>"
]
}
}.cba.arr[0]}
This should ${"${also work}"}
And after parsing it I should get something like that:
2 + 2 = 4
This is a string
This is an object: {"a":"B"}
This should be "<something>": <something>
This should ${also work}
So I need help implementing it in Java, I simply need to get what is between ${ and }.
I tried using a regular expression: \${(.+?)} but it fails when string inside contains }
So after a bit of testing, I've ended up with this:
ScriptEngine scriptEngine = new ScriptEngineManager(null).getEngineByName("JavaScript");
String str = "2 + 2 = ${2 + 2}\n" +
"This is a ${\"string\"}\n" +
"This is an object: ${JSON.stringify({a: \"B\"})}\n" +
"This should be \"F\": ${var test = {\n" +
" a : {\n" +
" c : \"F\"\n" +
" }\n" +
"};\n" +
"test.a.c\n" +
"}\n" +
"This should ${\"${also work}\"}"; // String to be parsed
StringBuffer result = new StringBuffer();
boolean dollarSign = false;
int bracketsOpen = 0;
int beginIndex = -1;
int lastEndIndex = 0;
char[] chars = str.toCharArray();
for(int i = 0; i < chars.length; i++) { // i is for index
char c = chars[i];
if(dollarSign) {
if(c == '{') {
if(beginIndex == -1) {
beginIndex = i + 1;
}
bracketsOpen++;
} else if(c == '}') {
if(bracketsOpen > 0) {
bracketsOpen--;
}
if(bracketsOpen <= 0) {
int endIndex = i;
String evalResult = ""; // evalResult is the replacement value
try {
evalResult = scriptEngine.eval(str.substring(beginIndex, endIndex)).toString(); // Using script engine as an example; str.substring(beginIndex, endIndex) is used to get string between ${ and }
} catch (ScriptException e) {
e.printStackTrace();
}
result.append(str.substring(lastEndIndex, beginIndex - 2));
result.append(evalResult);
lastEndIndex = endIndex + 1;
dollarSign = false;
beginIndex = -1;
bracketsOpen = 0;
}
} else {
dollarSign = false;
}
} else {
if(c == '$') {
dollarSign = true;
}
}
}
result.append(str.substring(lastEndIndex));
System.out.println(result.toString());
Good afternoon, I have a problem. When reading a property file, and passing it to an array, it looks like the array is repeated until you finish reading the document, as shown in the image
I'm supposed to read the properties from a txt file that contains them and pass the artist's name to an array of size 10.
Here the methods used by the program
/**
* Carga la información inicial del karaoke.
*/
private void cargarKaraoke() {
try {
Properties datos = new Properties();
FileInputStream in = new FileInputStream(RUTA_ARCHIVO);
datos.load(in);
in.close();
int numArtistas = Integer.parseInt(datos.getProperty("total.artistas"));
for(int i = 1; i <= numArtistas; i++) {
String nombre = datos.getProperty("artista" + i + ".nombre");
String categoria = datos.getProperty("artista" + i + ".categoria");
String imagen = datos.getProperty("artista" + i + ".imagen");
karaoke.agregarArtista(nombre, categoria, imagen);
int numCanciones = Integer.parseInt(datos.getProperty("artista"
+ i + ".total.canciones"));
for(int j = 1; j <= numCanciones; j++) {
String cancion = datos.getProperty("artista" + i + ".cancion"
+ j + ".nombre");
int duracion = Integer.parseInt(datos.getProperty("artista"
+ i + ".cancion" + j + ".duracion"));
String letra = datos.getProperty("artista" + i + ".cancion"
+ j + ".letra");
int dificultad = Integer.parseInt(datos.getProperty( "artista"
+ i + ".cancion" + j + ".dificultad"));
String genero = datos.getProperty("artista" + i + ".cancion"
+ j + ".genero");
String ruta = datos.getProperty("artista" + i + ".cancion"
+ j + ".ruta");
karaoke.agregarCancion(nombre, cancion, duracion, letra,
dificultad, genero, ruta);
}
}
}
catch(Exception e) {
JOptionPane.showMessageDialog(this, "No fue posible cargar la información "
+ "inicial del karaoke " + e.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void agregarArtista(String nombreArtista, String categoria, String imagen) {
for (int i = 0; i < artistas.length; i++) {
artistas[i] = new Artista(nombreArtista, categoria, imagen);
}
System.out.println(Arrays.toString(artistas));
}
public int agregarCancion(String nombre, int duracion, String letra, int dificultad,
String genero, String ruta) {
canciones.add(new Cancion(dificultad, duracion, genero, nombre, letra, ruta));
return 1;
}
But at the time of testing the results of the image appear.
Personally I think the problem is in the method to add artist, but I can not identify the problem.
Does anyone have any idea what's going on?
You can save all Artista obejcts in a List List<Artista> artistas = new ArrayList<Artista>() and change the Method agregarArtista to fill the list with the Artists Data:
public void agregarArtista(String nombreArtista, String categoria, String imagen) {
artistas.add(new Artista(nombreArtista, categoria, imagen));
System.out.println(artistas);
}
If You want only first 10 Artists then You could change the Method as below:
public void agregarArtista(String nombreArtista, String categoria, String imagen) {
if (artistas.size() < 10) {
artistas.add(new Artista(nombreArtista, categoria, imagen));
}
System.out.println(artistas);
}
If the result should be in a Array then You could convert List to an Array like this:
Artista[] artistasArray = artistas.toArray(new Artista[0]);
I have this java script code for ajax and I'm having trouble of get response.
xmlhttp.status always become 0. I have repeatCallHr Servlet and getting parameters from jsp page as follows.
function loadResults() {
var tt = document.getElementById("StartDate");
alert(tt);
if (xmlhttp) {
var query = "generateResults?name="
+ document.getElementById("name").value
+"&startDate="+document.getElementById("StartDate").value
+"&startTime="+document.getElementById("StartTime").value;
xmlhttp.open("GET", query, true);
xmlhttp.onreadystatechange = loadStallsResponse;
xmlhttp.send(null);
} else {
alert("Browser not supported!");
}}
function loadStallsResponse() {
alert("come here");
alert(xmlhttp.readyState);
if (xmlhttp.readyState == 4) {
alert("status is :"+xmlhttp.status);
if (xmlhttp.status == 200) {
resultList = [];
if (xmlhttp.responseText.indexOf("Error") == -1) {
alert("come to inside of status::")
console.log(xmlhttp.responseText);
stallList = $.parseJSON(xmlhttp.responseText);
populateStallData();
} else {
alert(xmlhttp.responseText);
}
} else {
alert("Error in loading salesman data");
}
}}
function populateStallData() {
var table = "<tr><th>Date</th><th>Time</th><th>Skill</th><th>Total Call</th><th>Unique Calls</th><th>Repeat Calls</th></tr>";
for (var i = 0; i < resultList.length; i++) {
table += "</td><td width='140'>"
+ resultList[i].date
+ "</td><td width='140'>"
+ resultList[i].time
+ "</td><td width='140'>"
+ resultList[i].skill
+ "</td><td width='140'><a style='color: -webkit-link; text-decoration: underline; cursor: auto;' href='http://"
+ resultList[i].totalCall
+ "</td><td width='140'>"
+ resultList[i].uniqueCall
+ "</td><td width='140'>"
+ resultList[i].repeatCall
+ "</td></tr>";
}
document.getElementById("ResultTable").innerHTML = table;}
In back end it takes more than 5 minutes to query the sql statement so that xmlhttp.status return as 0 (I guess, but i'm not sure). How can I delay the xmlhttp response time until I generate the results in back end?
I've created a servlet that use a class to convert the ResultSet of a mysql query in XML and return that XML to the browser. I can parse it correctly navigating with Javascript in the XML DOM but i can't count how much tags are in the document, because i obtain always "undefined" as value. Can anyone can help me to fix this ?
I post the XML response and the javascript source
function newXMLHttpRequest() {
var request = null;
var browser = navigator.userAgent.toUpperCase();
if(typeof(XMLHttpRequest) === "function" || typeof(XMLHttpRequest) === "object") {
request = new XMLHttpRequest();
} else if(window.ActiveXObject && browserUtente.indexOf("MSIE 4") < 0) {
if(browser.indexOf("MSIE 5") < 0) {
request = new ActiveXObject("Msxml2.XMLHTTP");
} else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return request;
}
function search_actor(){
var name = document.getElementById("actname").value;
if(name == "")
document.getElementById("risultati").innerHTML = "Inserisci un valore nel campo di ricerca";
else{
var req = newXMLHttpRequest();
req.onreadystatechange = function(){
if(req.readyState == 4){
if(req.status == 200){
getData(req.responseXML);
}
else if(req.status == 204){
delete_suggest();
}
}
}
}
req.open("POST", "GetActors", true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
var params = "name=" + escape(name);
req.send(params);
}
//debug function
function xml_to_string(xml_node)
{
if (xml_node.xml)
return xml_node.xml;
else if (XMLSerializer)
{
var xml_serializer = new XMLSerializer();
return xml_serializer.serializeToString(xml_node);
}
else
{
alert("ERROR: Extremely old browser");
return "";
}
}
function getData(responseXML){
delete_suggest();
var prec_risultati = document.getElementById("risultati");
// Se la risposta non è nulla
// Punto alla radice della risposta
var risposta = responseXML.getElementsByTagName('first_name');
var lenghtr = risposta.lenght;
document.getElementById("risultati").innerHTML = lenghtr;
if(lenghtr > 0){
for(x = 0; x < lenghtr; x++ ){
var valori = risposta[x].childNodes[0].nodeValue;
var row = document.createElement("tr");
var td = document.createElement("td");
td.appendChild(document.createTextNode(valori));
row.appendChild(td);
prec_risultati.appendChild(row);
}
}
}
function delete_suggest(){
document.getElementById("risultati").innerHTML = "";
}
The XML response is similar to
<results><row><actor_id>10</actor_id><first_name>CHRISTIAN</first_name><last_name>GABLE</last_name><last_update>2006-02-15 04:34:33.0</last_update></row><row><actor_id>21</actor_id><first_name>KIRSTEN</first_name><last_name>PALTROW</last_name><last_update>2006-02-15 04:34:33.0</last_update></row></results>
I want to count how much rows are in this XML and i've test
responseXML.getElementsByTagName("row").lenght
responseXML.getElementsByTagName("row")[0].lenght
responseXML.getElementsByTagName("row").childNodes.lenght
but all of these return me undefined. Someone can help me?
Hi I can't test it from here, but it seems that you have misspelled the length command.
It should be responseXML.getElementsByTagName("row").length;
For further details check out this example:
http://acsummer.wordpress.com/2007/12/30/quick-answers-count-the-number-of-child-elements-in-dom/