Building a JTree from a Database
Hi everyone,
I'm sort of new to Java. 3 months and still struggling.
My challenge is I would like to populate a tree from a Database. The problem is I do not know in advance how many children, children and children a node will have. There could be none or many.
For sure I'm able to build the root of the table and the involved folders both are coming from a database. The tables for this are like the following.
-root table-
root_id
root_name
-folders table-
folder_id
folder_name
Now each folder, and there are at least one can have children and the children could have children and so on. This is more or less infinit. Here is the children table
-folder_contents-
content_id
content_name
content_folder_id
parent_id
A record might look like this where the parent it is a record in the same table
1, 1.0, 1, null
2, 1.1, 1, 1
3, 1.2, 1, 2
4, 2.0, 1, null
3, 2.1, 1, 4
and so on
Some insight or code snippet would be highly appreciated and rewarded with Duke Dollars
Thanks Oscar
Hope this helps
http://forum.java.sun.com/thread.jsp?forum=57&thread=118604
http://forum.java.sun.com/thread.jsp?forum=57&thread=149431
http://forum.java.sun.com/thread.jsp?forum=57&thread=121264
Similar Messages
-
Hello everyone,
I have to build a JTree from a table data from database. The table structure is
(id,parent_id,name). In order to build the tree, I have to the following 2 loop searching for the parent_id
while (i<size){
while(j<size){
//find it's parent_id
j++;
i++;
It is too slow! Can anyone help me?
Thanks!
--tcYou just add children to whatever the parent node is for that object.DefaultMutableTreeNode root = new DefaultMutableTreeNode();
child1 = new DefaultMutableTreeNode();
root.add( child1 );
grandChild = new DefaultMutableTreeNode();
child1.add( grandChild );
greatGrandChild = new DefaultMutableTreeNode();
grandChild.add( greatGrandChild );Etc. -
Building jtree from database query
I am trying to build a JTREE from a database result-set. The resultset is listed below. I'm thinking I can somehow build a dynamic array of objects to build a TreePath, then use that to build the JTREE. Any input is appreciated.
ResultSet Output:
Here is how the results would be retrieved from the database (including the order of the output).
usr 1
local 2
sbin 2 file4
bin 3 file1
bin 3 file2
logs 3 file3
tmpdir 4
The first column is the directory name, the second column is the directory/file level/position, and the third column is the filename, if one exists.
So from above:
/usr/local/sbin has file "file4"
/usr/local/bin has files "file1" and "file2"
/usr/local/logs has file "file3" and directory "tmpdir"
How could I gather this information into an appropriate structure and create a JTREE from it.
Thanks.
-JimSo each line would:basically...
If I don't know the entire path of the parent (because I've read in a
line that only has the "one-up" parent name) .... However, when I
read the line from the database result-set, I don't know where "local" is.See... that's another problem with that data. Maybe you know cuz it's the last node if it's all in a proper order. In which case maybe you only need to hold the last parent node... Some recursive function would be useful.
If I were going to store the data, I would store either the name as a full path:
/usr
/usr/local
/usr/loca/bin
or
usr /
local /usr
bin /usr/local
If you have that, it might be easier to figure out without having to worry about what belongs where. -
hii all,
Does any one know hw to populate a Jtree from a database.pls hlep me with an example.
thanxHi there,
Im having exactly the same problem. If you find out, please let me know, and I will do the same for you.
Thanks
Simon -
Creating dynamically JTree from database values
Hi,
I have a local database with some node values. I receive these values from database as a String[].
short example:
String[] Values = {"mainNode","Processors","mainNode","RAM","mainNode","Monitors",
"Processors","INTEL","Processors","AMD","RAM","Kingston","RAM","GoodRAM",
"Kingston","400MHz","Kingston","433MHz"}First value is higher node, second is a child.
I'd like to produce dynamically JTree from Values[] like below:
MainNode
|----Processors
|----INTEL
|----AMD
|----RAM
|----Kingston
|----400MHz
|----433MHz
|----GoodRam
|----MonitorsI can't build up any working and fast solution :(
Can anyone help me ?
Please for any advices (samples) which will help me to apply it.
Dearly regards!This is a relatively straight forward task but it smacks of being homework so unless you post what you have already done you are unlikely to be given any code.
As a hint -
Go through the data creating a Map between the parent value and a child DefaultMutableTreeNode which contains as user object the child String.
When you extract a parent String from the data lookup the parent DefaultMutableTreeNode in the map and add the child DefaultMutableTreeNode to the parent DefaultMutableTreeNode.
Note - All the map is doing is giving you a quick way of looking up a DefaultMutableTreeNode given a parent name.
Note - that your tree will have problems if the same value appears in two or more branches! -
Application builder icon disappeared from database home page
i am wondering , is APPLICATION BUILDER ICON removed from database home page of all users or just mine. please i need help here..
Do you mean the icon display, or the ability to use the app identified by the icon?
(If just the display (it shows the empty box), there is a known problem with some images appearing broken. In which case, you can try forcing a reload form the server by adding a 'Shift' to your reload command (eg: use Shift-F5 in I.E. or Shift-Ctrl-R in Firefox) -
Populating JTree from database
Hi experts,
I need some feedbacks about the way i populate my JTree from database, Is there any better alternatives?
If yes, try explain it in detail.. I'm still new in Java.
Sample database table:
| node_id | name | parent | hasChild |
| 1 | garbage | null | 1 |
| 2 | item | 1 | 1 |
| 3 | mouse | 2 | 0 |
| 4 | board | 2 | 0 |
| 5 | item2 | 1 | 1 |
| 6 | item3 | 1 | 1 |
| 7 | pants | 5 | 0 |
-----------------------------------------------------------------------------------Here's the sample of my code:
//... ResultSet rs = .....
rs.last();
int rowCount = rs.getRow(); //Get the total number of row in database table
rs.beforeFirst();
int i = 0;
int j = 0;
String [] nodeID = new String[rowCount]; //The node ID
String [] parentID = new String[rowCount]; //A pointer to its parent ID
DefaultMutableTreeNode [] node = new DefaultMutableTreeNode[rowCount]; //The node
while(rs.next()) {
String name = rs.getString("name");
Boolean bool = rs.getBoolean("hasChild");
node[i] = new DefaultMutableTreeNode(name,bool);
parentID[i] = rs.getString("parent");
nodeID[i] = rs.getInt("node_id") + "";
//Set as root node when the pointer is null
if(parentID.equals("null")) {
rootNode = node[i];
i++;
for(i=0; i<rowCount; i++) {
for(j=0; j<rowCount; j++) {
if(parentID[j].equals(nodeID[i]) && node[i] != null) {
node[i].add(node[j]);
node[i] = null; //Obligates the parent after finish adding the child (to prevent unnecessary loops)
//... tree = new JTree(rootNode);
Thanks for the trouble,
Regards,
DavidThe execution time are base on the code i post'ed here.
Average over 30times using Vector = 640048 nanosecond to execute.
Vector<String> nodeID = new Vector<String>();
Vector<DefaultMutableTreeNode> node = new Vector<DefaultMutableTreeNode>();
Vector<String> parentID = new Vector<String>();
rs.last();
int rowCount = rs.getRow();
rs.beforeFirst();
k=0;
while(rs.next()) {
String name = rs.getString("name");
Boolean hasChild = rs.getBoolean("hasChild");
node.addElement(new DefaultMutableTreeNode(name,hasChild));
nodeID.addElement(rs.getInt("node_id")+"");
parentID.addElement(rs.getString("parent"));
if(parentID.elementAt(k).equals("null")) {
rootNode = node.elementAt(k);
k++;
i=0;
while(i<rowCount) {
j=0;
while(j<rowCount) {
if(parentID.elementAt(j).equals(nodeID.elementAt(i)) && node.elementAt(j) != null) {
node.elementAt(i).add(node.elementAt(j));
if(!node.elementAt(i).getAllowsChildren())
node.insertElementAt(null,j);
j++;
i++;
}Average over 30times using LinkedList = 95623 nanosecond to execute.
//This section will have a class Nodes
LinkedList<Nodes> gather = new LinkedList<Nodes>();
while(rs.next()) {
node = new DefaultMutableTreeNode(rs.getString("name"),rs.getBoolean("hasChild"));
gather.add(new Nodes(rs.getInt("node_id") + "",node,rs.getString("parent")));
for(Nodes findParent : gather) {
if(findParent.getParentID().equals("null")) {
findParent.setRoot(findParent.getNode());
rootNode = findParent.getRoot();
for(Nodes findChild : gather){
if(findChild.getParentID().equals(findParent.getNodeID()))
findParent.getNode().add(findChild.getNode());
}As for the Array method i used from the previous post, the Average code execution time is x3 larger than the vector i used. So please do not use that method.
Note: 1. The code i post can be improved further. 2. Execution time is based on individual computer.
Well, I think i'll stop here. Anyone who wanted to know which method is more efficient currently, here's the answer.
Hope that it helps anyone who have the problem here =).
Edited by: DavidTW on May 23, 2011 3:14 PM
Improved Version : Using for-each loop ( Effective Java, Second Edition, Joshua Bloch, Pg. 210). -
How to retrieve the nodes from the Database on JTree and many more
I am facing a problem with JTree. I want to retrieve all the nodes from the MS-Access database on the Frame(i.e. Frame will display the JTree), then I also want to perform function like Edit, insert , delete and Drag and Drop opeartion on the JTree and the database should also updated accordingly.
So, if you have any idea or if you have some code to look for then please send it to me.I am facing a problem with JTree. I want to retrieve all the nodes from the MS-Access database on the Frame(i.e. Frame will display the JTree), then I also want to perform function like Edit, insert , delete and Drag and Drop opeartion on the JTree and the database should also updated accordingly
pls give me code -
Building JTrees from Filename strings????
Does anybody know or have code to build JTrees from fileName string so that the tree is expandable and uses expansion listeners.
Does anybody have code that allows you to show the local filesystem and also file strings contained say in a file so they can both be viewed at the same time. ie if you know somebody else has a file but you want it reflected in your local filesystem.
Come on somebody must -
How I can transfer data from the database into a variable (or array)?
I made my application according to the example (http://corlan.org/2009/06/12/working-in-flash-builder-4-with-flex-and-php/). Everything works fine. I changed one function to query the database - add the two parameters and get the value of the table in String format. A test operation shows that all is ok. If I want to display this value in the text area, I simply drag and drop service to this element in the design mode
(<s:TextArea x="153" y="435" id="nameText" text="{getDataMeanResult.lastResult[0].name}" width="296" height="89" />).
It also works fine, just a warning and encouraged to use ArrayCollection.getItemAt().
Now I want to send the value to a variable or array, but in both cases I get an error: TypeError: Error #1010: A term is undefined and has no properties..
How can I pass a value from the database into a variable? Thank you.
public var nameTemp:String;
getDataMeanResult.token = authors.getDataMean(arrayOfNumber[0], dir_id);
nameTemp = getDataMeanResult.lastResult[0].name;
public var nameArray:Array = new Array();
for (var i:uint=o; i<3; i++){
getDataMeanResult.token = authors.getDataMean(arrayOfNumber[i], dir_id);
nameArray[i] = getDataMeanResult.lastResult[0].name;
And how i can use syntax highlighting in this forum?Astraport2012 wrote:
I have to go back to the discussion. The above example works fine when i want to get a single value of the database. But i need to pass an array and get an array, because i want to get at once all the values for all pictures tooltips. I rewrote the proposed Matt PHP-script and it works. However, i can not display the resulting array.
yep, it won't work for Arrays, you'll have to do something slightly more intelligent for them.
easiest way would be to get your PHP to generate XML, then read that into something like an ArrayList on your HTTPService result event (depends what you're doing with it).
for example, you could have the PHP generate XML such as:
<pictures>
<location>test1.png</location>
<location>test2.png</location>
<location>test3.png</location>
<location>test4.png</location>
<location>test5.png</location>
<location>test6.png</location>
</pictures>
then you'll read that in as the ResultEvent, and perform something like this on it
private var tempAC:ArrayList = new ArrayList
protected function getStuff_resultHandler(event:ResultEvent):void
for each(var item:Object in event.result.pictures)
var temp:String = (item.@location).toString();
tempAC.addItem(temp);
in my example on cookies
http://www.mattlefevre.com/viewExample.php?tut=flash4PHP&proj=Using%20Cookies
you'll see an example of how to format an XML structure containing multiple values:
if($_COOKIE["firstName"])
print "<stored>true</stored>";
print "<userInfo>
<firstName>".$_COOKIE["firstName"]."</firstName>
<lastName>".$_COOKIE["lastName"]."</lastName>
<userAge>".$_COOKIE["userAge"]."</userAge>
<gender>".$_COOKIE["gender"]."</gender>
</userInfo>";
else
print "<stored>false</stored>";
which i handle like so
if(event.result.stored == true)
entryPanel.title = "Welcome back " + event.result.userInfo.firstName + " " + event.result.userInfo.lastName;
firstName.text = event.result.userInfo.firstName;
lastName.text = event.result.userInfo.lastName;
userAge.value = event.result.userInfo.userAge;
userGender.selectedIndex = event.result.userInfo.gender;
depends on what type of Array you're after
from the sounds of it (with the mention of picture tooltips) you're trying to create a gallery with an image, and a tooltip.
so i'd probably adopt something like
<picture>
<location>example1.png</location>
<tooltip>tooltip for picture #1</tooltip>
</picture>
<picture>
<location>example2.png</location>
<tooltip>tooltip for picture #2</tooltip>
</picture>
<picture>
<location>example3.png</location>
<tooltip>tooltip for picture #3</tooltip>
</picture>
etc...
or
<picture location="example1.png" tooltip="tooltip for picture #1"/>
<picture location="example2.png" tooltip="tooltip for picture #2"/>
<picture location="example3.png" tooltip="tooltip for picture #3"/>
etc... -
Getting specific values From a database in Java
Hey,
I'm using XE and building an application in Java to do basic CRUD operations on the database.
One of these operations is searching for a customer by last name (which runs fine) and the result of the query (a customer ID, a first name, and a last name) is displayed in a JTable. I want to be able to click on the record I need and use the customer ID to do an insert on another table CUSTOMER_PURCHASES which maps purchases to customers.
How do I go about doing this knowing that customer ID is an auto-incremented number (using a SEQUENCE)?
I thought about creating a variable in Java of type String called customerID and initialize it like this: String customerID = "CUSTOMER_SEQUENCE.nextval"
But by doing this, I suspect that I'll be getting the next available customerID, not the one from the record I selected.
Can anybody suggest a workaround or lead me in the right direction?
Thank you in advance for the help and sorry about the long post, but I'm a newvbie to this field.As per raychen's advice, I was able to get the image from the database and bring it over into JavaFX.
In my java class I retrieved the image as follows:
BufferedImage image = null; //Buffered image coming from database
InputStream fis = null; //Inputstream
try{
ResultSet databaseResults; //Returned results from DB
stmt = conn.createStatement(); //Create the SQL statement
databaseResults= stmt.executeQuery("SELECT * FROM mydb.`user` WHERE userID = 'username';"); //Execute query
fis = blah.getBinaryStream(3); //It happens that the 3rd column in my database is where the image is stored (a BLOB)
image = javax.imageio.ImageIO.read(fis); //create the BufferedImaged
} catch (Exception e){
//print error if caught
return image //My function returns a BufferedImage objectSo in JavaFX, depending on how you have it set up, you essentially get the returned BufferedImage and create the image as follows:
var bufferedImage : BufferedImage = theJavaFunctionThatReturnsABufferedImage();
var newImage : Image = javafx.ext.swing.SwingUtils.toFXImage(bufferedImage); //BufferedImageCheers and Happy New Year. -
How to get the data from mysql database which is being accessed by a PHP application and process the data locally in adobe air application and finally commit the changes back in to mysql database through the PHP application.
If the data is on a remote server (for example, PHP running on a web server, talking to a MySQL server) then you do this in an AIR application the same way you would do it with any Flex application (or ajax application, if you're building your AIR app in HTML/JS).
That's a broad answer, but in fact there are lots of ways to communicate between Flex and PHP. The most common and best in most cases is to use AMFPHP (http://amfphp.org/) or the new ZEND AMF support in the Zend Framework.
This page is a good starting point for learning about Flex and PHP communication:
http://www.adobe.com/devnet/flex/flex_php.html
Also, in Flash Builder 4 they've added a lot of remote-data-connection functionality, including a lot that's designed for PHP. Take a look at the Flash Builder 4 public beta for more on that: http://labs.adobe.com/technologies/flashbuilder4/ -
Insert an image from a Database
Hi - I am trying to insert an image from a database into a webpage. Basically when clients register on the site they upload their logo which i want to come up when they look at their account details and when they post a job. When I test the file upload the file name is in an "image" field in my database and the image is in the website files on the server but I am having problems trying to get the logo to shop up on the webpage. I have one table called Recruiters where all the client's contact details (and logo upload goes) and a table called jobs where all the job details go when they post a job (this does not hold the logo upload).
At the moment i am trying to insert the image into the Recruiter account Details page where all the clients contact details are and all this information comes from the Recruiter table (including the image) but the image does not appear. the query in my recordset is:-
SELECT *
FROM recruiters
WHERE RecruiterID = colname
(colname = $_GET['RecruiterID'])
<?php require_once('../Connections/laura.php'); ?>
<?php
//initialize the session
if (!isset($_SESSION)) {
session_start();
// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
$logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
//to fully log out a visitor we need to clear the session varialbles
$_SESSION['MM_Username'] = NULL;
$_SESSION['MM_UserGroup'] = NULL;
$_SESSION['PrevUrl'] = NULL;
unset($_SESSION['MM_Username']);
unset($_SESSION['MM_UserGroup']);
unset($_SESSION['PrevUrl']);
$logoutGoTo = "../index.php";
if ($logoutGoTo) {
header("Location: $logoutGoTo");
exit;
?>
<?php
if (!isset($_SESSION)) {
session_start();
$MM_authorizedUsers = "Recruiter";
$MM_donotCheckaccess = "false";
// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) {
// For security, start by assuming the visitor is NOT authorized.
$isValid = False;
// When a visitor has logged into this site, the Session variable MM_Username set equal to their username.
// Therefore, we know that a user is NOT logged in if that Session variable is blank.
if (!empty($UserName)) {
// Besides being logged in, you may restrict access to only certain users based on an ID established when they login.
// Parse the strings into arrays.
$arrUsers = Explode(",", $strUsers);
$arrGroups = Explode(",", $strGroups);
if (in_array($UserName, $arrUsers)) {
$isValid = true;
// Or, you may restrict access to only certain users based on their username.
if (in_array($UserGroup, $arrGroups)) {
$isValid = true;
if (($strUsers == "") && false) {
$isValid = true;
return $isValid;
$MM_restrictGoTo = "../Unavailablepage.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {
$MM_qsChar = "?";
$MM_referrer = $_SERVER['PHP_SELF'];
if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0)
$MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
$MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
header("Location: ". $MM_restrictGoTo);
exit;
?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
if (PHP_VERSION < 6) {
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
return $theValue;
$colname_rsAccountDetails = "-1";
if (isset($_GET['RecruiterID'])) {
$colname_rsAccountDetails = $_GET['RecruiterID'];
mysql_select_db($database_laura, $laura);
$query_rsAccountDetails = sprintf("SELECT * FROM recruiters WHERE RecruiterID = %s", GetSQLValueString($colname_rsAccountDetails, "int"));
$rsAccountDetails = mysql_query($query_rsAccountDetails, $laura) or die(mysql_error());
$row_rsAccountDetails = mysql_fetch_assoc($rsAccountDetails);
$totalRows_rsAccountDetails = mysql_num_rows($rsAccountDetails);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Nursery and Childcare Jobs in the UK</title>
<link href="../CSS/Global.css" rel="stylesheet" type="text/css" />
<script src="../SpryAssets/SpryMenuBar.js" type="text/javascript"></script>
<link href="../SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" />
<link href="../SpryAssets/SpryMenuBarVertical.css" rel="stylesheet" type="text/css" />
<!-- google adwords -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-6435415-4']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
</script>
</head>
<body>
<div class="container">
<div class="header"><!-- end .header --><a href="../index.php"><img src="../Images/Logo.png" width="900" height="200" alt="Logo" /></a></div>
<ul id="MenuBar1" class="MenuBarHorizontal">
<li><a href="../index.php">Home</a> </li>
<li><a href="#" class="MenuBarItemSubmenu">Recruiters</a>
<ul>
<li><a href="recruiterbenefits.php">Benefits</a></li>
<li><a href="recruiterfees.php">Fees</a></li>
<li><a href="recreg.php">Register</a></li>
<li><a href="reclogin.php">Login </a></li>
</ul>
</li>
<li><a class="MenuBarItemSubmenu" href="#">Jobseekers</a>
<ul>
<li><a href="../Jobseekerarea/jobseekerbenefits.php">Benefits</a> </li>
<li><a href="../Jobseekerarea/jobseekerreg1.php">Register</a></li>
<li><a href="../Jobseekerarea/jslogin.php">Login</a></li>
</ul>
</li>
<li><a href="../contactus.php">Contact Us</a></li>
</ul>
<div class="sidebar1">
<p> </p>
<div class="recruitsidebar">
<ul id="MenuBar2" class="MenuBarVertical">
<li><a href="postajob.php">Post a Job</a></li>
<li><a href="recruiterjobs1.php">My Jobs</a></li>
<li><a href="recAccdetails.php?RecruiterID=<?php echo $row_rsAccountDetails['RecruiterID']; ?>">My Details</a></li>
<li><a href="Saferrecruitment.php">Safer Recruitment</a></li>
<li><a href="Interview1.php" class="MenuBarItemSubmenu">Interviewing Staff</a>
<ul>
<li><a href="recInterviewquestions.php">Nursery Staff Interview Questions</a></li>
</ul>
</li>
<li><a href="Nurseryjobsdescriptions.php">Nursery Job Descriptions</a></li>
<li><a href="recruiterarea.php">Recruiter Home</a></li>
<li><a href="<?php echo $logoutAction ?>">Log Out</a></li>
</ul>
<p> </p>
</div>
</div>
<div class="content">
<h1>Account Details</h1>
<p>Below are the details you have provided us with about your nursery/setting.</p>
<p> </p>
<form id="accountdetailsform" name="accountdetailsform" method="post" action="recUpdate.php?RecruiterID=<?php echo $row_rsAccountDetails['RecruiterID']; ?>">
<table width="580" border="0" cellpadding="3" cellspacing="3" id="accountdetails">
<tr>
<td width="212" scope="col">Nursery/Setting Name</td>
<td width="347" scope="col"><?php echo $row_rsAccountDetails['client']; ?></td>
</tr>
<tr>
<td>Contact Name</td>
<td><?php echo $row_rsAccountDetails['contactname']; ?></td>
</tr>
<tr>
<td>Setting Type</td>
<td><?php echo $row_rsAccountDetails['settingtype']; ?></td>
</tr>
<tr>
<td>Nursery/Setting</td>
<td><?php echo $row_rsAccountDetails['Setting']; ?></td>
</tr>
<tr>
<td>Building Name/Number</td>
<td><?php echo $row_rsAccountDetails['buildingnumber']; ?></td>
</tr>
<tr>
<td>Street Name</td>
<td><?php echo $row_rsAccountDetails['streetname']; ?></td>
</tr>
<tr>
<td>Address</td>
<td><?php echo $row_rsAccountDetails['address3']; ?></td>
</tr>
<tr>
<td>Town/City</td>
<td><?php echo $row_rsAccountDetails['town']; ?></td>
</tr>
<tr>
<td>Post Code</td>
<td><?php echo $row_rsAccountDetails['postcode']; ?></td>
</tr>
<tr>
<td>Region</td>
<td><?php echo $row_rsAccountDetails['region']; ?></td>
</tr>
<tr>
<td>Telephone</td>
<td><?php echo $row_rsAccountDetails['telephone']; ?></td>
</tr>
<tr>
<td>Email</td>
<td><?php echo $row_rsAccountDetails['email']; ?></td>
</tr>
<tr>
<td>Website</td>
<td><?php echo $row_rsAccountDetails['WebAddress']; ?></td>
</tr>
<tr>
<td>Password</td>
<td> </td>
</tr>
<tr>
<td>Logo</td>
<td><img src="<?php echo $row_rsAccountDetails['Image']; ?>" alt="Logo" /></td>
</tr>
<tr>
<td>Date Registered</td>
<td><?php echo $row_rsAccountDetails['dateregistered']; ?></td>
</tr>
</table>
<p>
<input name="hiddenField" type="hidden" id="hiddenField" value="<?php echo $row_rsAccountDetails['RecruiterID']; ?>" />
</p>
<p>
<input type="submit" name="Update" id="Update" value="Update Details" />
</p>
<p> </p>
</form>
<p> </p>
<table width="600" border="0" cellpadding="3" cellspacing="3" class="postform">
<tr> </tr>
<tr> </tr>
<tr> </tr>
</table>
<p> </p>
<p> </p>
</div>
<div class="sidebar2">
<h4> </h4>
<!-- end .sidebar2 --></div>
<div class="footer">
<p><a href="../index.php">Home</a> | <a href="../contactus.php">Contact us</a> | <a href="../PrivacyPolicy.php">Privacy</a> | <a href="../termsandconditions.php">Terms of Business</a></p>
<p>© theNurseryJobSite.com 2011</p>
<!-- end .footer --></div>
<!-- end .container --></div>
<script type="text/javascript">
var MenuBar1 = new Spry.Widget.MenuBar("MenuBar1", {imgDown:"SpryAssets/SpryMenuBarDownHover.gif", imgRight:"SpryAssets/SpryMenuBarRightHover.gif"});
var MenuBar2 = new Spry.Widget.MenuBar("MenuBar2", {imgRight:"../SpryAssets/SpryMenuBarRightHover.gif"});
</script>
</body>
</html>
<?php
mysql_free_result($rsAccountDetails);
?>Hi
You were right – I had to insert full path and it has worked so thanks.
Would you be able to help me out with inserting the logo into a job post page and the recordset I will need to insert the logo?
Basically I want to add the logo that is uploaded when a client registers on the site onto a job info page. To access the the details about a job, jobseekers just click on the job that interests them which takes them to the job details page which pulls all the information from the "Job" table in the database. However, the logo is stored in the "image" field in the "Recruiter" table in the database. I have tried setting up a recordset as:-
SELECT Image
FROM recruiters
WHERE RecruiterID = colname
(colname = $_GET['RecruiterID'])
<?php require_once('../Connections/laura.php'); ?>
<?php
//initialize the session
if (!isset($_SESSION)) {
session_start();
// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
$logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
//to fully log out a visitor we need to clear the session varialbles
$_SESSION['MM_Username'] = NULL;
$_SESSION['MM_UserGroup'] = NULL;
$_SESSION['PrevUrl'] = NULL;
unset($_SESSION['MM_Username']);
unset($_SESSION['MM_UserGroup']);
unset($_SESSION['PrevUrl']);
$logoutGoTo = "../index.php";
if ($logoutGoTo) {
header("Location: $logoutGoTo");
exit;
?>
<?php
if (!isset($_SESSION)) {
session_start();
$MM_authorizedUsers = "Recruiter";
$MM_donotCheckaccess = "false";
// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) {
// For security, start by assuming the visitor is NOT authorized.
$isValid = False;
// When a visitor has logged into this site, the Session variable MM_Username set equal to their username.
// Therefore, we know that a user is NOT logged in if that Session variable is blank.
if (!empty($UserName)) {
// Besides being logged in, you may restrict access to only certain users based on an ID established when they login.
// Parse the strings into arrays.
$arrUsers = Explode(",", $strUsers);
$arrGroups = Explode(",", $strGroups);
if (in_array($UserName, $arrUsers)) {
$isValid = true;
// Or, you may restrict access to only certain users based on their username.
if (in_array($UserGroup, $arrGroups)) {
$isValid = true;
if (($strUsers == "") && false) {
$isValid = true;
return $isValid;
$MM_restrictGoTo = "../Unavailablepage.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {
$MM_qsChar = "?";
$MM_referrer = $_SERVER['PHP_SELF'];
if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0)
$MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
$MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
header("Location: ". $MM_restrictGoTo);
exit;
?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
if (PHP_VERSION < 6) {
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
return $theValue;
$colname_rsDetails = "-1";
if (isset($_GET['JobID'])) {
$colname_rsDetails = $_GET['JobID'];
mysql_select_db($database_laura, $laura);
$query_rsDetails = sprintf("SELECT * FROM jobs WHERE JobID = %s", GetSQLValueString($colname_rsDetails, "text"));
$rsDetails = mysql_query($query_rsDetails, $laura) or die(mysql_error());
$row_rsDetails = mysql_fetch_assoc($rsDetails);
$totalRows_rsDetails = "-1";
if (isset($_GET['JobID'])) {
$totalRows_rsDetails = $_GET['JobID'];
mysql_select_db($database_laura, $laura);
$query_rsDetails = sprintf("SELECT recruiters.Image, jobs.JobID, jobs.RecruiterID, jobs.jobtitle, jobs.`Position`, jobs.Nursery, jobs.branchlocation, jobs.ContactName, jobs.JobDescription, jobs.Location, jobs.town, jobs.employmenttype, jobs.Hours, jobs.qualifications, jobs.Salary, jobs.ContactNo, jobs.Email, jobs.dateposted FROM jobs, recruiters WHERE JobID = %s", GetSQLValueString($colname_rsDetails, "int"));
$rsDetails = mysql_query($query_rsDetails, $laura) or die(mysql_error());
$row_rsDetails = mysql_fetch_assoc($rsDetails);
$totalRows_rsDetails = "-1";
if (isset($_GET['JobID'])) {
$totalRows_rsDetails = $_GET['JobID'];
mysql_select_db($database_laura, $laura);
$query_rsDetails = sprintf("SELECT recruiters.Image, jobs.JobID, jobs.RecruiterID, jobs.jobtitle, jobs.`Position`, jobs.Nursery, jobs.branchlocation, jobs.ContactName, jobs.JobDescription, jobs.Location, jobs.town, jobs.employmenttype, jobs.Hours, jobs.qualifications, jobs.Salary, jobs.ContactNo, jobs.Email, jobs.dateposted FROM jobs, recruiters WHERE JobID = %s", GetSQLValueString($colname_rsDetails, "int"));
$rsDetails = mysql_query($query_rsDetails, $laura) or die(mysql_error());
$row_rsDetails = mysql_fetch_assoc($rsDetails);
$totalRows_rsDetails = "-1";
if (isset($_GET['JobID'])) {
$totalRows_rsDetails = $_GET['JobID'];
mysql_select_db($database_laura, $laura);
$query_rsDetails = sprintf("SELECT recruiters.Image, jobs.JobID, jobs.RecruiterID, jobs.jobtitle, jobs.`Position`, jobs.Nursery, jobs.branchlocation, jobs.ContactName, jobs.JobDescription, jobs.Location, jobs.town, jobs.employmenttype, jobs.Hours, jobs.qualifications, jobs.Salary, jobs.ContactNo, jobs.Email, jobs.dateposted FROM jobs, recruiters WHERE JobID = %s", GetSQLValueString($totalRows_rsDetails, "int"));
$rsDetails = mysql_query($query_rsDetails, $laura) or die(mysql_error());
$row_rsDetails = mysql_fetch_assoc($rsDetails);
$totalRows_rsDetails = mysql_num_rows($rsDetails);
$colname_rsRecruiterID2 = "-1";
if (isset($_GET['RecruiterID'])) {
$colname_rsRecruiterID2 = $_GET['RecruiterID'];
mysql_select_db($database_laura, $laura);
$query_rsRecruiterID2 = sprintf("SELECT RecruiterID FROM recruiters WHERE RecruiterID = %s", GetSQLValueString($colname_rsRecruiterID2, "int"));
$rsRecruiterID2 = mysql_query($query_rsRecruiterID2, $laura) or die(mysql_error());
$row_rsRecruiterID2 = mysql_fetch_assoc($rsRecruiterID2);
$totalRows_rsRecruiterID2 = mysql_num_rows($rsRecruiterID2);
$colname_rsRecruiterID = "-1";
if (isset($_SESSION['MM_Username'])) {
$colname_rsRecruiterID = $_SESSION['MM_Username'];
mysql_select_db($database_laura, $laura);
$query_rsRecruiterID = sprintf("SELECT RecruiterID FROM recruiters WHERE email = %s", GetSQLValueString($colname_rsRecruiterID, "text"));
$rsRecruiterID = mysql_query($query_rsRecruiterID, $laura) or die(mysql_error());
$row_rsRecruiterID = mysql_fetch_assoc($rsRecruiterID);
$totalRows_rsRecruiterID = mysql_num_rows($rsRecruiterID);
$colname_Recordset1 = "-1";
if (isset($_GET['RecruiterID'])) {
$colname_Recordset1 = $_GET['RecruiterID'];
mysql_select_db($database_laura, $laura);
$query_Recordset1 = sprintf("SELECT Image FROM recruiters WHERE RecruiterID = %s", GetSQLValueString($colname_Recordset1, "int"));
$Recordset1 = mysql_query($query_Recordset1, $laura) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
$query_rsJobs = "SELECT * FROM jobs";
$rsJobs = mysql_query($query_rsJobs, $laura) or die(mysql_error());
$row_rsJobs = mysql_fetch_assoc($rsJobs);
$totalRows_rsJobs = mysql_num_rows($rsJobs);
$colname_rsJobs = "-1";
if (isset($_GET['Position'])) {
$colname_rsJobs = $_GET['Position'];
$varLocation_rsJobs = "-1";
if (isset($_GET['Location'])) {
$varLocation_rsJobs = $_GET['Location'];
mysql_select_db($database_laura, $laura);
$query_rsJobs = sprintf("SELECT `Position`, Nursery, Location, Salary, Email, ContactNo, JobDescription, JobID FROM jobs WHERE `Position` = %s AND jobs.Location = %s", GetSQLValueString($colname_rsJobs, "text"),GetSQLValueString($varLocation_rsJobs, "text"));
$rsJobs = mysql_query($query_rsJobs, $laura) or die(mysql_error());
$row_rsJobs = mysql_fetch_assoc($rsJobs);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Nursery and Childcare Jobs in the UK</title>
<link href="../CSS/Global.css" rel="stylesheet" type="text/css" />
<script src="../SpryAssets/SpryMenuBar.js" type="text/javascript"></script>
<link href="../SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" />
<link href="../SpryAssets/SpryMenuBarVertical.css" rel="stylesheet" type="text/css" />
<!-- google adwards -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-6435415-4']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
</script>
</head>
<body>
<div class="container">
<div class="header"><!-- end .header --><a href="../index.php"><img src="../Images/Logo.png" width="900" height="200" alt="the Nursery Job Site" /></a></div>
<div class="navbar"> <ul id="MenuBar1" class="MenuBarHorizontal">
<li><a href="thenurseryjobsite.php">About the Nursery Job Site</a> </li>
<li><a href="#" class="MenuBarItemSubmenu">Recruiters</a>
<ul>
<li><a href="Recruiterarea/recruiterbenefits.php">Benefits</a></li>
<li><a href="Recruiterarea/recruiterfees.php">Fees</a></li>
<li><a href="Recruiterarea/reclogin.php">Login</a></li>
<li><a href="Recruiterarea/recreg.php">Register</a></li>
</ul>
</li>
<li><a class="MenuBarItemSubmenu" href="#">Jobseekers</a>
<ul>
<li><a href="Jobseekerarea/jobseekerbenefits.php">Benefits</a> </li>
<li><a href="Jobseekerarea/jslogin.php">Login</a></li>
<li><a href="Jobseekerarea/jobseekerreg1.php">Register</a></li>
</ul>
</li>
<li><a href="contactus.php">Contact Us</a></li>
</ul> </div> <!--end navbar div -->
<div class="sidebar1">
<p> </p>
<div class="recruitsidebar">
<ul id="MenuBar2" class="MenuBarVertical">
<li><a href="postajob.php">Post a Job</a></li>
<li><a href="recAccdetails.php?RecruiterID=<?php echo $row_rsRecruiterID['RecruiterID']; ?>">My Details </a></li>
<li><a href="recruiterjobs1.php">My Jobs</a></li>
<li><a href="Saferrecruitment.php">Safer Recruitment</a></li>
<li><a href="Interview1.php" class="MenuBarItemSubmenu">Interviewing Staff</a>
<ul>
<li><a href="recInterviewquestions.php">Nursery Staff Interview Questions</a></li>
</ul>
</li>
<li><a href="Nurseryjobsdescriptions.php">Nursery Job Descriptions</a></li>
<li><a href="recruiterarea.php">Recruiter Home</a></li>
<li><a href="<?php echo $logoutAction ?>">Log Out</a></li>
</ul>
<p> </p>
</div>
</div>
<div class="content">
<h1> </h1>
<div class="detailheading" id="detailheading">
<h1> </h1>
<table width="564" border="0" align="center" cellpadding="3" cellspacing="3" id="headingtable">
<tr>
<td width="89" height="44" align="center" class="headertext"><h1>Nursery:</h1></td>
<td width="283" class="headertext"><?php echo $row_rsDetails['Nursery']; ?></td>
<td width="162" rowspan="2"><img src="<?php echo $row_Recordset1['Image']; ?>" alt="" name="nurserylogo" align="right" id="nurserylogo" /></td>
</tr>
<tr align="left" class="headertext">
<td width="89" height="44" align="center"><h1 class="headertext">Job Title:</h1></td>
<td align="left"><?php echo $row_rsDetails['jobtitle']; ?></td>
</tr>
</table>
<p> </p>
</div>
<table width="568" border="0" align="center" cellpadding="3" cellspacing="3" class="detail" id="detailtable">
<tr>
<td width="162" scope="col">Job Title</td>
<td width="381" scope="col"><?php echo $row_rsDetails['jobtitle']; ?></td>
</tr>
<tr>
<td>Nursery</td>
<td><?php echo $row_rsDetails['Nursery']; ?></td>
</tr>
<tr>
<td>Branch Name/Location</td>
<td><?php echo $row_rsDetails['branchlocation']; ?></td>
</tr>
<tr>
<td>Location</td>
<td><?php echo $row_rsDetails['Location']; ?>,<?php echo $row_rsDetails['town']; ?></td>
</tr>
<tr>
<td valign="top">Job Description</td>
<td><p> </p>
<p><?php echo $row_rsDetails['JobDescription']; ?></p>
<p> </p></td>
</tr>
<tr>
<td>Qualifications Required</td>
<td><?php echo $row_rsDetails['qualifications']; ?></td>
</tr>
<tr>
<td>Employment Type</td>
<td><?php echo $row_rsDetails['employmenttype']; ?></td>
</tr>
<tr>
<td>Hours</td>
<td><?php echo $row_rsDetails['Hours']; ?></td>
</tr>
<tr>
<td>Salary</td>
<td>£<?php echo $row_rsDetails['Salary']; ?></td>
</tr>
<tr>
<td>Contact Number</td>
<td><?php echo $row_rsDetails['ContactNo']; ?></td>
</tr>
<tr>
<td>Email</td>
<td><?php echo $row_rsDetails['Email']; ?></td>
</tr>
<tr>
<td>Date Posted</td>
<td><?php echo $row_rsDetails['dateposted']; ?></td>
</tr>
<tr>
<td>Job ID</td>
<td><?php echo $row_rsDetails['JobID']; ?></td>
</tr>
</table>
<p><br />
</p>
<form id="recruiterjobsform" name="recruiterjobsform" method="post" action="recruiterjobs1.php">
<input name="RecruiterIDjobs" type="hidden" id="RecruiterIDjobs" value="<?php echo $row_rsDetails['RecruiterID']; ?>" />
<input type="submit" name="button" id="button" value="return to my jobs" />
</form>
<p> </p>
<script type="text/javascript">
var MenuBar2 = new Spry.Widget.MenuBar("MenuBar2", {imgRight:"../SpryAssets/SpryMenuBarRightHover.gif"});
</script><script type="text/javascript">
var MenuBar1 = new Spry.Widget.MenuBar("MenuBar1", {imgDown:"SpryAssets/SpryMenuBarDownHover.gif", imgRight:"SpryAssets/SpryMenuBarRightHover.gif"});
var MenuBar2 = new Spry.Widget.MenuBar("MenuBar2", {imgRight:"../SpryAssets/SpryMenuBarRightHover.gif"});
</script>
<p> </p>
</div>
<div class="sidebar2">
<h4> </h4>
<!-- end .sidebar2 --></div>
<div class="footer">
<p><a href="../index.php">Home</a> | <a href="../contactus.php">Contact us</a> | <a href="../PrivacyPolicy.php">Privacy</a> | <a href="../termsandconditions.php">Terms of Business</a></p>
<p>© theNurseryJobSite.com 2011</p>
<!-- end .footer --></div>
<!-- end .container --></div>
<script type="text/javascript">
var MenuBar1 = new Spry.Widget.MenuBar("MenuBar1", {imgDown:"SpryAssets/SpryMenuBarDownHover.gif", imgRight:"SpryAssets/SpryMenuBarRightHover.gif"});
var MenuBar2 = new Spry.Widget.MenuBar("MenuBar2", {imgRight:"../SpryAssets/SpryMenuBarRightHover.gif"});
</script>
</body>
</html>
<?php
mysql_free_result($rsDetails);
mysql_free_result($rsRecruiterID2);
mysql_free_result($rsRecruiterID);
mysql_free_result($Recordset1);
?> -
Data from different databases in the same report.
Hi Everyone,
I am trying to build a reconciliation report in which I need to show the data from the source and target, side by side.
Source and target are both different databases, although being oracle only
Whenever a new data model is created, it gets attached to a data source and in the report we need to choose a specific data model.
Can we have data from different databases in the same report ?Yes, it is possible.
One way Is to use dataTemplates. There you can make queries from any number of different databases (The max I have done is 5).
It looks something like that:
<dataTemplate name="NameOfTemplate">
<dataQuery>
<sqlStatement name="Q1" dataSourceRef="Connection1">
<![CDATA[ select * from table1]]>
</sqlStatement>
<sqlStatement name="Q2" dataSourceRef="Connection2">
<![CDATA[ select * from table2]]>
</sqlStatement>
</dataQuery>
<dataStructure>
<group name="RESULT1" source="Q1">
<element name="P_FIRST_NAME" value="P_FIRST_NAME"/>
</group>
<group name="RESULT2" source="Q2">
<element name="P_DATE" value="P_DATE"/>
</group>
</dataStructure>
</dataTemplate>dataStructure is very important when you get data from different places, if you don't define those elements, then only the result from Q1 is shown.
The second possible way is to make as two different data models, each containing their own query and then set Main Data Set as concatenated SQL Data Source.
Best of luck,
Evelyn -
Help with building a JTree using tree node and node renderers
Hi,
I am having a few problems with JTree's. basically I want to build JTree from a web spider. The webspide searches a website checking links and stores the current url that is being processed as a string in the variable msg. I wan to use this variable to build a JTree in a new class and then add it to my GUI. I have created a tree node class and a renderer node class, these classes are built fine. can someone point me in the direction for actually using these to build my tree in a seperate class and then displaying it in a GUI class?
*nodeRenderer.java
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.net.*;
public class nodeRenderer extends DefaultTreeCellRenderer
implements TreeCellRenderer
public static Icon icon= null;
public nodeRenderer() {
icon = new ImageIcon(getClass().getResource("icon.gif"));
public Component getTreeCellRendererComponent(
JTree tree,
Object value,
boolean sel,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
super.getTreeCellRendererComponent(
tree, value, sel,
expanded, leaf, row,
hasFocus);
treeNode node = (treeNode)(((DefaultMutableTreeNode)value).getUserObject());
if(icon != null) // set a custom icon
setOpenIcon(icon);
setClosedIcon(icon);
setLeafIcon(icon);
return this;
*treeNode.java
*this is the class to represent a node
import javax.swing.*;
import javax.swing.tree.*;
import java.util.*;
import java.net.*;
* Class used to hold information about a web site that has
* been searched by the spider class
public class treeNode
*Url from the WebSpiderController Class
*that is currently being processed
public String msg;
treeNode(String urlText)
msg = urlText;
String getUrlText()
return msg;
//gui.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.net.*;
import java.io.*;
import java.util.*;
public class gui extends JFrame implements Runnable
*declare variable, boolean
*thread, a object and a center
*pane
protected URL urlInput;
protected Thread bgThread;
protected boolean run = false;
protected WebSpider webSpider;
public gui()
*create the gui here
setTitle("Testing Tool");
setSize(600,600);
//add Buttons to the tool bar
start.setText("Start");
start.setActionCommand("Start");
toolBar.add(start);
ButtonListener startListener = new ButtonListener();
start.addActionListener(startListener);
cancel.setText("Cancel");
cancel.setActionCommand("Cancel");
toolBar.add(cancel);
ButtonListener cancelListener = new ButtonListener();
cancel.addActionListener(cancelListener);
close.setText("Close");
close.setActionCommand("Close");
toolBar.add(close);
ButtonListener closeListener = new ButtonListener();
close.addActionListener(closeListener);
//creat a simple form
urlLabel.setText("Enter URL:");
urlLabel.setBounds(100,36,288,24);
formTab.add(urlLabel);
url.setBounds(170,36,288,24);
formTab.add(url);
current.setText("Currently Processing: ");
current.setBounds(100,80,288,24);
formTab.add(current);
//add scroll bars to the error messages screen and website structure
errorPane.setAutoscrolls(true);
errorPane.setHorizontalScrollBarPolicy(javax.swing.
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
errorPane.setVerticalScrollBarPolicy(javax.swing.
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
errorPane.setOpaque(true);
errorTab.add(errorPane);
errorPane.setBounds(0,0,580,490);
errorText.setEditable(false);
errorPane.getViewport().add(errorText);
errorText.setBounds(0,0,600,550);
treePane.setAutoscrolls(true);
treePane.setHorizontalScrollBarPolicy(javax.swing.
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
treePane.setVerticalScrollBarPolicy(javax.swing.
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
treePane.setOpaque(true);
treeTab.add(treePane);
treePane.setBounds(0,0,580,490);
treeText.setEditable(false);
treePane.getViewport().add(treeText);
treeText.setBounds(0,0,600,550);
//create the tabbed window
centerPane.setBorder(new javax.swing.border.EtchedBorder());
formTab.setLayout(null);
errorTab.setLayout(null);
treeTab.setLayout(null);
centerPane.addTab("Search Parameters", formTab);
centerPane.addTab("Error Messages", errorTab);
centerPane.addTab("Website Structure", treeTab);
//add the tool bar and tabbed pane
getContentPane().add(toolBar, java.awt.BorderLayout.NORTH);
getContentPane().add(centerPane, java.awt.BorderLayout.CENTER);
*create the tool bar pane, a center pane, add the buttons,
*labels, tabs, a text field for user input here
javax.swing.JPanel toolBar = new javax.swing.JPanel();
javax.swing.JButton start = new javax.swing.JButton();
javax.swing.JButton cancel = new javax.swing.JButton();
javax.swing.JButton close = new javax.swing.JButton();
javax.swing.JTabbedPane centerPane = new javax.swing.JTabbedPane();
javax.swing.JPanel formTab = new javax.swing.JPanel();
javax.swing.JLabel urlLabel = new javax.swing.JLabel();
javax.swing.JLabel current = new javax.swing.JLabel();
javax.swing.JTextField url = new javax.swing.JTextField();
javax.swing.JPanel errorTab = new javax.swing.JPanel();
javax.swing.JTextArea errorText = new javax.swing.JTextArea();
javax.swing.JScrollPane errorPane = new javax.swing.JScrollPane();
javax.swing.JPanel treeTab = new javax.swing.JPanel();
javax.swing.JTextArea treeText = new javax.swing.JTextArea();
javax.swing.JScrollPane treePane = new javax.swing.JScrollPane();
javax.swing.JTree searchTree = new javax.swing.JTree();
*show the gui
public static void main(String args[])
(new gui()).setVisible(true);
*listen for the button presses and set the
*boolean flag depending on which button is pressed
class ButtonListener implements ActionListener
public void actionPerformed(ActionEvent event)
Object object = event.getSource();
if (object == start)
run = true;
startActionPerformed(event);
if (object == cancel)
run = false;
startActionPerformed(event);
if (object == close)
System.exit(0);
*this method is called when the start or
*cancel button is pressed.
void startActionPerformed (ActionEvent event)
if (run == true && bgThread == null)
bgThread = new Thread(this);
bgThread.start();
if (run == false && bgThread != null)
webSpider.cancel();
*this mehtod will start the background thred.
*the background thread is required so that the
*GUI is still displayed
public void run()
try
webSpider = new WebSpider(this);
webSpider.clear();
urlInput = new URL(url.getText());
webSpider.addURL(urlInput);
webSpider.run();
bgThread=null;
catch (MalformedURLException e)
addressError addErr = new addressError();
addErr.addMsg = "URL ERROR - PLEASE CHECK";
SwingUtilities.invokeLater(addErr);
*this method is called by the web spider
*once a url is found. Validation of navigation
*happens here.
public boolean urlFound(URL urlInput,URL url)
CurrentlyProcessing pro = new CurrentlyProcessing();
pro.msg = url.toString();
SwingUtilities.invokeLater(pro);
if (!testLink(url))
navigationError navErr = new navigationError();
navErr.navMsg = "Broken Link "+url+" caused on "+urlInput+"\n";
return false;
if (!url.getHost().equalsIgnoreCase(urlInput.getHost()))
return false;
else
return true;
*this method is called internally to check
*that a link works
protected boolean testLink(URL url)
try
URLConnection connection = url.openConnection();
connection.connect();
return true;
catch (IOException e)
return false;
*this method is called when an error is
*found.
public void URLError(URL url)
*this method is called when an email
*address is found
public void emailFound(String email)
/*this method will update any errors found inc
*address errors and broken links
class addressError implements Runnable
public String addMsg;
public void run()
errorText.append(addMsg);
current.setText("Currently Processing: "+ addMsg);
class navigationError implements Runnable
public String navMsg;
public void run()
errorText.append(navMsg);
*this method will update the currently
*processing field on the GUI
class CurrentlyProcessing implements Runnable
public String msg;
public void run()
current.setText("Currently Processing: " + msg );
//webspider.java
import java.util.*;
import java.net.*;
import java.io.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import javax.swing.tree.*;
import javax.swing.*;
*this class implements the spider.
public class WebSpider extends HTMLEditorKit
*make a collection of the URL's
protected Collection urlErrors = new ArrayList(3);
protected Collection urlsWaiting = new ArrayList(3);
protected Collection urlsProcessed = new ArrayList(3);
//report URL's to this class
protected gui report;
*this flag will indicate whether the process
*is to be cancelled
protected boolean cancel = false;
*The constructor
*report the urls to the wui class
public WebSpider(gui report)
this.report = report;
*get the urls from the above declared
*collections
public Collection getUrlErrors()
return urlErrors;
public Collection getUrlsWaiting()
return urlsWaiting;
public Collection getUrlsProcessed()
return urlsProcessed;
* Clear all of the collections.
public void clear()
getUrlErrors().clear();
getUrlsWaiting().clear();
getUrlsProcessed().clear();
*Set a flag that will cause the begin
*method to return before it is done.
public void cancel()
cancel = true;
*add the entered url for porcessing
public void addURL(URL url)
if (getUrlsWaiting().contains(url))
return;
if (getUrlErrors().contains(url))
return;
if (getUrlsProcessed().contains(url))
return;
/*WRITE TO LOG FILE*/
log("Adding to workload: " + url );
getUrlsWaiting().add(url);
*process a url
public void processURL(URL url)
try
/*WRITE TO LOGFILE*/
log("Processing: " + url );
// get the URL's contents
URLConnection connection = url.openConnection();
if ((connection.getContentType()!=null) &&
!connection.getContentType().toLowerCase().startsWith("text/"))
getUrlsWaiting().remove(url);
getUrlsProcessed().add(url);
log("Not processing because content type is: " +
connection.getContentType() );
return;
// read the URL
InputStream is = connection.getInputStream();
Reader r = new InputStreamReader(is);
// parse the URL
HTMLEditorKit.Parser parse = new HTMLParse().getParser();
parse.parse(r,new Parser(url),true);
catch (IOException e)
getUrlsWaiting().remove(url);
getUrlErrors().add(url);
log("Error: " + url );
report.URLError(url);
return;
// mark URL as complete
getUrlsWaiting().remove(url);
getUrlsProcessed().add(url);
log("Complete: " + url );
*start the spider
public void run()
cancel = false;
while (!getUrlsWaiting().isEmpty() && !cancel)
Object list[] = getUrlsWaiting().toArray();
for (int i=0;(i<list.length)&&!cancel;i++)
processURL((URL)list);
* A HTML parser callback used by this class to detect links
protected class Parser extends HTMLEditorKit.ParserCallback
protected URL urlInput;
public Parser(URL urlInput)
this.urlInput = urlInput;
public void handleSimpleTag(HTML.Tag t,MutableAttributeSet a,int pos)
String href = (String)a.getAttribute(HTML.Attribute.HREF);
if((href==null) && (t==HTML.Tag.FRAME))
href = (String)a.getAttribute(HTML.Attribute.SRC);
if (href==null)
return;
int i = href.indexOf('#');
if (i!=-1)
href = href.substring(0,i);
if (href.toLowerCase().startsWith("mailto:"))
report.emailFound(href);
return;
handleLink(urlInput,href);
public void handleStartTag(HTML.Tag t,MutableAttributeSet a,int pos)
handleSimpleTag(t,a,pos); // handle the same way
protected void handleLink(URL urlInput,String str)
try
URL url = new URL(urlInput,str);
if (report.urlFound(urlInput,url))
addURL(url);
catch (MalformedURLException e)
log("Found malformed URL: " + str);
*log the information of the spider
public void log(String entry)
System.out.println( (new Date()) + ":" + entry );
I have a seperate class for parseing the HTML. Any help would be greatly appreciated
mrvHi Sorry to be a pain again,
I have re worked the gui class so it looks like this now:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.net.*;
import java.io.*;
import java.util.*;
public class gui extends JFrame implements Runnable
*declare variable, boolean
*thread, a object and a center
*pane
protected URL urlInput;
protected Thread bgThread;
protected boolean run = false;
protected WebSpider webSpider;
public String msgInfo;
public String brokenUrl;
public String goodUrl;
public String deadUrl;
protected DefaultMutableTreeNode rootNode;
protected DefaultTreeModel treeModel;
public gui()
*create the gui here
setTitle("Testing Tool");
setSize(600,600);
//add Buttons to the tool bar
start.setText("Start");
start.setActionCommand("Start");
toolBar.add(start);
ButtonListener startListener = new ButtonListener();
start.addActionListener(startListener);
cancel.setText("Cancel");
cancel.setActionCommand("Cancel");
toolBar.add(cancel);
ButtonListener cancelListener = new ButtonListener();
cancel.addActionListener(cancelListener);
close.setText("Close");
close.setActionCommand("Close");
toolBar.add(close);
ButtonListener closeListener = new ButtonListener();
close.addActionListener(closeListener);
//creat a simple form
urlLabel.setText("Enter URL:");
urlLabel.setBounds(100,36,288,24);
formTab.add(urlLabel);
url.setBounds(170,36,288,24);
formTab.add(url);
current.setText("Currently Processing: ");
current.setBounds(100,80,288,24);
formTab.add(current);
//add scroll bars to the error messages screen and website structure
errorPane.setAutoscrolls(true);
errorPane.setHorizontalScrollBarPolicy(javax.swing.
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
errorPane.setVerticalScrollBarPolicy(javax.swing.
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
errorPane.setOpaque(true);
errorTab.add(errorPane);
errorPane.setBounds(0,0,580,490);
errorText.setEditable(false);
errorPane.getViewport().add(errorText);
errorText.setBounds(0,0,600,550);
treePane.setAutoscrolls(true);
treePane.setHorizontalScrollBarPolicy(javax.swing.
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
treePane.setVerticalScrollBarPolicy(javax.swing.
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
treePane.setOpaque(true);
treeTab.add(treePane);
treePane.setBounds(0,0,580,490);
treeText.setEditable(false);
treePane.getViewport().add(treeText);
treeText.setBounds(0,0,600,550);
//JTree
// NEW CODE
rootNode = new DefaultMutableTreeNode("Root Node");
treeModel = new DefaultTreeModel(rootNode);
treeModel.addTreeModelListener(new MyTreeModelListener());
tree = new JTree(treeModel);
tree.setEditable(true);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setShowsRootHandles(true);
treeText.add(tree);
//create the tabbed window
centerPane.setBorder(new javax.swing.border.EtchedBorder());
formTab.setLayout(null);
errorTab.setLayout(null);
treeTab.setLayout(null);
centerPane.addTab("Search Parameters", formTab);
centerPane.addTab("Error Messages", errorTab);
centerPane.addTab("Website Structure", treeTab);
//add the tool bar and tabbed pane
getContentPane().add(toolBar, java.awt.BorderLayout.NORTH);
getContentPane().add(centerPane, java.awt.BorderLayout.CENTER);
*create the tool bar pane, a center pane, add the buttons,
*labels, tabs, a text field for user input here
javax.swing.JPanel toolBar = new javax.swing.JPanel();
javax.swing.JButton start = new javax.swing.JButton();
javax.swing.JButton cancel = new javax.swing.JButton();
javax.swing.JButton close = new javax.swing.JButton();
javax.swing.JTabbedPane centerPane = new javax.swing.JTabbedPane();
javax.swing.JPanel formTab = new javax.swing.JPanel();
javax.swing.JLabel urlLabel = new javax.swing.JLabel();
javax.swing.JLabel current = new javax.swing.JLabel();
javax.swing.JTextField url = new javax.swing.JTextField();
javax.swing.JPanel errorTab = new javax.swing.JPanel();
javax.swing.JTextArea errorText = new javax.swing.JTextArea();
javax.swing.JScrollPane errorPane = new javax.swing.JScrollPane();
javax.swing.JPanel treeTab = new javax.swing.JPanel();
javax.swing.JTextArea treeText = new javax.swing.JTextArea();
javax.swing.JScrollPane treePane = new javax.swing.JScrollPane();
javax.swing.JTree tree = new javax.swing.JTree();
*show the gui
public static void main(String args[])
(new gui()).setVisible(true);
*listen for the button presses and set the
*boolean flag depending on which button is pressed
class ButtonListener implements ActionListener
public void actionPerformed(ActionEvent event)
Object object = event.getSource();
if (object == start)
run = true;
startActionPerformed(event);
if (object == cancel)
run = false;
startActionPerformed(event);
if (object == close)
System.exit(0);
*this method is called when the start or
*cancel button is pressed.
void startActionPerformed (ActionEvent event)
if (run == true && bgThread == null)
bgThread = new Thread(this);
bgThread.start();
//new line of code
treeText.addObject(msgInfo);
if (run == false && bgThread != null)
webSpider.cancel();
*this mehtod will start the background thred.
*the background thread is required so that the
*GUI is still displayed
public void run()
try
webSpider = new WebSpider(this);
webSpider.clear();
urlInput = new URL(url.getText());
webSpider.addURL(urlInput);
webSpider.run();
bgThread = null;
catch (MalformedURLException e)
addressError addErr = new addressError();
addErr.addMsg = "URL ERROR - PLEASE CHECK";
SwingUtilities.invokeLater(addErr);
*this method is called by the web spider
*once a url is found. Validation of navigation
*happens here.
public boolean urlFound(URL urlInput,URL url)
CurrentlyProcessing pro = new CurrentlyProcessing();
pro.msg = url.toString();
SwingUtilities.invokeLater(pro);
if (!testLink(url))
navigationError navErr = new navigationError();
navErr.navMsg = "Broken Link "+url+" caused on "+urlInput+"\n";
brokenUrl = url.toString();
return false;
if (!url.getHost().equalsIgnoreCase(urlInput.getHost()))
return false;
else
return true;
*this method is returned if there is no link
*on a web page, e.g. there us a dead end
public void urlNotFound(URL urlInput)
deadEnd dEnd = new deadEnd();
dEnd.dEMsg = "No links on "+urlInput+"\n";
deadUrl = urlInput.toString();
*this method is called internally to check
*that a link works
protected boolean testLink(URL url)
try
URLConnection connection = url.openConnection();
connection.connect();
goodUrl = url.toString();
return true;
catch (IOException e)
return false;
*this method is called when an error is
*found.
public void urlError(URL url)
*this method is called when an email
*address is found
public void emailFound(String email)
/*this method will update any errors found inc
*address errors and broken links
class addressError implements Runnable
public String addMsg;
public void run()
current.setText("Currently Processing: "+ addMsg);
errorText.append(addMsg);
class navigationError implements Runnable
public String navMsg;
public void run()
errorText.append(navMsg);
class deadEnd implements Runnable
public String dEMsg;
public void run()
errorText.append(dEMsg);
*this method will update the currently
*processing field on the GUI
public class CurrentlyProcessing implements Runnable
public String msg;
//new line
public String msgInfo = msg;
public void run()
current.setText("Currently Processing: " + msg );
* NEW CODE
* NEED THIS CODE SOMEWHERE
* treeText.addObject(msgInfo);
public DefaultMutableTreeNode addObject(Object child)
DefaultMutableTreeNode parentNode = null;
TreePath parentPath = tree.getSelectionPath();
if (parentPath == null)
parentNode = rootNode;
else
parentNode = (DefaultMutableTreeNode)
(parentPath.getLastPathComponent());
return addObject(parentNode, child, true);
public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
Object child)
return addObject(parent, child, false);
public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
Object child,boolean shouldBeVisible)
DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(child);
if (parent == null)
parent = rootNode;
treeModel.insertNodeInto(childNode, parent, parent.getChildCount());
if (shouldBeVisible)
tree.scrollPathToVisible(new TreePath(childNode.getPath()));
return childNode;
public class MyTreeModelListener implements TreeModelListener
public void treeNodesChanged (TreeModelEvent e)
DefaultMutableTreeNode node;
node = (DefaultMutableTreeNode)
(e.getTreePath().getLastPathComponent());
try
int index = e.getChildIndices()[0];
node = (DefaultMutableTreeNode)
(node.getChildAt(index));
catch (NullPointerException exc)
public void treeNodesInserted(TreeModelEvent e)
public void treeStructureChanged(TreeModelEvent e)
public void treeNodesRemoved(TreeModelEvent e)
I beleive that this line of code is required:
treeText.addObject(msgInfo);
I have placed it where the action events start the spider, but i keep getting this error:
cannot resolve symbol
symbol : method addObject (java.lang.String)
location: class javax.swing.JTextArea
treeText.addObject(msgInfo);
Also the jtree is not showing the window that I want it to and I am not too sure why. could you have a look to see why? i think it needs a fresh pair of eyes.
Many thanks
MrV
Maybe you are looking for
-
Automatic Creation of Business Partens in Service Desk
Hello! I ma about to set up the Service Desk functionality in SAP Solution Manager 4.0 If I try to create (automatically)the Business partner from DSWP --> Operations --> Service Desk and choose "Create Business Partner" I receive the error: <b>DSWP
-
Mac OS 10.10.1 - Libraries error Log In - Adobe Creative Cloud
Hello, I never used the Libraries inside Photoshop CC and others CC's apps. The following error appears: "To use Creative Cloud Libraries, please sign in to Creative Cloud". I tried to sign out and sign in my account... but it didn't work! I'm using
-
WRT54GS won't connect (oddly enough, it gets info correctly)
Here's a strange situation: I have a three-year-old WRT54GS that was re-flashed to the latest Linksys firmware due to issues with DD-WRT; however, no clients (wired OR wireless) can connect to the Internet via this router. It gets the settings from
-
Doubt in coding to get idoc no
Hi , i want to get corresponding idoc no s for delivery nos I understood the logic of how to get the idoc no for particular delivery no.but unable to code it exactly. Message type is desadv Idoc type is delvry03. Segment name is E1EDL20 can u wr
-
Hi, I am using JMX which supports HTTP, RMI, CORBA, TL1 and SNMP protocols. Now I am planning to include SOAP as well. Looking at this scenario, I have the following questions: 1. Do I really need to support SOAP in JMX? The logic here is SOAP is alr