ServletInputStream error when reading more than once

I have an application which needs to look at fields in a multipart request in several different places of the code. The first time I look at the request, it works just fine, but every time after that it doesn't. Here is a simplified example of what is happening:
private ServletInputStream in;
private HttpServletRequest request;
private byte[] buff = new byte[100*1024];
public Class class1  {
    public class1(HttpServletRequest req) {
        super();
        request = req;
        in = request.getInputStream();
        String line = readLine();
        System.out.println("Testing line1: " + line);
private ServletInputStream in2;
private HttpServletRequest request;
private byte[] buff = new byte[100*1024];
public Class class2  {
    public class2(HttpServletRequest req) {
        super();
        request = req;
        in2 = request.getInputStream();
        String line = readLine();
        System.out.println("Testing line2: " + line);
}Not sure that it is relevant, but in case it is, my readLine() method looks like this:
private String readLine() throws IOException {
    int len = 0;
    String line = null;
    len = in.readLine(buff,0,buff.length);
    if(len < 0) return null;
    line = new String(buff,0,len,"ISO-8859-1");
    return line;
}The request is basically passed around so it is the same request object both times. The first one outputs the first line as expected. In the second one however, line is null.
Interestingly enough, I found the following to be true also:
private ServletInputStream in;
private ServletInputStream in2;
public Class class3 {
    public class3(HttpServletRequest request){
        super();
        in = request.getInputStream();
        if(in != null) {
            in.close();
        in = null;
        in2 = request.getInputStream();
        String line = in2.readLine();
        // IOException OCCURS HERE SAYING: Stream closed
}The stream was closed on the first "in" but not on the second, so why would I be getting this????
Help!!

I am not completely sure what to do now. Basically, I have a multipart request for a fileupload. Towards the beginning of my servlet, I need to get the form parameters. This is working fine. But since you say that the getInputStream() will return the same instance regardless of where it is called from, I am in trouble when later on in the code I need to actually upload the file. To integrate this into my core java framework, there really isn't a way that I can get all the information I need at the beginning and use it later. Is there a way I can get the form parameters WITHOUT using the inputstream? Then, my inputstream could be called in my mapper for uploading the file. I haven't found another way to do this, as multipart requests are handled differently. Any suggestions at all?

Similar Messages

  • DOI - I_OI_SPREADSHEET, poor performance when reading more than 9999 record

    Hi,
    Please read this message in the [ABAP Performance and Tuning|DOI - I_OI_SPREADSHEET, poor performance when reading more than 9999 record; section and see if you have any advise.
    Best Regards,
    Marjo

    Hi,
    I met this issue when I tried to write vaule to massive fields of excel range.
    And I solve this issue by using CL_GUI_FRONTEND_SERVICES=>CLIPBOARD_EXPORT.
    So, I think you may fix it in the same way.
    1. Select range in by the I_OI_SPREADSHEET
    2. Call method I_OI_DOCUMENT_PROXY->COPY_SELECTION
    3. Call method CL_GUI_FRONTEND_SERVICES=>CLIPBOARD_IMPORT
    Cheers,

  • Rendering Error when using more than one DataSheetView on a Enterprise Wiki-Page

    Hi Experts,
    how to reproduce:
    Add two Custom Lists with some Fields (Add Lookup-Columns to both Lists).
    Add a DataSheetView to each List and mark it as Default-View
    Create a Enterprise Wiki-Page
    Add a WebPart (Custom-List-1)
    You will see the Content from List 1 as DataSheet-View (because it is the Default-View)
    Add another WebPart below the previous added WebPart (Custom-List-2)
    You will see the Content from List 2 as DataSheet-View (because it is the Default-View)
    Notice that the First DataSheet has faulty Rendering. The Lookup-Columns having more than one 'Arror-Down' Image and it is even on the left. If you click into different Column, different row you get the same.
    I can reproduce this behaviour anytime.
    Environment: SharePoint 2013 Enterprise, IE10
    If you use Development-Tools to identify first datarow of first DataSheet you can see that it has to do something with the related <Input>-Tags:
    <div class="combobox-placeholder" id="jsgrid_combobox" style="left: 27px; top: 32px; width: 117px; height: 29px; border-top-color: currentColor; border-right-color: currentColor; border-bottom-color: currentColor; border-left-color:
    currentColor; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-top-style: none; border-right-style: none; border-bottom-style: none; border-left-style: none; visibility: inherit; ; direction: ltr; min-width:
    117px; background-color: transparent;">
    <input class="cb-textbox " style="width: 156px; height: 25px;" dir="ltr" type="text"/><input tabindex="-1" title="Dropdown" class="combobox-img" style="height: 29px;"
    dir="ltr" type="button" value="▼"/><input class="cb-textbox " style="width: 84px; height: 25px;" dir="ltr" type="text"/><input tabindex="-1" title="Dropdown"
    class="combobox-img" style="height: 29px;" dir="ltr" type="button" value="▼"/>
    Please have a look into it. Current Workaround for me is to have a Default-ListView in first WebPart. But then Customer has to click the Edit-Button to Change the Item in the releated EditForm. This is a Show-Stopper here!
    With Best Regards,
    Ronny

    Hi Ronny,
    According to your description, the lookup column would render incorrectly when adding more than one datasheet view in the Enterprise Wiki page.
    I tested the same scenario per your post, and I got the same results as you got.
    We will help to submit the issue to proper pipeline for you.
    Again, thank you for your report which will definitely make SharePoint a better products. There might be some time delay. 
    Appreciate your time and patience.
    Best regards.
    Thanks
    Victoria Xia
    TechNet Community Support

  • Error when connecting more than 50 users ??

    I use database 8iEE & form server (9ias rel1) on different box to deploy form on the web
    the error occur when user connect more than 50, but it's ok when connect to database using sqlplus
    Is there someone has the same experience ?

    I think this problem has been addressed and answered in this forum time and again …
    Opening files or creating new files while in Full Screen Mode will cause a cursor offset in Photoshop CS4 (I don’t know if there are configurations where that does not happen, but best assume it just does); the common remedy is circling through the Screen Modes by hitting F on the keyboard three times.
    Edit: The matter doesn’t seem to have made it into the FAQ, though. Maybe someone could add it there?

  • Export error when creating more than 2 gb file

    Good day,
    There is a problem with the export utility. while exporting a file size more than 2 gb an error occured.
    00002- Error in writing to export file
    my os is Unix 6 SCO and Orale database version is 7.1.3
    knidly look into this issue.
    Thanks & Regards.

    SCO OpenServer 6 now provides users with 1 TeraByte file support. A TeraByte is equal to approximately 1 trillion bytes. This new feature allows SCO OpenServer 6 users to create files that are over the previous 2 gigabyte file limit in older versions of SCO OpenServer. This new feature provides greater flexibility in file size and application usage.
    To showcase this new feature, we will create a file that is larger than 2+ Gigabytes. In order to accomplish this task, we will need to use SCO OpenServer 6 large filesystem-aware commands. These commands can be found in /u95/bin.
    To Create a 2+ Gigabyte File:
    In the KDE desktop environment, click on the UNIX icon. The UNIX terminal window will appear.
    In the terminal window, type
    /u95/bin/dd if=/dev/urandom of=bigfile bs=100k count=40000
    Press Enter. A 4+ Gigabyte file will be created.
    NOTE: This exercise will require approximately 5 minutes to complete. This test also requires approximately 5 Gigaytes of available disk space on your machine.
    You have now successfully created a 2+ Gigabyte file in SCO OpenServer 6. This completes the detailed instructions for the product walkthrough. Feel free to investigate other features within SCO OpenServer 6.

  • Error when inserting more than 500 characters

    Hello all,
    I am not sure if I should be posting here or in the Flex
    Forum, so I apologize ahead of time if I am in the wrong place.
    I am Using a Flex frontend and a ColdFusion backend to edit
    data in a simple Access Database (for testing). I have a ColdFusion
    CFC on the backend that handles everything just fine until I enter
    in more than 500 characters (Actually 510) into my text area and
    then I get the error "Unable to invoke CFC - Error Executing
    Database Query.". Now you might be saying that either the database
    field is not set to handle that many characters or the CFC is
    restricting more than 500 characters, but they are not. The
    database field is set to "memo" and the maxlength in the CFC is set
    to 5000. I am wondering if has something to do with Access
    databases I do not know because I don't use them that often.
    I have tested this over and over and it only throws the error
    if I exceed 510 characters in the Flex TextArea.
    Any thoughts are appreciated.
    The CFC code is below I didn't add the MXML because I figured
    there was nothing special about the TextArea block:

    Very strange as to why this worked but just in case someone
    else has the same problem here is how I got it to work.
    I just changed this line:
    rss_copy = <cfqueryparam value="#arguments.rss_copy_edit#"
    cfsqltype="cf_sql_varchar" maxlength="5000">
    to this:
    rss_copy = '#arguments.rss_copy_edit#"'
    and it worked just fine.

  • Error when sending more than 500 Characters

    Hello all,
    I am not sure if I should be posting here or in the
    ColdFusion Forum, so I apologize ahead of time if I am in the wrong
    place.
    I am Using a Flex frontend and a ColdFusion backend to edit
    data in a simple Access Database (for testing). I have a ColdFusion
    CFC on the backend that handles everything just fine until I enter
    in more than 500 characters (Actually 510) into my text area and
    then I get the error "Unable to invoke CFC - Error Executing
    Database Query.". Now you might be saying that either the database
    field is not set to handle that many characters or the CFC is
    restricting more than 500 characters, but they are not. The
    database field is set to "memo" and the maxlength in the CFC is set
    to 5000. I am wondering if has something to do with Access
    databases I do not know because I don't use them that often.
    I have tested this over and over and it only throws the error
    if I exceed 510 characters in the Flex TextArea.
    Any thoughts are appreciated.
    The CFC code is below I didn't add the MXML because I figured
    there was nothing special about the TextArea block:

    The code should be in my initial post.
    Very strange as to why this worked but just in case someone
    else has the same problem here is how I got it to work.
    I just changed this line:
    rss_copy = <cfqueryparam value="#arguments.rss_copy_edit#"
    cfsqltype="cf_sql_varchar" maxlength="5000">
    to this:
    rss_copy = '#arguments.rss_copy_edit#"'
    and it worked just fine.
    Not the best solution but it works fine now all the
    same.

  • Error opening environment more than once

    Hi,
    I have two java classes which both need to access a container in an environment (in parallel). When the first class is instantiated the environment is opened successfully. However, when the second class subsequently attempts to open the same environment I get an error. (I do not want to close the env from the first class, while the second class does its thing)
    The classes are Stylesheet extensions for an xmleditor which allows the stylesheet to look up item ID codes and display their names to the user by looking up the values in an xml file stored in a bdbxml container. There is a situation where two different objects need to have access to the environment at the same time - but its giving me an error when I instantiate the env for the second time - without having closed the first one)
    Any help would by gratefully received
    Kind Regards
    Swami Kevala
    I thought I could create multiple handles to the same environment?

    First is a class to encapsulate the environment (lifted mostly from the example code)
    package org.isha.archives.bdbxml;
    import java.io.*;
    import java.util.*;
    import com.sleepycat.db.*;
    import com.sleepycat.dbxml.*;
    //Class used to open and close a Berkeley DB environment
    public class DbEnv
    private Environment dbEnv_ = null;
    private XmlManager mgr_ = null;
    private boolean dbEnvIsOpen_ = false;
    private File path2DbEnv_ = null;
    public DbEnv(File path2DbEnv)
         throws Throwable {
              if (! path2DbEnv.isDirectory()) {
                   throw new Exception(path2DbEnv.getPath() +
                             " does not exist or is not a directory.");
              EnvironmentConfig config = new EnvironmentConfig();
              config.setCacheSize(50 * 1024 * 1024);
              config.setAllowCreate(true);
              config.setInitializeCache(true);
              config.setTransactional(true);
              config.setInitializeLocking(true);
              config.setInitializeLogging(true);
              config.setErrorStream(System.err);
              config.setThreaded(true);
              config.setRunRecovery(true);
              config.setLogAutoRemove(true);
              dbEnv_ = new Environment(path2DbEnv, config);
              //Boolean used to know whether to close the environment
              // when the cleanup() method is called.
              dbEnvIsOpen_ = true;
              path2DbEnv_ = path2DbEnv;
              mgr_ = new XmlManager(dbEnv_, null);
    //Returns the path to the database environment
    public File getDbEnvPath() { return path2DbEnv_; }
    //Returns the database environment encapsulated by this class.
    public Environment getEnvironment() { return dbEnv_; }
    //Returns the XmlManager encapsulated by this class.
    public XmlManager getManager() { return mgr_; }
    //Used to close the environment
    public void cleanup() throws DatabaseException
    if (dbEnvIsOpen_) {
    dbEnv_.close();
    dbEnvIsOpen_ = false;
    Second is a class which encapsulates a container with a method for querying itself
    package org.isha.archives.bdbxml;
    import java.io.*;
    import java.util.*;
    import com.sleepycat.db.*;
    import com.sleepycat.dbxml.*;
    //Class used to open, query and close a Berkeley DB container
    public class DbContainer
         private XmlContainer dbCont_ = null;
    private XmlManager mgr_ = null;
    private boolean dbContainerIsOpen_ = false;
    private File path2DbContainer_ = null;
    private XmlContainerConfig cfg_= null;
    private String cntr_ = "";
    public DbContainer(XmlManager myManager, String containerFileName, XmlContainerConfig containerConfig)
              throws Throwable {
              String containerFilepath = myManager.getHome() + "\\" + containerFileName;
              path2DbContainer_ = new File(containerFilepath);
              mgr_ = myManager;
              cfg_ = containerConfig;
              cntr_ = containerFileName;
              if (! path2DbContainer_.isFile()) {
                   throw new Exception(path2DbContainer_.getPath() +
                             " does not exist or is not a directory.");
              dbCont_ = new XmlContainer();
    //Return the XmlContainer itself
    public XmlContainer getContainer() { return dbCont_; }
    //Returns the filename of the container
         public String getFilename() { return cntr_; }
    //Returns the XmlManager encapsulated by this class.
    public XmlManager getManager() { return mgr_; }
    //Used to close the container
    public void close() throws DatabaseException
    if (dbContainerIsOpen_) {
    dbCont_.close();
    dbContainerIsOpen_ = false;
    //Used to open the container
    public void open() {
              try {
                   dbCont_ = mgr_.openContainer(cntr_, cfg_);
                   dbContainerIsOpen_ = true;
              catch (Exception e) {
    //Used to query the container
    public String[] runQuery(String myQuery){
              String [] queryOutput = null;
              int counter = 0;
              try {
                   XmlQueryContext context = mgr_.createQueryContext();
                   //Default namespace declaration does not work yet - this will work in the next release of BDB XML
                   //Until then we have to remove the namespace declaration from the reference.xml root element
                   //When this becomes available we can add the namespace declaration and uncomment the following line
                   //context.setNamespace("", defaultNS);
                   XmlResults results = mgr_.query(myQuery, context);
                   //Get the result set
                   queryOutput = new String[results.size()];
                   XmlValue value = results.next();
                   while (value != null)
                        queryOutput[counter] = value.asString().replaceAll("\\n", "").replaceAll(" "," ");
                        System.out.println(queryOutput[counter]);
                        counter ++;
                        value = results.next();
              catch (Exception e) {
                   //Exception Handling code here
              return queryOutput;
    Now to explain what is happening:
    When I open an xml document in xmlmind, it displays the document according to a prespecified CSS sheet. Sometimes the CSS rules alone are not sufficient to achieve the necessary effect/functionality, so the API allows you to write your own class, which contains methods to do what you want. As soon as the xml document is displayed, the CSS extension class gets instantiated.
    Here is my extension class (called StyleSheetExtension). It contains a method called getKeywords. This method can then be invoked from within the CSS sheet, and is used to replace the keyword ID codes in the xml document with their corresponding keyword names - stored in an xml reference look-up document...
    package org.isha.archives.xmlmind;
    import com.xmlmind.xmledit.xmlutil.*;
    import com.xmlmind.xmledit.doc.*;
    import com.xmlmind.xmledit.view.DocumentView;
    import com.xmlmind.xmledit.stylesheet.StyleValue;
    import com.xmlmind.xmledit.stylesheet.StyleSpec;
    import com.xmlmind.xmledit.stylesheet.StyleSpecsBase;
    import com.xmlmind.xmledit.styledview.StyledViewFactory;
    import com.xmlmind.xmledit.styledview.CustomViewManager;
    import com.sleepycat.dbxml.*;
    import com.sleepycat.db.*;
    import java.io.File;
    import java.util.logging.*;
    import java.util.*;
    import org.isha.archives.bdbxml.DbContainer;
    import org.isha.archives.bdbxml.DbEnv;
    public class StyleSheetExtension {
         //Logging variables
         private Logger logger = Logger.getLogger("StyleSheetExtension");
         private Handler fh = null;
         private java.util.logging.Formatter sf = null;
         //XMLMind variables
         private static final Namespace NS = Namespace.get("http://www.ishafoundation.org/archives/schema/transcript");
         //BDB variables
         private DbEnv myDbEnv = null;
         private File envDir = new File("C:\\BerkeleyDB");
         private DbContainer myDbContainer = null;
         private String containerFileName = "reference.dbxml";
         private XmlContainerConfig containerCfg = null;
         //Define Constructor
         public StyleSheetExtension(String[] args, StyledViewFactory viewFactory) {
    //Set up simple logging system
    try {
    fh = new FileHandler("%t/_styleSheetExtn.log");
    sf = new SimpleFormatter();
    fh.setFormatter(sf);
    logger.addHandler(fh);
    logger.setLevel(Level.ALL);
    logger.info("Starting StyleSheetExtension Class constructor");
    } catch (Exception e)
    {System.out.println("CustomErr: " + e.getMessage());
                    //Exception Handling code
    //Create custom BDB Environment and Container Objects
    try {
                        myDbEnv = new DbEnv(envDir);
                        containerCfg = new XmlContainerConfig();
                        myDbContainer = new DbContainer(myDbEnv.getManager(), containerFileName, containerCfg);
                        myDbContainer.open();
                   } catch (Throwable t) {
                        logger.severe("Problem with Env or Container new thing");
    viewFactory.addDependency( NS, "topic", NS, "keywordIDs");
         public StyleValue getKeywords (StyleValue[] args, Node contextNode,
                             StyledViewFactory viewFactory) {
    //Get keyword IDs as a String array
    String[] keywordID = null;
    String[] keywordValue = null;
    String keywordIDStr = "";
    String keywordValueStr ="";
    Name keywordIDs = Name.get("keywordIDs");
    keywordIDStr = contextNode.attributeValue(keywordIDs).trim();
    keywordID = keywordIDStr.split("\\s+");
    keywordValue = new String[keywordID.length];
    //for each keyword ID element retrieve the corresponding keyword value
    logger.info("getting values");
                   keywordValue = getKeywordValuesFromDB(keywordID);
                   Arrays.sort(keywordValue);
                   logger.info(keywordValue[0] + " " + keywordValue[1]);
                   int i = 0;
                   for(i=0; i < keywordID.length; i++) {
                        keywordValueStr += keywordValue[i] + " ";
                   keywordValueStr = keywordValueStr.trim();
              return StyleValue.createString(keywordValueStr);
    private String[] getKeywordValuesFromDB(String[] IDs){
                   String[] values = new String[IDs.length];
                   String id = "";
                   String value = "";
                   String flwor = "";
                   int i = 0;
                   for(i=0; i < IDs.length; i++) {
                        id = IDs.trim();
                        flwor = "for $i in collection('" + myDbContainer.getFilename() + "') /reference/keywords/keyword \n";
                        flwor += "let $id := $i/@id/text() \n";
                        flwor += "let $val := $i/@value/text() \n";
                        flwor += "where $id = '" + id + "'\n";
                        flwor += "return $val";
                        String[] temp = new String[1];
                        temp = myDbContainer.runQuery(flwor);
                        values[i] = temp[0];
                        logger.info("value is: " + values[i]);
                   return values;
    package org.isha.archives.xmlmind;
    import com.xmlmind.xmledit.xmlutil.*;
    import com.xmlmind.xmledit.doc.*;
    import com.xmlmind.xmledit.view.DocumentView;
    import com.xmlmind.xmledit.stylesheet.StyleValue;
    import com.xmlmind.xmledit.stylesheet.StyleSpec;
    import com.xmlmind.xmledit.stylesheet.StyleSpecsBase;
    import com.xmlmind.xmledit.styledview.StyledViewFactory;
    import com.xmlmind.xmledit.styledview.CustomViewManager;
    import com.sleepycat.dbxml.*;
    import com.sleepycat.db.*;
    import java.io.File;
    import java.util.logging.*;
    import java.util.*;
    import org.isha.archives.bdbxml.DbContainer;
    import org.isha.archives.bdbxml.DbEnv;
    public class StyleSheetExtension {
         //Logging variables
         private Logger logger = Logger.getLogger("StyleSheetExtension");
         private Handler fh = null;
         private java.util.logging.Formatter sf = null;
         //XMLMind variables
         private static final Namespace NS = Namespace.get("http://www.ishafoundation.org/archives/schema/transcript");
         //BDB variables
         private DbEnv myDbEnv = null;
         private File envDir = new File("C:\\BerkeleyDB");
         private DbContainer myDbContainer = null;
         private String containerFileName = "reference.dbxml";
         private XmlContainerConfig containerCfg = null;
         //Define Constructor
         public StyleSheetExtension(String[] args, StyledViewFactory viewFactory) {
    //Set up simple logging system
    try {
    fh = new FileHandler("%t/_styleSheetExtn.log");
    sf = new SimpleFormatter();
    fh.setFormatter(sf);
    logger.addHandler(fh);
    logger.setLevel(Level.ALL);
    logger.info("Starting StyleSheetExtension Class constructor");
    } catch (Exception e)
    {System.out.println("CustomErr: " + e.getMessage());
                    //Exception Handling code
    //Create custom BDB Environment and Container Objects
    try {
                        myDbEnv = new DbEnv(envDir);
                        containerCfg = new XmlContainerConfig();
                        myDbContainer = new DbContainer(myDbEnv.getManager(), containerFileName, containerCfg);
                        myDbContainer.open();
                   } catch (Throwable t) {
                        logger.severe("Problem with Env or Container new thing");
    viewFactory.addDependency( NS, "topic", NS, "keywordIDs");
         public StyleValue getKeywords (StyleValue[] args, Node contextNode,
                             StyledViewFactory viewFactory) {
    //Get keyword IDs as a String array
    String[] keywordID = null;
    String[] keywordValue = null;
    String keywordIDStr = "";
    String keywordValueStr ="";
    Name keywordIDs = Name.get("keywordIDs");
    keywordIDStr = contextNode.attributeValue(keywordIDs).trim();
    keywordID = keywordIDStr.split("\\s+");
    keywordValue = new String[keywordID.length];
    //for each keyword ID element retrieve the corresponding keyword value
    logger.info("getting values");
                   keywordValue = getKeywordValuesFromDB(keywordID);
                   Arrays.sort(keywordValue);
                   logger.info(keywordValue[0] + " " + keywordValue[1]);
                   int i = 0;
                   for(i=0; i < keywordID.length; i++) {
                        keywordValueStr += keywordValue[i] + " ";
                   keywordValueStr = keywordValueStr.trim();
              return StyleValue.createString(keywordValueStr);
    private String[] getKeywordValuesFromDB(String[] IDs){
                   String[] values = new String[IDs.length];
                   String id = "";
                   String value = "";
                   String flwor = "";
                   int i = 0;
                   for(i=0; i < IDs.length; i++) {
                        id = IDs[i].trim();
                        flwor = "for $i in collection('" + myDbContainer.getFilename() + "') /reference/keywords/keyword \n";
                        flwor += "let $id := $i/@id/text() \n";
                        flwor += "let $val := $i/@value/text() \n";
                        flwor += "where $id = '" + id + "'\n";
                        flwor += "return $val";
                        String[] temp = new String[1];
                        temp = myDbContainer.runQuery(flwor);
                        values[i] = temp[0];
                        logger.info("value is: " + values[i]);
                   return values;
    This instance (and consequently the newly created env and container objects) stay alive until the document is closed.
    The xmlmind API also allows you to specify custom classes that will return a component that can be embedded in the stylesheet. (My class returns a JButton which - when clicked - brings up a dialog box which allows the user to specify /modify/addnew keywords to the selected text). As soon as the button is pressed I create a new env and container instance, for the duration of the pop-up window (since I have no way to pass the reference to the existing environment created by the StyleSheetExtension class.
    Here's the class defn: (Here goes!) The env and container stuff is at the start of the nested-nested class called KpForm.
    package org.isha.archives.xmlmind;
    import com.sleepycat.dbxml.*;
    import com.sleepycat.db.*;
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.AbstractDocument;
    import javax.swing.text.DocumentFilter;
    import javax.swing.text.BadLocationException;
    import javax.swing.event.*;
    import javax.swing.text.DocumentFilter.FilterBypass;
    import java.util.*;
    import java.util.regex.*;
    import java.lang.*;
    import com.xmlmind.xmledit.xmlutil.*;
    import com.xmlmind.xmledit.doc.Element;
    import com.xmlmind.xmledit.edit.*;
    import com.xmlmind.xmledit.stylesheet.*;
    import com.xmlmind.xmledit.styledgadget.*;
    import com.xmlmind.xmledit.styledview.*;
    import com.xmlmind.xmledit.doc.*;
    import java.util.logging.*;
    import org.isha.archives.bdbxml.DbEnv;
    import org.isha.archives.bdbxml.DbContainer;
    public class OpenKeywordPicker implements ComponentFactory {
    public Component createComponent(Element element,
    Style style, StyleValue[] parameters,
    StyledViewFactory viewFactory,
    boolean[] stretch){
    KeywordEdit topic = new KeywordEdit();
    return topic;
         private class KeywordEdit extends JButton {
              //private Element element;
              public KeywordEdit()
                   super.setText("Edit");
                   super.addMouseListener(new java.awt.event.MouseAdapter() {
                                  public void mouseClicked(java.awt.event.MouseEvent evt) {
                                       myJButtonMouseClicked(evt);
              private void myJButtonMouseClicked(java.awt.event.MouseEvent evt) {
                        KpForm myForm = new KpForm();
                        myForm.setVisible(true);
    private class KpForm extends javax.swing.JFrame {
         // Variables declaration - do not modify
         private javax.swing.JButton jButton1;
         private javax.swing.JButton jButton2;
         private javax.swing.JButton jButton3;
         private javax.swing.JButton jButton4;
         private javax.swing.JButton jButton5;
         private javax.swing.JButton jButton6;
         private javax.swing.JLabel jLabel1;
         private javax.swing.JLabel jLabel2;
         private javax.swing.JLabel jLabel3;
         private javax.swing.JLabel jLabel4;
         private javax.swing.JLabel jLabel5;
         private javax.swing.JList jList1;
         private javax.swing.JList jList2;
         private javax.swing.JList jList3;
         private javax.swing.JScrollPane jScrollPane1;
         private javax.swing.JScrollPane jScrollPane2;
         private javax.swing.JScrollPane jScrollPane3;
         private javax.swing.JScrollPane jScrollPane4;
         private javax.swing.JTextArea jTextArea1;
         private javax.swing.JTextField jTextField1;
         private DefaultListModel model_1 = new DefaultListModel();
              private DefaultListModel model_2 = new DefaultListModel();
              private DefaultListModel model_3 = new DefaultListModel();
              private javax.swing.JOptionPane jOptionPane1;
              //private KeywordFilter filter_1 = new KeywordFilter();
              //BDB variables
              private DbEnv myDbEnv = null;
              private File envDir = new File("C:\\BerkeleyDB");
              private DbContainer myDbContainer = null;
              private String containerFileName = "reference.dbxml";
              private XmlContainerConfig containerCfg = null;
              private Logger logger = Logger.getLogger("OpenKeywordPicker.KeywordEdit.KpForm");
              private Handler fh = null;
              private java.util.logging.Formatter sf = null;
    // End of variables declaration
         /** Creates new form kpForm */
         public KpForm() {
                   super();
         initComponents();
         customInit();
              private void customInit(){
                        //Set up simple logging system
                   try {
                        fh = new FileHandler("%t/_keywordPicker.log");
                        sf = new SimpleFormatter();
                        fh.setFormatter(sf);
                        logger.addHandler(fh);
                        logger.setLevel(Level.ALL);
                        logger.info("Starting Custom initialization");
                   } catch (Exception e) {System.out.println("CustomErr: " + e.getMessage());
                              //Exception Handling code
                        //Create custom BDB Environment and Container Objects
                        try {
                             logger.info("0");
                             myDbEnv = new DbEnv(envDir);
                             logger.info("1");
                             containerCfg = new XmlContainerConfig();
                             logger.info("2");
                             myDbContainer = new DbContainer(myDbEnv.getManager(), containerFileName, containerCfg);
                             logger.info("3");
                             myDbContainer.open();
                        } catch (Throwable t) {
                             logger.severe("Problem with Env or Container new thing - Component: "+ t.getMessage());
              String[] dbIDKeywords;
              jList1.setModel(model_1);
              jList2.setModel(model_2);
              jList3.setModel(model_3);
              dbIDKeywords = getKeywordsFromDB();
              int i=0;
              for(i=0; i < dbIDKeywords.length; i+=2){
              model_1.addElement(new keywordOb(dbIDKeywords[i], dbIDKeywords[i+1]));
              jList1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              jList2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              jList3.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              //Setup Document Filter for TextField component
              AbstractDocument doc;
              doc = (AbstractDocument)(jTextField1.getDocument());
              doc.setDocumentFilter(filter_1);
              //Setup Document Listener for TextField component
              jTextField1.getDocument().addDocumentListener(new DocumentListener(){
              public void insertUpdate(DocumentEvent e) {
              String val = jTextField1.getText();
              if(val != null & val.trim() != ""){
              jButton1.setEnabled(true);
              else {
              jButton1.setEnabled(false);
              public void removeUpdate(DocumentEvent e) {
              String val = jTextField1.getText();
              if(val != null & !val.trim().equals("")){
              jButton1.setEnabled(true);
              else {
              jButton1.setEnabled(false);
              public void changedUpdate(DocumentEvent e) {
              //Plain text components do not fire these events
              private String[] getKeywordsFromDB(){
              String[] k = null;
              String flwor = "";
              flwor = "for $i in collection('" + containerFileName + "') /reference/keywords/keyword \n";
              flwor += "let $id := $i/@id/text() \n";
              flwor += "let $val := $i/@value/text() \n";
              flwor += "order by $val ascending \n";
              flwor += "return ($id, $val)";
              return k = myDbContainer.runQuery(flwor);
              private class keywordOb implements Comparable{
              private String id;
              private String value;
              public keywordOb(String id, String value){
              this.id = id;
              this.value = value;
              public String getId(){
              return id;
              public String getValue(){
              return value;
              public String toString(){
              return value;
              public int compareTo(Object o){
                                  int result = (((keywordOb)this).toString()).compareTo(((keywordOb)o).toString());
                                  return result;
              private class questionOb implements Comparable{
              private String id;
              private String value;
              private String[] keywordRefs;
              public questionOb(String id, String value, String[] keywordRefs){
              this.id = id;
              this.value = value;
              this.keywordRefs = keywordRefs;
              public questionOb(){
              this.id = "";
              this.value = "";
              this.keywordRefs = null;
              public String getId(){
              return id;
              public String getValue(){
              return value;
              public String toString(){
              return value;
              public String[] getKeywordRefs(){
              return keywordRefs;
              public void setId(String id){
              this.id = id;
              public void setValue(String value){
              this.value = value;
              public void setKeywordRefs(String[] keywords){
              this.keywordRefs = keywordRefs;
              public int compareTo(Object o){
                             int result = (((questionOb)this).toString()).compareTo(((questionOb)o).toString());
                             return result;
              //Add New Keyword to xml reference File
              private void addNewKeyword(String k){
              String keyword = k;
              int len = jTextField1.getDocument().getLength();
              //Tidy up string
              keyword = keyword.trim();
              keyword = keyword.replaceAll("\\s+"," ");
              keyword = capitalizeWords(keyword);
              String flwor = "";
              //Check that the keyword value doesn't already exist
              flwor = "let $i := collection('" + containerFileName + "')/reference/keywords/keyword[@value = '" + keyword + "'] \n";
              flwor += "return \n";
              flwor += "if(count($i)) then fn:true() \n";
              flwor += "else fn:false() \n";
              boolean keywordExists = bDbConnection.runBooleanQuery(flwor);
              if (keywordExists){
              jOptionPane1.showMessageDialog(new Frame(),
              "The keyword '" + keyword + "' already exists", "Message", jOptionPane1.INFORMATION_MESSAGE);
              try {
              jTextField1.getDocument().remove(0,len);
              } catch (Exception ex) {
              ex.printStackTrace();
              //Terminate method execution
              return;
              //Need to get ID of last keyword
              flwor = "for $i in collection('" + containerFileName + "')/reference/keywords/keyword/@id/text() \n";
              flwor += "order by $i descending \n";
              flwor += "return $i[fn:last()]";
              String[] lastIDArray = new String[1];
              lastIDArray = bDbConnection.runQuery(flwor);
              String lastIDStr = lastIDArray[0];
              //create incremented ID value
              //Note: XML ID attributes must start with a letter - that's why we need to do all this nonsense!
              int lastIDNum = new Integer(lastIDStr.substring(1));
              int nextIDNum = ++lastIDNum;
              String nextIDStr = String.format("%04d", nextIDNum);
              nextIDStr = "K" + nextIDStr;
              //OK Finally - actually add the keyword to the xml reference file
              //use BDB API for updating - since XQuery does not allow
              try
              XmlQueryContext qc = myManager.createQueryContext();
              XmlUpdateContext uc = myManager.createUpdateContext();
              XmlModify mod = myManager.createModify();
              XmlQueryExpression select = myManager.prepare("/reference/keywords", qc);
              mod.addAppendStep(select, XmlModify.Element, "keyword", "");
              select = myManager.prepare("/reference/keywords/keyword[fn:last()]", qc);
              mod.addAppendStep(select, XmlModify.Attribute, "id", nextIDStr);
              mod.addAppendStep(select, XmlModify.Attribute, "value", keyword);
              XmlDocument updateDoc = myContainer.getDocument(docName);
              XmlValue docValue = new XmlValue(updateDoc);
              mod.execute(docValue, qc, uc);
              catch(Exception e){
              System.out.println("Error adding keyword: " + e.getMessage());
              //Add the new keyword to the list of selected keywords
              model_2.addElement(keyword);
              sortModelElements(model_2);
              try {
              jTextField1.getDocument().remove(0,len);
              } catch (Exception ex) {
              ex.printStackTrace();
              private questionOb[] getQuestionsFromDB(keywordOb[] keywordIDs){
              questionOb[] qobs = null;
              String seq = "";
              String flwor = "";
              int num = 0;
              seq = keywordObsToSeq(keywordIDs);
              flwor = "for $i in " + seq + "\n";
              flwor += "let $q := collection('" + containerFileName + "') /reference/questions/question[./keywordRef/@idref/text() = $i] \n";
              flwor += "return $q";
              try
              XmlQueryContext context = myManager.createQueryContext();
              context.setEvaluationType(XmlQueryContext.Eager);
              context.setReturnType(XmlQueryContext.DeadValues);
              XmlResults results = myManager.query(flwor, context);
              // Report Query Info
              String message = "Found ";
              message += results.size() + " entries for query: '";
              message += flwor + "'\n";
              System.out.println(message);
              int numQuestions;
              numQuestions = results.size();
              qobs = new questionOb[numQuestions];
              String[] keyRefs = new String[1];
              String[] keyRefs2 = new String[1];
              XmlResults atts, atts2 = null;
              XmlValue keyRefElem, keyRefAtt = null;
              int i;
              for(i=0; i < numQuestions; i++){
              XmlValue val = results.next();
              atts = val.getAttributes();
              String id = atts.next().getNodeValue();
              String value = atts.next().getNodeValue();
              keyRefElem = val.getFirstChild();
              int j=0;
              while (!keyRefElem.isType(XmlValue.NONE)){
              if(keyRefElem.getType() == XmlValue.TEXT_NODE){
              keyRefElem = keyRefElem.getNextSibling();
              if(keyRefElem.isType(XmlValue.NONE)){
              break;
              System.out.println("1");
              atts2 = keyRefElem.getAttributes();
              System.out.println("2");
              keyRefs[j] = atts2.next().getNodeValue();
              System.out.println("3" + keyRefs[j]);
              System.arraycopy(keyRefs,0,keyRefs2,0,j+1);
              System.out.println("4");
              keyRefs = new String[j+2];
              System.out.println("5");
              System.arraycopy(keyRefs2,0,keyRefs,0,j+1);
              System.out.println("6");
              keyRefs2 = new String[j+2];
              System.out.println("7");
              keyRefElem = keyRefElem.getNextSibling();
              System.out.println("8");
              j++;
              System.out.println(keyRefs[0]+keyRefs[1]);
              //Create new Question Object with retrieved values
              System.out.println("bef");
              questionOb qo = new questionOb(id, value, keyRefs);
              System.out.println("aft");
              qobs[i] = qo;
                        catch(Exception e)
              System.out.println("XML Exception is "+ e.getMessage());
              return qobs;
              private void sortModelElements(DefaultListModel model){
              //Getting the size of the model
              int size = model.getSize();
              //Creating the keyword object based on the size of the model
              keywordOb[] word = new keywordOb[size];
              int i=0;
              //keywordOb j;
              for(i=0; i < size; i++){
              word[i] = (keywordOb) model.getElementAt(i);
              Arrays.sort(word);
              for(i=0; i < size; i++){
              //model.setElementAt(word[i], i);
              model.set(i,word[i]);
              public void messageBox(String message)
              jOptionPane1.showMessageDialog(new Frame(), message , "Message", jOptionPane1.INFORMATION_MESSAGE);
              class KeywordFilter extends DocumentFilter {
              public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
              throws BadLocationException {
              int len = fb.getDocument().getLength();
              if(len==0 & noFunnyChars(string) & !string.trim().equals("")){
              fb.insertString(offset, string, attr);
              if(len > 0 & noFunnyChars(string) & len < 30){
              fb.insertString(offset, string, attr);
              public void replace(FilterBypass fb, int offset, int length, String string, AttributeSet attr)
              throws BadLocationException {
              int len = fb.getDocument().getLength();
              if(len==0 & noFunnyChars(string) & !string.trim().equals("")){
              fb.replace(offset, length, string, attr);
              if(len > 0 & noFunnyChars(string) & len < 30){
              fb.insertString(offset, string, attr);
              private boolean noFunnyChars(String s){
              String regex = "[A-Za-z\\s]+";
              boolean b = Pattern.matches(regex, s);
              return b;
              private String capitalizeWords(String s){
              String s2;
              char[] c = s.toCharArray();
              int i = 0;
              c[0] = Character.toUpperCase(c[0]);
              for(i=0; i < c.length; i++){
              if (!Character.isLetter(c[i])){
              c[i+1] = Character.toUpperCase(c[i+1]);
              s2 = String.valueOf(c);
              return s2;
              private String keywordObsToSeq(keywordOb[] a) {
              StringBuffer result = new StringBuffer();
              String resultStr = "";
              result.append("('" + a[0].getId() + "', ");
              for (int i=1; i < a.length; i++) {
              result.append("'" + a[i].getId() + "', ");
              resultStr = result.toString();
              resultStr = resultStr.trim();
              resultStr = resultStr.substring(0,resultStr.length()-1) + ")";
              return resultStr;
         // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
              private void initComponents() {
              jScrollPane1 = new javax.swing.JScrollPane();
              jList1 = new javax.swing.JList();
              jScrollPane2 = new javax.swing.JScrollPane();
              jList2 = new javax.swing.JList();
              jLabel1 = new javax.swing.JLabel();
              jLabel2 = new javax.swing.JLabel();
              jLabel3 = new javax.swing.JLabel();
              jTextField1 = new javax.swing.JTextField();
              jButton1 = new javax.swing.JButton();
              jButton2 = new javax.swing.JButton();
              jButton3 = new javax.swing.JButton();
              jScrollPane3 = new javax.swing.JScrollPane();
              jList3 = new javax.swing.JList();
              jLabel4 = new javax.swing.JLabel();
              jButton4 = new javax.swing.JButton();
              jButton5 = new javax.swing.JButton();
              jLabel5 = new javax.swing.JLabel();
              jScrollPane4 = new javax.swing.JScrollPane();
              jTextArea1 = new javax.swing.JTextArea();
              jButton6 = new javax.swing.JButton();
              setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
              jList1.addMouseListener(new java.awt.event.MouseAdapter() {
              public void mouseClicked(java.awt.event.MouseEvent evt) {
              jList1MouseClicked(evt);
              jScrollPane1.setViewportView(jList1);
              jList2.addMouseListener(new java.awt.event.MouseAdapter() {
              public void mouseClicked(java.awt.event.MouseEvent evt) {
              jList2MouseClicked(evt);
              jScrollPane2.setViewportView(jList2);
              jLabel1.setText("Available Keywords");
              jLabel2.setText("Selected Keywords");
              jLabel3.setText("Add New Keyword");
              jTextField1.setFont(new java.awt.Font("Tahoma", 0, 12));
              jTextField1.addActionListener(new java.awt.event.ActionListener() {
              public void actionPerformed(java.awt.event.ActionEvent evt) {
              jTextField1ActionPerformed(evt);
              jButton1.setText("Add Keyword");
              jButton1.setEnabled(false);
              jButton1.addActionListener(new java.awt.event.ActionListener() {
              public void actionPerformed(java.awt.event.ActionEvent evt) {
              jButton1ActionPerformed(evt);
              jButton2.setText("Modify Keyword");
              jButton3.setText("Remove Keyword");
              jList3.setModel(new javax.swing.AbstractListModel() {
              String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
              public int getSize() { return strings.length; }
              public Object getElementAt(int i) { return strings[i]; }
              jScrollPane3.setViewportView(jList3);
              jLabel4.setText("Questions");
              jButton4.setText("OK");
              jButton4.addActionListener(new java.awt.event.ActionListener() {
              public void actionPerformed(java.awt.event.ActionEvent evt) {
              jButton4ActionPerformed(evt);
              jButton5.setText("Cancel");
              jLabel5.setText("Add New Question");
              jTextArea1.setColumns(20);
              jTextArea1.setRows(2);
              jScrollPane4.setViewportView(jTextArea1);
              jButton6.setText("Add Question");
              javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
              getContentPane().setLayout(layout);
              layout.setHorizontalGroup(
              layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
              .addContainerGap(488, Short.MAX_VALUE)
              .addComponent(jButton5)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addGap(29, 29, 29))
              .addGroup(layout.createSequentialGroup()
              .addGap(38, 38, 38)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addGroup(layout.createSequentialGroup()
              .addComponent(jButton6)
              .addContainerGap())
              .addGroup(layout.createSequentialGroup()
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
              .addComponent(jScrollPane4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 559, Short.MAX_VALUE)
              .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
              .addComponent(jLabel5)
              .addComponent(jLabel4)
              .addGroup(layout.createSequentialGroup()
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel1)
              .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))
              .addGap(31, 31, 31)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel2)
              .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE))
              .addGap(32, 32, 32)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(jLabel3)
              .addComponent(jButton1)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
              .addComponent(jButton2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
              .addComponent(jButton3, javax.swing.GroupLayout.Alignment.LEADING))))
              .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 559, Short.MAX_VALUE)))
              .addContainerGap(58, Short.MAX_VALUE))))
              layout.setVerticalGroup(
              layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addGroup(layout.createSequentialGroup()
              .addGap(24, 24, 24)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
              .addGroup(layout.createSequentialGroup()
              .addComponent(jLabel1)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE))
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
              .addGroup(layout.createSequentialGroup()
              .addComponent(jLabel2)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE))
              .addGroup(layout.createSequentialGroup()
              .addComponent(jLabel3)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jButton1)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
              .addComponent(jButton2)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jButton3))))
              .addGap(29, 29, 29)
              .addComponent(jLabel4)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addGap(20, 20, 20)
              .addComponent(jLabel5)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(jButton6)
              .addGap(31, 31, 31)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
              .addComponent(jButton4)
              .addComponent(jButton5))
              .addGap(21, 21, 21))
              pack();
    }// </editor-fold>
              //Event handlers
              private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
              // TODO add your handling code here:
                        try {
                             myDbContainer.close();
                             myDbEnv.cleanup();
                        } catch (Exception e) {
                             logger.info("Could not close container/or env - Component");
                        super.setVisible(false);
                        super.dispose();
                   private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
              // TODO add your handling code here:
                        String val;
                        val = jTextField1.getText();
                        if(val != null & val.trim() != "" & noFunnyChars(val) ){
                             jButton1.setEnabled(true);
                        else {
                             jButton1.setEnabled(false);
                   private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
              // TODO add your handling code here:
                   // Add new keyword to the xml reference file
                        //addNewKeyword(jTextField1.getText());
                   private void jList2MouseClicked(java.awt.event.MouseEvent evt) {
              // TODO add your handling code here:
                        if(evt.getClickCount() == 2) {
                             keywordOb k = (keywordOb)jList2.getSelectedValue();
                             model_2.removeElement(k);
                             model_1.addElement(k);
                             sortModelElements(model_1);
                             questionOb q = null;
                             //Remove associated questions from listbox
                             int i,j;
                             for(i=0; i < model_3.size(); i++){
                                  q = (questionOb)model_3.getElementAt(i);
                                  for(j=0; j < model_3.size(); j++){
                                       if (q.getKeywordRefs()[j].equals(k.getId())){
                                            model_3.removeElement(q);
                                            i--;
                                            break;
                   private void jList1MouseClicked(java.awt.event.MouseEvent evt) {
              // TODO add your handling code here:
                   if(evt.getClickCount() == 2) {
                             //Getting properties of the selecteditem item in jList1.
                        keywordOb k = (keywordOb)jList1.getSelectedValue();
                        //Removing the element from jList1
                        model_1.removeElement(k);
                        //Adding the element to jList2
                        model_2.addElement(k);
                        sortModelElements(model_2);
                        //Load the questions for the selected keywords
                        int len;
                        len = model_2.getSize();
                        keywordOb[] dbQuestionsOb = new keywordOb[5];
                        keywordOb[] selectedKeywordsOb = new keywordOb[len];
                        String[] selectedKeywordIDs = new String[len];
                        int i;
                        for(i=0; i < len; i++) {
                             selectedKeywordsOb[i] = (keywordOb)model_2.getElementAt(i);
                             selectedKeywordIDs[i] = selectedKeywordsOb[i].getId();
                        questionOb[] questionsOb = getQuestionsFromDB(selectedKeywordsOb);
                        model_3.removeAllElements();
                        for(i=0; i < questionsOb.length; i++){
                             model_3.addElement(questionsOb[i]);
                        // sortModelElements(model_3);
    I think thats too much code for one post!

  • 'More Info' disappears from 'Get Info' Inspector Tab when accessed more than once

    I've just got back from an appointment at my local Apple store Genius Bar and have had three members of staff all looking bewildered and unsure as to what to suggest with regard to this issue (apart from a fresh OS install/HD reformat). Basically, it seems that after initially using the Inspector to gather metadata about files - mp3, m4a, MOV, avi etc the 'More Info' section becomes blank, as if there is no metadata to display, even though metadata is definitely present (see attached pictures and linked video):
    Demonstration of issue (best to open in new tab, then click play or double click to start video)
    First use of Inspector to view metadata on an mp3 file, Flexible (Original Mix) at 17:05
    Second use of Inspector to view metadata on an mp3 file, Flexible (Original Mix) at 17:06
    As you can see, in the second instance, all mention of metadata is gone. Am somewhat perplexed as to why this is happening. Any thoughts or suggestions appreciated.
    Jonathan

    Ok, so this issue has resolved all by itself. Perhaps an update has rectified whatever the problem was, who knows. Anyway, job done tick lol
    FYI the link to the demo video won't work anymore either as I've removed corresponding video from my dropbox account

  • OutOfMemoryError: Java heap space error when exporting more than 65MB file

    Hi all,
    My requirement is to export 65Mb file in a CSV format.There is no possibility for me to increase the heap size.
    But ,I get the following error which is below the code while doing an export.
    Whole 65mb ,I am putting into the response stream.I am not sure whether this is allowed or not.If not,please tell me the alternatives.
    ServletOutputStream out = null;
    final FacesContext faces = FacesContext.getCurrentInstance();
    final HttpServletResponse response = (HttpServletResponse) faces
    .getExternalContext().getResponse();
    response.setContentType( "application/download" );
    response.setHeader( ...................);
    final byte[] byteArray = eachLine.toString().getBytes();
    response.setContentLength( byteArray.length );
    out.write(byteArray);
    java.lang.OutOfMemoryError: Java heap space
    at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:95)
    at org.apache.myfaces.webapp.filter.ExtensionsResponseWrapper$MyServletOutputStream.write(ExtensionsResponseWrapper.java:138)
    at org.ajax4jsf.io.FastBufferOutputStream.writeTo(FastBufferOutputStream.java:151)
    at org.ajax4jsf.framework.ajax.xmlfilter.FilterServletResponseWrapper.sendContent(FilterServletResponseWrapper.java:469)
    at org.ajax4jsf.framework.ajax.xmlfilter.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:193)
    at org.ajax4jsf.framework.ajax.xmlfilter.BaseFilter.doFilter(BaseFilter.java:220)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:100)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:147)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    Edited by: Neelims on Apr 4, 2009 3:48 AM
    Edited by: Neelims on Apr 4, 2009 3:51 AM

    Hi
    final byte[] byteArray = eachLine.toString().getBytes();
    response.setContentLength( byteArray.length );
    out.write(byteArray);
    I assume eachLine is an object that holds the 100MB file contents, just release the memory held by this object before you start the writing part as shown below
    final byte[] byteArray = eachLine.toString().getBytes();
    eachLine=null;//removed the reference holding the memory
    System.gc()//if JVM is in a good mood may be it will release some memory
    response.setContentLength( byteArray.length );
    out.write(byteArray);
    before throwing out of memeory JVM may try to run the garbage collecter as you have initialised your object it might free up some memory

  • Performance... Why a function column in a view is executed more than once...?

    Why a function column created inside a view is executed more than once when called more than once?
    EXAMPLE:
    create or replace view aux1 as
    date_column,
    any_function(date_column) column1
    from any_table
    create or replace view aux2 as
    column1 c1,
    column1 c2,
    column1 c3
    from aux1
    select * from aux2
    It will execute 3 times the function any_function... logically the value will be the same for all columns...
    I understand why!... are 3 calls... but...
    Why not to create a "small" verification and if the function column was execute replace the second, the third... value? ... instead of execute 3, 4... times...
    tks
    Braga

    Actually, this is more than a performance issue. This is a consistency problem. If the function is NOT deterministic then you may get different values for each call which is clearly not consistent with selecting 3 copies of the same column from a row. Oracle appears to have fixed this in 9i...
    Connected to:
    Oracle8i Enterprise Edition Release 8.1.7.2.0 - Production
    With the Partitioning option
    JServer Release 8.1.7.2.0 - Production
    create view v1 as select dbms_random.value(1,100) r from dual;
    create view v2 as select r r1, r r2 from v1;
    select * from v2;
              R1           R2
              93           74
    Connected to:
    Oracle9i Enterprise Edition Release 9.0.1.3.0 - Production
    With the Partitioning option
    JServer Release 9.0.1.3.0 - Production
    create view v1 as select dbms_random.value(1,100) r from dual;
    create view v2 as select r r1, r r2 from v1;
    select * from v2;
              R1           R2
              78           78Richard

  • Heading level hierarchy errors when topics are in TOC more than once

    I have discovered that the hierarchy in the Heading levels in
    the Printed Documentation will differ from than in my online help
    table of contents hierarchy, and that the problem is due to topics
    that are intentionally in the TOC more than once.
    For example, in chapter 5 of a particular help system the
    hierarchy should be:
    Heading 1 < Chapter 5 title from top-level book>
    Heading 2 <title of second level book>
    Heading 3 <title of topic that appears under second-level
    book>*
    What I actually get is:
    Heading 1 < Chapter title from top-level book>
    Heading 2 <title of second level book>
    Heading 4 <title of topic that appears under second-level
    book>*
    * This same topic appeared in an earlier chapter. In that
    chapter it was really at a Heading 4 level.
    Due to company styles, etc. we use a numbering system at the
    headings and in the TOC, so instead of
    5
    5.1
    5.1.1
    I erroneously get
    5
    5.1
    5.1.1.1
    This type of hierarchy issue appears multiple times in this
    particular document (which I inherited by the way.)
    Other than restructuring the document to not reuse topics in
    different places in the TOC, is there a solution or a workaround
    for this problem?
    What I am doing so far, is generating the Print Documentation
    one chapter at a time. As long as a topic is not reused with the
    same chapter, my hierarchy of heading levels is maintained;
    otherwise, it is not. Then I can put the chapters back together
    after fixing the few places that still have heading level problems.
    This however, will be quite cumbersome as this document is
    translated into nine other languages.
    I am using RoboHelp X5 for Word / Word 2003 for the source
    and most of the translations; RoboHelp Asian Edition, Simplified
    Chinese / Word 2003 for the Chinese translation. The heading level
    hierarchy error occurs in both versions.

    >> AF: I've commented in sections...
    Without Maintain Heading Levels, RH will apply heading levels
    to the books and then the topic levels will get bumped down. So a
    top level book will be Heading 1 and the Headings in the topic will
    get bumped down to 2, 3 and 4 etc. If then you have another book
    one level down so that it gets Heading 2 applied, the same topic
    but under the level two book would then get 3, 4 and 5 applied.
    That is not the original problem but hopefully we are agreed
    that is how things work on that.
    >> Yes - that is the expected behavior. When it didn't
    happen as expected, that's what led me to the discovery of the
    cause of the problem (topic reuse).
    Your problem was that firstly Heading 3 got bumped to Heading
    4 if the same topic was inserted into the TOC twice. I assume it
    was OK in the first instance, or is it that when you add it twice
    it goes wrong everywhere?
    >> Your assumption is correct. First occurrence is
    correct. Second, third, and fourth (yes - there is one topic that
    is used 4 times! ) are not correct based on TOC hierarchy.
    On the numbering, nothing surprises me. If you look at my
    site you will see that for RH HTML, i gave up on getting it right.
    I have had many queries on this and more than a few people have
    indicated they will work on the problem and get it working. I'm
    still waiting. There are many posts about outline numbering
    problems. Has anyone got it working satisfactorily?
    >> I don't really have numbering problems. The
    numbering is following the RoboHelp-generated hierarchy and the
    .dot template that I apply. It's just that the RH-generated
    hierarchy and its heading levels don't correspond to the "real"
    hierarchy because of the reuse issue.
    I have seen various Word gurus maintain that numbering has
    not worked entirely satisfactorily since Word 2! Also enough posts
    to convince me this is a Word issue, not a RH issue.
    If you want to create a new project and knock something up
    that demonstrates this problem, by all means zip it up and send it.
    I'll assume it will be a small project and zip to less than 5mb. If
    more, contact me first.
    >> Unless you have RoboHelp X3 Asian Edition,
    Simplified Chinese, there is really no need. I plan to either avoid
    the reuse issue in the source, or build the print doc in sections
    which is easy enough in RoboHelp X5 for the non-Chinese languages.
    It is in the older Asian edition where the problems are compounded
    by the omitted reuse topics. If you do have RoboHelp X3 Asian
    Edition, Simplified Chinese and want to experiment, I can send you
    a cut-down version of the project. Don't feel obligated though;
    unless you can read Chinese (I can't) it is very tedious to work
    with.

  • Error: An attribute cannot appear more than once in the same start tag

    Hi Everyone,
    when i run the page sometimes it works fine but sometimes it throws Compilation Error as below.
    "Error(502,1224): file:/C:/Jdeveloper/jdevhome/jdev/myhtml/OA_HTML/fwk/t/Session_2055663493/region1.uix<Line 502, Column 1224>: XML-20124: (Fatal Error) An attribute cannot appear more than once in the same start tag."
    And i delete the particular file from the path and run the page so this time it works fine.
    But later after sometime i get the same error but the session number will be changed, then again i need to delete it and run.
    What can be the permanent solution for this issue?
    Plz let me know any suggetions.
    Thanks.

    Seems like the mdl file is corrupted or was not generated correctly.
    Can you try to create the mdl file again and then try the import ?
    If it doesn't work then try contacting Oracle Support.

  • Permissions Error if Script is run more than once with out closing Diadem

    I am in a REAL pickle here and need some HELP......
    I get a permissions error message when I try and run my scripts more than once with out closing Diadem 2011.
    Call scriptinclude ("D:\_Calterm_Configuration_Files\Technical_Information\DIAdem_Scripts\Importing Multiple Data Logs_CaltermIII_Local.VBS")
    Error is around this portion of script:
    '******* GetFilePaths() *** *** NEW Function ***
    Function GetFilePaths(DefaultDir, ExtFilter, MultipleDir, Msg)
    Dim i, k, f, fso, iMax, FileListPath, StartIdx, CurrFiles, FileList
    ' Promt the User to select the ASCII files to load with a File Dialog
    FileListPath = AutoActPath & "FileDlgList.asc"
    Set fso = CreateObject("Scripting.FileSystemObject")
    StartIdx = 0
    ReDim FileList(0)
    Do ' Until (DlgState = "IDCancel")
    Call FileNameGet("ANY", "FileRead", DefaultDir, ExtFilter, FileListPath, 1, Msg)
    IF (DlgState = "IDCancel") THEN Exit Do
    ' Read in the saved list of file(s) selected in the File Dialog into FileList()
    **** This next line is where the ERROR happens *******
    Set f = fso.OpenTextFile(FileListPath, 1, True) ' f.ReadAll returns file contents
    CurrFiles = Split(vbCRLF & f.ReadAll, vbCRLF) ' turn file lines into an array
    f.Close ' close the file
    iMax = UBound(CurrFiles)
    IF iMax > 0 AND Trim(CurrFiles(iMax)) = "" THEN
    iMax = iMax - 1
    ReDim Preserve CurrFiles(iMax)
    END IF
    Call BubbleSort(CurrFiles) ' sort the array of file names alphabetically
    ' Append current file dialog selection(s) to any previous file dialog selection(s)
    IF iMax < 1 THEN iMax = 0
    ReDim Preserve FileList(k + iMax)
    FOR i = 1 TO iMax
    k = k + 1
    FileList(k) = CurrFiles(i)
    NEXT ' i
    IF MultipleDir <> TRUE THEN Exit Do ' forces only 1 dialog, good if all desired files are in the same folder
    Loop ' Until (DlgState = "IDCancel")
    GetFilePaths = FileList
    End Function ' GetFilePaths()
    266 6:18:34 PM Error:
    Error in <NoName(1).VBS> (Line: 8, Column: 1):
    Error in <Importing Multiple Data Logs_CaltermIII_Local.VBS> (Line: 140, Column: 5):
    Permission denied
    I can send the script and file I am loading if that would help.
    Solved!
    Go to Solution.

    Jcheese,
    I understood that if you call this script within DIAdem you don't get any error, however, when you run that script from another source (with DIAdem opened) for the second time you get the error, right? 
    If this is the case, I think it might be that the file haven't close correctly in the script. Could you upload the script file?
    Carmen C.

  • Error using pretrigger when capturing more than one channel

    I am having problems acquiring data with pretrigger samples when capturing more than one channel, using NI-PXI-6071E hardware and Labview's Analog Input VIs (Legacy NI-DAQ).
    My goal is to trigger on one signal, while capturing another. Unfortunately, I cannot use the PFI0 for external triggering, as our cables/hardware have already been built, so I must use an analog input channel as the trigger. I understand that to do so I must capture both channels, and the channel that I wish to trigger off of must be the first channel in the list.
    If I trigger and capture on the same channel (tried 1-4) then it
    works great, regardless of the number of pre-trigger samples set. If I
    capture more than one channel (passing the trigger channel first), with no pretrigger samples set, then triggering and capturing both work fine. However, if I do the same with the pretrigger sample > 0 I get the following error:
    Error -10621 occurred at AI Control. Possible reason(s):
    NI-DAQ LV: The specified trigger signal cannot be assigned to the trigger resource.  
    I don't se any such limitation explained in the user manual, and searching the forum, I have found a few other people that had the
    same
    problem
    but they did not have solutions. Any ideas?
    Solved!
    Go to Solution.

    I'm sorry for double-posting this. I was trying to post it in the DAQ board and it kept ending up on the LabView board.
    If moderators have the ability to delete this thread you are welcome to do so.

Maybe you are looking for