Java Preferences api jndi / jdbc implementations?

We have a requirement to save users gui layout preferences (swing client) in a central location (through a j2ee ejb container). the users should be allowed to log into any company workstation, and have the gui client come up with the users preferences restored.
does anyone know of commercial or open source implementations of the java preferences api that might accomplish this? (hoping not to re-invent...)
Thanks
Joe e.

I am sure this is not a difficult thing to implement, you might actually spend more time looking for open source implementations rather than do it on your own. I am sure you want to save things like window/frame positions, size, colours, look and feel etc. You can simply save this information in a property file/object. Just any idea...

Similar Messages

  • Preferences API: How to implement Preferences modifications methods?

    I want to implement methods in Preferences API like putSpi, removeSpi and flushSpi. Backend where all preferences exists is LDAP and XML. At present I have only prefs accessing methods. Please provide me some guidance in this regards.
    Regards,
    Varun

    found it out myself:
    private Preferences prefs = Preferences.userRoot().node(MyClass.class.getName());

  • Java Preferences API - Help needed

    Hi,
    I have to create a file which contains all the properties of my application using Preferences class.
    The properties file should look like:
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <!DOCTYPE preferences SYSTEM "http://java.sun.com/dtd/preferences.dtd">
    <preferences EXTERNAL_XML_VERSION="1.0">
    <root type="user">
    <map/>
    <node name="Service1">
    <map>
    <entry key="ssw" value="ggggg"/>
    <entry key="vfr" value="hhhhhhhh"/>
    <entry key="cfe" value="lkjhgg"/>
    <entry key="sdx" value="uytreww"/>
    <entry key="dsc" value="qqqqqqq"/>
    </map>
    </node>
    <node name="Service2">
    <map>
    <entry key="34" value="acd"/>
    <entry key="ert" value="sss"/>
    <entry key="frd" value="wed"/>
    <entry key="dvf" value="cf"/>
    <entry key="cfg" value="gvss"/>
    </map>
    </node>
    </root>
    </preferences>
    Thats means what I am trying to do is create a separate node for each of the services in my application.
    But when I try to add 2nd node after adding the 1st node the, the 1st node is overwritten and the properties file has only 2nd node information in it.
    Please see the snapshot of the code being used by me.
    public void setConfiguration(final Dictionary properties,
                   final String service) {
              Preferences pref = Preferences.userRoot().node(service);
              FileOutputStream output = null;
              FileLock lock = null;
              try {
                   output = new FileOutputStream(FILE_NAME);
                   lock = output.getChannel().lock();
                   Preferences.userRoot().flush();
                   if (null != lock) {
                        final Enumeration<?> pnen = ((Properties) properties)
                                  .propertyNames();
                        String propKey;
                        String propValue;
                        while (pnen.hasMoreElements()) {
                             propKey = (String) pnen.nextElement();
                             propValue = (String) properties.get(propKey);
                             pref.put(propKey, propValue);
                        pref.exportSubtree(output);
                   } else {
                        throw new Exception();
                   String message = "Write operation completed successfully.";
                   LOGGER_INSTANCE.info(message);
              } catch (Exception e) {
                   throw new ConfigurationServiceCommonException(
                             ConfigurationServiceExceptionConstants.FILE_NOT_FOUND, e
                                       .getCause());
              } finally {
                   try {
                        if (null != lock && lock.isValid()) {
                             lock.release();
                        if (null != output) {
                             output.close();
                   } catch (IOException e) {
              return;
    Please help me in resolving this issue.
    Java Rules :)
    Thanks
    Sameer

    SAMEERRITU wrote:
    ..I have to create a file which contains all the properties of my application using Preferences class.
    The properties file should look like:
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <!DOCTYPE preferences SYSTEM "http://java.sun.com/dtd/preferences.dtd">
    <preferences EXTERNAL_XML_VERSION="1.0">
      <root type="user">
        <map/>
        <node name="Service1">
          <map>
            <entry key="ssw" value="ggggg"/>
            <entry key="vfr" value="hhhhhhhh"/>
            <entry key="cfe" value="lkjhgg"/>
            <entry key="sdx" value="uytreww"/>
            <entry key="dsc" value="qqqqqqq"/>
          </map>
        </node>
        <node name="Service2">
          <map>
            <entry key="34" value="acd"/>
            <entry key="ert" value="sss"/>
            <entry key="frd" value="wed"/>
            <entry key="dvf" value="cf"/>
            <entry key="cfg" value="gvss"/>
          </map>
        </node>
      </root>
    </preferences>
    Thats means what I am trying to do is create a separate node for each of the services in my application.
    But when I try to add 2nd node after adding the 1st node the, the 1st node is overwritten and the properties file has only 2nd node information in it.
    Please see the snapshot of the code being used by me.
    public void setConfiguration(final Dictionary properties,
                   final String service)  {
              Preferences pref = Preferences.userRoot().node(service);
              FileOutputStream output = null;
              FileLock lock = null;
              try {
                   output = new FileOutputStream(FILE_NAME);
                   lock = output.getChannel().lock();
                   Preferences.userRoot().flush();
                   if (null != lock) {
                        final Enumeration<?> pnen = ((Properties) properties)
                                  .propertyNames();
                        String propKey;
                        String propValue;
                        while (pnen.hasMoreElements()) {
                             propKey = (String) pnen.nextElement();
                             propValue = (String) properties.get(propKey);
                             pref.put(propKey, propValue);
                        pref.exportSubtree(output);
                   } else {
                        throw new Exception();
                   String message = "Write operation completed successfully.";
                   LOGGER_INSTANCE.info(message);
              } catch (Exception e) {
                   throw new ConfigurationServiceCommonException(
                             ConfigurationServiceExceptionConstants.FILE_NOT_FOUND, e
                                       .getCause());
              }  finally {
                   try {
                        if (null != lock && lock.isValid()) {
                             lock.release();
                        if (null != output) {
                             output.close();
                   } catch (IOException e) {
              return;
    Please help me in resolving this issue.When posting code, code snippets, HTML/XML or input/output, please use the code tags. The code tags help retain the indentation and formatting of the sample. To use the code tags, select the code and click the CODE button.
    Some other points, now I can actually view the source without it making me go cross-eyed.
                   } catch (IOException e) {
                   }Never [swallow exceptions|http://pscode.org/javafaq.html#stacktrace] *(<- link),* especially in broken code!
    Note that for better help, sooner, post an SSCCE *(<- link),* rather than uncompilable code snippets.

  • JDBC implementation in an application ... newbie question

    Hi all ...
    My first post here. Hope Im at the right place.
    I've just started out with java, had gotten the basics and started to develop a little. Now, I would like to involve a MySQL database. I have made a few small connection tests and selections/insertions and all works fine.
    Now, I have been googleing the net a few times but I cant seem to find any good source of information on how you implement the DB layer in an application. How is it usually done?
    I got a few classes that need got get info from MySQL to fill a ArrayList for example. I need authentication agains the MySQL database for users. Regular things. I understand how this should be done but not how to go about implementing it. Where should the DB connection be done so I dont have to make a connect in every method I want DB access in. Please, anything would be helpful.
    Thanx in advance ...
    /Roger

    Hi all ...
    My first post here. Hope Im at the right place. Welcome. You've come to the right spot.
    >
    I've just started out with java, had gotten the
    basics and started to develop a little. Now, I would
    like to involve a MySQL database. I have made a few
    small connection tests and selections/insertions and
    all works fine. Excellent.
    Now, I have been googleing the net a few times but I
    cant seem to find any good source of information on
    how you implement the DB layer in an application. How
    is it usually done? I don't think there's one way that everyone would agree on. I'm sure your Google search has turned up a lot of stuff: object-relational mapping, JDO, entity EJBs, the new Java Persistence API, straight JDBC.
    One pattern that's popular these days is the Data Access Object, or DAO. Google for that and see what you think.
    The idea is to isolate the SQL stuff into a single package of classes.
    I got a few classes that need got get info from MySQL
    to fill a ArrayList for example. I need
    authentication agains the MySQL database for users.
    Regular things. I understand how this should be done
    but not how to go about implementing it.
    Where should
    the DB connection be done so I dont have to make a
    connect in every method I want DB access in. I'm not sure what you mean by this, but I would say that a fresh connection for each database unit of work is a good idea. The idea is to get a connection when you need it, use it, and close it so somebody else can use it. It scales better that way.
    You'll want to read about connection pooling, too.
    %

  • Disabling backing store on Preferences API

    I'm working with a third-party API that makes heavy use of the Java Preferences API.
    However for the application I'm building persistent storage of preferences makes no sense. Therefore I want to disable the backing store so that my "preferences" becomes something that lives in memory only. I also want to avoid the hassle that might come from not having write permission to the backing store.
    I can find lots of examples on the Internet for disabling the Preferences API all-together. This is done by creating a new PrefencesFactory that does absolutely nothing and using this factory instead of the default.
    (all references on the Internet seem to ultimately come from this article: http://www.allaboutbalance.com/disableprefs/)
    I'm not sure what is in that article is what I want. I do not want to disable the Preferences API all-together, I only want to disable the backing store. I'm uncertain if that is what I get from the above mentioned DisabledPreferences implementation.
    Any ideas of how I can disable the backing store ?
    Thanks.

    Thanks, Kaj.
    My question was not entirely clear. As I understand Sun's Preferences API in its standard form it holds the data both in memory (cache) and in the persistent backing store. Therefore I'm not sure it is even required to build a backing store that holds data in memory, i.e. I can use DisabledPreferences in its unmodified form.
    If I'm lucky then all the "get" methods do not in fact go to the backing store to get the value but instead answer with a value from cache. I would expect the backing store to be asked only if the question cannot be answered from cache. If true I will not have to implement my own memory-based backing store.
    But why do I waste your time with this when a simple test will quickly reveal what is going on. :-)
    Stay tuned.
    Thanks.

  • Java.utils.prefs.Preferences API throws exception on Mac, not Windows

    This is a Mac-specific problem. Is it a bug, or am I misusing the java.utils.prefs.Preferences API?
    The Preferences flush() API call always throws a BackingStoreException if a system tree preferences root has been read. The system tree has not been modified or written to, but the flush() call is nevertheless throwing an exception. This occurs when running as a normal user without the ability to write to /Library/Preferences.
    See sample code below. Note that I only want to read the system prefs tree. The user tree write flush fails. If the system tree node is not created, the user flush() succeeds.
    Steps to Reproduce
    Delete any existing Java prefs files:
    ~/Library/Preferences/com.apple.java.util.prefs.plist
    ~/Library/Preferences/com.mycompany.prefstest
    /Library/Preferences/com.apple.java.util.prefs.plist
    /Library/Preferences/com.mycompany.prefstest
    Run the following Java code:
    package com.mycompany.prefstest;
    import java.util.prefs.BackingStoreException;
    import java.util.prefs.Preferences;
    public class PrefsTest {
          * @param args
         public static void main(String[] args) {
              String strKey1 = "com/mycompany/prefstest/one/two/three/four/key1";
              Preferences systemRoot = Preferences.systemRoot();
              Preferences userRoot = Preferences.userRoot();
              // Get a value for user prefs.
              String value1 = userRoot.get(strKey1, "missing");
              // Fall back to system prefs if it is not defined.
              if (value1.equals("missing"))
                   value1 = systemRoot.get(strKey1, "missing");
              System.out.println("key1 --> " + value1);
              // If still not defined, set a user-specific value
              if (value1.equals("missing"))
                   userRoot.put(strKey1, "value1");
                   try {
                        userRoot.flush();
                        System.out.println("flushed prefs successfully");
                   catch (BackingStoreException e)
                        System.out.println("Exception: " + e.toString());
    Expected Results
    Should produce the output:
    key --> missing
    flushed prefs successfully
    Actual Results
    Console output is
    key --> missing
    Exception: java.util.prefs.BackingStoreException: Synchronization failed for node '/'
    Notes
    $ java -version
    java version "1.6.0_29"
    Java(TM) SE Runtime Environment (build 1.6.0_29-b11-402-11D50b)
    Java HotSpot(TM) 64-Bit Server VM (build 20.4-b02-402, mixed mode)
    also tested with:
    java version "1.7.0_04-ea"
    Java(TM) SE Runtime Environment (build 1.7.0_04-ea-b16)
    Java HotSpot(TM) 64-Bit Server VM (build 23.0-b17, mixed mode)
    Mac OS X 10.7.3.
    The "Expected Results" are correctly obtained running the same code on MS-Windows.
    Running the jar as sudo works (with write access to /Library/Preferences), as expected.

    Just for fun, try a key without slashes in it (but for example dots if you must use such a long key).
    I say that because a quick Google search points out that Apple stores the preferences in a file hierarchy in the user home folder. I can already see how using keys which look like a file path are going to cause nuclear reactors to meltdown...

  • Preferences API Faulty Implementation

    Hello.
    I am tyring to use te Preferences API. I feel the implementation is faulty. See if you agree:
    In order to use the API, you must invoke one of xxNodeForPackage(Class) or xxRoot(). All 4 of these methods throw SecurityException. How can you make a fallback mechanism?
    Basically this problem is that when you go to get the Preferences, if it's not there you end up with nothing but a null reference -- you can't force-feed an instance with some file you might have containing defaults. You can't come up with even a noop implementation in reality.
    So what are you supposed to do -- go around checking if (myPrefs != null) through all your code?! This is my dilemma.

    I'm glad someone found this post!
    The problem is in the SecurityException. An example looks like this:
    To create the preferences object, we go looking on disk. We use:
    Preferences.userNodeForPackage(Class)or systemNode.. or ..Root. Now: we must catch the SecurityException. So our code will go something like this:
    Preferences userPref = null;
    try {
        userPref = Preferences.userNodeForPackage(getClass());
    catch (SecurityException e) {
         * userPref stays null.
         * And: we have no way to provide a default object or to
         * "force-feed" default values into one somehow.
    }Here you see, in the case where that exception is thrown, we can't create any kind of Preferences object that we could use to just return default values (or some similar fallback technique). -- In all future attempts to get preference data from that node, we would have to check if we actually did get the object. (That's what I said about checking for null.) So, every time we want a pref we would have to test something like this:
    boolean theRealDefault = false;
    if (userPref != null) {
        setState(userPref.getBoolean("state", theRealDefault);
    else {
        setState(theRealDefault);
    }Which is just silly -- but I can't see the way around it!
    Maybe I'm missing something?
    Thanks for the help!
    - Steev.

  • [End of TNS data channel] with Java SDO API (JDBC thin 9.0.1.2.1)

    Hello folks,
    Environment:
    Win2K, 1.2GHz Intel, 500MB RAM, Oracle 9i, Oracle JDBC Thin (9.0.1.2.1), JDK1.3
    Our data in the DB is 2-D. It consists of SDO LineString geometries. We use SRID = 8307.
    I run into this problem with Java SDO API. I got this exception: "Io exception: End of TNS data channel"
    when I try to execute query that uses the SDO_RELATE function:
    SELECT e.shape
    FROM edge e
    WHERE SDO_RELATE(e.shape,
    mdsys.sdo_geometry( 2003, 8307, NULL,
    mdsys.sdo_elem_info_array(1,1003,1),
    mdsys.sdo_ordinate_array(-125.8,49.9,-125.6,49.9,-125.6,50.0,-125.8,50.0,-125.8,49.9) ),
    'mask=ANYINTERACT querytype=WINDOW') = 'TRUE'
    If I use SDO_FILTER instead of SDO_RELATE it works!
    Here is how I execute the query in Java:
    public int executeSpatialQuery(OracleConnection conn, String spatialQuery) throws Exception
    int numberOfGeometries = 0;
    conn.setDefaultRowPrefetch(1000);
    Statement ps = conn.createStatement();
    ResultSet rs = ps.executeQuery(spatialQuery);
    while (rs.next()) {
    numberOfGeometries++;
    rs.close();
    ps.close();
    return numberOfGeometries;
    Note: I was playing with the "conn.setDefaultRowPrefetch(n)" method hoping that there might be something to do with that but with no success.
    Any help will be much appreciated. Thank you.
    GKK

    Hello folks,
    Here is what I've done:
    1. Created a "mini" Realtional model (modelB) which mimics exactly our existing "big" Realtional model (modelA). The tables, sequences, indices, etc. in modelB have been created in exactly the same fashion we'd created the corresponding entities in modelA. The only difference is that I preceeded the entities in our test modelB with "TEST_".
    2. Populated the modelB with 1298 Lakes (3993 edges in total) in exatly the same fashion we use to populate our modelA - using a Data Loader based on Java SDO API.
    3. Indexed the test modelB in exactly the same fashion as modelA.
    4. Ran the query:
    SELECT e.shape FROM test_edge e WHERE SDO_RELATE(e.shape,
    mdsys.sdo_geometry(
    2003,
    8307,
    NULL,
    mdsys.sdo_elem_info_array(1,1003,1),
    mdsys.sdo_ordinate_array(
    -123.80833332065798,48.58352678668598,
    -123.80833332065798,48.675352618459506,
    -123.65050767229724,48.675352618459506,
    -123.65050767229724,48.58352678668598,
    -123.80833332065798,48.58352678668598
    ), 'mask=ANYINTERACT querytype=WINDOW'
    ) = 'TRUE'
    in SQL*PLUS and it worked fine (retrieved a bunch of geometries)!
    Ran the same query in the Daniel Geringer's OraTest utility and it worked this time and returned:
    TIME : 1.222 seconds, TOTAL FETCH TIME 267 ROWS
    Ran the query with our JCS Query Plug-In and it worked fine!
    ANALYSIS
    ========
    ModelA
    ======
    - 59652 Lakes and 178764 edges
    - it's properly indexed
    - its SDO layers and geometries are valid
    - when we count the number of related SDO geometries for this query we get:
    SQL> SELECT count(e.shape) FROM edge e WHERE SDO_RELATE(e.shape,
    2 mdsys.sdo_geometry(
    3 2003,
    4 8307,
    5 NULL,
    6 mdsys.sdo_elem_info_array(1,1003,1),
    7 mdsys.sdo_ordinate_array(
    8 -123.80833332065798,48.58352678668598,
    9 -123.80833332065798,48.675352618459506,
    10 -123.65050767229724,48.675352618459506,
    11 -123.65050767229724,48.58352678668598,
    12 -123.80833332065798,48.58352678668598
    13 )
    14 ), 'mask=ANYINTERACT querytype=WINDOW'
    15 ) = 'TRUE';
    COUNT(E.SHAPE)
    267
    - when we run the following query via the Java SDO API:
    SELECT e.shape FROM edge e WHERE SDO_RELATE(e.shape,
    mdsys.sdo_geometry(
    2003,
    8307,
    NULL,
    mdsys.sdo_elem_info_array(1,1003,1),
    mdsys.sdo_ordinate_array(
    -123.80833332065798,48.58352678668598,
    -123.80833332065798,48.675352618459506,
    -123.65050767229724,48.675352618459506,
    -123.65050767229724,48.58352678668598,
    -123.80833332065798,48.58352678668598
    ), 'mask=ANYINTERACT querytype=WINDOW'
    ) = 'TRUE'
    it FAILS with: "TNS end of communaction channel"!
    ModelB
    ======
    - 1298 Lakes and 3993 edges
    - it's properly indexed
    - its SDO layers and geometries are valid
    - when we count the number of related SDO geometries for this query we get:
    SQL> SELECT count(e.shape) FROM test_edge e WHERE SDO_RELATE(e.shape,
    2 mdsys.sdo_geometry(
    3 2003,
    4 8307,
    5 NULL,
    6 mdsys.sdo_elem_info_array(1,1003,1),
    7 mdsys.sdo_ordinate_array(
    8 -123.80833332065798,48.58352678668598,
    9 -123.80833332065798,48.675352618459506,
    10 -123.65050767229724,48.675352618459506,
    11 -123.65050767229724,48.58352678668598,
    12 -123.80833332065798,48.58352678668598
    13 )
    14 ), 'mask=ANYINTERACT querytype=WINDOW'
    15 ) = 'TRUE';
    COUNT(E.SHAPE)
    267
    - when we run the following query via the Java SDO API:
    SELECT e.shape FROM test_edge e WHERE SDO_RELATE(e.shape,
    mdsys.sdo_geometry(
    2003,
    8307,
    NULL,
    mdsys.sdo_elem_info_array(1,1003,1),
    mdsys.sdo_ordinate_array(
    -123.80833332065798,48.58352678668598,
    -123.80833332065798,48.675352618459506,
    -123.65050767229724,48.675352618459506,
    -123.65050767229724,48.58352678668598,
    -123.80833332065798,48.58352678668598
    ), 'mask=ANYINTERACT querytype=WINDOW'
    ) = 'TRUE'
    it SUCCESSFULLY returns the related geometries!
    So, what can we make of all this? We know that there exists a model for which the SDO_RELATE works via the Java SDO API. This model is a subset (w.r.t. the data set) of our original model in which we detected the "TNS end of communication channel problem". The environment we used for these tests is exactly the same: JDBC Thin driver (version 9.0.1.0.0), Oracle9i Enterprise Edition (Release 9.0.1.2.1 - Production).
    One can think that the problem lies in the Oracle Object-Realational or Oracle Spatial but the fact that we can successfully execute the same SDO_RELATE queries in SQL*PLUS rejects this possibility. Perhaps it depends on the amount of data passed to the JDBC driver and the fashion in which it handles it! In our test above we had RELATED 267 geometries. We know that there exist SDO_RELATE queries that run successfully with modelA, but those are queries which ONLY retrieve an EMPTY set of RELATED geometries. In other words we don't get the "TNS end of communication channel" because NO data gets fetched from the server to the client! As soon as we find a SDO_RELATE query which retrieves (RELATES) at least 1 geometry that runs successfully in SQL*PLUS and run it via the Java SDO API - it FAILS! This means that no matter what volume of data is fetched from the server-JDBCThin-SDOAPI-client as long as there is ANY data, the query FAILS in modelA.
    Perhaps something internally in the Oracle 9i Server happens that prevent the data being fetch to the JDBCThin for that particular modelA. But what that might be?
    Very peculiar problem!
    Regards,
    Georgi

  • How to use java print API???  very very urgent

    Hi
    I fed up with the JAVA print API. If anybody knows how to print a file .txt, please let me know.
    cheers
    shyam

    import javax.swing.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import java.sql.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import utility.*;
    import java.awt.print.*;
    public class remRunPrint extends JFrame implements ActionListener, Printable {
         static JButton j = new JButton("Print");
         String printer = "IT";
         java.util.Date pDate;
         public void setCopies(int i) {
              copies = i;
         public void setPrinter(String s) {
              if (s.length() > 0) {
                   printer = s;
         public void getInfo(int vid) {
              ResultSet verRS;
              try {
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   Connection conn = DriverManager.getConnection("jdbc:odbc:SOMEdbnAME");
                   Statement stmt = conn.createStatement();
                   verRS = stmt.executeQuery("SOME SQL QUERY HERE");
                   verRS.next();
                   //SET SOME VARIABLES HERE..
              } catch (Exception e) {
                   System.out.println("getinfo: " + e);
    public void actionPerformed(ActionEvent e) {
    if (e.getSource() instanceof JButton) {  
                   wookie();
         public void wookie() {
              PrinterJob printJob = PrinterJob.getPrinterJob();
              Paper paper = new Paper();
              PageFormat page = new PageFormat();
              paper.setImageableArea(0, 0, 600, 800);     
              page.setPaper(paper);
              printJob.setPrintable(this, page);
              PrintService[] services = PrintServiceLookup.lookupPrintServices(null, new HashPrintRequestAttributeSet());
              PrintService ps = PrintServiceLookup.lookupDefaultPrintService();
              for (int i=0; i<services.length;i++) {
                   if (services.toString().indexOf(printer) > 0) {
                        ps = services[i];     
              try{
                   printJob.setCopies(copies);
                   //printJob.pageDialog(page);
                   printJob.setPrintService(ps);
                   //if (printJob.printDialog()) {
                        printJob.print();
              } catch (Exception e) {
                   System.out.println("wookie1run1" + e);
         public static void main(String[] args) {
              remRunPrint at = new remRunPrint();
              at.getInfo((new Integer(args[0])).intValue());
              at.drawShapes();
              at.wookie();
         public void drawShapes() {
              setBounds(0, 0, 670, 550);
              addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}});
              JLabel l = new JLabel("<html><body><table><tr bgcolor=blue><td><font color=red>Hello EVERYONE</font></td></tr></table></body></html>");
              l.setBounds(20, 20, 120, 20);
              j.setBounds(10, 10, 10, 10);
              j.addActionListener(this);
              getContentPane().setLayout(null);
              getContentPane().add(l);
              getContentPane().add(j);
              show();
         public remRunPrint(){}
         public void paint(Graphics g) {
              g.setFont(new Font("SansSerif", Font.PLAIN, 6));
              g.drawString("PrintDate:", 520, 20);
              g.setFont(new Font("SansSerif", Font.BOLD, 9));
              g.drawString(pDateSTR, 550, 20);
              g.drawString("JOB: ", 23, 37);
              g.drawString("VERSION:", 310, 37);
              g.drawString("#" + vID, 310, 28);
              g.setFont(new Font("SansSerif", Font.BOLD, 18));
              g.drawString(jName, 48, 37);
              g.drawString(vName, 355, 37);
              //HERE ARE A COUPLE LINES OF AWT DRAWING TO A SCREEN THAT WORK ... IF YOU LAUNCH THIS APP FROM THE COMMAND LINE
              //IT WILL SHOW YOU WHAT YOU ARE GOING TO PRINT.. SO YOU CAN FORMAT IT AND BUILD IT FIRST THEN PRINT IT WITH THE
              //BUTTON...
         public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {
    if (pi >= 1) {
    return Printable.NO_SUCH_PAGE;
              paint(g);
    return Printable.PAGE_EXISTS;

  • Java Speech API

    Hi
    When i compile the following program it give me error some of the Java speech API.
    import javax.speech.AudioException;
    import javax.speech.Central;
    import javax.speech.EngineException;
    import javax.speech.synthesis.Synthesizer;
    import javax.speech.synthesis.SynthesizerModeDesc;
    Can any one help.
    Thanks
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.Locale;
    import java.util.Hashtable;
    import java.util.prefs.Preferences;
    import javax.speech.AudioException;
    import javax.speech.Central;
    import javax.speech.EngineException;
    import javax.speech.synthesis.Synthesizer;
    import javax.speech.synthesis.SynthesizerModeDesc;
    import javax.swing.DefaultComboBoxModel;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.JTextArea;
    import javax.swing.JToolBar;
    public class JavaVoice extends JFrame implements Comparator {
         private Synthesizer synth;
         private File readFile = null;
         Preferences preferences = Preferences.userRoot().node("dlb/JavaVoice");
         JComboBox voices;
         Hashtable list;
         public JavaVoice() {
              super("Java Voice Synthesizer");
              addWindowListener(new AppCloser());
              DefaultComboBoxModel model = new DefaultComboBoxModel();
              try {
                   javax.speech.EngineList elist = Central.availableSynthesizers(null);
                   list = new Hashtable(elist.size());
                   Collections.sort(elist,this);
                   for (int i=0;i<elist.size();i++) {
                        SynthesizerModeDesc desc = (SynthesizerModeDesc)elist.elementAt(i);
                        model.addElement(desc.getModeName());
                        list.put(desc.getModeName(),desc);
                   synth = Central.createSynthesizer((SynthesizerModeDesc) list.get(preferences.get("voice.selected","")));
                   synth.allocate();
                   synth.resume();
              catch(EngineException ex) {
                   ex.printStackTrace();
              catch(AudioException ex) {
                   ex.printStackTrace();
              final JTextArea textArea = new JTextArea();
              textArea.setLineWrap(true);
              textArea.setWrapStyleWord(true);
              JScrollPane scrollPane = new JScrollPane(textArea);
              getContentPane().add(scrollPane,BorderLayout.CENTER);
              JToolBar toolBar = new JToolBar();
              JButton button = new JButton("Open");
              button.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ev) {
                        JFileChooser fileChooser = new JFileChooser(preferences.get("voice.openDirectory",System.getProperty("user.dir")));
                        if(fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                             readFile = fileChooser.getSelectedFile();
                             preferences.put("voice.openDirectory",readFile.getParent());
                             try {
                                  FileReader reader = new FileReader(readFile);
                                  textArea.read(reader,readFile.getName());
                                  reader.close();
                             catch(IOException ex) {
                                  ex.printStackTrace();
              toolBar.add(button);
              button = new JButton("Clear");
              button.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ev) {
                        textArea.setText("");
              toolBar.add(button);
              toolBar.add(button);
              button = new JButton("Start");
              button.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ev) {
                        String str = textArea.getSelectedText();
                        if(str != null && str.length() > 0) {
                             synth.speakPlainText(str.toLowerCase(),null);
                             textArea.setSelectionStart(0);
                             textArea.setSelectionEnd(0);
                        else {
                             str = textArea.getText();
                             synth.speakPlainText(str.toLowerCase(),null);
              toolBar.add(button);
              button = new JButton("Stop");
              button.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ev) {
                        try {
                             synth.cancel();
                        catch(ArrayIndexOutOfBoundsException ex) {}
              toolBar.add(button);
              toolBar.addSeparator();
              toolBar.add(new JLabel("Voice:"));
              voices = new JComboBox(model);
              voices.setSelectedItem(preferences.get("voice.selected",""));
              voices.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ev) {
                        try {
                             synth.deallocate();
                             String str = (String) voices.getSelectedItem();
                             preferences.put("voice.selected",str);
                             synth = Central.createSynthesizer((SynthesizerModeDesc) list.get(str));
                             synth.allocate();
                             synth.resume();
                        catch(EngineException ex) {
                             ex.printStackTrace();
                        catch(AudioException ex) {
                             ex.printStackTrace();
              toolBar.add(voices);
              toolBar.addSeparator();
              button = new JButton("Exit");
              button.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ev) {
                        try {
                             synth.deallocate();
                        catch(EngineException ex) {
                             ex.printStackTrace();
                        preferences.putInt("voice.mainWindow.x",getLocation().x);
                        preferences.putInt("voice.mainWindow.y",getLocation().y);
                        preferences.putInt("voice.mainWindow.width",getSize().width);
                        preferences.putInt("voice.mainWindow.height",getSize().height);
                        System.exit(1);
              toolBar.add(button);
              getContentPane().add(toolBar,BorderLayout.NORTH);
              final JTextField textField = new JTextField();
              textField.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ev) {
                        String txt = textField.getText();
                        if(txt.length() > 0) {
                             textArea.append(txt+'\n');
                             synth.speakPlainText(txt, null);
                             textField.setText("");
              getContentPane().add(textField,BorderLayout.SOUTH);
              int x = preferences.getInt("voice.mainWindow.x",1);
              int y = preferences.getInt("voice.mainWindow.y",1);
              int width = preferences.getInt("voice.mainWindow.width",640);
              int height = preferences.getInt("voice.mainWindow.height",480);
              setLocation(x,y);
              setSize(width,height);
              setVisible(true);
         public int compare(Object obj1, Object obj2) {
              SynthesizerModeDesc desc1 = (SynthesizerModeDesc) obj1;
              SynthesizerModeDesc desc2 = (SynthesizerModeDesc) obj2;
              return desc1.getModeName().compareToIgnoreCase(desc2.getModeName());
         public static void main(String args[]) {
              new JavaVoice();
         class AppCloser extends WindowAdapter {
              public void windowClosing(WindowEvent ev) {
                   try {
                        synth.deallocate();
                   catch(EngineException ex) {
                        ex.printStackTrace();
                   System.exit(1);
    ---------------------------------------------------------------------------------------------------------

    use code tags, post the error message.
    http://forum.java.sun.com/help.jspa?sec=formatting

  • Performance issue with Business Objects Java JRC API in CRXI R2 version

    A report is developed using java JRC API in CR XI release 2. When I generate the report in the designer, it took less than 5 seconds to display the results in crystal report viewer inside the designer. But in the QA environment, when I generate the same report from the application, it takes almost 1 to 1.5 minutes to display the same results in PDF. I also noticed that if the dataset contains bigger volume of data, then the reports are taking even longer almost 15 to 20 minutes.
    While generating the report from the application, I noticed that most of time is taken during the execution of the com.crystaldecisions.report.web.viewer.ReportExportControl Object method as shown in following line of code
    exportControl.processHttpRequest(request, response, context, null)
    We thought the delay in exporting the report to PDF might be the layout of the report and data conversion to PDF for such a bigger volume of data.
    Then we investigated the issue and experimented quickly to generate the same report with same result set data from the application using XML, XSL and converted the output XSL-FO to PDF using Apache FOP (Formatting Objects Processor) implementation. The time taken to export the report to PDF is less than 6 seconds. By doing this experiment, it is proved that the issue is not with conversion of data to PDF but it is the performance problem with Business Objects Java JRC API in CR XI R2.
    In this regard, I searched for the above issue in the SAP community Network Forums -> Crystal Reports and Xcelsius -> Java Development -> Crystal Reports. But I did not find any answers or solutions for this kind of issue in the forums.
    Any suggestion, hint in this matter is very much appreciated.

    Ted, The setReportAppServer problem is resolved. Now I could able to generate the report with hardcoded values in the SQLs in just 6 seconds where as the same report was generated in CRXI R2 in 1 minute 15 seconds as mentioned in the earlier message.
    But, our exisiting application passes the parameter values to the SQLs embedded in the report. For some reason the parameters are not being passed to the report and the report displays only the labels without data.
    As per the crj 12 samples codes, the code is written as shown below.
    1. Created ReportClient Document
    2. SetReportAppServer
    3. Open the report
    4. Getting DatabaseController and switching the database connection at runtime
    5. Then setting the parameters as detailed below
    ParameteFields parameterFieldController = reportClientDoc.getDataDefController().getParameterFieldController();
    parameterFieldController.setCurrentValue("", "paramname",paramvalue);
    parameterFieldController.setCurrentValue("", "paramname",paramavalue);
    byteArrayInputStream = (ByteArrayInputStream)reportClientDoc.getPrintOutputController().export(ReportExportFormat.PDF); 
    6. Streaming the report to the browser
    Why the parematers are not being passed to the report?  Do I need to follow the order of setting these parameters?  Did I miss any line of code for setting Params using  crj 12?
    Any help in this regard would be greatly appreciated.

  • How to print a document in reverse order using Java Print API ?

    I need to print a document in reverse order using Java Print API (*Reverse Order Printing*)
    Does Java Print API supports reverse order printing ?
    Thnks.,

    deepak_c3 wrote:
    Thanks for the info.,
    where should the page number n-1-i be returned ?
    Which method implementation of Pageable interface should return the page number ?w.r.t. your first question: don't return that number but return page n-1-i when page i is requested; your document will be printed in reverse order. Your class should implement the entire interface and wrap the original Pageable. (for that number n your class can consult the wrapped interface; read the API for the Pageable interface).
    kind regards,
    Jos

  • Java Persistence API and creation of databases

    Hi All
    I have designed a small address book application which uses a database to store the information. I have used the new Java Persistence API to take care of my transactions and querrys with the database. This works great for one set database which is generated the first time the application runs and is used all the time.
    However I would like to make it so that the user can create a new address book (database) with a different name, I am not sure how I would do this using the Java Persistence API. I know the persistence.xml file must be placed in the META-INF directory of the source, so how would I be able manipulate the file or could I place the file somewhere else.
    David

    I am using the Derby database. I can create a database by passing the create command when I create the entity Manager like so:
    Connection c = DriverManager.getConnection("jdbc:derby:AddressBook;create=true", "app", "app");My problem is that as I understand it the persistence.xml file must know the name of the database. Unless there is another way of setting this. The line in the persistence file I am referring to is:
    <property name="toplink.jdbc.url" value="jdbc:derby:AddressBook"/>I wonder if I can progamatically set this value so that I have a default database in the persistence.xml and others can then create there own.
    David

  • Java.lang.AbstractMethodError: oracle.jdbc.driver.OracleDatabaseMetaData.lo

    I am evaluating the sun RI of javax.sql package . I downloaded the jdbc_rowset_tiger-1_0_1-mrel-jwsdp.zip package and installed in my machine.
    I tried the JdbcRowSet implmenation and it worked pretty smooth. I wanted to try the disconnected Rowset implementation. I tried CachedRowSet Implementation with thin driver. I get the following error message.
    Exception in thread "main" java.lang.AbstractMethodError: oracle.jdbc.driver.OracleDatabaseMetaData.locatorsUpdateCopy()Z
    at com.sun.rowset.CachedRowSetImpl.execute(Unknown Source)
    at com.sun.rowset.CachedRowSetImpl.execute(Unknown Source)
    at CachedRowSetSampl.main(CachedRowSetSampl.java:79)
    I am using thin driver with Oracle8i db.
    Appreciate any early responses

    I had the same problem initially.
    I fixed it by downloading an updated ojdbc14.jar (1).
    It may be because I downloaded the ocrs12.jar from there a bit earlier and the versions of ojdbc14.jar and ocrs12.jar need to match (that is, come from the Oracle10g suite of jars).
    Here is the class I used:
    import java.sql.*;
    import javax.sql.*;
    import com.sun.rowset.WebRowSetImpl;
    import com.sun.rowset.providers.RIXMLProvider;
    public class test {
      public static void main(String[] args) {
        try {
          Class.forName("oracle.jdbc.driver.OracleDriver");
          WebRowSetImpl wrs = new WebRowSetImpl();
          wrs.setCommand("select table_name from user_tables");
          wrs.setUsername("scott");
          wrs.setPassword("tiger");
          wrs.setUrl("jdbc:oracle:thin:@paramount.com:1521:ORCL");
          wrs.execute();
          wrs.writeXml(System.out);
        } catch (Exception e) {
          System.out.println("Exception:"+e);
    Dale(1) http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/htdocs/jdbc101020.html (Oracle Database 10g JDBC Drivers)

  • DAO pattern and Java Persistence API

    Hi
    This is a question for anyone who might be familiar with the standard DAO design pattern and the Java Persistence API (JPA - part of EJB3). I'm new to this technology, so apologies for any terminology aberrations.
    I am developing the overall architecture for an enterprise system. I intend to use the DAO pattern as the conceptual basis for all data access - this data will reside in a number of forms (e.g. RDBMS, flat file). In the specific case of the RDBMS, I intend to use JPA. My understanding of JPA is that it does/can support the DAO concept, but I'm struggling to get my head around how the two ideas (can be made to) relate to each other.
    For example, the DAO pattern is all about how business objects, data access objects, data transfer objects, data sources, etc relate to each other; JPA is all about entities and persistence units/contexts relate to each other. Further, JPA uses ORM, which is not a DAO concept.
    So, to summarise - can DAO and JPA work together and if so how?
    Thanks
    P.S. Please let me know if you think this topic would be more visible in another forum (e.g. EJB).

    Thanks, duffymo, that makes sense. However ... having read through numerous threads in which you voice your opinion of the DAO World According to Sun, I'd be interested to know your thoughts on the following ...
    Basically, I'm in the process of proposing an enterprise system architecture, which will use DAO as the primary persistence abstraction, and DAO + JPA in the particular case of persistence to a RDBMS. In doing so, I'd like to illustrate the various elements of the DAO pattern, a la the standard class diagram that relates BusinessObject / DataAccessObject / DataSource / TransferObject (http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html). With reference to this model, I know that you have a view on the concept of TransferObject (aka ValueObject?) - how would you depict the DAO pattern in its most generic form? Or is the concept of a generic DAO pattern compromised by the specific implementation that is used (in this case JPA)?

Maybe you are looking for

  • Page breaks in smart form based on condition

    Dear all, I want to give a page break based on month in smartform. How can i do it. Thanks In advance. Regards satish.

  • SQL question - please help!

    Hi, I am working on a SQL, please help ms with the question below .... thanks (1)Increase by 10% salary of these captain pilots who have traveled more than 800,000 miles. Routes | | Flights | |Pilots | | | | | | #routeID | | #flightNO | |#pilotID | d

  • How to enable document rights

    How do I enable the document rights to enable the comment and markup tools in 9.4 adobe reader?

  • Quick contract gig: Data Merge with inDesign

    My client has a small college directory created with inDesign, and a spreadsheet of contact info / headshots. They would like to perform a data merge so they can ready the directory for print. Please contact me if this is within your wheelhouse! Paul

  • Domain value range

    hi i am changing the table field domain value range. after changing i am getting the warning msg like below. if i ignore it and transport odes it affect anyways. and also does anyone tell me when we transport only the structure get transported or eve