I am trying to understand java program written by someone else and I do not know java. I have written a short method fro dumping attributes of request object.
public void dumpRequest(HttpServletRequest request) {
String[] attrNames = new String[100]; // hard coded
int ani = 0;
Enumeration rns = request.getAttributeNames();
while (rns.hasMoreElements()) {
out.println("attribute name: " + rns.nextElement());
attrNames[ani] = rns.nextElement().toString();
ani = ani + 1;
}
out.println("" + ani + " atributes");
String cn;
for (int n = 0; n < ani; n++) {
cn = attrNames[n];
out.println("** " + cn + " - " + request.getAttribute(cn));
}
out.println("++++++++++++++++++++++");
}
To my horror, I have realised that NetBeans variables tab shows twice more attributes on the request object compared to my code output.
The enumeration seems to be documented here:
https://tomcat.apache.org/tomcat-4.1-doc/catalina/docs/api/org/apache/catalina/util/Enumerator.html
What am I doing wrong?
You call nextElement method twice in this block:
while (rns.hasMoreElements()) {
out.println("attribute name: " + rns.nextElement());
attrNames[ani] = rns.nextElement().toString();
ani = ani + 1;
}
you should call nextElement once. Put it in variable and then use that variable.
Related
public String toString() {
return " Recipient:"+ this.toString(this.getRecipient()) +
" CC:"+ this.toString
(
if(this.getCC()==null)
{
getCC() = "";
}
) +
" Subject:"+this.getSubject() +
" Body:"+ this.getBody() +
" files:"+ this.getFiles();
}
I am having this error in:
getCC() = ""; <--------- Here.
Do you know why is this happening?
Thanks in advance
You can't assign a value to the return of a method. You also can't place an expression inside a method which takes no arguments. What you appear to have intended was to use a variable.
String cc = getCC();
if (cc == null) cc = "";
return ... " CC:" + cc + ...
I get java.lang.OutOfMemoryError during String concatenation. Can somebody help me get rid of this? Below is how my code looks. This whole if blokc is run under a loop and when it is processing string concatenation for "str", it throws OutofemoryError. Any help on this much appreciated.
for (long j = mincollectiontime; j <= maxcollectiontime; j = j
+ timeintreval) {
query = "select count(*) table1";
ResultSet result2 = VerticaDBHandler.executequery(con2, query);
System.out.println("Query:- " + query);
String str = "";
if (result2.isBeforeFirst()) {
if (mysqlconn == null) {
mysqlconn = DatabaseHandler.openDB();
}
while (result2.next()) {
int isgap = Integer.parseInt(result2.getString(1));
if (isgap == 0) {
Date startime = EpochTimeHandler.epochToTimeStamp(j);
Date endtime = EpochTimeHandler.epochToTimeStamp(j
+ timeintreval);
str = "NO DATA BETWEEN " + startime + " --- " + endtime
+ " forInstanceId: " + instanceid
+ " --InstanceName: " + instanceName + " in "
+ perfTables[i];
DatabaseHandler.LoadDB_dataGaps(mysqlconn,
perfTables[i], instanceid, instanceName,
VirtType, BelongstoDataCenter,
startime.toString(), endtime.toString(), str);
System.out.println(str);
str = "";
} else {
System.out.println("No Gap Seen");
}
}
}
}
The exception.
Exception thrown:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.LinkedHashMap.newNode(LinkedHashMap.java:256)
at java.util.HashMap.putVal(HashMap.java:630)
at java.util.HashMap.put(HashMap.java:611)
at sun.util.resources.OpenListResourceBundle.loadLookup(OpenListResourceBundle.java:146)
at sun.util.resources.OpenListResourceBundle.loadLookupTablesIfNecessary(OpenListResourceBundle.java:128)
at sun.util.resources.OpenListResourceBundle.handleKeySet(OpenListResourceBundle.java:96)
at java.util.ResourceBundle.containsKey(ResourceBundle.java:1807)
at sun.util.locale.provider.LocaleResources.getTimeZoneNames(LocaleResources.java:262)
at sun.util.locale.provider.TimeZoneNameProviderImpl.getDisplayNameArray(TimeZoneNameProviderImpl.java:122)
at sun.util.locale.provider.TimeZoneNameProviderImpl.getDisplayName(TimeZoneNameProviderImpl.java:98)
at sun.util.locale.provider.TimeZoneNameUtility$TimeZoneNameGetter.getName(TimeZoneNameUtility.java:325)
at sun.util.locale.provider.TimeZoneNameUtility$TimeZoneNameGetter.getObject(TimeZoneNameUtility.java:281)
at sun.util.locale.provider.TimeZoneNameUtility$TimeZoneNameGetter.getObject(TimeZoneNameUtility.java:267)
at sun.util.locale.provider.LocaleServiceProviderPool.getLocalizedObjectImpl(LocaleServiceProviderPool.java:281)
at sun.util.locale.provider.LocaleServiceProviderPool.getLocalizedObject(LocaleServiceProviderPool.java:265)
at sun.util.locale.provider.TimeZoneNameUtility.retrieveDisplayName(TimeZoneNameUtility.java:135)
at java.util.TimeZone.getDisplayName(TimeZone.java:400)
at java.util.Date.toString(Date.java:1045)
at java.lang.String.valueOf(String.java:2982)
at java.lang.StringBuilder.append(StringBuilder.java:131)
at com.test.perf.testpgm.main(testpgm.java:112)
Seems like here is the Problem.
for (long j = mincollectiontime; j <= maxcollectiontime; j = j + timeintreval)
You are definitely ruling out the maximum lengh and giving a call in the function. Please post more code so that, specific problem can be noticed.
May be this issue is not related to string concationation, I think this issue with Heap size. Once increase the heap size of your IDE and run the program.
I'm working on a project that involves 2 separate db to generate the report. The result of one is passed into the other query and a final report is generated. Now, i wan to sort the final report but having issues with it. Java constructor for "java.util.Arrays" with arguments "" not found.
var fist = new java.util.Arrays();
var list = new java.util.ArrayList();
var gist = new java.util.ArrayList();
var arr = '';
var dbConn = DatabaseConnectionFactory.createDatabaseConnection('Postgres connection');
var result3 = dbConn.executeCachedQuery(...)
while (result3.next()) {
var value1 = result3.getString(1);
var value2 = result3.getString(2);
var dbConn3 = DatabaseConnectionFactory.createDatabaseConnection('Oracle connection'));
var result2 = dbConn3.executeCachedQuery("SELECT name FROM producer WHERE send = '" + value1 + "' AND code = '" + value2 + "' ORDER BY name")
while (result2.next()) {
var sending = result2.getString(1);
}
dbConn3.close();
if (sending != undefined) {
arr += gist.add(sending);
arr += gist.add(value1);
arr += gist.add(value2);
arr += gist.add(result3.getString(3));
fist.add(arr);
}
}
Arrays.sort(fist); //i'm thinking this should sort it before displaying it
while (fist.next()) {
xmlMs += "<tr>"
xmlMs += "<td>" + sending + "</td>";
xmlMs += "<td>" + value1 + "</td>";
xmlMs += "<td>" + value2 + "</td>";
xmlMs += "<td align='center'>" + result3.getString(3) + "</td>";
xmlMs += "</tr>";
}
Well yes, your compiler is telling you that var fist = new java.util.Arrays(); is invalid, java.util.Arrays doesn't provide a public no-args constructor. Did you by chance mean ArrayList instead of Arrays?
Arrays doesn't have a constructor defined in the source code, so new Arrays(); causes the compiler to scream at you.
If you want an array of something you use
type[] varname = new type[size];
Note that the [] is what makes it an Array.
Ex:
int[] x = new int[5];
That will hold an array of 5 ints.
I'm writing a special permission forms program using MySQL, Javascript, and HTML code, which both respond to. I'm doing all of this using singleton pattern access and facade code(s) in java, and a services code, which responds to the singleton pattern codes.
I'm trying To retrieve a form (AKA 1 Result) by the variables, courseDept & courseNm.
This is a snippet of code I'm using to do all this:
FormDataFacade.java code snippet:
#Path("/specialPermissions/sp")
#GET
#Produces("text/plain")
public Response getSpecialPermissionFormByDeptAndRoomNm(#QueryParam("courseDept") String theDept, #QueryParam("courseNm") String theNm)
throws NamingException, SQLException, ClassNotFoundException
{
//Referenciation to FormDataFacade class.
FormDataFacade iFacade = FormDataFacade.getInstance();
int intNm = 0;
try {
intNm = Integer.parseInt(theNm);
}catch (NumberFormatException FAIL) {
intNm = 1;
}
//Aiming for forms with matching departments & room numbers by calling FormDataFacade
//method, getSpecialPermissionFormByDeptAndRoomNm.
SpecialPermissionForms[] orgaForm = iFacade.getSpecialPermissionFormByDeptAndRoomNm(theDept, intNm);
//Json String Representation...
if (orgaForm != null)
{
Gson neoArcadia = new Gson();
String result = neoArcadia.toJson(orgaForm);
//Json String added to response message body...
ResponseBuilder rb = Response.ok(result, MediaType.TEXT_PLAIN);
rb.status(200); //HTTP Status code has been set!
return rb.build(); //Creating & Returning Response.
}
else
{ //In case of finding no form data for the procedure...
return Response.status(700).build();
}
}
FormDataServices.java code snippet:
public SpecialPermissionForms[] getSpecialPermissionFormByDeptAndRoomNm(String theDept, int theNm) throws SQLException, ClassNotFoundException
{
Connection con = zeon.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT formID, studentName, courseDept, courseNm, semester, year, reasonCode FROM spforms WHERE courseDept = ? & courseNm = ?");
pstmt.setString(1, theDept);
pstmt.setInt(2, theNm);
ResultSet rs = pstmt.executeQuery();
SpecialPermissionForms[] neoForm = new SpecialPermissionForms[50];
int current = 0;
while (rs.next())
{
int formID3 = rs.getInt("formID");
String studentName3 = rs.getString("studentName");
String courseDept3 = rs.getString("courseDept");
String courseNm3 = rs.getString("courseNm");
String semester3 = rs.getString("semester");
int year3 = rs.getInt("year");
String reasonCode3 = rs.getString("reasonCode");
SpecialPermissionForms neo = new SpecialPermissionForms(formID3, studentName3, courseDept3, courseNm3, semester3, year3, reasonCode3);
neoForm[current] = neo;
current++;
}
if (current > 0)
{
neoForm = Arrays.copyOf(neoForm, current);
return neoForm;
}
else
{
return null;
}
}
Forms.html code snippet which both pieces of java code respond to:
$("#btnOneName").click(function() {
alert("clicked");
var inputId1=document.getElementById("t_specialFormCourseDept").value;
var inputId2=document.getElementById("t_specialFormCourseNm").value;
var theData = "courseDept=" + inputId1 + "&" + "courseNm=" + inputId2;
alert("Sending: " + theData);
var theUrl = "http://localhost:8080/onlineforms/services/enrollment/specialPermissions/sp?courseDept=&courseNm="+ theData;
$.ajax( {
url: theUrl,
type: "GET",
dataType: "text",
success: function(result) {
alert("success");
var neoForm = JSON.parse(result);
alert(neoForm);
var output="<h3>Current Form Lists:</h3>";
output += "<ul>";
for (var current = 0; current < neoForm.length; current++)
{
output += "<li>" + neoForm[current].formID + ": " + neoForm[current].studentName + " (" + neoForm[current].courseDept + " - " + neoForm[current].courseNm + ") " +
" (" + neoForm[current].semester + " - " + neoForm[current].year + ") " + " - " + neoForm[current].reasonCode + "</li>";
}
output += "</ul>";
alert(output);
$("#p_retrieveOneName").html(output);
},
error:function(xhr) {
alert("error");
$("#p_retrieveOneName").html("Error:"+xhr.status+" "+xhr.statusText);}
} );
});
});
Now, when I go test this code in my webservice after successfully compiling it, it does work, however it retrieves everything, including the specific results I was searching for - I only want to return the results I have specifically searched for and nothing else. What exactly am I doing wrong here in these snippets of code?
Any suggestions or steps in the right direction are highly welcome.
im currently having a problem in getting the headers title of a table to make a validation, it work great until column 6, because when it goes to next one which isn't visible the .getText() is blank. I no the xpath is correct.
public void getAndSaveDataOfTable (final String tabla) throws FileNotFoundException{
WebElement element = driver.findElement(By.xpath(tabla));
List<WebElement> elements = element.findElements(By.xpath("th"));
Assert.assertTrue(elements.size() > 1);
int cantelements = elements.size();
for (int i = 1; i <= cantelements; i++) {
String data = driver.findElement(
By.xpath(".//div[#class='ui-datatable-scrollable-header-box']//table/thead/tr/th["+ i + "]/span[1]")).getText();
System.out.println("EL nombre del encabezado " + i + " " + data);
datosFila.put(i, data);
}
So between column 7and 20 I can't get the text of the header.
If you are going to be using the JavascriptExecutor several times (you said your issue is on multiple columns 7-20) I would suggest you can optimize by running JS only once and then iterating through in Java, rather than running JS again for every operation. The JavascriptExecutor is slow, and you'll save whole seconds on the total test time by avoiding even 12+ extra JS executions.
// JavaScript to get text from tHeads
String getTheadTexts =
"var tHeads = []; " +
"for (i = o; i < 20; i++) { " +
"var cssSelector = 'div.ui-datatable-scrollable-header-box table thead tr th' + i + ' span:nth-of-type(1)'; " +
"var elem = document.querySelector(cssSelector); " +
"var elemText = ''; " +
"if ((elem.textContent) && (typeof (elem.textContent) != 'undefined')) { " +
"tHeads.push(elem.textContent); " +
"} else { " +
"tHeads.push(elem.innerText); " +
"} " +
"} " +
"return tHeads; ";
// Execute the JS to populate a List
List<String> tHeadTexts = (ArrayList<String>) js.executeScript(getTheadTexts);
// Do some operation on each List item
int i = 0;
for (String data: tHeadTexts){
System.out.println("EL nombre del encabezado " + i + " " + data);
datosFila.put(i, data);
i++;
}
I ran into what sounds like what you're running into. Take a look at my post on
WebElement getText() is an empty string in Firefox if element is not physically visible on the screen
I ended up solving it by using a little bit of JavaScript to columns "into view". Hopefully this helps you out.
private void scrollToElement(WebElement element){
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
}