StringBuffer delete (int start, int end) is too slow - HELP!!

I've traced a performance problem to one line of code: a StringBuffer "delete (int start, int end)" call.
My StringBuffer contains a lot of data, maybe 500,000 characters. My code loops, searching for a particular character (the search is fast, btw). When that particular character is found, I want to delete that character plus the characters following it. My code looks something like:
int pos;
while ((pos = myStringBuffer.toString().indexOf('~')) != -1)
     myStringBuffer.delete(pos, pos + 3);I'm 100% sure the bottleneck is the delete call. If I change the code to the following, where I've commented out the delete, it loops the same number of times and runs lightning-fast:
int pos = 0;
while ((pos = myStringBuffer.toString().indexOf('~', pos)) != -1)
     pos++;The loop, and therefore the delete method, will be executed thousands of times. To give you some idea of the poor performance I'm seeing, the first code (with the delete) takes more than 10 minutes to run, while the second code (without the delete) takes less than one-tenth of one second.
Any suggestions? Thank you.

Thanks for all the help! da.futt's solution works perfectly: 65,000 times through the loop in about one-tenth of one second. Problem solved.
We're still on Java 1.3.1 (large company = slow to upgrade), so I can't even remove toString(). I wonder how many "small" performance problems we have (and are unaware of) that could be addressed by upgrading?
My first posting here and a positive result. I'm not a Java expert, but neither am I a rookie. I'll be back to try and help others as I've been helped here.
Thanks again.

Similar Messages

  • Safari too slow - help finding a bug?

    Hi all,
    Sorry for such a noob question, this is a problem I never have myself. My wife's iMac (10.4) is running Safari extremely slow. This occurred when we were out of town and our inlaws were house-sitting.
    My inlaws have been known to (inadvertently) change settings and download things they should not. (Flash players or radio listening programs, etc). I'm betting something similar happened, but couldn't find anything in the surfing history since it was too much to go through. Other ideas?
    Ran Onyx and all that is clean, btw. I've never needed any other anti-malware software myself...
    (As a sidenote, would upgrading to 10.5 make a difference?) I have an unopened copy of Leopard - Server (I don't need the server part) at my disposal. What needs to happen for that?
    Thanks so much,
    -josh

    HI,
    Try uninstalling then reinstalling a new copy of the Adobe Flash Player plugin.
    How to Uninstall Flash plug in
    How to reinstall Flash plug in
    Try Safari maintenance also.
    
From the Safari Menu Bar, click Safari / Empty Cache.
    When you are done with that...

from the Safari Menu Bar, click Safari / Reset Safari. Select the top 5 buttons and click Reset.
    Mac OS: Web Browser Quits Unexpectedly or Stops Responding
    Safari add-ons can cause performance issues or other situations
    

Repair disk permissions:

Quit any open applications/programs. Launch Disk Utility. (Applications/Utilities) Select MacintoshHD in the panel on the left, select the FirstAid tab. Click: Repair Disk Permissions. When it's finished from the Menu Bar, Quit Disk Utility and restart your Mac. If you see a long list of "messages" in the permissions window, it's ok. That can be ignored. As long as you see, "Permissions Repair Complete" when it's finished... you're done. Quit Disk Utility and restart your Mac.
    *As for Leopard... minimum requirements are as follows:*
    an Intel processor or a PowerPC G4 or G5 processor
    a DVD drive
    built-in FireWire
    at least 256 MB of RAM for a PowerPC based Mac, and 512 MB for an Intel-based Mac
    a built-in display or a display connected to an Apple-supplied video card supported by your computer
    at least 6 GB of disk space available, or 8 GB if you install the developer tools
    Upgrading from one Mac OS X to another does not necessarily "fix" bugs. It's better to trouble shoot and make sure the drive is ok before upgarding. You can boot from the install disk that came with the iMac to do that.
    Insert Installer disk and Restart, holding down the "C" key until grey Apple appears.
    Go to Installer menu and launch Disk Utility.
    Select your HDD (manufacturer ID) in the left panel.
    Select First Aid in the Main panel.
    *(Check S.M.A.R.T Status of HDD at the bottom of right panel. It should say: Verified)*
    Click Repair Disk on the bottom right.
    If DU reports disk does not need repairs quit DU and restart.
    If DU reports errors Repair again and again until DU reports disk is repaired.
    When you are finished with DU, from the Menu Bar, select Utilities/Startup Manager.
    Select your start up disk and click Restart
    While you have the Disk Utility window open, look at the bottom of the window. Where you see Capacity and Available. *Make sure there is always 10% to 15% free disk space*
    As for Leopard Server:
    Mac OS X Server is a UNIX server operating system from Apple. The platform is based on the same architecture as Mac OS X, but includes additional services, applications, and administration tools for managing users and services and for deploying servers and clients. The server operating system is included on Xserve, a rack mount server designed by Apple. It is also available preinstalled on the Mac mini and Mac Pro and is sold separately for use on any Macintosh computer meeting its minimum requirements. *Mac OS X Server is commonly found in small business, education, and large enterprise organizations.*
    Carolyn

  • USB of my iMac 3G Too slow HELP!!

    I received and old imac 3g from my brother. Now I'm using it as a "media center" for my apple TVs and Macbook. It was connected to a HD of 500Gb via firewire, but it got full. So I replace it with a HD of 1Tb (Westbook), but via USB. The iMac Reads it but it take like 5 minutes to recognize it, it works well streaming to my Apple TV, but it doesn't work via itunes to my MacBook. Another not: I can't connect any new Ipod to the USB, it says that it needs a faster blablabla...
    Can I change my USB or I'm forced to reback up my library and buy another HD?
    Thanks for any help.

    You need to stick with using Firewire drives. Even on modern iMacs using Firewire is preferable as it out-performs USB2.0 in data transfer rates. 
    mrtotes

  • Difference between IN and OUT and Media Start and Media END??  NEED HELP!!!

    As the titles states, what is the difference?
    I edited my film in preview/jpeg mode and now need to online the project to full quality. So far it hasn't gone to well. For example the media starts at 00:09:45:12. When I do a batch capture I watch the camera fly right by the time code that it should start capturing at. What am I doing wrong???
    Some files onlined easy, but there is a set from one tape that just won't sync up or capture.
    It also keeps telling me that I have time code breaks from time to time, but when I play the tapes back they look fine to me. No obvious breaks in time code from start to end.
    thanks for any help or advice

    Recapturing can be really tricky. Takes practice and it's never recommended that you try it out on a critical piece. Timecode breaks can be perceived by FCP as being caused by several things besides actual breaks in the flow of code. The most common is probably tape dropout.
    The clips that are giving you trouble, try parking the tape very close to one of the start points and recapture only that one clip.
    If your in point is too close to a timecode glitch, you will never be able to recapture it. You'll need to capture it using NOW and then recut the clip into the scene.
    bogiesan

  • Problem with keyframe effect - at start and end (crop and scale)

    I'm having this odd problem with keyframe effects.
    Setup:
    I have a gif image that I have on video 1 for say 2 minutes.
    I have my real video on video 2.  It is a person talking.
    First I start with my video full size on top of video 1.
    Though the motion and cropping keyframe management I slowly reduce the scale and crop my video image so that it is reduced to the lower left bottom of the screen, on top of the gif, which is now revealed.
    My problem is at the start and end of the transition from full video to small box on lower left on top of my gif I often get 1-2 frames where the video goes blank and/or I get a bunch of random red bars on black background appearing on the video - Or I get the gif from video 1 without the video 2 at all (it disappears).
    I've tried moving my start of end of the transition to skip the bad spots - but these new transition starts or ends not get their own bad spots in the same way.  Its only a couple of frames but it's really unacceptable for the finished video.
    Note, when I say transition here I don't mean real transition events, but rather the start of effects that are managed with keyframes.  My move from start to end of the effect runs for about 4-6 seconds.
    Any ideas?

    Bill,
    Here is more detail and screen captures.
    Concept:
    I have 3 minutes of video.  It contains a person making a speech.  During parts of the speech I want to reveal a graphic image that will be discussed.  The speech will begin with the speaker full screen.  Half way in, the speaker will shrink down to 45% in the lower left corner of the screen.  While the animation occurs (the shrink, move and cropping) it will reveal the graphic below.  The graphic will take up the full screen with the speaker at 45%.
    Technique:
    I put the video in Video 2 and the graphic, a GIF image in Video 1.  The scene begins with the speaker talking at full screen.  After a minute, I animate the move of the speaker using Motion: Scale and Position and Effect: Crop changing Top, Bottom, Left and Right sides.  The animation occurs over approximately 8 seconds.
    I am manually adding keyframes at the start and end of the animation.  I set the ending state of the video image in the end keyframes.  The interpolation between these start and end keyframes should be managing the animation.
    Problem:
    At the beginning and end of the animation – usually 1-3 frames from the start and 1-3 frames from the end, where the change has barely begun or almost ended, I get these problems.  On some frames, the video (in Video 2) completely disappears only showing the Video 1 GIF image below.  On other frames, the video image turns black with horizontal red bands half way across.
    Troublshooting:
    I’ve tried deleting all start and end keyframes and moving the start and end earlier or later to see if I can fix this, but the problem continues to show up in these new locations.
    I have added a few screen shots.
    1:32:15 is the start of the animation change and 1:40:22 is the end of increasing from the mini video speaker to full size (on top of the GIF).
    At 1:40:16 the video image completely disappears only showing the GIF below.
    At 1:40:17 its back and slowly increases in size through the interpolation until it is full size at 1:40:22.
    Let me know if you need anything else.
    Thanks!
    Evan

  • Error while updating reimbursements Journey start date / End date missing

    Dear All,
    From ESS employee requested for Reimbursement of LTA from Benifits & Payments - Reimbursements & Claims.
    There is 3 level approval process and got the approval for reimbursement. We maintained Earned leave record for 6 days  in 2001 - Absences infotype.
    But while running the report HRPBSIN_AC_INFU - Advanced Claims: Infotype Update Report system is giving the error Journey Start date / End date is missing.
    help me how can I solve this issue.
    System details: ECC 6.0 - EHP1 and SP 63.
    Portal Details: Netweaver 7.0
    Regards,
    Potru.

    Hi Sangu,
    See if the following notes help you:
    Error when calling API from SQL*Developer, eg. ORA-01403 in API OE_ORDER_PUB.PROCESS_ORDER (Doc ID 1054295.1)
    Cancellation Of Transfer Orders Is Not Possible - ORA-01403: no data found in Package OE_Order_PVT Procedure Process_Order (Doc ID 391307.1)
    Thanks &
    Best Regards,

  • Disk Too Slow??? Why now?

    Hello all,
    I have been using Logic Pro for the last five years on my system with no problems and all of a sudden, now I can't record a single audio track without a "Disk Too Slow" problem. Literally, the project can have only one track and it will still give me an error.
    My System:
    PowerMac Dual G5 2.5GHz w/ 3GB RAM
    Mac OSX 10.4.11
    160 GB Hard Drive (provided by Apple) - 58.9 GB left - Logic installed here
    250 GB Hard Drive - 130 GB left - recording done on here
    M-Audio Project Mix I/O
    For years I have been recording with Logic and I've never had this problem. I haven't done anything new, haven't installed anything new, or anything like that and just now I've been having these problems. I'm a DJ and audio recording constantly for upwards of 90 minutes straight is vital.
    Here's what I've done:
    * Tried changing buffer settings (set from 128 --> 512)
    * Tried making sure no other applications are running
    * Tried emptying trash
    * Tried turning off Airport
    Nothing seems to work. Any ideas?

    Hi there,
    Sorry to read you are having troubles with this.
    I have had the same troubles since Tuesday. All of a sudden I started getting Beach Balls and "Disc too slow". A few occasions I had a message saying that my "midi port was not found" on my MOTU.
    Here what I spent the last couple of days doing.... I am sure you have tried them all but maybe something here may help
    With some kind help from a forum regular, I reset my MOTU interface to factory settings. I repaired my permissions on my system drive.
    I ran a "check disc" for my external audio drive, it past every time, but I repaired it any way.
    I took my drive out of the firewire case to check the connections because it seemed it could be a power issue, tried it in another case. (I put the drive together so I felt comfortable doing this)
    I also removed a plug in that I had added IK CSR reverb, I had installed it the day my system started giving me "disc too slow" messages.
    I also removed all of my TRacks plugins from sessions, they are resource hogs and may have not been helping.
    I also trashed my logic preferences.
    Things at the moment are looking better.
    If my problem still exists it may be in my case the drive being on its way out. It is only a year and a half old, and dose pass disc utility tests every time.
    So I am thinking that I may have been mixing out my machine with plugs then having to do hard re-boots not helping things.
    Sorry to hijack things, just hoping that we can maybe find a common cause, and solution,
    Good luck,
    Jay

  • SAX-ContentHandler -characters methods gets wrong int end sometimes

    Hi
    I am having problems with SAX-ContentHandler -characters methods. It gets wrong int end values time to time ---means that it chops up my strings when it reads large XML files.
    Is there any way to correct it? Any suggestions will be very helpful. Thank you.
    My code is below.
    public class MyContentHandlerDemo extends Thread implements ContentHandler{
    private ArrayList hitList = new ArrayList(1000);
    private ArrayList hitId = new ArrayList(1000);
    private ArrayList hspNum = new ArrayList(1000);
    private ArrayList hitLength = new ArrayList(1000);
    private ArrayList queryFrom = new ArrayList(1000);
    private ArrayList hspith = new ArrayList(1000);
    private ArrayList idith = new ArrayList(1000);
    private String localname;
    private Locator locator;
    private int know=1;
    private int knowid=1;
    private int knowlength=1;
    private int knowhitlength=1;
    private int knowhspnum=1;
    private int knowhspnumadd=1;
    private int knowhspnumlength=1;
    private int knowquery=1;
    private int knowqueryfrom=1;
    private int processon =1;
    private int processcount = 0;
    private int hspithnum=0;
    private int idithnum=0;
    String allstr;
    String addseq;
    char [] allchar;
    int icount=0;
    int lengthsum=0;
    public synchronized void setDocumentLocator(Locator locator) {
    System.out.println(" * setDocumentLocator() called");
    // We save this for later use if desired.
    this.locator = locator;
    public synchronized void startDocument() throws SAXException {
    System.out.println("Parsing begins...");
    public synchronized void endDocument() throws SAXException {
    try {
    FileOutputStream outputfileDemo;
    PrintStream printoutDemo;
    outputfileDemo= new FileOutputStream("apoe500.fasta");
    printoutDemo=new PrintStream(outputfileDemo);
    FileOutputStream reSaxfile;
    PrintStream printoutReSax;
    reSaxfile= new FileOutputStream("reSax.txt");
    printoutReSax=new PrintStream(reSaxfile);
    int m = hitList.size();
    for (int k=0; k < m; k++) {
    int comp = (((hitList.get(k)).toString()).length());
    String strComp = Integer.toString(comp);
    String hitleng = (hitLength.get(k)).toString();
    if(strComp.compareTo(hitleng)!=0)
    {System.out.println("Warning: Length is different at hit number (-1) " + hitId.get(k));}
    for (int l=0; l < hspith.size(); l++){
    printoutReSax.println((hspith.get(l)).toString());
    outputfileDemo.close();
    printoutDemo.close();
    reSaxfile.close();
    printoutReSax.close();
    } catch (IOException e) {
    System.out.println("IOException errors");
    System.out.println("...Parsing ends.");
    public synchronized void processingInstruction(String target, String data)
    throws SAXException {
    //System.out.println("PI: Target:" + target + " and Data:" + data);
    public synchronized void startPrefixMapping(String prefix, String uri) {
    //System.out.println("Mapping starts for prefix " + prefix +
    // " mapped to URI " + uri);
    public synchronized void endPrefixMapping(String prefix) {
    //System.out.println("Mapping ends for prefix " + prefix);
    public synchronized void startElement(String namespaceURI, String localName,
    String rawName, Attributes atts)
    throws SAXException {
    localname =localName;
    int which =100;
    if (localname.equals("Hit_id")) {which = 0;}
    if (localname.equals("Hsp_num")) {which = 1;}
    if (localname.equals("Hsp_hseq")) {which = 2;}
    if (localname.equals("Hsp_align-len")) {which =3;}
    if (localname.equals("Hsp_query-from")) {which =4;}
    switch (which){
    case 0: knowid=0;
    //icount=icount+1;
    break;
    case 1: knowhspnum=0;icount=icount+1;
    break;
    case 2: know=0; //icount=icount+1;
    break;
    case 3: knowlength=0; //icount=icount+1;
    break;
    case 4: knowquery=0; //icount=icount+1;
    break;
    default: knowid=1; know=1; knowlength=1; knowhspnum=1;knowhitlength=1;knowquery=1;
    public synchronized void endElement(String namespaceURI, String localName,
    String rawName)
    throws SAXException {
    //System.out.println("endElement: " + localName + "\n");
    public synchronized void characters(char[] ch, int start, int end)
    throws SAXException {
    String s = new String(ch, start, end);
    int process=100;
    if (knowid==0) {process=0;}
    if (knowhspnum==0){process=1;}
    if (know==0) {process=2;}
    if (knowlength==0) {process=3;}
    if(knowquery==0){process=4;}
    switch(process){
    case 0:
    idithnum = idithnum+1;
    //int start1 = start;
    //int end1 = end;
    //char [] datahold1 = new char[end1];
    //for (int i=0;i<end1;i++){
    //datahold1=ch[start1+i];
    //warn if the length is differernt
    int n=s.length();
    allchar = new char[n+1];
    allchar[0] = '>';
    for (int i=0; i<n; i++){
    allchar[i+1]=s.charAt(i);
    allstr = new String(allchar);
    hitId.add(allstr);
    knowid=1;
    processon=1;
    break;
    case 1:
    hspNum.add(s);
    if ((s.compareTo(Integer.toString(1)))!=0){
    String hspallstr = new String (allstr.concat(s));
    hitId.add(hspallstr);
    knowhspnum=1;
    processon=1;
    break;
    case 2:
    hitList.add(s);
    know=1;
    processon=1;
    break;
    case 3:
    hitLength.add(s);
    knowlength=1;
    processon=1;
    break;
    case 4:
    queryFrom.add(s);
    knowquery=1;
    processon=1;
    break;
    default: processon=0;
    public synchronized void ignorableWhitespace(char[] ch, int start, int end)
    throws SAXException {
    String s = new String(ch, start, end);
    public synchronized void skippedEntity(String name) throws SAXException {

    I put some more codes in characters(). Then I got OutOfMemory: Java Heap Error.
    I probably have to write something in startElement() to limit input for characters() method.
    Could anyone help me? I need to limit inputs for charactes() in startElement().
    I added some codes in characters() method
    public synchronized void characters(char[] ch, int start, int end)
            throws SAXException {
            String s;
            StringBuffer stringbuf1;
            String finalstring1;
            int process=100;
            if (knowid==0) {process=0;}
            if (knowhspnum==0){process=1;}
            if (know==0) {process=2;}
            if (knowlength==0) {process=3;}
            if(knowquery==0){process=4;}
            switch(process){
            case 0:
            //s = new String(ch, start, end);
            idithnum = idithnum+1;
            //int start1 = start;
            //int end1 = end;
            //char [] datahold1 = new char[end1];
            stringbuf1 = new StringBuffer();
            while(ch!=null){
            stringbuf1.append(ch);   
            finalstring1 = stringbuf1.toString();
            //warn if the length is differernt
            int n=finalstring1.length();
            allchar = new char[n+1];
            allchar[0] = '>';
            for (int i=0; i<n; i++){
            allchar[i+1]=finalstring1.charAt(i);
            allstr = new String(allchar);
            hitId.add(allstr);
            knowid=1;
            processon=1;
            break;
            case 1:
            //s = new String(ch, start, end);
            stringbuf1 = new StringBuffer();
            while(ch!=null){
            stringbuf1.append(ch);   
            finalstring1 = stringbuf1.toString();
            hspNum.add(finalstring1);
            if ((finalstring1.compareTo(Integer.toString(1)))!=0){
            String hspallstr = new String (allstr.concat(finalstring1));
            hitId.add(hspallstr);
            //System.out.println(allstr);
            knowhspnum=1;
            processon=1;
            break;
            case 2:
            //s = new String(ch, start, end);
            //int lengthend=end;
            stringbuf1 = new StringBuffer();
            while(ch!=null){
            stringbuf1.append(ch);   
            finalstring1 = stringbuf1.toString();
            checklength:
            while(know==0){
            if(lengthend!=new Integer((hitLength.get(hitLength.size()-1)).toString())){
            String s1=new String(ch, start, end);
            s = (((hitList.get((hitList.size())-1)).toString()).concat(s1));
            hitList.add(s);know=1;
            break;
            hitList.add(finalstring1);
            processon=1;
            break;
            case 3:
            //s = new String(ch, start, end);
            stringbuf1 = new StringBuffer();
            while(ch!=null){
            stringbuf1.append(ch);   
            finalstring1 = stringbuf1.toString();
            hitLength.add(finalstring1);
            knowlength=1;
            processon=1;
            break;
            case 4:
            //s = new String(ch, start, end);
            stringbuf1 = new StringBuffer();
            while(ch!=null){
            stringbuf1.append(ch);   
            finalstring1 = stringbuf1.toString();
            queryFrom.add(finalstring1);
            knowquery=1;
            processon=1;
            break;
            default: processon=0;

  • How to delete data from a DSO using start or end routine

    Is it possible to delete records from a DSO in the start or end routine.
    My example:  I have order 123, item 10, sched line 1.  This gets loaded into the DSO.
    Next day I have order 123, item 10, sched line 2 coming in.
    I want to delete the first one (with sched line 1) from the DSO and load the second one (with sched line 2).
    Can code be put in the start or end routine to do this?

    unless I can do it within the start routine I don't want to have to create new records.
    In the start routine I am comparing records coming in with what are already in the DSO.  If there is a match on order and item and the sched line is different, then I want to delete the record from the DSO and load the new one.  Is there code that I can put in a start routine to accomplish this?

  • Easy way to delete large chunks of audio by entering start and end time?

    I am removing segments from within an audio file. Right now I select the part I want to cut out using the mouse. Is there a way to delete exact portions by entering start and end times? For example, delete the audio from 5:03 to 7:16.
    Is this possible?
    Thanks!

    At the bottom of the track window at the left hand side ( bit above the loops window etc ) is a little slider. Look carefully, it is in line with the left control portion of the tracks at the bottom. Slide far left and see the whole of the song, slide right zooms in ........

  • XML document structures must start and end within the same entity

    Hi there,
    I'm working with a client/server application and using SaxParser for reading in xml. I get the SaxParserException: XML document structures must start and end within the same entity. I understand what that means, but it isn't applicable! The xml data being used is well-formed. I checked the well-formedness with Stylus Studio to make sure. Here's the data:
    <?xml version='1.0' encoding='UTF-8'?>
    <vcmessage>
         <vcsource>3</vcsource>
         <processevent>16</processevent>
         <shape>
              <llindex>0</llindex>
              <shapetype>9</shapetype>
              <shapeproperties>
                   <shapelocation>
                        <xcoord>54</xcoord>
                        <ycoord>184</ycoord>
                   </shapelocation>
                   <bounds>
                        <width>24</width>
                        <height>24</height>
                   </bounds>
                   <fgcolor>
                        <fgred>0</fgred>
                        <fggreen>0</fggreen>
                        <fgblue>0</fgblue>
                   </fgcolor>
                   <bgcolor>
                        <bgred>255</bgred>
                        <bggreen>255</bggreen>
                        <bgblue>255</bgblue>
                   </bgcolor>
                   <thickness>1</thickness>
                   <isfilled>false</isfilled>
              </shapeproperties>
         </shape>
    </vcmessage>The parser generally stops around the </bgcolor> tag.
    I'm using Eclypse as my IDE. I'm wondering if there's something wrong with it? Or maybe there's something wrong with the class I'm using for reading in the XML? Followng is the class.
    Please advise,
    Alan
    package vcclient;
    import java.io.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    import javax.xml.parsers.*;
    public class XMLDocumentReader extends DefaultHandler
      private VCClient client = null;
      private Writer out;
      private String lineEnd =  System.getProperty("line.separator");
      private boolean haveSourceType = false;
      private boolean haveUserName = false;
      private boolean haveMessage = false;
      private boolean haveProcessEvent = false;
      private boolean haveLinkedListIndex = false;
      private boolean haveOpeningShapePropertiesTag = false;
      private boolean haveShapeType = false;
      private boolean haveOpeningShapeLocationTag = false;
      private boolean haveShapeLocation = false;
      private boolean haveOpeningXCoordTag = false;
      private boolean haveOpeningYCoordTag = false;
      private boolean haveOpeningBoundsTag = false;
      private boolean haveBoundsWidth = false;
      private boolean haveBoundsHeight = false;
      private boolean haveOpeningFGColorTag = false;
      private boolean haveOpeningBGColorTag = false;
      private boolean haveOpeningThicknessTag = false;
      private boolean haveOpeningIsFilledTag = false;
      private boolean haveOpeningImageDataTag = false;
      private boolean haveOpeningTextDataTag = false;
      private boolean haveFGRed = false;
      private boolean haveFGGreen = false;
      private boolean haveFGBlue = false;
      private boolean haveBGRed = false;
      private boolean haveBGGreen = false;
      private boolean haveBGBlue = false;
      private boolean haveThickness = false;
      private boolean haveIsFilled = false;
      private boolean haveImageData = false;
      private boolean haveTextData = false;
      private VCMessage vcmessage = null;
      public XMLDocumentReader(VCClient value)
           client = value;
           vcmessage = new VCMessage();
      public VCMessage getVCMessage()
           return vcmessage;
      public boolean haveSourceType()
         return haveSourceType; 
      public boolean ParseXML(InputStream stream)
         boolean success = false;
         // Use the default (non-validating) parser
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try
             // Set up output stream
            out = new OutputStreamWriter(System.out, "UTF-8");
            // Parse the input
            SAXParser saxParser = factory.newSAXParser();
            saxParser.parse( stream, this );
            success = true;
        catch (SAXParseException spe)
            // Error generated by the parser
            System.out.println("\n** Parsing error"
               + ", line " + spe.getLineNumber()
               + ", uri " + spe.getSystemId());
            System.out.println("   " + spe.getMessage() );
            // Unpack the delivered exception to get the exception it contains
            Exception  x = spe;
            if (spe.getException() != null)
                x = spe.getException();
            x.printStackTrace();
            return success;
        catch (SAXException sxe)
             // Error generated by this application
             // (or a parser-initialization error)
             Exception  x = sxe;
             if (sxe.getException() != null)
                 x = sxe.getException();
             x.printStackTrace();
             return success;
        catch (ParserConfigurationException pce)
            // Parser with specified options can't be built
            pce.printStackTrace();
            return success;
        catch (Throwable t)
             t.printStackTrace();
             return success;
        return success;
      public void startDocument()throws SAXException
          emit("<?xml version='1.0' encoding='UTF-8'?>");
          nl();
      public void endDocument()throws SAXException
          try {
              nl();
              out.flush();
          } catch (IOException e) {
              throw new SAXException("I/O error", e);
      public void startElement(String namespaceURI,
                               String lName, // local name
                               String qName, // qualified name
                               Attributes attrs)throws SAXException
          String eName = lName; // element name
          if (eName.equals(""))
             eName = qName; // namespaceAware = false
          emit("<"+eName);
          if (attrs != null) {
              for (int i = 0; i < attrs.getLength(); i++) {
                  String aName = attrs.getLocalName(i); // Attr name
                  if (aName.equals("")) aName = attrs.getQName(i);
                  emit(" ");
                  emit(aName + "=\"" + attrs.getValue(i) + "\"");
          emit(">");
          if(makeStartTag(eName).equals(Constants.OPENING_SHAPEPROPERTIES))
                haveOpeningShapePropertiesTag = true;
          else if(makeStartTag(eName).equals(Constants.OPENING_SHAPELOCATION))
              haveOpeningShapeLocationTag = true;
          else if(makeStartTag(eName).equals(Constants.OPENING_BOUNDS))
                haveOpeningBoundsTag = true;
          else if(makeStartTag(eName).equals(Constants.OPENING_FGCOLOR))
                 haveOpeningFGColorTag = true;
          else if(makeStartTag(eName).equals(Constants.OPENING_BGCOLOR))
              haveOpeningBGColorTag = true;
          else if(makeStartTag(eName).equals(Constants.OPENING_BGGREEN))
               System.out.println("See BGGreen");
          else if(makeStartTag(eName).equals(Constants.OPENING_BGBLUE))
               System.out.println("See BGBlue");
          else if(makeStartTag(eName).equals(Constants.OPENING_THICKNESS))
              haveOpeningThicknessTag = true;
          else if(makeStartTag(eName).equals(Constants.OPENING_ISFILLED))
              haveOpeningIsFilledTag = true;
          else if(makeStartTag(eName).equals(Constants.OPENING_IMAGEDATA))
              haveOpeningImageDataTag = true;
          else if(makeStartTag(eName).equals(Constants.OPENING_TEXTDATA))
              haveOpeningTextDataTag = true;
      public void endElement(String namespaceURI,
                             String sName, // simple name
                             String qName  // qualified name
                            )throws SAXException
           if(sName.equals("") && !qName.equals(""))
              sName = qName;
              emit("</"+sName+">");
           else
              emit("</"+sName+">");
           if(makeEndTag(sName).equals(Constants.CLOSING_SOURCE_TYPE))
              haveSourceType = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_USER))
              haveUserName = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_MESSAGE))
              haveMessage = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_PROCESSEVENT))
               haveProcessEvent = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_LINKEDLISTINDEX))
               haveLinkedListIndex = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_SHAPETYPE))
               haveShapeType = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_SHAPELOCATION))
                haveOpeningShapeLocationTag = false;
           else if(makeEndTag(sName).equals(Constants.CLOSING_WIDTH))
               haveBoundsWidth = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_HEIGHT))
               haveBoundsHeight = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_BOUNDS))
                haveOpeningBoundsTag = false;
           else if(makeEndTag(sName).equals(Constants.CLOSING_FGRED))
               haveFGRed = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_FGGREEN))
               haveFGGreen = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_FGBLUE))
               haveFGBlue = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_FGCOLOR))
                haveOpeningFGColorTag = false;
           else if(makeEndTag(sName).equals(Constants.CLOSING_BGRED))
               haveBGRed = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_BGGREEN))
             haveBGGreen = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_BGBLUE))
               System.out.println("See closing BGBlue");
               haveBGBlue = true;
           else if(makeEndTag(sName).equals(Constants.CLOSING_BGCOLOR))
                haveOpeningBGColorTag = false;
           else if(makeEndTag(sName).equals(Constants.CLOSING_THICKNESS))
               System.out.println("XMLDocumentReader: Step2");
                haveOpeningThicknessTag = false;
           else if(makeEndTag(sName).equals(Constants.CLOSING_ISFILLED))
               haveOpeningIsFilledTag = false;
           else if(makeEndTag(sName).equals(Constants.CLOSING_IMAGEDATA))
               haveOpeningImageDataTag = false;
           else if(makeEndTag(sName).equals(Constants.CLOSING_TEXTDATA))
               haveOpeningTextDataTag = false;
      private String makeStartTag(String tag_name)
           String start = "<";
           String end = ">";
           return start.concat(tag_name).concat(end);
      private String makeEndTag(String tag_name)
           String start = "</";
           String end = ">";
           return start.concat(tag_name).concat(end);
      public void characters(char buf[], int offset, int len)throws SAXException
           String s = new String(buf, offset, len);
          if(haveSourceType == false)
               if(vcmessage.getSourceType() == null)
                  try
                    if(s.equals(""))return;
                   int sourcetype = Integer.parseInt(s);
                   vcmessage.setSourceType(sourcetype);                            
                  catch(NumberFormatException nfe){}
          else if(vcmessage.getSourceType() == SourceType.CHAT_SOURCE)
            if(vcmessage.getSourceType() == SourceType.CHAT_SOURCE && haveUserName == false)
                 vcmessage.setUserName(s);          
            else if(vcmessage.getSourceType() == SourceType.CHAT_SOURCE && haveMessage == false)
               //When the parser encounters interpreted characters like: & or <,
               //then this method gets invoked more than once for the whole message.
               //Therefore, we need to concatonate each portion of the message.  The
               //following method call automatically concatonates.
               vcmessage.concatMessage(s);                    
          else if(vcmessage.getSourceType() == SourceType.WHITEBOARD_SOURCE)
               if(haveProcessEvent == false)
                 try
                   vcmessage.setProcessEvent(Integer.parseInt(s));
                 catch(NumberFormatException nfe){}
               else if(haveLinkedListIndex == false)
                    try
                       vcmessage.setLinkedListIndex(Integer.parseInt(s));
                     catch(NumberFormatException nfe){}
               else if(haveShapeType == false)
                    try
                       vcmessage.setShapeType(Integer.parseInt(s));
                     catch(NumberFormatException nfe){}
               if(haveOpeningShapePropertiesTag)
                    if(haveOpeningShapeLocationTag)
                         if(haveOpeningXCoordTag)
                              try
                                vcmessage.setXCoordinate(Integer.parseInt(s));
                              catch(NumberFormatException nfe){}
                         else if(haveOpeningYCoordTag)
                              try
                                vcmessage.setYCoordinate(Integer.parseInt(s));
                                //reset all flags for ShapeLocation, X and Y coordinates
                                haveOpeningXCoordTag = false;
                                haveOpeningYCoordTag = false;
                                //haveOpeningShapeLocationTag = false;
                              catch(NumberFormatException nfe){}
                    else if(haveOpeningBoundsTag)
                         if(haveBoundsWidth == false)
                              try
                                vcmessage.setBoundsWidth(Integer.parseInt(s));
                              catch(NumberFormatException nfe){}
                         else if(haveBoundsHeight == false)
                              try
                                vcmessage.setBoundsHeight(Integer.parseInt(s));
                                //reset flag
                                //haveOpeningBoundsTag = false;
                              catch(NumberFormatException nfe){}
                    else if(haveOpeningFGColorTag)
                         if(haveFGRed == false)
                              try
                                vcmessage.setFGRed(Integer.parseInt(s));                           
                              catch(NumberFormatException nfe){}
                         else if(haveFGGreen == false)
                              try
                                vcmessage.setFGGreen(Integer.parseInt(s));                           
                              catch(NumberFormatException nfe){}
                         else if(haveFGBlue == false)
                              try
                                vcmessage.setFGBlue(Integer.parseInt(s));
                                //reset flag
                                //haveOpeningFGColorTag = false;
                              catch(NumberFormatException nfe){}
                    else if(haveOpeningBGColorTag)
                         if(haveBGRed == false)
                              try
                                vcmessage.setBGRed(Integer.parseInt(s));                           
                              catch(NumberFormatException nfe){}
                         else if(haveBGGreen == false)
                              try
                                vcmessage.setBGGreen(Integer.parseInt(s));                           
                              catch(NumberFormatException nfe){}
                         else if(haveBGBlue == false)
                         {   System.out.println("getting BGBlue data");
                              try
                                vcmessage.setBGBlue(Integer.parseInt(s));
                                //reset flag
                                //haveOpeningBGColorTag = false;
                              catch(NumberFormatException nfe){}
                    else if(haveOpeningThicknessTag)
                         try
                            vcmessage.setThickness(Integer.parseInt(s));                       
                          catch(NumberFormatException nfe){}
                    else if(haveOpeningIsFilledTag)
                         vcmessage.setIsFilled(s);
                    else if(haveOpeningImageDataTag && vcmessage.getProcessEvent() == org.jcanvas.comm.ProcessEvent.MODIFY)
                         vcmessage.setBase64ImageData(s);                    
                    else if(haveOpeningTextDataTag && vcmessage.getProcessEvent() == org.jcanvas.comm.ProcessEvent.MODIFY)
                         vcmessage.setTextData(s);
                    //reset
                    haveOpeningShapePropertiesTag = false;
          emit(s);
      //===========================================================
      // Utility Methods ...
      //===========================================================
      // Wrap I/O exceptions in SAX exceptions, to
      // suit handler signature requirements
      private void emit(String s)throws SAXException
          try {
              out.write(s);
              out.flush();
          } catch (IOException e) {
              throw new SAXException("I/O error", e);
      // Start a new line
      private void nl()throws SAXException
          try {
              out.write(lineEnd);
          } catch (IOException e) {
              throw new SAXException("I/O error", e);
      //treat validation errors as fatal
      public void error(SAXParseException e)
      throws SAXParseException
        throw e;
      // dump warnings too
      public void warning(SAXParseException err)
      throws SAXParseException
        System.out.println("** Warning"
            + ", line " + err.getLineNumber()
            + ", uri " + err.getSystemId());
        System.out.println("   " + err.getMessage());
    }

    Just out of curiosity what happens if you append a space to the end of the XML document?

  • Matcher.start() and end() help with indexing.....

    I looked at the API and tried to figure out the following...
    public class class2{
        String[] x = {"abba"};
        public static void main(String args[]){
            Pattern p = Pattern.compile("a?");
            Matcher m = p.matcher("a");
           while(m.find()){
               System.out.println(m.start()+" "+ m.end());
    }To my understanding the start() returns the int index for the previous match and is zero based? Is this true?
    And the end () returns the last index in the form of an int and is 1 based?
    Finally Why do i get a second loop in my while block? I was under the impression that once the "a" was tested the while loop would fail as there are no more "a" characters? Is there something I am missing?

    Yucca wrote:
    sabre150 wrote:
    start() gives one the index of the first character of the match. end() gives one the index of the first character after the match. Your find() gives you a match against the 'a' of width 1. There Pattern then steps on past the match so the find() starts after the first match and looks again. Since your regex says the 'a' is optional you get a second match of zero width. The find then steps on past the second match (find() always advances by at least one char) so you cannot have any further matches.Ok so do you mean that the end() returns the last position of the current matchNo. end() gives the index of the character following the match.
    (which is zero based) All indexes are zero based.
    and then the start moves from that same position meaning that the start position will always be the end position on previous match?Nearly. The start for finding the next match will be the end() of the previous match except when the previous match was of zero width when it will be 1+ end(). i.e. the start position always advances at least one character.
    Edited by: sabre150 on Dec 19, 2008 3:24 PM

  • Adding a summary column in a table which contains the start and end dates in the week

    Hi,
    I've got a DIMENSION DATE table and want to add in another column which shows the start and end date of the week.
    See below, the new column is WEEKOFYEARTEXT.
    Does anybody know how i may generate this column using SQL and using the existing columns?
    Umar Javed

    See:  http://www.sqlusa.com/bestpractices/datetimeconversion/
    DECLARE @Year INT = '2015';
    WITH cteDays AS (SELECT DayOfYear=Dateadd(dd, number,
    CONVERT(DATE, CONVERT(char(4),@Year)+'0101'))
    FROM master.dbo.spt_values WHERE type='P'),
    CTE AS (SELECT DayOfYear, WeekOfYear=DATEPART(week,DayOfYear)
    FROM cteDays WHERE YEAR(DayOfYear)= @YEAR)
    SELECT WeekOfYear, StartOfWeek=MIN(DayOfYear), EndOfWeek=MAX(DayOfYear)
    FROM CTE GROUP BY WeekOfYear ORDER BY WeekOfYear;
    WeekOfYear StartOfWeek EndOfWeek
    1 2015-01-01 2015-01-03
    2 2015-01-04 2015-01-10
    3 2015-01-11 2015-01-17
    4 2015-01-18 2015-01-24
    5 2015-01-25 2015-01-31
    6 2015-02-01 2015-02-07
    7 2015-02-08 2015-02-14
    8 2015-02-15 2015-02-21
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Database Design
    New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

  • I deleted a contact, but they still show up in my text options to send.  I would like to delete the contact from my texts too.

    I deleted a contact, but they still show up in my text options to send.  I would like to delete the contact from my texts too.

    No don't restore your iphone. I've done that several times &amp; it has never worked. -I still have deleted contacts in my iphone texts.  *However if you do restore it you will not lose all your data, pics, text messages etc if you backup in iCloud. It restores back to original phone. Very nice :). Anyhowwww....
    I JUST  figured it out!! :))). Remove the contact from recents.
      Start a text. You should see the deleted contact. All the way to the right of the name is a symbol. The symbol is a circle with "i" in the middle. Click that symbol then in red lettering click "remove from recents".

  • Is there a way to enter an event time in Calendar as a reminder for me and NOT have Calendar erase it in the info as it reads it into the event start and end times?

    Calendar can recognize and derive event start and end times from the text description entered.  However, when it seizes on a time (start and/or end) and automatically enters it as the start and/or end time, it also (sigh) deletes the time from the text.  I enter the times as reminders for me, how can one prevent them from being deleted by Calendar??

    I am having the same darn problem. I really dislike this auto feature in Calendar.
    Can anyone help us please?

Maybe you are looking for

  • JFileChooser weird problem (Help!!!)

    Does anyone here have loading problem with JFileChooser? I have a class that inherited the JFileChooser class and another class that inherited the JFrame class and this class create an instance of the JFileChooser class. My program sometime will not

  • How to restore Ipod Touch running ios 5 without passcode or itunes?

    Hello All, I updated my Fourth Generation Ipod Touch to ios5. The Itouch's home computer broke down so i am now forced to use my other pc which is authorised with the same apple id as the one on my old pc and on my itouch. I have not used my itouch i

  • Locking iPhone via icloud doesn't work

    I recently lost an iPhone 5. I went on to my iCloud account and locked the handset via the find my iPhone app. I have since discovered that it's of no consequence at all, apparently. My telco informed me that the SIM was replaced and the phone has be

  • Image database corrupt!!

    i have changed my memory card from 4gb to 8gb. And copied all the files as such from old card to new card.. Now got a problem in this.. In my gallery the images are not exactly shown as before.. Only the newer images are shown in the gallery and the

  • Error on Lockbox starting....

    Hello all, Please guide me on Lockbox.... I have created my own ctl file Lockbox with the help of Metalink note. Its giving error but i'm using the same query and same data file, how the metalink note explained. Do I need to do any thing in database