Java Regex Question (HTML Tokenizing

Hello
I would like to tokenize a HTML Page into its html tags and could not find any working expression. I tried it with:
<[.]*>
and for all input fields:
<(INPUT.*)>
But it doesn't find anything either or it findes anything.
Can somebody help me?

</?\S+?[\s\S+]*?>
"/?" means: "/" can be there but doesnt have to
"\S" means: every character which isnt a whitespace
"+" means: look for the previous character if it is there at least one time.
the "?" after the "+" means: look only for as few of the previous characters as needed to fullfill the regex.
thats why <adf>sdf> isnt found because <adf> is the shortest string that fullfills the regex.
"[]" means: treat everything inside the brackets as one term
"\s" means: look for a whitespace
"*" means: the previous character (which is the term inside the brackets) can be there as many times as it wants, even zero times
"*?" is like "+?"

Similar Messages

  • Java Regex Question extract Substring

    Hello
    I've readt the regex course on http://www.regenechsen.de/regex_de/regex_1_de.html but the regex rules described in the course and its behavior in the "real world" doesn't makes sense. For sample: in the whole string: <INPUT TYPE="Text" name="Input_Vorname">
    the matcher should extract only the fieldname so "Input_Vorname" i tried a lot of patterns so this:
    "name="(.*?)\"";
    "<.*name=\"(.*)\".?>";
    "<.*?name=\"(w+)\".*>";
    "name=\".*\"";
    and so on. But nothing (NOTHING) works. Either it finds anything or nothing. Whats wrong ?
    Can somebody declare me what I've made wrong and where my train of thought was gone wrong?
    Roland

    When you use the matches() method, the regex has to match the entire input, but if you use find(), the Matcher will search for a substring that matches the regex. Here's how you would use it:  String nameRegex = "name=\"(.*?)\"";
      Pattern namePattern = Pattern.compile(nameRegex,Pattern.CASE_INSENSITIVE);
      Matcher nameMatcher = namePattern.matcher(token);
      if (nameMatcher.find()) {
        String fieldName = nameMatcher.group(1);
      }But the main issue is that you're using the wrong method(s) to retrieve the name. The start() and end() methods return the start and end positions of the entire match, but you're only interested in whatever was matched by the subexpression inside the parentheses (round brackets). That's called a capturing group, and groups are numbered according to the order in which they appear, so you should be using start(1) and end(1) instead of start() and end(). Or you can just use group(1), as I've done here, which returns the same thing as your substring() call.
    Knowing that, you could go ahead and use matches(), with an appropriate regex:  String nameRegex = "<.*?name=\"(\\w+)\".*?>";
      Pattern namePattern = Pattern.compile(nameRegex,Pattern.CASE_INSENSITIVE);
      Matcher nameMatcher = namePattern.matcher(token);
      if (nameMatcher.matches()) {
        String fieldName = nameMatcher.group(1);
      }

  • Simple Java regex question

    I have a file with set of Name:Value pairs
    e.g
    Action1:fail
    Action2:pass
    Action3:fred
    Using regex package I Want to get value of Name "Action1"
    I have tried diff things but I cannot figure out how I can do it. I can find Action1: is present or not but dont know how I can get value associated with it.
    I have tried:
    Pattern pattern = Pattern.compile("Action1");
    CharSequence charSequence = CharSequenceFromFile(fileName); // method retuning charsq from a file
    Matcher matcher = pattern.matcher(charSequence);
    if(matcher.find()){
         int start = matcher.end(0);
         System.out.println("matcher.group(0)"+ matcher.group(0));
    how I can get value associated with specific tag?
    thanks
    anmol

    read the data from the text file on a line basis and you can do:
    String line //get this somehow
    String[] keyPair = line.split(":")g
    System.out.println(keyPair[0]); //your name
    System.out.println(keyPair[1]); //your valueor if you've got the text file in one big string:
    String pattern = "(\\a*):(\\a*)$"; //{alpha}:{alpha}newline //?
    //then
    //do some things with match objects
    //look in the API at java.util.regex

  • Java Regex Question

    I wanted to do some regex to see if a string has a subdomain.
    I want to pass string then check if there is a xxx.example.com or if it's just example.com. Anyone have a clue?
    Thanks,
    Brian

    I just went around and used the split method to check, I'm posting my code in case someone else has this problem and limited to the 1.4 jdk.
    String split = domain.split("[.]") ;
    if(split.length > 2)
        domain = split[split.length - 2] + "." + split[split.lengh -1] ;basically what I wanted to do was see if it was a subdomain and then strip the preceding and just get to the actual domain.
    Thanks for the replys

  • JAVA 5.15 / HTML/ FLASH 5/ WIN98 SE questions

    I'm a green Java 5.15 /HTML /Flash 5 user, with a PIII 450MgHz computer, using Win 98 SE. Whew! Now that the important preliminaries are out of the way, here are my problems:
    1) Most programs I've installed, have indicated where they will install and they add menu (and submenu) items in the Start Menu. Java 5 (update 15) did not. Why?
    2) The Java does not come with a compiler/decompiler/editor. Is there an all-in-one that I can download? Do I need a compiler to produce an executable which will run on any OS/Browser platform?
    3) When I run the VERIFY INSTALLATION, only the first part is successful (Duke); and then only skewed, because it tells me that I have Win XP installed!! :-) LOL.. The second part of the result shows me a red X, indicating some applet failure. I guess this verification is meant for latest Java 6-update 9, right?
    4) Is Java 5.15 compatible with HTML and Flash 5? In other words, can I write a simple initialize/increment variable routine in Java, and have it interface properly with the HTML that embeds my Flash 5? The goal is to load my Flash files at a particular frame in the movie, depending on the value of the variable (set in Java).
    Sincerely,
    Jakob
    Montreal

    Dear Inryii,
    2) Yes, I do have some rudimentary knowledge of Java and programming in general. Are you suggesting a text editor like Notepad? I would prefer a Java editor which could show me syntax errors. Any suggestions?
    3) What is there not to understand about the link: http://www.java.com/en/download/installed.jsp ?? You just click on the VERIFY INSTALLATION button to see if the Java you just installed, did so correctly. In my case, the Java installed itself (with the automatic install wizard) in a manner that I am not used to. The bottom line is that the verification was only partly correct because it was checking for Java 6 update 9 on a minimum OS of Win2000. I have Win98 SE.
    4) Again, what is so mysterious about Java 5.15 being compatible with HTML and Flash 5? In a nutshell, here is what I want to do: Initialize a numeric variable in Java, and either have Flash use this variable on the Home page, or load the Home page from the beginning.When a certain page is called, increment this variable in Java and again, either pass this variable to Flash, or load Flash at a particular frame. Is this possible?
    Jakob
    Montreal

  • Java Regex Pattern

    Hello,
    I have parsed a text file and want to use a java regex pattern to get the status like "warning" and "ok" ("ok" should follow the "warning" then need to parser it ), does anyone have idea? How to find ok that follows the warning status? thanks in advance!
    text example
    121; test test; test0; ok; test test
    121; test test; test0; ok; test test
    123; test test; test1; warning; test test
    124; test test; test1; ok; test test
    125; test test; test2; warning; test test
    126; test test; test3; warning; test test
    127; test test; test4; warning; test test
    128; test test; test2; ok; test test
    129; test test; test3; ok; test testjava code:
    String flag= "warning";
              while ((line= bs.readLine()) != null) {
                   String[] tokens = line.split(";");
                   for(int i=1; i<tokens.length; i++){
                        Pattern pattern = Pattern.compile(flag);
                        Matcher matcher = pattern.matcher(tokens);
                        if(matcher.matches()){
    // save into a list

    sorry, I try to expain it in more details. I want to parse this text file and save the status like "warning" and "ok" into a list. The question is I only need the "ok" that follow the "warning", that means if "test1 warning" then looking for "test1 ok".
    121; content; test0; ok; 12444      <-- that i don't want to have
    123; content; test1; warning; 126767
    124; content; test1; ok; 1265        <-- that i need to have
    121; content; test9; ok; 12444      <-- that i don't want to have
    125; content; test2; warning; 2376
    126; content; test3; warning; 78787
    128; content; test2; ok; 877666    <-- that i need to have
    129; content; test3; ok; 877666    <-- that i need to have
    // here maybe a regex pattern could be deal with my problem
    // if "warning|ok" then list all element with the status "warning and ok"
    String flag= "warning";
              while ((line= bs.readLine()) != null) {
                   String[] tokens = line.split(";");
                   for(int i=1; i<tokens.length; i++){
                        Pattern pattern = Pattern.compile(flag);
                        Matcher matcher = pattern.matcher(tokens);
                        if(matcher.matches()){
    // save into a list

  • Converting sed regex to Java regex

    I am new to reguler expressions.I have to write a regex which will do some replacements
    If the input string is something like test:[email protected];value=abcd
    when I apply the regex on it,this string should be changed to test:[email protected];value=replacedABC
    I am trying to replace test.com and abcd with the values i have supplied...
    The regex I have come up with is in sed
    s/\(^.*@\)\(.*\)$/\1replaceTest.com;value=replacedABC/i
    Now I am trying to get the regex in Java,I would think it will be something like (^.*@\)(.*\)$\1replaceTest.com;value=replacedABC
    But not sure How i can test this.Any idea on how to make sure my java regex is valid and does the required replacements?

    rsv-us wrote:
    Yep.Agreed.
    Since that these replacements should be done in a single regex.Note that the sed replacement I posted is really made of two replacements! Just like your Java solution would.
    I think once we send this regex to the third party,they will haev to use either sed or perl(will perl do this replacements,not sure though) to get the output.
    Since we are not sure what tool/software the third party is going to use,I was trying to see how i can really test this.Then I read about sed and this regex as is didn't work,so,I had to put all the sed required / and then the regex had become like s/\(^.*@\)\(.*\)$"/1replaceTest.com;value=replacedabcd/iAgain: AFAIK that does not work. I tried it like this:
    {code}$ echo test:[email protected];value=abcd | sed 's/\(^.*@\)\(.*\)$"/1replaceTest.com;value=replacedabcd/i'and the following is returned:test:[email protected] that we will have to send the java regex to the third party,I was trying to see how i can convert this sed regex to java.If I am right,with jave regex,we won;t be able to all the finds and replacements in a single regex..right?...If this is true,this will leave me a question of whether I need to send the sed regex to the thrid party or If I send java regex,they have to convert that to either sed or perl regex.
    One more question,can we do thse replacement in perrl also,if so,what will the equivalent regex for this in perl?
    I can't understand what you are talking about. The large amount of spelling errors also doesn't help to make it clearer.
    Good luck though.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • JAVA Regex Illegal Characters

    Hello - I am trying to find a list of all illegal characters which have to be escaped in JAVA Regex pattern matching but I cannot find a complete list.
    Also I understand that when doing the replaceall function that there is a special list of characters which can't be used for that as well, which also have to be escaped differently.
    If anyone has access to a full complete list as to when to escape and how I would greatly appreciated it!
    Thanks,
    Dan

    I also noticed this below link:
    http://java.sun.com/docs/books/tutorial/extra/regex/literals.html
    It said the following characters are meta-characters in regex API:
    ( [ { \ ^ $ | ) ? * + .
    But it also says the below:
    Note: In certain situations the special characters listed above will not be treated as metacharacters. You'll encounter this as you learn more about how regular expressions are constructed. You can, however, use this list to check whether or not a specific character will ever be considered a metacharacter. For example, the characters ! @ and # never carry a special meaning.
    Does anyone know if there would be any issues if I escaped when a character didn't need to be escaped?

  • Problem while calling java function from html

    when i tried to call a java function from html i'm getting an error
    object don't support this property.
    what could be the reason.
    This is my html.
    I got this from this forum only.
    My applet is accessing the system property "user.home".
    I ran it in IE
    <DIV id="dvObjectHolder">Applet comes here</DIV>
    <br><br>
    <script>
    if(window.navigator.appName.toLowerCase().indexOf("netscape")!=-1){ // set object for Netscape:
         document.getElementById('dvObjectHolder').innerHTML = " <object ID='appletTest1' classid=\"java:test.class\"" +
    "height=\"0\" width=\"0\" onError=\"changeObject();\"" +
              ">" +
    "<param name=\"mayscript\" value=\"Y\">" +
    "<param name=\"archive\" value=\"sTest.jar\">" +
    "</object>";
    }else if(window.navigator.appName.toLowerCase().indexOf('internet explorer')!=-1){ //set object for IE
         document.getElementById('dvObjectHolder').innerHTML = "<object ID='appletTest1' classid=\"clsid:8AD9C840-044E-11D1-B3E9-00805F499D93\"" +
              " height=\"0\" width=\"0\" >" +
              " <param name=\"code\" value=\"test.class\" />" +
         "<param name=\"archive\" value=\"sTest.jar\">" +
              " </object>"
    </script>
    <LABEL id="lblOutputText">This text will be replaced by the applet</LABEL>
    <BR>
    <input value="Javascript to java" type=button onClick="document.appletTest1.fromJavaScript()">

    I tried this example using the repy given to an earlier post.
    But its not working with me.
    What i did in addition was adding plugin.jar to classpath to import netscape.javascript.*;
    Let me add some more details
    1) I'll add the stack trace
    2) my java progrma
    3) batch file to sign the applet.
    1) This is the stack trace i don't know whether u will undertand this
    load: class test.class not found.
    java.lang.ClassNotFoundException: test.class
         at sun.applet.AppletClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.applet.AppletClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.applet.AppletClassLoader.loadCode(Unknown Source)
         at sun.applet.AppletPanel.createApplet(Unknown Source)
         at sun.plugin.AppletViewer.createApplet(Unknown Source)
         at sun.applet.AppletPanel.runLoader(Unknown Source)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Caused by: java.io.FileNotFoundException: C:\FastranJava\AppletObject\bin\test\class.class (The system cannot find the path specified)
         at java.io.FileInputStream.open(Native Method)
         at java.io.FileInputStream.<init>(Unknown Source)
         at java.io.FileInputStream.<init>(Unknown Source)
         at sun.net.www.protocol.file.FileURLConnection.connect(Unknown Source)
         at sun.net.www.protocol.file.FileURLConnection.getInputStream(Unknown Source)
         at sun.applet.AppletClassLoader.getBytes(Unknown Source)
         at sun.applet.AppletClassLoader.access$100(Unknown Source)
         at sun.applet.AppletClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         ... 10 more
    Exception in thread "Thread-5" java.lang.NullPointerException
         at sun.plugin.util.GrayBoxPainter.showLoadingError(Unknown Source)
         at sun.plugin.AppletViewer.showAppletException(Unknown Source)
         at sun.applet.AppletPanel.runLoader(Unknown Source)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    2) Java Program
    import netscape.javascript.*;
    import java.applet.*;
    public class test extends Applet
         private JSObject win;
         private JSObject outputLabel;
         private boolean buttonFromJavaClicked=false;
         checkJavaScriptEvent evt=new checkJavaScriptEvent();
         public void init()
              try
                   evt.start();
                   win=JSObject.getWindow(this);
                   outputLabel=(JSObject)win.eval("document.getElementById('lblOutputText')");
                   outputLabel.setMember("innerHTML", "<center><h1>From Init<br>Your Home directory" + System.getProperty("user.home") + "</h1></center>");
              catch(Exception e)
                   e.printStackTrace();
         public void fromJavaScript()
              buttonFromJavaClicked=true;          
         public void fromJavaScript2()
              System.out.println("Started Form JavaScript2");
              try
                   String strLbl="<center><h1>From JavaScript<br>Your Homedir:" + System.getProperty("user.home") + "</h1></center>";
                   outputLabel.setMember("innerHTML", strLbl);
              catch(Exception e)
                   e.printStackTrace();
         class checkJavaScriptEvent extends Thread
              public void run()
                   while(true)
                        if(test.this.buttonFromJavaClicked)
                             System.out.println("OK buttonfromjava is true");
                             test.this.buttonFromJavaClicked=false;
                             fromJavaScript2();
                        try
                             Thread.sleep(3000);
                        catch(Exception e)
                             e.printStackTrace();
    3) Batch file
    del *.cer
    del *.com
    del *.jar
    del *.class
    javac -classpath ".;C:\Program Files\Java\jre1.5.0_06\lib\plugin.jar" test.java
    keytool -genkey -keystore harm.com -keyalg rsa -dname "CN=Harm Meijer, OU=Technology, O=org, L=Amsterdam, ST=, C=NL" -alias harm -validity 3600 -keypass password -storepass password
    jar cf0 test.jar *.class
    jarsigner -keystore harm.com -storepass password -keypass password -signedjar sTest.jar test.jar harm
    del *.class

  • What is the escape character for DOT in java regex?

    How to specify a dot character in a java regex?
    . itself represents any character
    \. is an illegal escape character

    The regex engine needs to see \. but if you're putting it into a String literal in a .java file, you need to make it \\., as Rene said. This is because the compiler also uses \ as an escape character, so it will take the first \ as escaping the second one, and remove it, and the string that gets passed onto the regex will be \.

  • Inserting JAVA program in HTML

    I want insert a program made with JAVA in a HTML file. How can I do it? I think is not possible!!
    THANKS, JUAN

    I have a hard time believing that this can't be an applet. You might not want it to be an applet, but you should be able to do anything in an applet that you can do in an application. The only way I know to run it on a web page is to make an applet.
    If this has to be an application, I think you're only option is to allow the user to download and run it.
    Here is a link for making jar files more or less runnable.
    http://forum.java.sun.com/thread.jsp?forum=22&thread=196383
    You might also look at Web Start
    http://java.sun.com/products/javawebstart/

  • Java.sql.SQLException: Unexpected token: IN in statement

    I use Toplink 2.0-b41-beta2 (03/30/2007) and have a problem with the following JPQL query:
    “SELECT DISTINCT OBJECT(e) FROM Entry e WHERE e.location IN (SELECT loc From View v JOIN v.viewLocs vl JOIN vl.location loc where v.code = :code)”
    “Entry” is a subclass of “TrainElement”, location points to Entity Location. Entity View has a one-to-many relationship to ViewLoc whereas each ViewLoc has a relationship to a Location object.
    Toplink creates the following incorrect sql statement – I inserted some CRLF for better readability::
    Local Exception Stack:
    Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2.0 (Build b41-beta2 (03/30/2007))): oracle.toplink.essentials.exceptions.DatabaseException
    Internal Exception: java.sql.SQLException: Unexpected token: IN in statement
    [SELECT DISTINCT t0.TELEM_TRAINELEM_ID, t0.TRAINELEMENT_TYPE, t0.TELEM_INDEX, t0.TTELEM_TRAIN_ID, t0.ENTRY_TYPE, t0.ENTRY_ARRIVAL, t0.DISPLAY, t0.ENTRY_ORDERED_STOP, t0.ENTRY_DEPARTURE, t0.ENTRY_ORDER_CODE, t0.ENTRY_PREV_SEC_ID, t0.ENTRY_NEXT_SEC_ID, t0.ENT_LOC_ID FROM TRAINELEMENT t0, LOCATION t1
    WHERE (( IN ((SELECT DISTINCT t2.LOC_ID, t2.LOC_GPSY, t2.LOC_GRX, t2.LOC_CODE, t2.LOC_GRY, t2.LOC_GPSX, t2.LOC_LOCAL_RADIO, t2.LOC_NAME, t2.DELETED, t2.LOC_CLASS_ID FROM VIEW t4, VIEWLOC t3, LOCATION t2 WHERE ((t4.VIEW_CODE = ?) AND ((t3.VIEWLOC_VIEW_ID = t4.VIEW_ID) AND (t2.LOC_ID = t3.VIEWLOC_LOCACTION_ID))))) AND (t0.TRAINELEMENT_TYPE = ?)) AND (t1.LOC_ID = t0.ENT_LOC_ID))]
    Error Code: -11
    Call: SELECT DISTINCT t0.TELEM_TRAINELEM_ID, t0.TRAINELEMENT_TYPE, t0.TELEM_INDEX, t0.TTELEM_TRAIN_ID, t0.ENTRY_TYPE, t0.ENTRY_ARRIVAL, t0.DISPLAY, t0.ENTRY_ORDERED_STOP, t0.ENTRY_DEPARTURE, t0.ENTRY_ORDER_CODE, t0.ENTRY_PREV_SEC_ID, t0.ENTRY_NEXT_SEC_ID, t0.ENT_LOC_ID FROM TRAINELEMENT t0, LOCATION t1 WHERE (( IN ((SELECT DISTINCT t2.LOC_ID, t2.LOC_GPSY, t2.LOC_GRX, t2.LOC_CODE, t2.LOC_GRY, t2.LOC_GPSX, t2.LOC_LOCAL_RADIO, t2.LOC_NAME, t2.DELETED, t2.LOC_CLASS_ID FROM VIEW t4, VIEWLOC t3, LOCATION t2 WHERE ((t4.VIEW_CODE = ?) AND ((t3.VIEWLOC_VIEW_ID = t4.VIEW_ID) AND (t2.LOC_ID = t3.VIEWLOC_LOCACTION_ID))))) AND (t0.TRAINELEMENT_TYPE = ?)) AND (t1.LOC_ID = t0.ENT_LOC_ID))
         bind => [ROMAN W-Pb, ENT]
    There sould be a “t0.ENT_LOC_ID” before the IN in the WHERE clause and the implicit join “ID FROM TRAINELEMENT t0, LOCATION t1” seems incorrect to me. At any rate the database (HSQLDB) rejects that incorrect sql statement.
    How can I circumvent that problem?
    A add the relevant mapping part of the involved classes.
    @Entity
    @DiscriminatorValue("ENT")
    public class Entry extends TrainElement implements IEntry {
         @ManyToOne(cascade = CascadeType.ALL)
         @JoinColumn(name = "ENT_LOC_ID", nullable = true)
         private Location location;
    @Entity
    @Table(name = "LOCATION")
    public class Location implements ILocation {
         // persistent part
         // primary key field
         @Id
         @GeneratedValue
         @Column(name = "LOC_ID")
         private Long id;
         @Column(name = "LOC_CODE", nullable = false)
         private String code;
         @Column(name = "LOC_NAME", nullable = false)
         private String name;
    @Entity
    @EntityListeners(EntityListener.class)
    @Table(name = "VIEW")
    public class View implements IView {
         // persistent
         // primary key field
         @Id
         @GeneratedValue
         @Column(name = "VIEW_ID")
         private Long id;
         @OneToMany(mappedBy = "view", cascade = CascadeType.ALL)
         private List<ViewLoc> viewLocs = new ArrayList<ViewLoc>();
    @Entity
    @Table(name = "VIEWLOC")
    @EntityListeners(EntityListener.class)
    public class ViewLoc implements IViewLoc {
         // persistent fields
         // primary key field
         @Id
         @GeneratedValue
         @Column(name = "VIEWLOC_ID")
         private Long id;
         @ManyToOne(cascade = CascadeType.ALL)
         @JoinColumn(name = "VIEWLOC_VIEW_ID", nullable = false)
         private View view;
         // direct Linking to the infrastrucutre location
         @ManyToOne(cascade = CascadeType.ALL)
         @JoinColumn(name = "VIEWLOC_LOCACTION_ID")
         private Location location;
    ….

    IN doesn't support objects, only state_field_path_expression that must have a string, numeric, or enum value.
    Try using
    “SELECT DISTINCT OBJECT(e) FROM Entry e WHERE e.location.id IN (SELECT loc.id From View v JOIN v.viewLocs vl JOIN vl.location loc where v.code = :code)”
    Best Regards,
    Chris

  • How to call java program by HTML page

    Hi guys,
    I'm new java programer and want to build an HTML page to access to ORACLE database on NT server by JDBC, Can anyone give me a sample?
    I already know how to access database by JDBC, but I don't know how to call java program by HTML page.
    If you have small sample,pls send to me. [email protected], thanks in advance
    Jian

    This code goes with the tutorial from this web page
    http://java.sun.com/docs/books/tutorial/jdbc/basics/applet.html
    good luck.
    * This is a demonstration JDBC applet.
    * It displays some simple standard output from the Coffee database.
    import java.applet.Applet;
    import java.awt.Graphics;
    import java.util.Vector;
    import java.sql.*;
    public class OutputApplet extends Applet implements Runnable {
    private Thread worker;
    private Vector queryResults;
    private String message = "Initializing";
    public synchronized void start() {
         // Every time "start" is called we create a worker thread to
         // re-evaluate the database query.
         if (worker == null) {     
         message = "Connecting to database";
    worker = new Thread(this);
         worker.start();
    * The "run" method is called from the worker thread. Notice that
    * because this method is doing potentially slow databases accesses
    * we avoid making it a synchronized method.
    public void run() {
         String url = "jdbc:mySubprotocol:myDataSource";
         String query = "select COF_NAME, PRICE from COFFEES";
         try {
         Class.forName("myDriver.ClassName");
         } catch(Exception ex) {
         setError("Can't find Database driver class: " + ex);
         return;
         try {
         Vector results = new Vector();
         Connection con = DriverManager.getConnection(url,
                                  "myLogin", "myPassword");
         Statement stmt = con.createStatement();
         ResultSet rs = stmt.executeQuery(query);
         while (rs.next()) {
              String s = rs.getString("COF_NAME");
              float f = rs.getFloat("PRICE");
              String text = s + " " + f;
              results.addElement(text);
         stmt.close();
         con.close();
         setResults(results);
         } catch(SQLException ex) {
         setError("SQLException: " + ex);
    * The "paint" method is called by AWT when it wants us to
    * display our current state on the screen.
    public synchronized void paint(Graphics g) {
         // If there are no results available, display the current message.
         if (queryResults == null) {
         g.drawString(message, 5, 50);
         return;
         // Display the results.
         g.drawString("Prices of coffee per pound: ", 5, 10);
         int y = 30;
         java.util.Enumeration enum = queryResults.elements();
         while (enum.hasMoreElements()) {
         String text = (String)enum.nextElement();
         g.drawString(text, 5, y);
         y = y + 15;
    * This private method is used to record an error message for
    * later display.
    private synchronized void setError(String mess) {
         queryResults = null;     
         message = mess;     
         worker = null;
         // And ask AWT to repaint this applet.
         repaint();
    * This private method is used to record the results of a query, for
    * later display.
    private synchronized void setResults(Vector results) {
         queryResults = results;
         worker = null;
         // And ask AWT to repaint this applet.
         repaint();

  • Accessing oracle DB from a java program - question for oracle driver

    Hi,
    I have Oracle 10 G under vista on my desktop. I am trying to write a simple java program to access/update database tables. I saw in one of oracle example to import 2 packages - namely --- import oracle.jdbc.driver.*; import oracle.sql.*;
    Where do I find these 2 packages. Also I read some documentation to download drivers. I would like to use 2 drivers, the thin driver and the OCI driver. Can someone tell me where I can find these drivers and where do I copy these two drivers - so javac and java command can recognize it.
    I will greatly appreciate the help. Julia
    My program is as follows
    (It was working few years ago but things have changed now and I have Vista because my old machine died):
    import java.sql.*; // JDBC package
    //import com.inet.tds.JDBCRowSet;
    import java.util.*;
    import oracle.jdbc.driver.*;
    import oracle.sql.*;
    public class HomeDB
    run as follows:
    C:\Documents and Settings\MMM>cd \jj
    C:\john>set CLASSPATH=.;c:\oracle9i\classes12;%CLASSPATH%
    C:\john>javac HomeDB.java
    C:\john>java HomeDB
    King: 24000.0
    Kochhar: 17000.0
    De Haan: 17000.0
    Hunold: 9000.0
    Ernst: 6000.0
    Austin: 4800.0
    public static void main(String[] argv)throws SQLException
    Connection conn=null;
    try // may throw a SQLException
    conn = getConnection();
    doQuery (conn);
    catch (SQLException e)
    System.err.println(e.getErrorCode() + ": " + e.getMessage());
    finally // make sure the connection is closed
    if (conn != null) try {conn.close();} catch (SQLException e) {};
    //out.close(); // close PrintWriter stream
    private static Connection getConnection() throws SQLException
    String username = "scott";
    String password = "tiger";
    String url = "jdbc:oracle:thin:@localhost:1521:newora";
    // "jdbc:oracle:thin:@localhost:1521:COCKYJOB";
    Connection conn = null;
    String driver = "oracle.jdbc.driver.OracleDriver";
    try {
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
    } catch ( ClassNotFoundException cnfex ) {
    System.err.println(
    "Failed to load JDBC/ODBC driver." );
    cnfex.printStackTrace();
    }catch (Exception e){
    e.printStackTrace();
    //DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
    conn = java.sql.DriverManager.getConnection(url,username,password);
    conn.setAutoCommit(false);
    return conn;
    private static void doQuery (Connection c) throws SQLException
    // statement to be executed
    String query = "SELECT ename, job, mgr FROM EMP";
    Statement st = null;
    ResultSet rs = null;
    try // make sure the close statements are executed (in the finally block)
    // create the statement
    st = c.createStatement();
    // execute the query
    rs = st.executeQuery(query);
    // process results
    while (rs.next())
    // get the employee last name
    String eName = rs.getString("ename");
    String eJob = rs.getString("job");
    String eMgr = rs.getString("mgr");
    System.out.println("Emp Name:" + eName +
    "Job: " + eJob +
    "MGR: " + eMgr);
    finally // make sure the close statements are executed
    // close the result set if it exists
    if (rs != null) try {rs.close();} catch (Exception e) {};
    // close the statement if it exists
    if (st != null) try {st.close();} catch (Exception e) {};
    Edited by: user455788 on Dec 19, 2008 9:13 PM

    You can download the drivers from http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/index.html.
    Note that oracle.jdbc.driver is desupported after 10.2, http://forums.oracle.com/forums/ann.jspa?annID=201, so you might want to consider using a DataSource to provide Connections.
    E.G.
    {message:id=2819114}

  • Flash/java remoting question

    Hi,
    i'm new to flash remoting and am finding using it with java
    quite troublesome. I've also found using the FileReference class
    troublesome if you use java. my question is can you somehow tie the
    remoting functionality to the FileReference.upload method
    fucntionality??
    thanks in advance

    I will use the program with photo detector to test
    the response time of the LCD screenWhy Java?I second that. With a test like that, you want to reduce the experiment down to a single variable, in this case the lcd response time. Using a java program to feed the monitor input introduces a second variable, the response time of the program. The java program's timer may not be exact, the components may not be repainted completely quickly enough, etc. If this is just for your own amusement, maybe that doesn't matter, but if you want your results to have any reliability, you'll need a more accurate and controllable input source.

Maybe you are looking for

  • IOS 8.3 deletes album artwork off iPod?

    I have a fifth generation iPod touch which I have on manually managing music since we have two computers in the house.  As soon as i updated to iOS 8.3 the album artwork no longer displays on my iPod but when i plug it in to the computer and right li

  • Certificate signing request with subject alternative names?

    Has anyone been successful at generating a certificate signing request for a certificate that uses subject alternative names via the Server Manager GUI? It seems to skip the entire X509 section of the CSR for me. Command line via openssl works but I'

  • Oracle DataGuard Logical Standby

    Hi , I'd like to know what are the premisses to make a standby logical replication. I have two environments (production and standby) with different number of processors and storage. I'd like to know if it's possible to create data guard solution with

  • Simple question, please help

    I just need to know right now can SSL be used for secure FTP to send commands and data over separate channels, and if so, how? I want to replace a simple FTP socket connection with a secure one, nothing fancy. I don't want to use HTTP unless I absolu

  • Getting Device Properties like OS,Model,Brand,SDK,Version and CPU on Air for Android

    Hi there, I just wanted to share this old blog post in case no one knew about this here (like i didn't). I have no affiliation with this person, i just think its great! Getting Device Properties like OS,Model,Brand,SDK,Version and CPU on Air for Andr