Create Timer Jobs dynamically using code (on the fly)

What I am trying to accomplish here is different from the usual "Create and deploy a new custom timer job". So please co operate.
Scenario : I have around 200 lists in my site. Each list gets its data from a third part web service (cutom code / not BCS). The data retrieval happens via Timer Jobs. The Timer Jobs call the web service, gets the fresh data and updates the
list items. This is currently working fine with multiple lists and 1 timer job to refresh the data.
Problem : Now the issue I am facing is, each of the lists have its own Refresh Frequency. Say List 1 to 30 needs to be refreshed every 5 mins. List 31 to 60 every 10 mins, etc. I am currently handling this by having a RefreshLastRun timestamp.
This works fine in most of the scenarios - unless the Web service returns large data, in which case it takes more than 5 to 10 mins for the Update to complete on 4 to 5 lists. At the same time, the other lists - they were supposed to be updated 5 mins ago,
but are still waiting to get updated because the timer job is busy updating another list, and the refresh is in Que. This is a completely unaccepatable solution to my client because the list with lower frequency duration (5 mins) is of a higher priority than
the lists getting refreshed every 10 mins.
My Question is : How do I create a new Timer Job for each list? Whenever I add a new list (through code), I want to create a Timer Job at the same time, which will take care of refreshing the data in this and this list only. This way, I will
have a independent Timer Job for each list and dont have to depend on 1 timer job to take all the load. With this approach I will have 200 timer jobs running. Which is OK with my client. So I create one class inhereting from SPJobDefinition class, and
use it repeatedly to create unlimted timer jobs?
I hope I am able to convey the message. My Timer Jobs are working fine. I dont need suggestions on how to get the timer job working etc. My question is, how do I create a new Job Definition dynamically through code (no deployment).
Hanif

I'm afraid this leads to a path where you create a single timer job (or windows service) that uses parallel programming (tpl) to handle all the lists. However, that places a huge burden on you to manage schedules, monitoring etc., something the timer job
framework handles for you.
Kind regards,
Margriet Bruggeman
Lois & Clark IT Services
web site: http://www.loisandclark.eu
blog: http://www.sharepointdragons.com

Similar Messages

  • Why we are using event receivers in creating timer jobs?

    Hi All,
    Why we are using event receivers in creating timer jobs?
    Thanks in advance!

    Hi,
    Suppose you are creating a custom timer job following the steps which are similar as what this demo provides:
    http://www.codeproject.com/Articles/403323/SharePoint-Create-Custom-Timer-Jobs
    In this demo, an Event Receiver is created for installing the Job Definition when we deploy the solution or uninstalling it when we extract this solution.
    Here, the Event Receiver listens to the FeatureActivated evetn and the FeatureDeactivating event, which corresponding to the timing of activating and deactivating the feature
    of this solution, it just like a switch during the life cycle of a solution in a SharePoint site collection which will make us easier to manage the features coming with a solution package.
    More information about feature and solution:
    http://msdn.microsoft.com/en-us/library/office/aa543214(v=office.14).aspx
    https://www.simple-talk.com/dotnet/.net-tools/using-features-and-solutions-to-deploy-your-sharepoint-customizations/
    Feel free to reply if this is not what your question about or there are still any questions.
    Best regards,
    Patrick
    Patrick Liang
    TechNet Community Support

  • Useful Code of the Day:  Multipart Form File Upload

    So, you want to upload files to your web server, do ya? Well, I've seen this topic posted a few times in the last month or so and many of the response I've seen here haven't included definitive answers. Of course, the actual problems vary, but ultimately, a bunch of people want to do file upload from an applet or application to an existing file upload script (CGI, PHP, JSP, etc.) on a web server. And invariably, there are problems with formatting the HTTP request to get things working.
    Well, I had a need to do the same thing. I realize there are other solutions out there, such as some sample code that comes with Jakarta Commons Upload. But since we all like reusable code, and we also all seem to like reinventing wheels, here's my go at it: MultiPartFormOutputStream!
    MultiPartFormOutputStream is a specialized OutputStream-like class. You create your URLConnection to the server (a static method included can do this for a URL for you, as some of the settings, doInput and doOutput specifically, seem to confuse people). Then get the OutputStream from it and create a boundary string (a static method to create one is provided as well) and pass them to the constructor. Now you have a MultiPartFormOutputStream which you can use to write form fields like text fields, checkboxes, etc., as well as write file data (from Files, InputStreams or raw bytes).
    There are some convenience methods for writing primative type values as well as strings, but any higher level objects (aside from Files or InputStreams) aren't supported. (You can always serialize and pass the raw bytes.)
    Sample usage code is below. Also, any recommendations for improvement are requested. The code was tested with the Jakarta Struts.
    import java.io.*;
    import java.net.*;
    * <code>MultiPartFormOutputStream</code> is used to write
    * "multipart/form-data" to a <code>java.net.URLConnection</code> for
    * POSTing.  This is primarily for file uploading to HTTP servers. 
    * @since  JDK1.3
    public class MultiPartFormOutputStream {
          * The line end characters. 
         private static final String NEWLINE = "\r\n";
          * The boundary prefix. 
         private static final String PREFIX = "--";
          * The output stream to write to. 
         private DataOutputStream out = null;
          * The multipart boundary string. 
         private String boundary = null;
          * Creates a new <code>MultiPartFormOutputStream</code> object using
          * the specified output stream and boundary.  The boundary is required
          * to be created before using this method, as described in the
          * description for the <code>getContentType(String)</code> method. 
          * The boundary is only checked for <code>null</code> or empty string,
          * but it is recommended to be at least 6 characters.  (Or use the
          * static createBoundary() method to create one.)
          * @param  os        the output stream
          * @param  boundary  the boundary
          * @see  #createBoundary()
          * @see  #getContentType(String)
         public MultiPartFormOutputStream(OutputStream os, String boundary) {
              if(os == null) {
                   throw new IllegalArgumentException("Output stream is required.");
              if(boundary == null || boundary.length() == 0) {
                   throw new IllegalArgumentException("Boundary stream is required.");
              this.out = new DataOutputStream(os);
              this.boundary = boundary;
          * Writes an boolean field value. 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, boolean value)
                   throws java.io.IOException {
              writeField(name, new Boolean(value).toString());
          * Writes an double field value. 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, double value)
                   throws java.io.IOException {
              writeField(name, Double.toString(value));
          * Writes an float field value. 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, float value)
                   throws java.io.IOException {
              writeField(name, Float.toString(value));
          * Writes an long field value. 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, long value)
                   throws java.io.IOException {
              writeField(name, Long.toString(value));
          * Writes an int field value. 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, int value)
                   throws java.io.IOException {
              writeField(name, Integer.toString(value));
          * Writes an short field value. 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, short value)
                   throws java.io.IOException {
              writeField(name, Short.toString(value));
          * Writes an char field value. 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, char value)
                   throws java.io.IOException {
              writeField(name, new Character(value).toString());
          * Writes an string field value.  If the value is null, an empty string
          * is sent (""). 
          * @param  name   the field name (required)
          * @param  value  the field value
          * @throws  java.io.IOException  on input/output errors
         public void writeField(String name, String value)
                   throws java.io.IOException {
              if(name == null) {
                   throw new IllegalArgumentException("Name cannot be null or empty.");
              if(value == null) {
                   value = "";
              --boundary\r\n
              Content-Disposition: form-data; name="<fieldName>"\r\n
              \r\n
              <value>\r\n
              // write boundary
              out.writeBytes(PREFIX);
              out.writeBytes(boundary);
              out.writeBytes(NEWLINE);
              // write content header
              out.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"");
              out.writeBytes(NEWLINE);
              out.writeBytes(NEWLINE);
              // write content
              out.writeBytes(value);
              out.writeBytes(NEWLINE);
              out.flush();
          * Writes a file's contents.  If the file is null, does not exists, or
          * is a directory, a <code>java.lang.IllegalArgumentException</code>
          * will be thrown. 
          * @param  name      the field name
          * @param  mimeType  the file content type (optional, recommended)
          * @param  file      the file (the file must exist)
          * @throws  java.io.IOException  on input/output errors
         public void writeFile(String name, String mimeType, File file)
                   throws java.io.IOException {
              if(file == null) {
                   throw new IllegalArgumentException("File cannot be null.");
              if(!file.exists()) {
                   throw new IllegalArgumentException("File does not exist.");
              if(file.isDirectory()) {
                   throw new IllegalArgumentException("File cannot be a directory.");
              writeFile(name, mimeType, file.getCanonicalPath(), new FileInputStream(file));
          * Writes a input stream's contents.  If the input stream is null, a
          * <code>java.lang.IllegalArgumentException</code> will be thrown. 
          * @param  name      the field name
          * @param  mimeType  the file content type (optional, recommended)
          * @param  fileName  the file name (required)
          * @param  is        the input stream
          * @throws  java.io.IOException  on input/output errors
         public void writeFile(String name, String mimeType,
                   String fileName, InputStream is)
                   throws java.io.IOException {
              if(is == null) {
                   throw new IllegalArgumentException("Input stream cannot be null.");
              if(fileName == null || fileName.length() == 0) {
                   throw new IllegalArgumentException("File name cannot be null or empty.");
              --boundary\r\n
              Content-Disposition: form-data; name="<fieldName>"; filename="<filename>"\r\n
              Content-Type: <mime-type>\r\n
              \r\n
              <file-data>\r\n
              // write boundary
              out.writeBytes(PREFIX);
              out.writeBytes(boundary);
              out.writeBytes(NEWLINE);
              // write content header
              out.writeBytes("Content-Disposition: form-data; name=\"" + name +
                   "\"; filename=\"" + fileName + "\"");
              out.writeBytes(NEWLINE);
              if(mimeType != null) {
                   out.writeBytes("Content-Type: " + mimeType);
                   out.writeBytes(NEWLINE);
              out.writeBytes(NEWLINE);
              // write content
              byte[] data = new byte[1024];
              int r = 0;
              while((r = is.read(data, 0, data.length)) != -1) {
                   out.write(data, 0, r);
              // close input stream, but ignore any possible exception for it
              try {
                   is.close();
              } catch(Exception e) {}
              out.writeBytes(NEWLINE);
              out.flush();
          * Writes the given bytes.  The bytes are assumed to be the contents
          * of a file, and will be sent as such.  If the data is null, a
          * <code>java.lang.IllegalArgumentException</code> will be thrown. 
          * @param  name      the field name
          * @param  mimeType  the file content type (optional, recommended)
          * @param  fileName  the file name (required)
          * @param  data      the file data
          * @throws  java.io.IOException  on input/output errors
         public void writeFile(String name, String mimeType,
                   String fileName, byte[] data)
                   throws java.io.IOException {
              if(data == null) {
                   throw new IllegalArgumentException("Data cannot be null.");
              if(fileName == null || fileName.length() == 0) {
                   throw new IllegalArgumentException("File name cannot be null or empty.");
              --boundary\r\n
              Content-Disposition: form-data; name="<fieldName>"; filename="<filename>"\r\n
              Content-Type: <mime-type>\r\n
              \r\n
              <file-data>\r\n
              // write boundary
              out.writeBytes(PREFIX);
              out.writeBytes(boundary);
              out.writeBytes(NEWLINE);
              // write content header
              out.writeBytes("Content-Disposition: form-data; name=\"" + name +
                   "\"; filename=\"" + fileName + "\"");
              out.writeBytes(NEWLINE);
              if(mimeType != null) {
                   out.writeBytes("Content-Type: " + mimeType);
                   out.writeBytes(NEWLINE);
              out.writeBytes(NEWLINE);
              // write content
              out.write(data, 0, data.length);
              out.writeBytes(NEWLINE);
              out.flush();
          * Flushes the stream.  Actually, this method does nothing, as the only
          * write methods are highly specialized and automatically flush. 
          * @throws  java.io.IOException  on input/output errors
         public void flush() throws java.io.IOException {
              // out.flush();
          * Closes the stream.  <br />
          * <br />
          * <b>NOTE:</b> This method <b>MUST</b> be called to finalize the
          * multipart stream.
          * @throws  java.io.IOException  on input/output errors
         public void close() throws java.io.IOException {
              // write final boundary
              out.writeBytes(PREFIX);
              out.writeBytes(boundary);
              out.writeBytes(PREFIX);
              out.writeBytes(NEWLINE);
              out.flush();
              out.close();
          * Gets the multipart boundary string being used by this stream. 
          * @return  the boundary
         public String getBoundary() {
              return this.boundary;
          * Creates a new <code>java.net.URLConnection</code> object from the
          * specified <code>java.net.URL</code>.  This is a convenience method
          * which will set the <code>doInput</code>, <code>doOutput</code>,
          * <code>useCaches</code> and <code>defaultUseCaches</code> fields to
          * the appropriate settings in the correct order. 
          * @return  a <code>java.net.URLConnection</code> object for the URL
          * @throws  java.io.IOException  on input/output errors
         public static URLConnection createConnection(URL url)
                   throws java.io.IOException {
              URLConnection urlConn = url.openConnection();
              if(urlConn instanceof HttpURLConnection) {
                   HttpURLConnection httpConn = (HttpURLConnection)urlConn;
                   httpConn.setRequestMethod("POST");
              urlConn.setDoInput(true);
              urlConn.setDoOutput(true);
              urlConn.setUseCaches(false);
              urlConn.setDefaultUseCaches(false);
              return urlConn;
          * Creates a multipart boundary string by concatenating 20 hyphens (-)
          * and the hexadecimal (base-16) representation of the current time in
          * milliseconds. 
          * @return  a multipart boundary string
          * @see  #getContentType(String)
         public static String createBoundary() {
              return "--------------------" +
                   Long.toString(System.currentTimeMillis(), 16);
          * Gets the content type string suitable for the
          * <code>java.net.URLConnection</code> which includes the multipart
          * boundary string.  <br />
          * <br />
          * This method is static because, due to the nature of the
          * <code>java.net.URLConnection</code> class, once the output stream
          * for the connection is acquired, it's too late to set the content
          * type (or any other request parameter).  So one has to create a
          * multipart boundary string first before using this class, such as
          * with the <code>createBoundary()</code> method. 
          * @param  boundary  the boundary string
          * @return  the content type string
          * @see  #createBoundary()
         public static String getContentType(String boundary) {
              return "multipart/form-data; boundary=" + boundary;
    }Usage: (try/catch left out to shorten the post a bit)
    URL url = new URL("http://www.domain.com/webems/upload.do");
    // create a boundary string
    String boundary = MultiPartFormOutputStream.createBoundary();
    URLConnection urlConn = MultiPartFormOutputStream.createConnection(url);
    urlConn.setRequestProperty("Accept", "*/*");
    urlConn.setRequestProperty("Content-Type",
         MultiPartFormOutputStream.getContentType(boundary));
    // set some other request headers...
    urlConn.setRequestProperty("Connection", "Keep-Alive");
    urlConn.setRequestProperty("Cache-Control", "no-cache");
    // no need to connect cuz getOutputStream() does it
    MultiPartFormOutputStream out =
         new MultiPartFormOutputStream(urlConn.getOutputStream(), boundary);
    // write a text field element
    out.writeField("myText", "text field text");
    // upload a file
    out.writeFile("myFile", "text/plain", new File("C:\\test.txt"));
    // can also write bytes directly
    //out.writeFile("myFile", "text/plain", "C:\\test.txt",
    //     "This is some file text.".getBytes("ASCII"));
    out.close();
    // read response from server
    BufferedReader in = new BufferedReader(
         new InputStreamReader(urlConn.getInputStream()));
    String line = "";
    while((line = in.readLine()) != null) {
          System.out.println(line);
    in.close();------
    "Useful Code of the Day" is supplied by the person who posted this message. This code is not guaranteed by any warranty whatsoever. The code is free to use and modify as you see fit. The code was tested and worked for the author. If anyone else has some useful code, feel free to post it under this heading.

    I have a weird problem here. I'm using the Java POST (slightly altered for my purposes) mechanism but the receiving script doesn't receive any form variables (neither files nor regular form fields). If I try using the same receiving script with a regular upload form, it works. Because I've been pulling my hair out, I even went so far as to analyze the ip-packets. I can see that the file is actually sent through the Java POST mecahnism. Anybody any ideas. Here's the ip-packet of the failing upload:
    ----- Hypertext Transfer Protocol -----
    HTTP: POST /fotoxs/upload.cfm HTTP/1.1
    HTTP: Connection: Keep-Alive
    HTTP: Content-Type: multipart/form-data; boundary=-----------------------------fb2649be18
    HTTP: User-Agent: Mozilla/4.7 [en] (WinNT; U)
    HTTP: Accept-Language: en-us
    HTTP: Accept-Encoding: gzip, deflate
    HTTP: Accept: image/gif, image/jpeg, image/pjpeg, */*
    HTTP: CACHE-CONTROL: no-cache
    HTTP: Host: newmarc
    HTTP: Content-Length: 15511
    ----- Hypertext Transfer Protocol -----
    HTTP: -----------------------------fb2649be18
    HTTP: Content-Disposition: form-data; name="uploadFile"; filename="out.jpg"
    HTTP: Content-Type: image/jpeg
    HTTP: Data
    ....[data packets]
    The one that works (from the regular post) is as follows:
    ----- Hypertext Transfer Protocol -----
    HTTP: POST /fotoxs/upload.cfm HTTP/1.1
    HTTP: Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-gsarcade-launch, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
    HTTP: Referer: http://localhost:8500/fotoxs/test.cfm
    HTTP: Accept-Language: nl
    HTTP: Content-Type: multipart/form-data; boundary=---------------------------7d41961f201c0
    HTTP: Accept-Encoding: gzip, deflate
    HTTP: User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
    HTTP: Host: newmarc
    HTTP: Content-Length: 59022
    HTTP: Connection: Keep-Alive
    HTTP: Cache-Control: no-cache
    ----- Hypertext Transfer Protocol -----
    HTTP: -----------------------------7d41961f201c0
    HTTP: Content-Disposition: form-data; name="FiletoUpload"; filename="D:\My Documents\My Pictures\fotomarc.jpg"
    HTTP: Content-Type: image/pjpeg
    HTTP: Data
    ----- Hypertext Transfer Protocol -----
    HTTP: HTTP/1.1 100 Continue
    HTTP: Server: Microsoft-IIS/5.0
    HTTP: Date: Sun, 07 Mar 2004 17:14:41 GMT
    ....[data packets]
    One detail worth mentioning is that I don't read a file from harddisk, I'm streaming it directly to the connection outputstream from an image compression utility. But I can see the data in the ip-packets, and even if that somehow didn't work right, it doesn't explaing the fact that the receiving scripts reports no form fields whatsoever.
    Thanks,
    Marc

  • Useful Code of the Day:  Button fires events while held

    Have you ever been making a GUI application with Swing and used some JButtons? Fun, right? Have you ever wanted to have the button fire action events while the button was being held down? Well, if you just stick a plain JButton in your application and press and hold the mouse button on it, you'll see it doesn't do anything except sit there looking pressed in. Insolent button!
    RepeatButton (code below, couldn't think of a better name) is a JButton subclass which contains a timer that is set when the mouse button presses the button, and after a slight initial delay (configurable), fires action events to all registered action listeners repeatedly (with another configurable delay between events) until either the mouse is released or the mouse moves out of the button (it starts up again if the mouse moves back over without releasing the mouse button) or the button is disabled. The event modifiers are passed on as well, so you know if the shift or control buttons (or whatever) are being pressed at the same time.
    There is also a method to disable the repeated action firing while holding. This, in effect, turns the button into a normal JButton, if needed.
    There is a main method for testing which will show a button in a frame and print out the action command for each action event fired.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.event.*;
    * <code>RepeatButton</code> is a <code>JButton</code> which contains a timer
    * for firing events while the button is held down.  There is a default
    * initial delay of 300ms before the first event is fired and a 60ms delay
    * between subsequent events.  When the user holds the button down and moves
    * the mouse out from over the button, the timer stops, but if the user moves
    * the mouse back over the button without having released the mouse button,
    * the timer starts up again at the same delay rate.  If the enabled state is
    * changed while the timer is active, it will be stopped.
    * NOTE:  The normal button behavior is that the action event is fired after
    * the button is released.  It may be important to konw then that this is
    * still the case.  So in effect, listeners will get 1 more event then what
    * the internal timer fires.  It's not a "bug", per se, just something to be
    * aware of.  There seems to be no way to suppress the final event from
    * firing anyway, except to process all ActionListeners internally.  But
    * realistically, it probably doesn't matter. 
    public class RepeatButton extends JButton
              implements ActionListener, MouseListener {
          * The pressed state for this button.
         private boolean pressed = false;
          * Flag to indicate that the button should fire events when held. 
          * If false, the button is effectively a plain old JButton, but
          * there may be times when this feature might wish to be disabled. 
         private boolean repeatEnabled = true;
          * The hold-down timer for this button.
         private Timer timer = null;
          * The pressed state for this button.
         private int delay = 60;
          * The pressed state for this button.
         private int initialDelay = 300;
          * Holder of the modifiers used when the mouse pressed the button. 
          * This is used for subsequently fired action events.  This may change
          * after mouse pressed if the user moves the mouse out, releases a key
          * and then moves the mouse back in. 
         private int modifiers = 0;
          * Creates a button with no set text or icon.
         public RepeatButton() {
              super();
              init();
          * Creates a button where properties are taken from the Action supplied.
          * @param  a  the button action
         public RepeatButton(Action a) {
              super(a);
              init();
          * Creates a button with an icon.
          * @param  icon  the button icon
         public RepeatButton(Icon icon) {
              super(icon);
              init();
          * Creates a button with text.
          * @param  text  the button text
         public RepeatButton(String text) {
              super(text);
              init();
          * Creates a button with initial text and an icon.
          * @param  text  the button text
          * @param  icon  the button icon
         public RepeatButton(String text, Icon icon) {
              super(text, icon);
              init();
          * Initializes the button.
         private void init() {
              this.addMouseListener(this);
              // initialize timers for button holding...
              this.timer = new Timer(this.delay, this);
              this.timer.setRepeats(true);
          * Gets the delay for the timer of this button. 
          * @return  the delay
         public int getDelay() {
              return this.delay;
          * Set the delay for the timer of this button. 
          * @param  d  the delay
         public void setDelay(int d) {
              this.delay = d;
          * Gets the initial delay for the timer of this button. 
          * @return  the initial delay
         public int getInitialDelay() {
              return this.initialDelay;
          * Sets the initial delay for the timer of this button. 
          * @param  d  the initial delay
         public void setInitialDelay(int d) {
              this.initialDelay = d;
          * Checks if the button should fire events when held.  If false, the
          * button is effectively a plain old JButton, but there may be times
          * when this feature might wish to be disabled. 
          * @return  if true, the button should fire events when held
         public boolean isRepeatEnabled() {
              return this.repeatEnabled;
          * Sets if the button should fire events when held.  If false, the
          * button is effectively a plain old JButton, but there may be times
          * when this feature might wish to be disabled.  If false, it will
          * also stop the timer if it's running.
          * @param  en  if true, the button should fire events when held
         public void setRepeatEnabled(boolean en) {
              if(!en) {
                   this.pressed = false;
                   if(timer.isRunning()) {
                        timer.stop();
              this.repeatEnabled = en;
          * Sets the enabled state of this button.  Overridden to stop the timer
          * if it's running.
          * @param  en  if true, enables the button
         public void setEnabled(boolean en) {
              if(en != super.isEnabled()) {
                   this.pressed = false;
                   if(timer.isRunning()) {
                        timer.stop();
              super.setEnabled(en);
          * Handle action events.
          * @param  ae  the action event
         public void actionPerformed(ActionEvent ae) {
              // process events only from this components
              if(ae.getSource() == this.timer) {
                   ActionEvent event = new ActionEvent(
                        this, ActionEvent.ACTION_PERFORMED,
                        super.getActionCommand(), this.modifiers);
                   super.fireActionPerformed(event);
              // testing code...
              else if(testing && ae.getSource() == this) {
                   System.out.println(ae.getActionCommand());
          * Handle mouse clicked events.
          * @param  me  the mouse event
         public void mouseClicked(MouseEvent me) {
              // process events only from this components
              if(me.getSource() == this) {
                   this.pressed = false;
                   if(this.timer.isRunning()) {
                        this.timer.stop();
          * Handle mouse pressed events.
          * @param  me  the mouse event
         public void mousePressed(MouseEvent me) {
              // process events only from this components
              if(me.getSource() == this && this.isEnabled() && this.isRepeatEnabled()) {
                   this.pressed = true;
                   if(!this.timer.isRunning()) {
                        this.modifiers = me.getModifiers();
                        this.timer.setInitialDelay(this.initialDelay);
                        this.timer.start();
          * Handle mouse released events.
          * @param  me  the mouse event
         public void mouseReleased(MouseEvent me) {
              // process events only from this components
              if(me.getSource() == this) {
                   this.pressed = false;
                   if(this.timer.isRunning()) {
                        this.timer.stop();
          * Handle mouse entered events.
          * @param  me  the mouse event
         public void mouseEntered(MouseEvent me) {
              // process events only from this components
              if(me.getSource() == this && this.isEnabled() && this.isRepeatEnabled()) {
                   if(this.pressed && !this.timer.isRunning()) {
                        this.modifiers = me.getModifiers();
                        this.timer.setInitialDelay(this.delay);
                        this.timer.start();
          * Handle mouse exited events.
          * @param  me  the mouse event
         public void mouseExited(MouseEvent me) {
              // process events only from this components
              if(me.getSource() == this) {
                   if(this.timer.isRunning()) {
                        this.timer.stop();
          * Testing flag.  Set in main method.
         private static boolean testing = false;
          * Main method, for testing.  Creates a frame with both styles of menu.
          * @param  args  the command-line arguments
         public static void main(String[] args) {
              testing = true;
              JFrame f = new JFrame("RepeatButton Test");
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JPanel p = new JPanel();
              RepeatButton b = new RepeatButton("hold me");
              b.setActionCommand("test");
              b.addActionListener(b);
              p.add(b);
              f.getContentPane().add(p);
              f.pack();
              f.show();
    "Useful Code of the Day" is supplied by the person who posted this message. This code is not guaranteed by any warranty whatsoever. The code is free to use and modify as you see fit. The code was tested and worked for the author. If anyone else has some useful code, feel free to post it under this heading.

    This makes word completion possible for JTextArea:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.util.*;
    * This class provides word completion for JTextArea.
    public class WordCompleteArea extends JTextArea {
        private boolean isTextComplete = true;
        public WordCompleteArea (Document doc, String text,
                                      int rows, int columns, KeyStroke expandKey) {
            super (doc, text, rows, columns);
            String s = "word-complete";
            Action wordComplete = new AbstractAction () {
                public void actionPerformed (ActionEvent e) {
                    wordComplete ();
            getInputMap ().put (expandKey, s);
            getActionMap ().put (s, wordComplete);
        public WordCompleteArea (Document doc, String text, int rows, int columns) {
            this (doc, text, rows, columns,
                            KeyStroke.getKeyStroke ("ctrl pressed SPACE"));
        public WordCompleteArea (Document doc) {
            this (doc, null, 0, 0);
        public WordCompleteArea (String text, int rows, int columns) {
            this (new PlainDocument (), text, rows, columns);
        public WordCompleteArea (int rows, int columns) {
            this (null, rows, columns);
        public WordCompleteArea (String text) {
            this (text, 0, 0);
        public WordCompleteArea () {
            this (0, 0);
         * Define if text already written in the JTextArea will be used
         * for expansion.
        public void setTextComplete (boolean b) {
            isTextComplete = b;
         * Find out if text already written in the JTextArea will be used
         * for expansion.
        public boolean isTextComplete () {
            return isTextComplete;
        private String tokenDelimiters = "\t\r\n ,;()[]{}%+/-*<>=&|!\"\'.@#";
         * Get delimiters that form a word.
        public String getTokenDelimiters () {
            return tokenDelimiters;
         * Set delimiters that form a word.
        public void setTokenDelimiters (String s) {
            tokenDelimiters = s;
        // Additional words used for expansion.
        private LinkedList wordCompleteList = new LinkedList ();
         * Add words that will be used as expansion.
        public void addCompleteWords (java.util.List words) {
            wordCompleteList.add (words);
         * Add a word that will be used as expansion.
        public void addCompleteWord (String word) {
            wordCompleteList.add (word);
        private String lastExpanded = null;
        private String lastExpansion = null;
        private Set dontAccept = new HashSet ();
        protected void wordComplete () {
            int caret = getCaretPosition ();
            if (caret == 0)
                return;
            String text = getText ();
            if (caret != text.length () && isCompletionLetter (text.charAt (caret)))
                return;
            StringBuffer sb = new StringBuffer ();
            int index = caret - 1;
            char ch;
            while (index >= 0 && isCompletionLetter ((ch = text.charAt (index)))) {
                sb.append (ch);
                index--;
            if (sb.length () == 0)
                return;
            sb.reverse ();
            String word = sb.toString ();
            String toExpand = word;
            if (toExpand.equals (lastExpansion)) {
                dontAccept.add (lastExpansion);
                toExpand = lastExpanded;
            } else {
                dontAccept.clear ();
            String s = findExpansion (toExpand, caret);
            if (s != null) {
                lastExpanded = toExpand;
                lastExpansion = s;
                replaceRange (s, caret - word.length (), caret);
            } else {
                dontAccept.clear ();
                lastExpanded = null;
                lastExpansion = null;
                int diff = word.length () - toExpand.length ();
                replaceRange ("", caret - diff, caret);
        private boolean isCompletionLetter (char ch) {
            return tokenDelimiters.indexOf (ch) < 0;
        protected String findExpansion (String word, int caret) {
            StringTokenizer st;
            if (isTextComplete) {
                st = new StringTokenizer (getText (), getTokenDelimiters ());
                while (st.hasMoreTokens ()) {
                    String s = st.nextToken ();
                    if (    s.startsWith (word)
                            && s.length () != word.length ()
                            && !dontAccept.contains (s)      ) {
                        return s;
            for (Iterator it = wordCompleteList.iterator (); it.hasNext (); ) {
                st = new StringTokenizer
                                ((String) it.next (), getTokenDelimiters ());
                while (st.hasMoreTokens ()) {
                    String s = st.nextToken ();
                    if (    s.startsWith (word)
                            && s.length () != word.length ()
                            && !dontAccept.contains (s)      ) {
                        return s;
            return null;
        // TEST
        public static void main (String[] args) {
            WordCompleteArea a = new WordCompleteArea ();
            JFrame window = new JFrame ();
            window.getContentPane ().add (a, BorderLayout.CENTER);
            window.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
            window.setSize (300, 300);
            window.setVisible (true);
    }

  • Useful Code of the Day:  Splash Screen & Busy Application

    So you are making an Swing application. So what are two common things to do in it?
    1) Display a splash screen.
    2) Block user input when busy.
    Enter AppFrame! It's a JFrame subclass which has a glass pane overlay option to block input (setBusy()). While "busy", it displays the system wait cursor.
    It also supports display of a splash screen. There's a default splash screen if you don't provide a component to be the splash screen, and an initializer runner which takes a Runnable object. The Runnable object can then modify the splash screen component, for example to update a progress bar or text. See the main method for example usage.
    It also has a method to center a component on another component (useful for dialogs) or center the component on the screen.
    NOTE on setBusy: I do recall issues with the setBusy option to block input. I recall it having a problem on some Unix systems, but I can't remember the details offhand (sorry).
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    * <CODE>AppFrame</CODE> is a <CODE>javax.swing.JFrame</CODE> subclass that
    * provides some convenient methods for applications.  This class implements
    * all the same constructors as <CODE>JFrame</CODE>, plus a few others. 
    * Methods exist to show the frame centered on the screen, display a splash
    * screen, run an initializer thread and set the frame as "busy" to block 
    * user input. 
    public class AppFrame extends JFrame implements KeyListener, MouseListener {
          * The splash screen window. 
         private JWindow splash = null;
          * The busy state of the frame. 
         private boolean busy = false;
          * The glass pane used when busy. 
         private Component glassPane = null;
          * The original glass pane, which is reset when not busy. 
         private Component defaultGlassPane = null;
          * Creates a new <CODE>AppFrame</CODE>. 
         public AppFrame() {
              super();
              init();
          * Creates a new <CODE>AppFrame</CODE> with the specified
          * <CODE>GraphicsConfiguration</CODE>. 
          * @param  gc  the GraphicsConfiguration of a screen device
         public AppFrame(GraphicsConfiguration gc) {
              super(gc);
              init();
          * Creates a new <CODE>AppFrame</CODE> with the specified title. 
          * @param  title  the title
         public AppFrame(String title) {
              super(title);
              init();
          * Creates a new <CODE>AppFrame</CODE> with the specified title and
          * <CODE>GraphicsConfiguration</CODE>. 
          * @param  title  the title
          * @param  gc     the GraphicsConfiguration of a screen device
         public AppFrame(String title, GraphicsConfiguration gc) {
              super(title, gc);
              init();
          * Creates a new <CODE>AppFrame</CODE> with the specified title and
          * icon image. 
          * @param  title  the title
          * @param  icon   the image icon
         public AppFrame(String title, Image icon) {
              super(title);
              setIconImage(icon);
              init();
          * Creates a new <CODE>AppFrame</CODE> with the specified title and
          * icon image. 
          * @param  title  the title
          * @param  icon  the image icon
         public AppFrame(String title, ImageIcon icon) {
              this(title, icon.getImage());
          * Initializes internal frame settings. 
         protected void init() {
              // set default close operation (which will likely be changed later)
              setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
              // set up the glass pane
              glassPane = new JPanel();
              ((JPanel)glassPane).setOpaque(false);
              glassPane.addKeyListener(this);
              glassPane.addMouseListener(this);
          * Displays a new <CODE>JWindow</CODE> as a splash screen using the
          * specified component as the content.  The default size of the
          * component will be used to size the splash screen.  See the
          * <CODE>showSplash(Component, int, int)</CODE> method description for
          * more details. 
          * @param  c  the splash screen contents
          * @return  the window object
          * @see  #showSplash(Component, int, int)
          * @see  #hideSplash()
         public JWindow showSplash(Component c) {
              return showSplash(c, -1, -1);
          * Displays a new <CODE>JWindow</CODE> as a splash screen using the
          * specified component as the content.  The component should have all
          * the content it needs to display, like borders, images, text, etc. 
          * The splash screen is centered on monitor.  If width and height are
          * <CODE><= 0</CODE>, the default size of the component will be used
          * to size the splash screen. 
          * <P>
          * The window object is returned to allow the application to manipulate
          * it, (such as move it or resize it, etc.).  However, <B>do not</B>
          * dispose the window directly.  Instead, use <CODE>hideSplash()</CODE>
          * to allow internal cleanup. 
          * <P>
          * If the component is <CODE>null</CODE>, a default component with the
          * frame title and icon will be created. 
          * <P>
          * The splash screen window will be passed the same
          * <CODE>GraphicsConfiguration</CODE> as this frame uses. 
          * @param  c  the splash screen contents
          * @param  w  the splash screen width
          * @param  h  the splash screen height
          * @return  the window object
          * @see  #showSplash(Component)
          * @see  #hideSplash()
         public JWindow showSplash(Component c, int w, int h) {
              // if a splash window was already created...
              if(splash != null) {
                   // if it's showing, leave it; else null it
                   if(splash.isShowing()) {
                        return splash;
                   } else {
                        splash = null;
              // if the component is null, then create a generic splash screen
              // based on the frame title and icon
              if(c == null) {
                   JPanel p = new JPanel();
                   p.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createRaisedBevelBorder(),
                        BorderFactory.createEmptyBorder(10, 10, 10, 10)
                   JLabel l = new JLabel("Loading application...");
                   if(getTitle() != null) {
                        l.setText("Loading " + getTitle() + "...");
                   if(getIconImage() != null) {
                        l.setIcon(new ImageIcon(getIconImage()));
                   p.add(l);
                   c = p;
              splash = new JWindow(this, getGraphicsConfiguration());
              splash.getContentPane().add(c);
              splash.pack();
              // set the splash screen size
              if(w > 0 && h > 0) {
                   splash.setSize(w, h);
              } else {
                   splash.setSize(c.getPreferredSize().width, c.getPreferredSize().height);
              centerComponent(splash);
              splash.show();
              return splash;
          * Disposes the splash window. 
          * @see  #showSplash(Component, int, int)
          * @see  #showSplash(Component)
         public void hideSplash() {
              if(splash != null) {
                   splash.dispose();
                   splash = null;
          * Runs an initializer <CODE>Runnable</CODE> object in a new thread. 
          * The initializer object should handle application initialization
          * steps.  A typical use would be:
          * <OL>
          *   <LI>Create the frame.
          *   <LI>Create the splash screen component.
          *   <LI>Call <CODE>showSplash()</CODE> to display splash screen.
          *   <LI>Run the initializer, in which: 
          *   <UL>
          *     <LI>Build the UI contents of the frame.
          *     <LI>Perform other initialization (load settings, data, etc.).
          *     <LI>Pack and show the frame.
          *     <LI>Call <CODE>hideSplash()</CODE>.
          *   </UL>
          * </OL>
          * <P>
          * <B>NOTE:</B>  Since this will be done in a new thread that is
          * external to the event thread, any updates to the splash screen that
          * might be done should be triggered through with
          * <CODE>SwingUtilities.invokeAndWait(Runnable)</CODE>. 
          * @param  r  the <CODE>Runnable</CODE> initializer
         public void runInitializer(Runnable r) {
              Thread t = new Thread(r);
              t.start();
          * Shows the frame centered on the screen. 
         public void showCentered() {
              centerComponent(this);
              this.show();
          * Checks the busy state.
          * @return  <CODE>true</CODE> if the frame is disabled;
          *          <CODE>false</CODE> if the frame is enabled
          * @see  #setBusy(boolean)
         public boolean isBusy() {
              return this.busy;
          * Sets the busy state.  When busy, the glasspane is shown which will
          * consume all mouse and keyboard events, and a wait cursor is
          * set for the frame. 
          * @param  busy  if <CODE>true</CODE>, disables frame;
          *               if <CODE>false</CODE>, enables frame
          * @see  #getBusy()
         public void setBusy(boolean busy) {
              // only set if changing
              if(this.busy != busy) {
                   this.busy = busy;
                   // If busy, keep current glass pane to put back when not
                   // busy.  This is done in case the application is using
                   // it's own glass pane for something special. 
                   if(busy) {
                        defaultGlassPane = getGlassPane();
                        setGlassPane(glassPane);
                   } else {
                        setGlassPane(defaultGlassPane);
                        defaultGlassPane = null;
                   glassPane.setVisible(busy);
                   glassPane.setCursor(busy ?
                        Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR) :
                        Cursor.getDefaultCursor()
                   setCursor(glassPane.getCursor());
          * Handle key typed events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  ke  the key event
         public void keyTyped(KeyEvent ke) {
              ke.consume();
          * Handle key released events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  ke  the key event
         public void keyReleased(KeyEvent ke) {
              ke.consume();
          * Handle key pressed events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  ke  the key event
         public void keyPressed(KeyEvent ke) {
              ke.consume();
          * Handle mouse clicked events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  me  the mouse event
         public void mouseClicked(MouseEvent me) {
              me.consume();
          * Handle mouse entered events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  me  the mouse event
         public void mouseEntered(MouseEvent me) {
              me.consume();
          * Handle mouse exited events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  me  the mouse event
         public void mouseExited(MouseEvent me) {
              me.consume();
          * Handle mouse pressed events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  me  the mouse event
         public void mousePressed(MouseEvent me) {
              me.consume();
          * Handle mouse released events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  me  the mouse event
         public void mouseReleased(MouseEvent me) {
              me.consume();
          * Centers the component <CODE>c</CODE> on the screen. 
          * @param  c  the component to center
          * @see  #centerComponent(Component, Component)
         public static void centerComponent(Component c) {
              centerComponent(c, null);
          * Centers the component <CODE>c</CODE> on component <CODE>p</CODE>. 
          * If <CODE>p</CODE> is null, the component <CODE>c</CODE> will be
          * centered on the screen. 
          * @param  c  the component to center
          * @param  p  the parent component to center on or null for screen
          * @see  #centerComponent(Component)
         public static void centerComponent(Component c, Component p) {
              if(c != null) {
                   Dimension d = (p != null ? p.getSize() :
                        Toolkit.getDefaultToolkit().getScreenSize()
                   c.setLocation(
                        Math.max(0, (d.getSize().width/2)  - (c.getSize().width/2)),
                        Math.max(0, (d.getSize().height/2) - (c.getSize().height/2))
          * Main method.  Used for testing.
          * @param  args  the arguments
         public static void main(String[] args) {
              final AppFrame f = new AppFrame("Test Application",
                   new ImageIcon("center.gif"));
              f.showSplash(null);
              f.runInitializer(new Runnable() {
                   public void run() {
                        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        f.getContentPane().add(new JButton("this is a frame"));
                        f.pack();
                        f.setSize(300, 400);
                        try {
                             Thread.currentThread().sleep(3000);
                        } catch(Exception e) {}
                        f.showCentered();
                        f.setBusy(true);
                        try {
                             Thread.currentThread().sleep(100);
                        } catch(Exception e) {}
                        f.hideSplash();
                        try {
                             Thread.currentThread().sleep(3000);
                        } catch(Exception e) {}
                        f.setBusy(false);
    "Useful Code of the Day" is supplied by the person who posted this message. This code is not guaranteed by any warranty whatsoever. The code is free to use and modify as you see fit. The code was tested and worked for the author. If anyone else has some useful code, feel free to post it under this heading.

    Hi
    Thanks fo this piece of code. This one really help me
    Deepa

  • Useful Code of the Day:  Hideable Tree Nodes

    Someone posted about how they could selectively hide tree nodes, and I already had this AbstractTreeModel class (which does some things DefaultTreeModel does and some it doesn't) and a concrete subclass for TreeNode objects, so I was thinking how one could do hideable nodes. So I came up with this solution.
    There's 4 classes here:
    - AbstractTreeModel is the base for the concrete TreeNodeTreeModel
    - TreeNodeTreeModel extends AbstractTreeModel to support TreeNodes (DefautlMutableTreeNode, etc.)
    - HideableMutableTreeNode which is a DefautlMutableTreeNode subclass which has a visible field (with is/set methods, of course).
    - HideableTreeModel is the hideable model which is a subclass of TreeNodeTreeModel.
    A HideableMutableTreeNode can be set invisible directly, but the tree still needs to be notified to update. So it's best to use the methods in HideableTreeModel which set a node's visibility which notify the tree of changes accordingly. Methods are also provided to check a full path's visibility or ensure a node including all parent nodes are visible.
    A HideableTreeModel can take any TreeNode class, it doesn't have to be all HideableMutableTreeNodes, but only HideableMutableTreeNodes can be made invisible, of course. Any other TreeNode type would just be considered visible.
    Hiding nodes works basically by making the tree think there's less nodes then there are. And to do this, the node counts and child index search just works by looping thru the parent's children. This has potential perfomance drawbacks of course, since one has to loop thru the node's children to get nodes every time. This could be alleviated by not supporting non-hideable nodes changing the internal maintenance of HideableMutableTreeNode contents. But I'll leave that to whoever really needs it. It shouldn't be a problem if there are are a relatively small set of child nodes in any given parent.
    Also, note that the root node in the model cannot be made invisible, cuz it'd be redundant since JTree can be set to hide the root node.
    // *** HideableTreeModel ***
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    * <code>HideableTreeModel</code> is an <code>TreeNodeTreeModel</code>
    * implementation for <code>HideableMutableTreeNode</code> objects.  The
    * model can also take any other <code>javax.swing.tree.TreeNode</code>
    * objects. 
    public class HideableTreeModel extends TreeNodeTreeModel {
          * Creates a new <code>HideableTreeModel</code> object.
          * @param  root  the root node
         public HideableTreeModel(TreeNode root) {
              super(root);
          * Checks if the specified node is visible.  A node can only be
          * hidden if the node is an instance of <code>HideableMutableTreeNode</code>.  <br />
          * <br />
          * Note that this only test the visibility of the specified node, not
          * whether a parent node is visible.  Use <code>isPathToNodeVisible(Object)</code>
          * to check if the full path is visible. 
          * @param  node  the node
          * @param  true if the node is visible, else false
         public boolean isNodeVisible(Object node) {
              if(node != getRoot()) {
                   if(node instanceof HideableMutableTreeNode) {
                        return ((HideableMutableTreeNode)node).isVisible();
              return true;
          * Sets the specified node to be hidden.  A node can only be made hidden
          * if the node is an instance of <code>HideableMutableTreeNode</code>.  <br />
          * <br />
          * Note that this method will notify the tree to reflect any changes to
          * node visibility.  <br />
          * <br />
          * Note that this will not alter the visibility of any nodes in the
          * specified node's path to the root node.  Use
          * <code>ensurePathToNodeVisible(Object)</code> instead to make sure the
          * full path down to that node is visible.  <br />
          * <br />
          * Note that this method will notify the tree to reflect any changes to
          * node visibility. 
          * @param  node  the node
          * @param  v     true for visible, false for hidden
          * @param  true if the node's visibility could actually change, else false
         public boolean setNodeVisible(Object node, boolean v) {
              // can't hide root
              if(node != getRoot()) {
                   if(node instanceof HideableMutableTreeNode) {
                        HideableMutableTreeNode n = (HideableMutableTreeNode)node;
                        // don't fix what ain't broke...
                        if(v != n.isVisible()) {
                             TreeNode parent = n.getParent();
                             if(v) {
                                  // need to get index after showing...
                                  n.setVisible(v);
                                  int index = getIndexOfChild(parent, n);
                                  super.nodeInserted(parent, n, index);
                             } else {
                                  // need to get index before hiding...
                                  int index = getIndexOfChild(parent, n);
                                  n.setVisible(v);
                                  super.nodeRemoved(parent, n, index);
                        return true;
              return false;
          * Checks if the specified node is visible and all nodes above it are
          * visible. 
          * @param  node  the node
          * @param  true if the path is visible, else false
         public boolean isPathToNodeVisible(Object node) {
              Object[] path = getPathToRoot(node);
              for(int i = 0; i < path.length; i++) {
                   if(!isNodeVisible(path)) {
                        return false;
              return true;
         * Sets the specified node and all nodes above it to be visible.
         * Note that this method will notify the tree to reflect any changes to
         * node visibility.
         * @param node the node
         public void ensurePathToNodeVisible(Object node) {
              Object[] path = getPathToRoot(node);
              for(int i = 0; i < path.length; i++) {
                   setNodeVisible(path[i], true);
         * Returns the child of parent at index index in the parent's child array.
         * @param parent the parent node
         * @param index the index
         * @return the child or null if no children
         public Object getChild(Object parent, int index) {
              if(parent instanceof TreeNode) {
                   TreeNode p = (TreeNode)parent;
                   for(int i = 0, j = -1; i < p.getChildCount(); i++) {
                        TreeNode pc = (TreeNode)p.getChildAt(i);
                        if(isNodeVisible(pc)) {
                             j++;
                        if(j == index) {
                             return pc;
              return null;
         * Returns the number of children of parent.
         * @param parent the parent node
         * @return the child count
         public int getChildCount(Object parent) {
              int count = 0;
              if(parent instanceof TreeNode) {
                   TreeNode p = (TreeNode)parent;
                   for(int i = 0; i < p.getChildCount(); i++) {
                        TreeNode pc = (TreeNode)p.getChildAt(i);
                        if(isNodeVisible(pc)) {
                             count++;
              return count;
         * Returns the index of child in parent.
         * @param parent the parent node
         * @param child the child node
         * @return the index of the child node in the parent
         public int getIndexOfChild(Object parent, Object child) {
              int index = -1;
              if(parent instanceof TreeNode && child instanceof TreeNode) {
                   TreeNode p = (TreeNode)parent;
                   TreeNode c = (TreeNode)child;
                   if(isNodeVisible(c)) {
                        index = 0;
                        for(int i = 0; i < p.getChildCount(); i++) {
                             TreeNode pc = (TreeNode)p.getChildAt(i);
                             if(pc.equals(c)) {
                                  return index;
                             if(isNodeVisible(pc)) {
                                  index++;
              return index;
         * Main method for testing.
         * @param args the command-line arguments
         public static void main(String[] args) {
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              HideableMutableTreeNode root = new HideableMutableTreeNode("root");
              root.add(new HideableMutableTreeNode("child_1"));
              final HideableMutableTreeNode c2 = new HideableMutableTreeNode("child_2");
              c2.setVisible(false);
              final HideableMutableTreeNode c2a = new HideableMutableTreeNode("child_2_A");
              c2.add(c2a);
              c2.add(new HideableMutableTreeNode("child_2_B"));
              root.add(c2);
              HideableMutableTreeNode c3 = new HideableMutableTreeNode("child_3");
              HideableMutableTreeNode cC = new HideableMutableTreeNode("child_3_C");
              cC.setVisible(false);
              c3.add(cC);
              c3.add(new HideableMutableTreeNode("child_3_D"));
              root.add(c3);
              root.add(new HideableMutableTreeNode("child_4"));
              root.add(new HideableMutableTreeNode("child_5"));
              DefaultMutableTreeNode c6 = new DefaultMutableTreeNode("child_6");
              c6.add(new DefaultMutableTreeNode("child_6_A"));
              c6.add(new DefaultMutableTreeNode("child_6_B"));
              root.add(c6);
              final HideableTreeModel model = new HideableTreeModel(root);
              JTree tree = new JTree(model);
              f.getContentPane().add(new JScrollPane(tree), BorderLayout.CENTER);
              JButton b = new JButton("toggle");
              b.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        model.setNodeVisible(c2, !model.isNodeVisible(c2));
                        //model.ensurePathToNodeVisible(c2a);
              f.getContentPane().add(b, BorderLayout.SOUTH);
              f.pack();
              f.setSize(300, 500);
              f.show();
    // *** HideableMutableTreeNode ***
    import javax.swing.*;
    import javax.swing.tree.*;
    * <code>HideableMutableTreeNode</code> is a <code>DefaultMutableTreeNode</code>
    * implementation that works with <code>HideableTreeModel</code>.
    public class HideableMutableTreeNode extends DefaultMutableTreeNode {
         * The node is visible flag.
         public boolean visible = true;
         * Creates a tree node that has no parent and no children, but which
         * allows children.
         public HideableMutableTreeNode() {
              super();
         * Creates a tree node with no parent, no children, but which allows
         * children, and initializes it with the specified user object.
         * @param userObject - an Object provided by the user that
         * constitutes the node's data
         public HideableMutableTreeNode(Object userObject) {
              super(userObject);
         * Creates a tree node with no parent, no children, initialized with the
         * specified user object, and that allows children only if specified.
         * @param userObject - an Object provided by the user that
         * constitutes the node's data
         * @param allowsChildren - if true, the node is allowed to have child
         * nodes -- otherwise, it is always a leaf node
         public HideableMutableTreeNode(Object userObject, boolean allowsChildren) {
              super(userObject, allowsChildren);
         * Checks if the node is visible.
         * @return true if the node is visible, else false
         public boolean isVisible() {
              return this.visible;
         * Sets if the node is visible.
         * @param v true if the node is visible, else false
         public void setVisible(boolean v) {
              this.visible = v;
    // *** TreeNodeTreeModel ***
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    * <code>TreeNodeTreeModel</code> is an <code>AbstractTreeModel</code>
    * implementation for <code>javax.swing.tree.TreeNode</code> objects.
    public class TreeNodeTreeModel extends AbstractTreeModel {
         * Creates a new <code>TreeNodeTreeModel</code> object.
         * @param root the root node
         public TreeNodeTreeModel(TreeNode root) {
              super();
              setRoot(root);
         * Returns the parent of the child node.
         * @param node the child node
         * @return the parent or null if root
         public Object getParent(Object node) {
              if(node != getRoot() && (node instanceof TreeNode)) {
                   return ((TreeNode)node).getParent();
              return null;
         * Returns the child of parent at index index in the parent's child array.
         * @param parent the parent node
         * @param index the index
         * @return the child or null if no children
         public Object getChild(Object parent, int index) {
              if(parent instanceof TreeNode) {
                   return ((TreeNode)parent).getChildAt(index);
              return null;
         * Returns the number of children of parent.
         * @param parent the parent node
         * @return the child count
         public int getChildCount(Object parent) {
              if(parent instanceof TreeNode) {
                   return ((TreeNode)parent).getChildCount();
              return 0;
         * Returns the index of child in parent.
         * @param parent the parent node
         * @param child the child node
         * @return the index of the child node in the parent
         public int getIndexOfChild(Object parent, Object child) {
              if(parent instanceof TreeNode && child instanceof TreeNode) {
                   return ((TreeNode)parent).getIndex((TreeNode)child);
              return -1;
         * Returns true if node is a leaf.
         * @param node the node
         * @return true if the node is a leaf
         public boolean isLeaf(Object node) {
              if(node instanceof TreeNode) {
                   return ((TreeNode)node).isLeaf();
              return true;
         * Main method for testing.
         * @param args the command-line arguments
         public static void main(String[] args) {
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
              root.add(new DefaultMutableTreeNode("child_1"));
              DefaultMutableTreeNode c2 = new DefaultMutableTreeNode("child_2");
              c2.add(new DefaultMutableTreeNode("child_2_A"));
              c2.add(new DefaultMutableTreeNode("child_2_B"));
              root.add(c2);
              root.add(new DefaultMutableTreeNode("child_3"));
              root.add(new DefaultMutableTreeNode("child_4"));
              JTree tree = new JTree(new TreeNodeTreeModel(root));
              f.getContentPane().add(new JScrollPane(tree));
              f.pack();
              f.setSize(300, 500);
              f.show();
    // *** AbstractTreeModel ***
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    public abstract class AbstractTreeModel implements TreeModel {
         * The list of tree model listeners.
         private Vector modelListeners = new Vector();
         * The root object of the tree.
         private Object root = null;
         * Basic no-op constructor.
         public AbstractTreeModel() {
         * Gets the root object of the tree.
         * @return the root object
         public Object getRoot() {
              return this.root;
         * Sets the root object of the tree.
         * @param r the root object
         protected void setRoot(Object r) {
              this.root = r;
         * Gets the path to the root node for the specified object.
         * @param node the root node
         * @return the path to the object or <CODE>null</CODE>
         public Object[] getPathToRoot(Object node) {
              return getPathToRoot(node, 0);
         * Gets the path to the root node for the specified object.
         * @param node the root node
         * @param i the current index
         * @return the path to the object or <CODE>null</CODE>
         private Object[] getPathToRoot(Object node, int i) {
              Object anode[];
              if(node == null) {
                   if(i == 0) {
                        return null;
                   anode = new Object[i];
              } else {
                   i++;
                   if(node == getRoot()) {
                        anode = new Object[i];
                   } else {
                        anode = getPathToRoot(getParent(node), i);
                   anode[anode.length - i] = node;
              return anode;
         * Gets the parent object of the specified object. This method is not
         * part of the <code>javax.swing.tree.TreeModel</code> interface, but is
         * required to support the <code>getPathToRoot(Object)</code> method,
         * which is widely used in this class. Therefore, it is important to
         * correctly implement this method.
         * @param obj the object
         * @parma the parent object or null if no parent or invalid object
         protected abstract Object getParent(Object obj);
         * Adds a listener for the <CODE>TreeModelEvent</CODE> posted after the
         * tree changes.
         * @param l the tree model listener
         public void addTreeModelListener(TreeModelListener l) {
              modelListeners.addElement(l);
         * Removes a listener previously added with addTreeModelListener().
         * @param l the tree model listener
         public void removeTreeModelListener(TreeModelListener l) {
              modelListeners.removeElement(l);
         * Forces the tree to reload. This is useful when many changes occur
         * under the root node in the tree structure.
         * <b>NOTE:</b> This will cause the tree to be collapsed. To maintain
         * the expanded nodes, see the <code>getExpandedPaths(JTree)</code>
         * and <code>expandPaths(JTree, ArrayList)</code> methods.
         * @see #getExpandedPaths(JTree)
         * @see #expandPaths(JTree, ArrayList)
         public void reload() {
              reload(getRoot());
         * Forces the tree to repaint. This is useful when many changes occur
         * under a specific node in the tree structure.
         * <b>NOTE:</b> This will cause the tree to be collapsed below the
         * updated node.
         * @param node the node that changed
         public void reload(Object node) {
              if(node != null) {
                   TreePath tp = new TreePath(getPathToRoot(node));
                   fireTreeStructureChanged(new TreeModelEvent(this, tp));
         * Messaged when the user has altered the value for the item identified
         * by <CODE>path</CODE> to <CODE>newValue</CODE>.
         * @param path the path to the changed object
         * @param newValue the new value
         public void valueForPathChanged(TreePath path, Object newValue) {
              nodeChanged(path.getLastPathComponent());
         * Notifies the tree that nodes were inserted. The index is looked up
         * automatically.
         * @param node the parent node
         * @param child the inserted child node
         public void nodeInserted(Object node, Object child) {
              nodeInserted(node, child, -1);
         * Notifies the tree that nodes were inserted.
         * @param node the parent node
         * @param child the inserted child node
         * @param index the index of the child
         public void nodeInserted(Object node, Object child, int index) {
              if(index < 0) {
                   index = getIndexOfChild(node, child);
              if(node != null && child != null && index >= 0) {
                   TreePath tp = new TreePath(getPathToRoot(node));
                   int[] ai = { index };
                   Object[] ac = { child };
                   fireTreeNodesInserted(new TreeModelEvent(this, tp, ai, ac));
         * Notifies the tree that nodes were removed. The index is required
         * since by this point, the object will no longer be in the tree.
         * @param node the parent node
         * @param child the removed child node
         * @param index the index of the child
         public void nodeRemoved(Object node, Object child, int index) {
              if(node != null && child != null && index >= 0) {
                   TreePath tp = new TreePath(getPathToRoot(node));
                   int[] ai = { index };
                   Object[] ac = { child };
                   fireTreeNodesRemoved(new TreeModelEvent(this, tp, ai, ac));
         * Notifies the tree that a node was changed.
         * @param node the changed node
         public void nodeChanged(Object node) {
              if(node != null) {
                   TreePath tp = new TreePath(getPathToRoot(node));
                   fireTreeNodesChanged(new TreeModelEvent(this, tp, null, null));
         * Fires "tree nodes changed" events to all listeners.
         * @param event the tree model event
         protected void fireTreeNodesChanged(TreeModelEvent event) {
              for(int i = 0; i < modelListeners.size(); i++) {
                   ((TreeModelListener)modelListeners.elementAt(i)).treeNodesChanged(event);
         * Fires "tree nodes inserted" events to all listeners.
         * @param event the tree model event
         protected void fireTreeNodesInserted(TreeModelEvent event) {
              for(int i = 0; i < modelListeners.size(); i++) {
                   ((TreeModelListener)modelListeners.elementAt(i)).treeNodesInserted(event);
         * Fires "tree nodes removed" events to all listeners.
         * @param event the tree model event
         protected void fireTreeNodesRemoved(TreeModelEvent event) {
              for(int i = 0; i < modelListeners.size(); i++) {
                   ((TreeModelListener)modelListeners.elementAt(i)).treeNodesRemoved(event);
         * Fires "tree structure changed" events to all listeners.
         * @param event the tree model event
         protected void fireTreeStructureChanged(TreeModelEvent event) {
              for(int i = 0; i < modelListeners.size(); i++) {
                   ((TreeModelListener)modelListeners.elementAt(i)).treeStructureChanged(event);
         * Records the list of currently expanded paths in the specified tree.
         * This method is meant to be called before calling the
         * <code>reload()</code> methods to allow the tree to store the paths.
         * @param tree the tree
         * @param pathlist the list of expanded paths
         public ArrayList getExpandedPaths(JTree tree) {
              ArrayList expandedPaths = new ArrayList();
              addExpandedPaths(tree, tree.getPathForRow(0), expandedPaths);
              return expandedPaths;
         * Adds the expanded descendants of the specifed path in the specified
         * tree to the internal expanded list.
         * @param tree the tree
         * @param path the path
         * @param pathlist the list of expanded paths
         private void addExpandedPaths(JTree tree, TreePath path, ArrayList pathlist) {
              Enumeration enum = tree.getExpandedDescendants(path);
              while(enum.hasMoreElements()) {
                   TreePath tp = (TreePath)enum.nextElement();
                   pathlist.add(tp);
                   addExpandedPaths(tree, tp, pathlist);
         * Re-expands the expanded paths in the specified tree. This method is
         * meant to be called before calling the <code>reload()</code> methods
         * to allow the tree to store the paths.
         * @param tree the tree
         * @param pathlist the list of expanded paths
         public void expandPaths(JTree tree, ArrayList pathlist) {
              for(int i = 0; i < pathlist.size(); i++) {
                   tree.expandPath((TreePath)pathlist.get(i));

    Hey
    I'm not trying to show anyone up here, but having just built a tree model for displaying an XML document in a tree, I thought this seemed like a neat exercise.
    I implemented this very differently from the @OP. I only have one class, HiddenNodeTreeModel. All the hidden node data is stored in the model itself in my class. The advantage of what I've created is it will work with any TreeModel. The disadvantage is that I think it's not going to be very scalable - the additional computing to get the number of child nodes and to adjust indexes is heavy. So if you need a scalable solution definitely don't use this.
    Anyway here you go
    HiddenNodeTreeModel.java
    ======================
    package tjacobs.ui.tree;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Iterator;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JTree;
    import javax.swing.event.TreeModelListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    import tjacobs.ui.WindowUtilities;
    public class HiddenNodeTreeModel implements TreeModel {
         TreeModel mModel;
         ArrayList<Object> mHidden = new ArrayList<Object>();
         public HiddenNodeTreeModel (TreeModel model) {
              mModel = model;
         public void addTreeModelListener(TreeModelListener arg0) {
              mModel.addTreeModelListener(arg0);
         private ArrayList<Integer> getHiddenChildren(Object parent) {
              ArrayList<Integer> spots = new ArrayList<Integer>();
              Iterator _i = mHidden.iterator();
              while (_i.hasNext()) {
                   Object hidden = _i.next();
                   int idx = mModel.getIndexOfChild(parent, hidden);
                   if (idx != -1) {
                        spots.add(idx);
              return spots;
         public Object getChild(Object arg0, int index) {
              ArrayList<Integer> spots = getHiddenChildren(arg0);
              Collections.sort(spots);
              Iterator<Integer> _i = spots.iterator();
              while (_i.hasNext()) {
                   int num = _i.next();
                   if (num <= index) {
                        index++;
              return mModel.getChild(arg0, index);
         public int getChildCount(Object arg0) {
              ArrayList list = getHiddenChildren(arg0);
              System.out.println("size = " + list.size());
              return mModel.getChildCount(arg0) - list.size();
         public int getIndexOfChild(Object arg0, Object arg1) {
              int index = mModel.getIndexOfChild(arg0, arg1);
              ArrayList<Integer> spots = getHiddenChildren(arg0);
              Collections.sort(spots);
              Iterator<Integer> _i = spots.iterator();
              int toSub = 0;
              while (_i.hasNext()) {
                   int num = _i.next();
                   if (num <= index) {
                        toSub++;
              return index - toSub;
         public Object getRoot() {
              // TODO Auto-generated method stub
              return mModel.getRoot();
         public boolean isLeaf(Object arg0) {
              // TODO Auto-generated method stub
              return mModel.isLeaf(arg0);
         public void removeTreeModelListener(TreeModelListener arg0) {
              mModel.removeTreeModelListener(arg0);
         public void valueForPathChanged(TreePath arg0, Object arg1) {
              mModel.valueForPathChanged(arg0, arg1);
         public void hideNode(Object node) {
              if (node instanceof TreePath) {
                   node = ((TreePath)node).getLastPathComponent();
              mHidden.add(node);
         public void showNode(Object node) {
              mHidden.remove(node);
         public void showAll() {
              mHidden.clear();
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              DefaultMutableTreeNode A = new DefaultMutableTreeNode("A");
              DefaultMutableTreeNode B = new DefaultMutableTreeNode("B");
              DefaultMutableTreeNode C = new DefaultMutableTreeNode("C");
              DefaultMutableTreeNode D = new DefaultMutableTreeNode("D");
              DefaultMutableTreeNode E = new DefaultMutableTreeNode("E");
              DefaultMutableTreeNode F = new DefaultMutableTreeNode("F");
              A.add(B);
              B.add(C);
              B.add(D);
              B.add(E);
              E.add(F);
              DefaultTreeModel model = new DefaultTreeModel(A);
              final HiddenNodeTreeModel hmodel = new HiddenNodeTreeModel(model);
              final JTree tree = new JTree(hmodel);
              JFrame jf = new JFrame("HiddenNodeTreeModel Test");
              jf.add(tree);
              JMenuBar bar = new JMenuBar();
              jf.setJMenuBar(bar);
              JMenu menu = new JMenu("Options");
              bar.add(menu);
              final JMenuItem hide = new JMenuItem("Hide");
              final JMenuItem show = new JMenuItem("ShowAll");
              menu.add(hide);
              menu.add(show);
              ActionListener al = new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        if (ae.getSource() == hide) {
                             hmodel.hideNode(tree.getSelectionPath());
                             tree.updateUI();
                        else {
                             hmodel.showAll();
                             tree.updateUI();
              hide.addActionListener(al);
              show.addActionListener(al);
              jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              jf.setBounds(100,100,100,100);
              jf.setVisible(true);
    }

  • How do you create a login page using dashcode for the iPhone's mobile safari that will transfer you to the next page?

         Hey I have created a login page in Dashcode for a mobile safari app (aka iphone web app) and I am having trouble since I can not find any useful info about multiple pages. I don't want to use a stack layout view because it is only a login page and I need to check with a database to make sure the user's login info is correct. Right now I have it set up so that it loads another iphone web app project once it validates the info.
         The only problem with this is I am having a good bit of trouble trying to pass values from my php code to javascript or html. For some reason calling the javascript inside the php code makes the actual code inside the app not be called and same with the echo statment for the html.
    So I would like to be able to create the app in this way:
    Login page > PHP > MS SQL > PHP > UNKNOWN (if I can't get the javascript or html to output both) > Secure info on the next page
         I believe It would be a lot easier if I had the option for a multiple page but instead I am having to load up an entirely new dashcode project. If anyone knows a better way please let me know. Or if anyone knows a link to good information on passing values from php to javascript, because I couldn't get any of the code I tried to work, I would really appreciate it.

    Addendum to previous reply:
    OK.  This is weird--but I should be used to that, and just grateful that it seems to work (for now).
    What I had done is FTPd some image files to my site using Filezilla, but when I had tried to access them, I was unsuccessful.  I am almost sure that I used the same url (and variations of it) as you suggested, namely,  http://mysite.verizon.net/username/filename , and it either did not work, or gave me the "Page under construction", or, in some cases asked me for my username and password.
    But, when I did it this time, it worked.  So I probably had something off, but I can now do what I want.
    By the way, if you'll permit another question, while on the site-builder site, it said that there was a "Web Photo Manager", and said that "To download the Web Photo Manager: Open the Site Builder application and go to the All My Sites page. Click on the Web Photo Manager link (listed under Advanced Building Tools )."  I can't find it--would you happen to know where it is?
    In any case, thanks a lot for all your help--it solved my problem. 

  • How to include Forward button dynamically using code?

    hello,
    i am creating my notification message dynamically using clob type document type attribute , and its working fine. But how i include the Forword Button in my message body.
    please advice

    i am allready doing that only, in that what will be the name of the button.
    can i put like this.
    htp.p( '<input type="button" name="forward">');
    then what about the event, shall i have to write the code for forward also.
    please advice.

  • How to create ADF selectManyChoice dynamically using arrayList?

    Hi,
    I am using JDEVADF_11.1.1.3.PS2_GENERIC_100408.2356.5660. I want to dynamically create selectManyChoice through my backing using and populating the same using ArrayList. Can anyone provide me sample code for the same?
    Thanks,
    Vikas

    Duplicate

  • Plese Help...i have to create a table dynamically using JSP

    Hi all,
    Depending upon what user fills as year & month I have to create a table dynamically.The table should look like this...
    DAY     S     M     T     W
    DATE     1     2     3     4
    Name1     -     -     -     -
    Name2     -     -     -     -
    I know how to get total no available days of any month so i'll use for loop to create <tr>
    The info i need is-
    How to get the first day of the month ,the user entered using calendar because the first row should start with it.
    and the second thing is...
    How to keep incrementing it in the loop..like after sun-->mon-->tue....sat-->sun....
    & also..sat & sun cols should be of different colors than other weekdays
    Please help me.

    Sounds like you already knows about the Calendar class. You should use that class to get the first day of the month.
    Kaj

  • Want to create a new dynamic DL based on the country location of the 365 license..

    We're presently in hybrid mode, but we'll soon be moving entirely to 365.  In preparation i'd like to start creating new dynamic distribution groups.  We have offices in Korea, China, EU, and the US.  My idea is to create the dynamic DL's
    based on the country where the license was applied.  In the example below, the users license was assigned in Korea.  So ideally my new dynamic DL would filter on that property (i.e. anyone's mailbox where the users license was assigned to Korea)
    to create an "All Korea" distribution group.
    Does anyone know what the powershell syntax might be? Any help is greatly appreciated!

    Interesting.  The command ran without error, but then when i checked the group through the portal it didn't display the recipient filter.  Seemed like it just created a generic dynamic DL and it was prompting me for things like mailbox type.

  • Recording a stream and using it on the fly

    Hi,
    I'm trying to upload a video stream from a flash client and
    convert the video stream on the fly (from an external converter
    like ffmpeg or vlc).
    Since I don't manage to send the stream directly to the
    converter, a solution I have found is to publish the sream as
    "record", and have a converter read the file to perform the
    operation.
    However, when setting the record method for publishing, the
    recorded file is not written continuously. Incoming stream is
    buffered, written, buffered, written and so on. So, the program
    reading the file stops it reaches the end.
    Is there a way in FMS2 to either:
    - forward incoming RTMP stream to a stream converter (using
    an outgoing RTSP stream or something like that) ?
    - force FMS2 to dump the stream continuously, as soon as it
    receives the incoming data ?
    Thanks for any help,
    Greg

    Stream.syncWrite
    Availability Flash Media Server 2.
    Usage myStream.syncWrite
    Description
    Property; a Boolean value that controls when a stream writes
    the contents of the buffer to a
    FLV file when the stream is recording. When syncWrite is
    true, all the messages that pass
    through the stream are flushed to the FLV file immediately.
    It is highly recommended that
    user should only set syncWrite to true in a stream that
    contains only data. Synchronization
    problems might occur when syncWrite is set to true in a
    stream that contains data and
    audio, video, or both.
    ... sounds like a problem is occuring :)

  • Possible to create java code on the fly?

    I'm just curious.
    I am in the process of making a bunch of custom Lightweight components which will be a part of a physics tutorial package. (Stuff like arrows, charges, fields, cars, rocks, etc.). I have some specific tutorial applets I am creating for a prof at my local u using these components.
    In the middle of this, I thought...
    Wouldn't it be GREAT if I could make an extremely simple "editor" which my prof could use directly to create his own applets? (I can certainly do the drag and drop, menus and stuff that would go along with this)
    Is it possible to write a program in Java which writes and compiles Java, without too much fuss?
    Another words, it would be wonderful if my prof could:
    Click on the Charge Object
    Drag it to the Physics Container
    Click on the Physics Container
    Turn on the Electric Field by changing the Container's properties
    Then hit Some Menu->Compile Applet
    and boom!! he'd have his applet exactly the way he wants it. (and the program would create the code for him to put on his website).
    Is it possible?
    :) Jen
    (P.S. please remember that my prof can't do Java, so even Java Beans in an IDE are out).

    Sure it's possible, but there are three things you need to consider here.
    1. Your IDE would support drag-and-drop as per your requirements. You'd have to learn that incase you haven't already done so.
    2. There's no point in writing your own Java compiler. You could after pouring through the specifications, but it's better just to generate the source file and compile it by running javac through your application.
    3. The source code generation. Depending on which part of your final applet code is fixed and which is variable this could be lot of work (the trickiest part being to decide what is fixed and what is variable.. in other words, the design).
    It sounds like fun alright, but you would get the same results by just putting all these features in the applet itself. Have the applet allow the user to choose amongst a host of features (the ones that you plan to put into your editor). I guess you'll have to make your final decision based on how much time you have.
    Have fun and best of luck.
    Arjun

  • Need example to create File names dynamically using File adapter

    hello,
    I am mapping an IDOC to a flat file using XI and a file adapter. I need to be able to output a file name dynamically depending on the data in the IDOC.  For example if the IDOC has 310 as the company code, the file name should be xyz.310 and if the IDOC has 600 as the company code, the file name created by the file adapter should be xyz.600.  Please some body provide me with an example of the XSLT code that I will have to write in the dispatcher User Exit.
    Any help will be greatly appreciated.

    Nope
    But you could add a dummy row to your source to include column headers and then use options column headers in first row in flat file connection manager.
    So suppose you've three columns column0,coulmn1,column2 and you want to make it as ID,Name,Datethen make source query as
    SELECT 'ID' AS Col1,'Name' AS Col2,'Date' AS Col3, 0 AS ord
    UNION ALL
    SELECT Column1,Column2,Column3,1
    FROM YourTable
    ORDER BY Ord
    then choose  column headers in first row option
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Create Crystal Report Dynamically using XML based design metadata

    Hi,
    I have a CR Report Development environment. Please refer to workflow and requirement description below;
    I have a Java application(Report Customization Tool), which allows users to dynamically select structure and content for a report.
    The process goes as follows:
    1. In Java Application, user first gets option to select Report Header, Page Orientation, Font etc for master report.
    2. User can select a sub-report (pre-developed report frames. Not Sure about tool.) and apply the same format option (mentioned in step 1, except orientation) to it.
    3. User can select individual row/data cell to be displayed on the report through reference to DB tables in sub-reports.
    4. There can be N number of sub-reports each with independant formatting, data and data layout that could be integrated in single report.
    5 Once all selection is done, Java code generates an XML with all this info.
    Now, my requirement is dynamically write CR report based on this XML. I am not using BO enterprise, hence RAS SDK is out of scope. This report will be called thorough stand-alone .NET application in CITRIX environment.
    Can we do it in CR XI/CR 2008?
    Please feel free to comment in case you need more info. But I won't be able to post screenshots. NDA of course!
    Thanks in advance.

    I moved your post to the NET - SAP Crystal Reports forum.
    To start, you have a fair bit of work ahead of you. The Crystal reports SDK will not do the job. You will have to use the InProc RAS SDK which is included in both CR XI and CR 2008. I'd recommend going with CR 2008 as CR XI R1 (11.0) is out of support now and CR XI R2 (11.5) will be out of support come June of 2011. Next, make sure you have applied SP 3 for CR 2008:
    https://smpdl.sap-ag.de/~sapidp/012002523100007123572010E/cr2008_sp3.exe
    As an FYI, all files can be found on the downloads page:
    http://service.sap.com/sap/bc/bsp/spn/bobj_download/main.htm
    Next, you want to read up on RAS. I suggest the following:
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/10b840c0-623f-2b10-03b5-9d1913866b32
    https://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/b050afe0-2fa5-2b10-658d-98f214ba6a4a
    http://help.sap.com/businessobject/product_guides/boexir31/en/rassdk_net_dg_12_en.chm
    Samples are here:
    https://wiki.sdn.sap.com/wiki/display/BOBJ/NETRASSDK+Samples
    and here:
    http://www.sdn.sap.com/irj/boc/samples?rid=/webcontent/uuid/80774579-b086-2b10-db91-ed58c4dda375 [original link is broken]
    I also find this 3rd party link useful:
    http://book.soundonair.ru/sams/
    And as always, search these forums. Lots of info here. E.g.;
    Programaticaly add Table in CR database fields
    InProc RAS Issue
    Adding the columns dynamically in crystal report
    Also, see the search box at the top right of this page. It searches blogs, wikis, Kbases, articles and more - all in one go.
    Ludek
    Follow us on Twitter http://twitter.com/SAPCRNetSup

Maybe you are looking for

  • Endpoint Protection Antimalware Policy SQL 2008

    We use SCCM 2012 to manage our antimalware solution (SCEP). We created policies for different servers for example SQL server 2008 R2. We created Endpoint Protection Antimalware policy SQL 2008: To prevent performance issues MS reccomends to exclude s

  • Corruption of EOS-1 Ds and 5D RAW

    I know this has been posted before, but I have explored the problem further. On the new Mac Pro machines, with the ATI 2600 video card, you cannot zoom, straighten or use the loupe on EOS 1Ds Mk III images and cannot use the straighten tool on EOS 5D

  • Where do I find my profile ?

    previously if I wanted to see my profile I would go to... http://www.speedtester.bt.com/ that link still runs a speedtest but no longer shows my profile info anyone have the right link ?

  • HELP! noob requires help

    hi , im new to java and im writing a simple program, but the arithmetic is just too confusing! i have to write a program that asks a user for their birth year encoded as two digits (like "62") and for the current year, also encoded as two digits (lik

  • BAPI for Txn FB60

    Hi friends,    I want to upload data to transaction FB60. I have found a BAPI 'BAPI_ACC_DOCUMENT_POST' for the same but I am not sure about it.    Can anybody help me or if anybody has used the BAPI for uploading data to Txn FB60.    Thanks in Advanc