Waitone and waitany

Whts diff between waitone and waitany procedure present in DBMS_ALERT package?
Can anybody explain wid example?
Thanks in advance

[This link|http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_alert.htm#sthref366] should be clear enough?

Similar Messages

  • What is windows service self-aware

    Hi
    How to make windows service self-aware
    I tried single ton pattern but no use
    Issue is :http://social.msdn.microsoft.com/Forums/office/en-US/5031074e-bab7-4659-b4b3-909a7d32ec6f/exchange-web-service-error-while-moving-mail-to-other-folder?forum=exchangesvrdevelopment 
    Regards,
    Jagdish
    Jagdish

    I
    got the Answer 
    Threading with Mutex (Mutual exclusion):
    When two or more threads need to access a shared resource at the same time, the system needs a synchronization mechanism to ensure that only one thread at a time uses the resource. Mutex is
    a synchronization primitive that grants exclusive access to the shared resource to only one thread. If a thread acquires a mutex, the second thread that wants to acquire that mutex is suspended until the first thread releases the mutex.
    Steps:
    Instantiating a new Mutex object that's accessible from each thread.
    Wrapping whatever code you want to be executed in the critical section with that object's WaitOne() and ReleaseMutex() methods in each thread
    Implementation:
    Add class
    SingleGlobalInstance to your project
    class
    SingleGlobalInstance :
    IDisposable
        public
    bool hasHandle = false;
        Mutex
    mutex;
        private
    void
    InitMutex()
            string
    appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute),
    false).GetValue(0)).Value.ToString();
            string
    mutexId = string.Format("Global\\{{{0}}}",
    appGuid);
            mutex =
    new
    Mutex(false,
    mutexId);
            var
    allowEveryoneRule = new
    MutexAccessRule(new
    SecurityIdentifier(WellKnownSidType.WorldSid,
    null),
    MutexRights.FullControl,
    AccessControlType.Allow);
            var
    securitySettings = new
    MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);
            mutex.SetAccessControl(securitySettings);
        public
    SingleGlobalInstance(int
    TimeOut)
            InitMutex();
            try
                if(TimeOut
    <= 0)
                    hasHandle = mutex.WaitOne(Timeout.Infinite,
    false);
                else
                    hasHandle = mutex.WaitOne(TimeOut,
    false);
                if
    (hasHandle == false)
                    throw
    new
    TimeoutException("Timeout
    waiting for exclusive access on SingleInstance");
            catch
    (AbandonedMutexException)
                hasHandle =
    true;
        public
    void
    Dispose()
            if
    (mutex != null)
                if
    (hasHandle)
                    mutex.ReleaseMutex();
                mutex.Dispose();
    Add following condition to check whether thread is already running
    using (new
    SingleGlobalInstance(1000))
    //code which should be executed in single thread
    Regards,
    Jagdish Kotian
    Jagdish

  • Trying to get a Trigger and Alert to work

    So im trying to get a trigger to work with an alert and the Alert seems to be right and the trigger complies which seems right to me, however the instruction that I have in my book does not produce the same output that I get from my Update.
    Here is the deal. I am to log into sql * with a default account as well as login as "SYSTEM"
    the trigger should invoke the Alert and output a message to re-order some more product and the status should = 0 since there is no wait time. However I don't get a "Message" from the Alert and the status = 1 which indicates timeout. So if you can take a look at my code and let me know what I did wrong or how to "Connect" the two that would be great.
    Trigger I created.
    CREATE OR REPLACE TRIGGER order_replace_trg
    AFtER UPDATE OF stock on bb_product
    FOR EACH ROW
    WHEN (OLD.stock = 24 AND NEW.stock = -2)
    DECLARE
    stock NUMBER(5,1);
    idproduct NUMBER(2);
    lv_msg_txt VARCHAR2(25);
    lv_status_num NUMBER(1);
    reorder NUMBER(3);
    BEGIN
    IF stock <> 24 AND reorder = 25 THEN
    lv_msg_txt := 'Product 4 Reorder Time!';
    DBMS_OUTPUT.PUT_LINE(lv_msg_txt);
    ELSE
    lv_status_num := 0;
    DBMS_OUTPUT.PUT_LINE(lv_status_num);
    END IF;
    END;
    The Alert:
    BEGIN
    DBMS_ALERT.REGISTER('reorder');
    END;
    DECLARE
    lv_msg_txt VARCHAR2(25);
    lv_status_num NUMBER(1);
    BEGIN
    DBMS_ALERT.WAITONE('reorder', lv_msg_txt, lv_status_num, 120);
    DBMS_OUTPUT.PUT_LINE('Alert: ' ||lv_msg_txt);
    DBMS_OUTPUT.PUT_LINE('Status: ' ||lv_status_num);
    END;
    Here is the block I need to run to test the trigger and alert.
    UPDATE bb_product
    SET stock = stock -2
    WHERE idproduct = 4;
    COMMIT;
    The message I should get is:
    Alert: Product 4 Reorder Time!
    Status: 0
    PL/SQL procedure successfully completed.
    This is what I get.
    SQL> /
    Alert:
    Status: 1
    PL/SQL procedure successfully completed.
    Thanks for your help!
    Mac

    Right. Register says "I'm interested in getting alerted to some particular event", Waitone says "I'm waiting until some event happens". Signal is the key thing that indicates that a particular event happened.
    As for your trigger, a couple of issues
    - I don't know why you're calling DBMS_OUTPUT. I'm guessing that you probably want to send a message along with your alert that the receiver gets and displays, not that you want to print a message to the window from inside the trigger.
    - You're using the local variables stock and reorder in your IF statement but you never initialize them. I'm guessing that you would want to eliminate those local variables and just use :new.stock and :new.reorder (assuming that REORDER is a column in the table).
    - Your WHEN clause doesn't seem to make sense. It's telling the trigger to fire only if you update stock from 24 to -2, which doesn't make sense. I'm not sure you would even need a WHEN clause here.
    Justin

  • How can i calculate the percentages and update the progressBar in the splash screen form ?

    I created a splash screen form:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Threading;
    namespace GetHardwareInfo
    public partial class SplashScreen : Form
    public SplashScreen()
    InitializeComponent();
    private Mutex mutex = new Mutex();
    public void SyncedClose()
    mutex.WaitOne();
    this.Close();
    mutex.ReleaseMutex();
    public void UpdateProgressBar(int percentage)
    if (this.InvokeRequired)
    mutex.WaitOne();
    if (!IsDisposed)
    this.BeginInvoke(new Action<int>(UpdateProgresPRV), percentage);
    mutex.ReleaseMutex();
    else
    UpdateProgresPRV(percentage);
    private void UpdateProgresPRV(int per)
    if (progressBar1.IsDisposed) return;
    progressBar1.Value = per;
    private void SplashScreen_Load(object sender, EventArgs e)
    The SplashScreen form have in the designer image and on the image a progressBar1.
    Then in form1 i did in the top:
    List<string> WmiClassesKeys = new List<string>();
    IEnumerable<Control> controls;
    string comboBoxesNames;
    SplashScreen splash = new SplashScreen();
    And in the constructor:
    controls = LoopOverControls.GetAll(this, typeof(ComboBox));
    string[] lines = File.ReadAllLines(@"c:\wmiclasses\wmiclasses1.txt");
    foreach (string line in lines)
    foreach (ComboBox comboBox in controls.OfType<ComboBox>())
    if (line.StartsWith("ComboBox"))
    comboBoxesNames = line.Substring(14);
    else
    if (line.StartsWith("Classes"))
    if (comboBox.Name == comboBoxesNames)
    comboBox.Items.Add(line.Substring(14));
    foreach (ComboBox comboBox in controls.OfType<ComboBox>())
    comboBox.SelectedIndex = 0;
    The method GetAll is to loop over specific controls:
    public static IEnumerable<Control> GetAll(Control control, Type type)
    var controls = control.Controls.Cast<Control>();
    return controls.SelectMany(ctrl => GetAll(ctrl, type))
    .Concat(controls)
    .Where(c => c.GetType() == type);
    When i'm running the program it's taking some time to make the foreach loops in this time i need to show the SplashScreen and update the progressBar untill the foreach loops over.

    Don't use Application.Doevents. It's not required and can cause problems.
    I do not really grasp the approach you are taking here. So let me make a different suggestion:
    SplashScreen:
    using System;
    using System.Windows.Forms;
    using System.Threading;
    namespace WindowsFormsApplication1
    public partial class SplashScreen : Form
    private static SplashScreen DefaultInstance;
    public SplashScreen()
    InitializeComponent();
    public static void ShowDefaultInstance()
    Thread t = new Thread(TMain);
    t.Name = "SplashUI";
    t.Start();
    public static void CloseDefaultInstance()
    DefaultInstance.Invoke(new Action(DefaultInstance.Close));
    private static void TMain()
    DefaultInstance = new SplashScreen();
    DefaultInstance.Show();
    Application.Run(DefaultInstance);
    public static void UpdateProgress(int Progress)
    if (DefaultInstance.InvokeRequired)
    DefaultInstance.Invoke(new Action<int>(UpdateProgress), Progress);
    else
    DefaultInstance.progressBar1.Value = Progress;
    Form1:
    using System.Windows.Forms;
    namespace WindowsFormsApplication1
    public partial class Form1 : Form
    public Form1()
    InitializeComponent();
    SplashScreen.ShowDefaultInstance();
    for (int i = 1; i<=100; i++)
    System.Threading.Thread.Sleep(20); // simulates work
    SplashScreen.UpdateProgress(i);
    SplashScreen.CloseDefaultInstance();
    EDIT: Please note that the progressbar itself is being animated by the system, so it might look slower than it really is. To workaround this, there are solutions available (you'll find them) that first set the value one higher than necessary, then
    back to the actual value.
    Edit #2: You do need a different thread, otherwise the UI is locked while the loop is running in your Form1's constructor.
    Armin

  • How to run DBMS_JOB in parallel and Serial

    I have total 8 procedure to run in parallel . and after that my 9th procedure should run.
    below is my job submission procedure
    create or replace procedure DURATION_ALARM_WEEKLY as
    l_job number ;
    begin
    dbms_job.submit(l_job,'begin ALARMS_WEEKLY_CALL_OUT ; end;');
    dbms_job.submit(l_job,'begin ALARMS_WEEKLY_CALL_IN ; end;');
    dbms_job.submit(l_job,'begin ALARMS_WEEKLY_DURATIN_OUT ; end;');
    dbms_job.submit(l_job,'begin ALARMS_WEEKLY_DURATIN_IN ; end;');
    dbms_job.submit(l_job,'begin ALARMS_WEEKLY_SMS_OUT ; end;');
    dbms_job.submit(l_job,'begin ALARMS_WEEKLY_SMS_IN ; end;');
    dbms_job.submit(l_job,'begin ALARMS_WEEKLY_SHORT_CALL_OUT ; end;');
    dbms_job.submit(l_job,'begin ALARMS_WEEKLY_IMEI_CHANGE ; end;');
    dbms_job.submit(l_job,'begin FINALE ; end;');
    COMMIT;
    end;
    what is the syntax I have to do in my FINALE procedure . using DBMS_ALERT.REGISTER , DBMS_ALERT.WAITANY .....?
    I read many article , but i did not understand where and which order I have to write the syntax.
    Edited by: OraFighter on Jul 26, 2012 11:31 AM

    All process on Oracle runs serial. There is no threading inside a process. So a DBMS_JOB process is a serial process. It is started by the system. It executes. It terminates.
    Parallel processing means running a number of these serial processes in parallel. Typically you will break up the unit of work to do into smaller units. And then run a serialised process to do a unit of work - by starting a number of these at the same time, you have parallel processing.
    So if you start 9 jobs (processes) at the same time, and there is sufficient job processing capacity, all 9 processes will run at the same time.
    If you want to have the 9th process wait for the others to finish first, you need some kind of logic to either start the 9th process after the other 8 have completed - or you need logic in the 9th process so that it could spin and wait for the 8 others to complete, before it starts its processing.
    The first method is fairly easy. Your code start each of the 8 job processes. The DBMS_JOB.Submit() call gives you the job number of that process. You will thus have 8 job numbers. You can now loop in your code, wait a minute or more, and then check the dictionary view user_jobs to determine if these 8 job numbers still exist. If so, the job is still scheduled and/or executing.
    If none of the 8 job numbers exist in the view, the 9th job process can be started.
    Other methods are more complex. For example, the 8 job processes can send a notification that they are completed to the 9th process. This requires additional logic and code in all 9 processes. And you also need to deal with issues like one of the 8 processes completing before the 9th process started - so how will it then know that one of the 8 processes as completed? Etc.

  • Get screenshot with mouse cursor and send for client application

    I took
    this function for getting a screenshot from a client application. I to tried adapt this function in my project, but I can not capture desktop showing mouse cursor (coming from a remote pc) in my server application (controller).
    Here is my adaptation (in client side) but without success:
    void SendScreenProc()
    // Send First Bitmap
    MemoryStream streamScreen = new MemoryStream();
    this.bmpScreenSend = CaptureScreen(true);//new Bitmap(this.boundScreen.Width, this.boundScreen.Height, PixelFormat.Format24bppRgb);
    Graphics g = Graphics.FromImage(this.bmpScreenSend);
    g.CopyFromScreen(0, 0, 0, 0, this.boundScreen.Size);
    this.bmpScreenSend.Save(streamScreen, System.Drawing.Imaging.ImageFormat.Png);
    Compress.CompressStream(streamScreen);
    Byte[] bufferScreen = streamScreen.ToArray();
    mreSendData.WaitOne();
    this.queueSendData.AddScreen(streamScreen.GetBuffer());
    streamScreen.Close();
    this.receivedScreen = 0;
    while (this.remoted)
    // Send next bitmap result by difference with previous bitmap.
    if(this.receivedScreen == 0) {
    } else {
    Bitmap bmpCurrentScreen = CaptureScreen(true);//new Bitmap(this.boundScreen.Width, this.boundScreen.Height, PixelFormat.Format24bppRgb);
    g = Graphics.FromImage(bmpCurrentScreen);
    g.CopyFromScreen(0, 0, 0, 0, this.boundScreen.Size);
    if (this.receivedScreen == 1) {
    if(this.bmpScreen != null) {
    this.bmpScreen.Dispose();
    this.bmpScreen = this.bmpScreenSend;
    } else if(this.receivedScreen == 2) {
    if (queueSendData.AvailableScreenAdd && IsDifferent(bmpCurrentScreen, this.bmpScreen))
    streamScreen = new MemoryStream();
    Bitmap bmpDiff = XorBitmap(this.bmpScreen, bmpCurrentScreen);
    bmpDiff.Save(streamScreen, System.Drawing.Imaging.ImageFormat.Png);
    this.bmpScreenSend.Dispose();
    bmpDiff.Dispose();
    this.bmpScreenSend = bmpCurrentScreen;
    mreSendData.WaitOne();
    this.queueSendData.AddScreen(streamScreen.GetBuffer());
    streamScreen.Close();
    this.receivedScreen = 0;
    else
    bmpCurrentScreen.Dispose();
    Thread.Sleep(30);

     Hi FlashCoder,
    Do you mean like this capture? Use mouse cursor to capture the specified area.
    If so, here is a sample that I wrote. It should meet your requirement.  If not, please feel free to let me know.
    The following is ScreenForm code
    public partial class ScreenForm : Form
    public ScreenForm()
    InitializeComponent();
    public event copyToFatherTextBox copytoFather;
    public bool begin = false;
    public bool isDoubleClick = false;
    public Point firstPoint = new Point(0, 0);
    public Point secondPoint = new Point(0, 0);
    public Image cachImage = null;
    public int halfWidth = 0;
    public int halfHeight = 0;
    /*Copy the entire screen, and form fill the screen*/
    public void copyScreen()
    Rectangle r = Screen.PrimaryScreen.Bounds;
    Image img = new Bitmap(r.Width, r.Height);
    Graphics g = Graphics.FromImage(img);
    g.CopyFromScreen(new Point(0, 0), new Point(0, 0), r.Size);
    //Maximize form
    this.Width = r.Width;
    this.Height = r.Height;
    this.Left = 0;
    this.Top = 0;
    pictureBox1.Width = r.Width;
    pictureBox1.Height = r.Height;
    pictureBox1.BackgroundImage = img;
    cachImage = img;
    halfWidth = r.Width / 2;
    halfHeight = r.Height / 2;
    this.Cursor = new Cursor(GetType(), "MyCursor.cur");
    private void ScreenForm_Load(object sender, EventArgs e)
    copyScreen();
    /*Begins when the mouse is pressed screenshots*/
    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    if(!isDoubleClick)
    begin = true;
    firstPoint = new Point(e.X, e.Y);
    changePoint(e.X, e.Y);
    msg.Visible = true;
    /*Displayed when the mouse moves to intercept the border*/
    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    if (begin)
    //Redraw the background image
    secondPoint = new Point(e.X, e.Y);
    int minX = Math.Min(firstPoint.X, secondPoint.X);
    int minY = Math.Min(firstPoint.Y, secondPoint.Y);
    int maxX = Math.Max(firstPoint.X, secondPoint.X);
    int maxY = Math.Max(firstPoint.Y, secondPoint.Y);
    Image tempimage = new Bitmap(cachImage);
    Graphics g = Graphics.FromImage(tempimage);
    //Picture cropping frames
    g.DrawRectangle(new Pen(Color.Red),minX,minY,maxX-minX,maxY-minY);
    pictureBox1.Image = tempimage;
    //Calculation of coordinate information
    msg.Text = "Upper left corner coordinates:(" + minX.ToString() + "," + minY.ToString() + ")\r\n";
    msg.Text += "Lower right corner coordinates:(" + maxX.ToString() + "," + maxY.ToString() + ")\r\n";
    msg.Text += "Screenshot size:" + (maxX - minX) + "×" + (maxY - minY) + "\r\n";
    msg.Text += "Double-click end screenshots anywhere!";
    changePoint((minX + maxX) / 2, (minY + maxY) / 2);
    /*Dynamically adjusts the displayed location, enter the parameters for the current screen mouse position*/
    public void changePoint(int x, int y)
    if (x < halfWidth)
    if (y < halfHeight)
    { msg.Top = halfHeight; msg.Left = halfWidth; }
    else
    { msg.Top = 0; msg.Left = halfWidth; }
    else
    if (y < halfHeight)
    { msg.Top = halfHeight; msg.Left = 0; }
    else
    { msg.Top = 0; msg.Left = 0; }
    /*Screenshot is completed when you let go of the mouse operation */
    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    begin = false;
    isDoubleClick = true;
    /*When I double-click a screenshot when notifying parent form complete screenshot action, while closing the form*/
    private void pictureBox1_DoubleClick(object sender, EventArgs e)
    if (firstPoint != secondPoint)
    int minX = Math.Min(firstPoint.X, secondPoint.X);
    int minY = Math.Min(firstPoint.Y, secondPoint.Y);
    int maxX = Math.Max(firstPoint.X, secondPoint.X);
    int maxY = Math.Max(firstPoint.Y, secondPoint.Y);
    Rectangle r = new Rectangle(minX, minY, maxX - minX, maxY - minY);
    copytoFather(r);
    this.Close();
    //msg.Text = r.ToString();
    This is the mainFrom code.
    public delegate void copyToFatherTextBox(Rectangle r);
    public partial class Form1 : Form
    public Form1()
    InitializeComponent();
    /*Start screenshot*/
    private void button1_Click(object sender, EventArgs e)
    ScreenForm screen = new ScreenForm();
    screen.copytoFather += new copyToFatherTextBox(copytoTextBox);
    screen.ShowDialog();
    /*Screenshot of subsequent operations*/
    public void copytoTextBox(Rectangle rec)
    Rectangle rec2=rec;
    if(rec.Width>2&&rec.Height>2)
    rec2= new Rectangle(rec.X + 1, rec.Y + 1, rec.Width - 2, rec.Height - 2);
    Rectangle r = Screen.PrimaryScreen.Bounds;
    Image img = new Bitmap(rec2.Width, rec2.Height);
    Graphics g = Graphics.FromImage(img);
    g.CopyFromScreen(rec2.Location, new Point(0, 0), rec2.Size);
    Clipboard.SetDataObject(img, false);
    richTextBox1.Paste();
    Best regards,
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Need to understand the relation between ManualResetEvent and thread

    please help me to understand the below code
    what is resetEvent.Set() and WaitOne() ? what it does ?
    var resetEvent = new ManualResetEvent(false);
    ThreadPool.QueueUserWorkItem(
    arg =>
    DoWork();
    resetEvent.Set();
    resetEvent.WaitOne();
    again help me to understand the below code
    var events = new List<ManualResetEvent>();
    foreach(var job in jobs)
    var resetEvent = new ManualResetEvent(false);
    ThreadPool.QueueUserWorkItem(
    arg =>
    DoWork(job);
    resetEvent.Set();
    events.Add(resetEvent);
    WaitHandle.WaitAll(events.ToArray());
    why this line WaitHandle.WaitAll(events.ToArray()); is required ?
    why adding ManualResetEvent instance to list ?
    looking for discussion. thanks

    WaitOne() will cause the current (main) thread to wait until the thread pool thread has called the Set() method. If you don't call the WaitOne() method, the code line below ThreadPool.QueueUserWorkItem(...) will get executed before the delegate that you
    pass do the ThreadPool.QueueUserWorkItem method has actually finished its execution because the threads are being executed simultaneously:
    var resetEvent = new ManualResetEvent(false);
    ThreadPool.QueueUserWorkItem(
    arg =>
    //this will be executed simultaneously on thread B
    Thread.Sleep(10000);
    //tell thread A to continue
    resetEvent.Set();
    //thread A waits here until thread B calls the Set() method...
    resetEvent.WaitOne();
    string s = "abc"; //this line won't get executed until thread B has called the Set() method provided that the WaitOne() method is called by thread A above.
    >>why this line WaitHandle.WaitAll(events.ToArray()); is required ?
    It causes the main thread to wait until the Set method of all ManualResetEvent objects in the events list has been called. Othwerwise the execution of the main thread would continue immediately after the foreach loop has been executed. By this time the DoWork
    method of all jobs has not yet been completed because they are being executed on another thread.
    WaitHandle.WaitAll(events.ToArray());
    string s = "abc"; //this line won't get executed until all the Set() method of all ManualResetEvent objects in events has been called
    >>why adding ManualResetEvent instance to list ?
    Because you (appearantly) want to wait for all objects in the list, i.e. you want to wait for the DoWork method to complete for all jobs before you continue the execution of the main thread (and go on to assign the string s to the value "abc"
    in the above example).
    Hope that helps.
    Please remember to close your threads by marking helpful posts as answer then start a new thread if you have a new question. Please don't ask several questions in the same thread.

  • Extraction of CData Part and later its embedding

    Hi All,
    Could someone please help me figure out how I can extract from my xml the CData part, which is also an xml. Once I have the CData xml, I will then apply some xslt script on it and then embed the processed xml back in the CData area.
    For example:
    <?xml version="1.0" encoding="UTF-8"?>
    <fareRequest da="true">
    <vcrs>
    <vcr>U2</vcr>
    </vcrs>
    <fareTypes/>
    <tourOps/>
    <flights>
    <flight depApt="SXF" depDate="2012-04-19" dstApt="BUD"/>
    <flight depApt="BUD" depDate="2012-04-25" dstApt="SXF"/>
    </flights>
    <![CDATA[<CreditCardNumber>123456123</CreditCardNumber>]]>
    <limit>20</limit>
    <offset>0</offset>
    <waitOnList>
    <waitOn>ALL</waitOn>
    </waitOnList>
    <coses/>
    </fareRequest>
    I would like to extract the <CreditCardNumber>123456123</CreditCardNumber>, process it with my xslt script and then embed it back in the original xml, e.g. my desired out:
    <?xml version="1.0" encoding="UTF-8"?>
    <fareRequest da="true">
    <vcrs>
    <vcr>U2</vcr>
    </vcrs>
    <fareTypes/>
    <tourOps/>
    <flights>
    <flight depApt="SXF" depDate="2012-04-19" dstApt="BUD"/>
    <flight depApt="BUD" depDate="2012-04-25" dstApt="SXF"/>
    </flights>
    <![CDATA[<CreditCardNumber>*******23</CreditCardNumber>]]>
    <limit>20</limit>
    <offset>0</offset>
    <waitOnList>
    <waitOn>ALL</waitOn>
    </waitOnList>
    <coses/>
    </fareRequest>
    The masking <CreditCardNumber>*******23</CreditCardNumber> above is done by my xslt script.
    What I need to know is how I can extract the CData part and embedd it back.
    Second important thing is that the structure of my input xml is not fix. The input xml could vary in structure, i.e. it might or might not have CData, incase if the CData is not there, the xslt script should simply be applied and masking is performed if required. The masking logic is handled entirely in the xslt script. But in-case, if the CData is present, then the extraction->xslt script->embed logic is applied.
    A pure xslt based solution is not feseable, but some java and xslt solution.
    So in short, I am looking for a kind osolution as to how I can check if CData is present, and if yes, extract its contents, then xslt and then embedding it back in the original xml.
    Thanks.

    Thanks tsuji!
    The problem as stated in my original message is that:
    1). The solution should work (mask) for both the scenarios, i.e. when the element is encapsulated inside CData and without CData.
    With CData (just an example):
    <![CDATA[<CreditCardNumber>123456123</CreditCardNumber>]]>
    And Without CData (just an example):
    <CreditCardNumber>123456123</CreditCardNumber>
    in both the cases, the masking should work.
    2). The input XML was just one example, the final script should be able to take any input xml (w and w/o CDAta and of different structure) and perform masking. The node which is to be masked can also be different.
    For the masking logic, I have already implemented a generic script (see below). I need to extend it, that is, it should be able to take even XMLs with CData in it.
    Masking.xslt
    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.2" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ota="http://www.opentravel.org/OTA/2003/05" xmlns:anyway="http://anyway.com/webservices/" xmlns:k="http://webservices.kuoni.ch" xmlns:xft="http://www.exchangefortravel.org/xft/current" xmlns:tu="http://tempuri.org/" xmlns:jet2="http://Jet2.Com/External/2009/01/V4">
    <xsl:output encoding="UTF-8" version="1.0" method="xml" indent="yes" cdata-section-elements="anyway:request k:request k:ForwardRequestResult xft:NameText xft:Description xft:URL xft:From xft:To xft:Code tu:XRq tu:ProcessTransactionXFTUResult libelle nom prenom adresse1 ville pays email"/>
    <xsl:strip-space elements="*"/>
    <!--add coma separated element names without namespace prefix to be masked, dont remove first coma! -->
    <xsl:param name="names">!,Number,CCV,cc_number,cc_cvv,AccountNumber,CardSecurityCode,card_number,options,CreditCardNumber,CardNumber,IssueNumber,SecurityCode,</xsl:param>
    <xsl:template match="/">
    <xsl:apply-templates select="node()"/>
    </xsl:template>
    <xsl:template match="@*">
    <xsl:variable name="attr-name" select="concat(',' , local-name() , ',')"/>
    <xsl:attribute name="{name()}" namespace="{namespace-uri()}">
    <xsl:choose>
    <xsl:when test="string-length(substring-before($names, $attr-name)) > 0">
    <xsl:call-template name="mask"/>
    </xsl:when>
    <xsl:otherwise>
    <xsl:value-of select="."/>
    </xsl:otherwise>
    </xsl:choose>
    </xsl:attribute>
    </xsl:template>
    <xsl:template match="text()">
    <xsl:copy/>
    </xsl:template>
    <xsl:template match="*">
    <xsl:variable name="el-name" select="concat(',' , local-name(), ',')"/>
    <xsl:choose>
    <xsl:when test="string-length(substring-before($names, $el-name)) > 0">
    <xsl:element name="{name()}" namespace="{namespace-uri()}">
    <xsl:call-template name="mask"/>
    </xsl:element>
    <xsl:apply-templates select="@*"/>
    <xsl:apply-templates select="*"/>
    </xsl:when>
    <xsl:otherwise>
    <xsl:element name="{name()}" namespace="{namespace-uri()}">
    <xsl:apply-templates select="@*"/>
    <xsl:apply-templates/>
    </xsl:element>
    </xsl:otherwise>
    </xsl:choose>
    </xsl:template>
    <xsl:template name="index-of">
    <xsl:param name="param1"/>
    <xsl:param name="param2"/>
    <xsl:value-of select="string-length(substring-before(concat(' ' ,$param1), $param2))"/>
    </xsl:template>
    <xsl:template name="mask">
    <xsl:variable name="length" select="string-length(.)"/>
    <xsl:choose>
    <xsl:when test="$length > 3">
    <xsl:value-of select="concat ('************', substring(.,$length - 1, 2))"/>
    </xsl:when>
    <xsl:when test="$length > 1">***</xsl:when>
    <xsl:otherwise/>
    </xsl:choose>
    </xsl:template>
    </xsl:stylesheet>
    Thanks again for your help so far.

  • A problem with Threads and loops.

    Hi, I have some code that needs to be constantly running, like while(true)
          //code here
    }However, the code just checks to see if the user has input anything (and then if the user has, it goes to do some other stuff) so I don't need it constantly running and hogging up 98% of the CPU. So I made my class (which has the method that needs to be looped, call it ClassA) implement Runnable. Then I just added the method which needed to be looped into the public void run()
    I have another class which creates an instance of the above class (call it ClassB), and the main(String[] args) is in there.
    public static void main(String[] args)
              ClassA test = new ClassA();
              Thread thread = new Thread(test.getInstanceOfClassA());
              thread.start();
              while(true)
                           //I do not know what to put here
                   try
                        thread.sleep(100);
                   catch(InterruptedException iex)
         }However, the thread only calls run() once,(duh...) but I can't think of away to get it to run - sleep - run -sleep forever. Can someone help me?

    Hi, I have some code that needs to be constantly
    running, like while(true)
    //code here
    }However, the code just checks to see if the user has
    input anything (and then if the user has, it goes to
    do some other stuff) so I don't need it constantly
    running and hogging up 98% of the CPU. Where does the user input come from. Are you reading from an InputStream? If so, then your loop will be blocked anyway when reading from the InputStream until data is available. During that time, the loop will not consume processor cycles.
    public static void main(String[] args)
              ClassA test = new ClassA();
    Thread thread = new Thread(test.getInstanceOfClassA());I have never seen this idiom. If ClassA instanceof Runnable, you simply write new Thread(test).
              thread.start();
              while(true)
    //I do not know what to put
    do not know what to put here
                   try
                        thread.sleep(100);
                   catch(InterruptedException iex)
         }However, the thread only calls run() once,(duh...)Yeah, why would you want to call it more than once given that you have an infinite loop in ClassA.run()?
    Harald.
    Java Text Crunching: http://www.ebi.ac.uk/Rebholz-srv/whatizit/software

  • A problem with Threads and MMapi

    I am tring to execute a class based on Game canvas.
    The problem begin when I try to Play both a MIDI tone and to run an infinit Thread loop.
    The MIDI tone "Stammers".
    How to over come the problem?
    Thanks in advance
    Kobi
    See Code example below:
    import java.io.IOException;
    import java.io.InputStream;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.game.GameCanvas;
    import javax.microedition.media.Manager;
    import javax.microedition.media.MediaException;
    import javax.microedition.media.Player;
    public class MainScreenCanvas extends GameCanvas implements Runnable {
         private MainMIDlet parent;
         private boolean mTrucking = false;
         Image imgBackgound = null;
         int imgBackgoundX = 0, imgBackgoundY = 0;
         Player player;
         public MainScreenCanvas(MainMIDlet parent)
              super(true);
              this.parent = parent;
              try
                   imgBackgound = Image.createImage("/images/area03_bkg0.png");
                   imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
                   imgBackgoundY = this.getHeight() - imgBackgound.getHeight();
              catch(Exception e)
                   System.out.println(e.getMessage());
          * starts thread
         public void start()
              mTrucking = true;
              Thread t = new Thread(this);
              t.start();
          * stops thread
         public void stop()
              mTrucking = false;
         public void play()
              try
                   InputStream is = getClass().getResourceAsStream("/sounds/scale.mid");
                   player = Manager.createPlayer(is, "audio/midi");
                   player.setLoopCount(-1);
                   player.prefetch();
                   player.start();
              catch(Exception e)
                   System.out.println(e.getMessage());
         public void run()
              Graphics g = getGraphics();
              play();
              while (true)
                   tick();
                   input();
                   render(g);
          * responsible for object movements
         private void tick()
          * response to key input
         private void input()
              int keyStates = getKeyStates();
              if ((keyStates & LEFT_PRESSED) != 0)
                   imgBackgoundX++;
                   if (imgBackgoundX > 0)
                        imgBackgoundX = 0;
              if ((keyStates & RIGHT_PRESSED) != 0)
                   imgBackgoundX--;
                   if (imgBackgoundX < this.getWidth() - imgBackgound.getWidth())
                        imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
          * Responsible for the drawing
          * @param g
         private void render(Graphics g)
              g.drawImage(imgBackgound, imgBackgoundX, imgBackgoundY, Graphics.TOP | Graphics.LEFT);
              this.flushGraphics();
    }

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

  • Problem with Threads and a static variable

    I have a problem with the code below. I am yet to make sure that I understand the problem. Correct me if I am wrong please.
    Code functionality:
    A timer calls SetState every second. It sets the state and sets boolean variable "changed" to true. Then notifies a main process thread to check if the state changed to send a message.
    The problem as far I understand is:
    Assume the timer Thread calls SetState twice before the main process Thread runs. As a result, "changed" is set to true twice. However, since the main process is blocked twice during the two calls to SetState, when it runs it would have the two SetState timer threads blocked on its synchronized body. It will pass the first one, send the message and set "changed" to false since it was true. Now, it will pass the second thread, but here is the problem, "changed" is already set to false. As a result, it won't send the message even though it is supposed to.
    Would you please let me know if my understanding is correct? If so, what would you propose to resolve the problem? Should I call wait some other or should I notify in a different way?
    Thanks,
    B.D.
    Code:
    private static volatile boolean bChanged = false;
    private static Thread objMainProcess;
       protected static void Init(){
            objMainProcess = new Thread() {
                public void run() {
                    while( objMainProcess == Thread.currentThread() ) {
                       GetState();
            objMainProcess.setDaemon( true );
            objMainProcess.start();
        public static void initStatusTimer(){
            if(objTimer == null)
                 objTimer = new javax.swing.Timer( 1000, new java.awt.event.ActionListener(){
                    public void actionPerformed( java.awt.event.ActionEvent evt){
                              SetState();
        private static void SetState(){
            if( objMainProcess == null ) return;
            synchronized( objMainProcess ) {
                bChanged = true;
                try{
                    objMainProcess.notify();
                }catch( IllegalMonitorStateException e ) {}
        private static boolean GetState() {
            if( objMainProcess == null ) return false;
            synchronized( objMainProcess ) {
                if( bChanged) {
                    SendMessage();
                    bChanged = false;
                    return true;
                try {
                    objMainProcess.wait();
                }catch( InterruptedException e ) {}
                return false;
        }

    Thanks DrClap for your reply. Everything you said is right. It is not easy to make them alternate since SetState() could be called from different places where the state could be anything else but a status message. Like a GREETING message for example. It is a handshaking message but not a status message.
    Again as you said, There is a reason I can't call sendMessage() inside setState().
    The only way I was able to do it is by having a counter of the number of notifies that have been called. Every time notify() is called a counter is incremented. Now instead of just checking if "changed" flag is true, I also check if notify counter is greater than zero. If both true, I send the message. If "changed" flag is false, I check again if the notify counter is greater than zero, I send the message. This way it works, but it is kind of a patch than a good design fix. I am yet to find a good solution.
    Thanks,
    B.D.

  • Problem with Threads and "plase wait..."-Window

    Hi everyone,
    I have a problem that I'm not able to solve in any way... I have a time-consuming task (a file decryption) which I execute in a separate thread; I've used the SwingWorker class, like suggested by sun-tutorial, and it works right. The problem is that I have to wait that the decryption have finished before continuing with program-execution. Therefore I would like to display a "please wait"-window while the task runs. I've tryed all the possible ways I know but the problem is always the same: the waitWindow is displayed empty, the bounds are painted but the contents no; it's only painted when the decrypt-task has finished. Please help me, I have no more resources....
    decrypt-file code:
    public class DecryptFile {
      private String cryptedFileNameAndPath;
      private ByteArrayInputStream resultStream = null;
      // need for progress
      private int lengthOfTask;
      private int current = -1;
      private String statMessage;
      public DecryptFile(String encZipFileNameAndPath) {
        cryptedFileNameAndPath = encZipFileNameAndPath;
        //Compute length of task...
        // 0 for indeterminate
        lengthOfTask = 0;
      public ByteArrayInputStream getDecryptedInputStream() {
        return this.resultStream;
       * Called from ProgressBarDemo to start the task.
      public void go() {
        current = -1;
        final SwingWorker worker = new SwingWorker() {
          public Object construct() {
            return new ActualTask();
        worker.start();
       * Called from ProgressBarDemo to find out how much work needs
       * to be done.
      public int getLengthOfTask() {
        return lengthOfTask;
       * Called from ProgressBarDemo to find out how much has been done.
      public int getCurrent() {
        return current;
      public void stop() {
        current = lengthOfTask;
       * Called from ProgressBarDemo to find out if the task has completed.
      public boolean done() {
        if (current >= lengthOfTask)
          return true;
        else
          return false;
      public String getMessage() {
        return statMessage;
       * The actual long running task.  This runs in a SwingWorker thread.
      class ActualTask {
        ActualTask () {
          current = -1;
          statMessage = "";
          resultStream = AIUtil.getInputStreamFromEncZip(cryptedFileNameAndPath); //here the decryption happens
          current = 0;
          statMessage = "";
      }The code that calls decryption and displays waitWindow
          final WaitSplash wS = new WaitSplash("Please wait...");
          final DecryptFile cryptedTemplate = new DecryptFile (this.templateFile);
          cryptedTemplate.go();
          while (! cryptedTemplate.done()) {
            try {
              wait();
            } catch (Exception e) { }
          this.templateInputStream = cryptedTemplate.getDecryptedInputStream();
          wS.close();Thanks, thanks, thanks in advance!
    Edoardo

    Maybe you can try setting the priority of the long-running thread to be lower? so that the UI will be more responsive...

  • Problem with threads and graphics

    I have a thread that chooses paths for a Travelling salesman problem, it then calls a TSPdraw class and passes it the path, which the class then draws. the problem is when i have two threads it creates two windows but only draws a path in one of them. any ideas where i`m going wrong

    Are you using swing components? Swing isn't threadsafe. If you have multiple threads that want to update your UI you need to use the SwingUtilities.invokeLater(...)or invokeAndWait(...). There is a page in the swing tutorial about this at: http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html

  • Problem with threads and ProgressMonitor

    Dear Friends:
    I have a little problem with a thread and a ProgressMonitor. I have a long time process that runs in a thread (the thread is in an separate class). The thread has a ProgressMonitor that works fine and shows the tasks progress.
    But I need deactivate the main class(the main class is the user interface) until the thread ends.
    I use something like this:
    LongTask myTask=new LongTask();
    myTask.start();
    myTask.join();
    Now, the main class waits for the task to end, but the progress monitor don`t works fine: it shows only the dialog but not the progress bar.
    What's wrong?

    Is the dialog a modal dialog? This can block other UI updates.
    In general, you should make sure that it isn't modal, and that your workThread has a fairly low priority so that the UI can do its updating

  • Problem with threads and/or memory

    I'm developing an application where there are 3 threads. One of them sends a request to the other, and if the 2nd can't answer it, it sends it to the 3rd (similar to CPU -> CACHE -> MEMORY). When i run the program with 1000-10.000 requests, no problem occurs. When i run it with 300.000-1.000.000 requests, it sometimes hangs. Is this a problem with the garbage collector, or should it be related to the threads mecanism.
    (note: eache thread is in execution using a finite state machine)

    i had been running the program inside Netbeans.
    Running the jar using the command line outside
    Netbeans i have no more problems... Does Netbeans use
    it's own JVM?Depends how you set it up, but look under the options. There are settings for the compiler and jvm that it uses.

Maybe you are looking for