Usage of exits

Hi experts,
I would like to get some information on user exits. how to identify which user exit is in needed for what scenario.
USEREXIT_DELETE_DCUMENT  //// USEREXIT_MOVE_FIELD_TO_VBAK /// USEREXIT_MOVE_FIELD_TO_VBKD....like this , I just want to know in what situation we use these exits , can anybody provide with a small examples.
And whats the purpose of CMOD Tcode to indetify user exit and adding code to the include?  ( when we can use the above Mentioned userexits?) correct Me if i am wrong.
Thank you,
Kanna.
Edited by: kanna palle on May 31, 2010 7:50 PM

Go through these links
[Customer Exits (CMOD)|http://wiki.sdn.sap.com/wiki/display/ABAP/CustomerExits(CMOD)]
[What is the difference between SMOD and CMOD?|http://www.sap-img.com/abap/what-is-the-difference-between-smod-and-cmod.htm]
thanks
G. Lakshmipathi

Similar Messages

  • Usage Customer Exit EXIT_SAPLCUKO_003 / Enhancement CCUX0004

    Hello,
    I like to add new attributes of instances in LOVC during configuration of material in VA02. I found this Userexit and with function module CUDB_SET_VAL it is possible to add new values in the global table cudbd_pr_at_msg of function group CUDB. After calling EXIT_SAPLCUKO_003 SAP calls function module CUDB_PR_GET_AT_MSGS to get changed values.
    Is this the only solution to add new values, because exit EXIT_SAPLCUKO_003 has no changing parameters and there is no sample coding in CMOD or other documentations. Please add your sample to show your solution.
    Another question : It is possible to change attributes of multilevel instances? For example : Root instance is for material in sales document position, but in sales order BOM there are other configurable materials, which attributes should be maintained by userexit ( external configurator ), too. Normally only root instance is editable, but I want to add new attributes on the lower levels in background.
    Best regards,
    Markus

    Hi Markus,
    I have the problem that I want to delete some characteristics after configuration befor saving. Therefor I found the same exit and only your question in the web. Did you make further expierence with it? It would be very helpful if you could give me an answer.
    Best regards,
    Harald

  • Usage of Exit Plugs

    Dear All,
    Please give me the scenario where we should use an EXIT plug to close an application.
    In which hook method should the plug be fired?
    What are the possible parameters of the plug?
    Thank you.
    Regards,
    Prosenjit.

    hi,
    Please give me the scenario where we should use an EXIT plug to close an application.
    there are two scenarios :
    1. When you want to close a Window.
    2. When you want to open new window by giving the URL.
    What are the possible parameters of the plug?
    There are two parameters of this plug:
    1. URL of type String.
    2. Close Window type boolean.
    In which hook method should the plug be fired?
    You can call this plug on any ONAction.
    Ex :
    Do the following steps :
    -> Make an Outbound Plug to the Window.
    ->Make the type of Outbound plug to Exit Type.
    ->Add URL of type String as a parameter to the outbound plug of Window.
    ->Do remember to add Component Name in the Properties Tab of View ( othervs Calling Outbound plug of window from view wont b possible ).
    To open a new URL with closing the previous one write this Code in OnAction of Button : ( this Code can be get from Code Wizard too ).
    DATA lo_zexit TYPE REF TO ig_zexit . <zexit is name of my Component>
    lo_zexit = wd_this->get_zexit_ctr( ).
    lo_zexit->fire_out_window_plg(
    url = 'http://www.google.com' " string
    Similarly you can do for Closing a Window using parameter Close Window.
    Thanx.
    Edited by: Saurav Mago on Apr 17, 2009 10:32 AM

  • Is it possible to work with Field Exits in R/3 Enterp. Basis 6.20???

    How could I work with them?

    Yes you can.
    SE 38 --> Prog RSMODPRF
    http://www.sapdevelopment.co.uk/enhance/fexits.htm
    But Have a look at OSS note 29377 as well:
    Symptom
    Problems and questions concerning field exits
    Other terms
    FAQ, Q+A, SMOD/CMOD, field exits
    Reason and Prerequisites
    Note
    Field exits are frozen on the 4.6C maintenance level and are not further developed. This means that the existing functionality is kept with all restrictions (see also the last item below). Existing exits can be further used and are called at runtime as usual.
    Existing exits can be maintained using program RSMODPRF (run the
    program using transaction SE38). Activation of the field exits and
    assignment of the dynpros can also be carried out using program
    RSMODPRF. For this purpose, the program must be started without
    parameters (input fields remain blank).
    If required, new field exits can be created using program
    RSMODPRF (see the program documentation).
    Solution
    1. Field exit was created with CMOD, but is not processed when calling the screen.
    Since the field exit is not processed until PAI, an action must be triggered on the screen (Return, Save, ...).
    Set profile parameter abap/fieldexit to YES and restart the system.
    After activating the function module FIELD_EXIT... and the field exit, leave the transaction on whose screen the field exit is to be executed. The screen is not generated until the transaction is started.
    Do not work on different application servers since there may be some delay before the field exit is activated.
    The profile parameter must be set on all or none of the application servers.
    If the field exit is to only be active on specific screens, check whether you chose the correct program and the correct screen number (take care with subscreens).
    Generate the screen on which the exit should be active using SE51. It is possible that it was not correctly generated. If you want to be sure that all screens that use the data element are regenerated, you can transfer Report rsmodfdg from the correction instructions and start it with SE38. The Report uses the affected data element as the input parameter and regenerates all screens that use the data element.
    Using SE51 -> Field list, check that the screen field does have a reference to a data element. In the name of the field exit, use the name of the data element and not the field name.
    After transport, field exits are marked as active but will not be processed. Tip: First try deactivating the field exit once more and then activate it again.
    2. How is performance affected by setting abap/fieldexit?
    If a screen is generated and the profile parameter is set, a check is run on 2 tables (TDDIR, TDDIRS) to see whether a field exit must be generated for the respective field. In practice, the screen load is not generated until the screen is selected after an update. The user should not notice any difference because screen generation is very fast.
    3. Can you read the contents of other screen fields in the field exit?
    In principle, every field exit can store its value in the global variables of the function group (TOP) and hence make them available to other field exits. Note here that field exits are always called, not only if an entry is made in the field or if the field is empty. In addition, it is not possible to make any assumptions about the order in which the field exits will be called in the future.
    4. How does the field exit behave on step loop fields ?
    After the user has entered data, the field exit is called in PAI as often as there are visible fields in the step loop. The system variable SY-STEPL is incremented each time. If a new value is assigned to the field, it is displayed in the module between LOOP and ENDLOOP. This module is also called once for each visible step loop line.
    5. Can field exits be debugged ?
    No. Field exits must be tested separately in the ABAP/4 Development Workbench. For errors which only occur in the screen environment, it is helpful to write interesting variables to the file system using TRANSFER... . These can then be analysed there.
    6. What can you do if the field contents are no longer transported to ABAP/4?
    Check whether a value is assigned to the field OUTPUT.
    7. When is the field exit called if a conversion exit is attached to the data element?
    The field exit is called after the conversion exit. This means that the INPUT field receives the data in the same format as the ABAP/4 program receives it.
    8. Although a global field exit is inactive, a function module is called which does not exist (for example FIELD_EXIT_PROGRAMM_@). This can lead to an ABAP dump error when function module FIELD_EXIT_<data element name> is called.
    This is an error in the kernel which no longer occurs as of Release 3.0C. As a temporary measure, it is useful to assign a program and a screen which do not exist to the field exit and then activate the field exit.
    Due to performance reasons, the active/inactive indicator is stored in the screenload. This can cause inconsistencies between Source and Load. Generate the affected screen with se51. If you want to be sure that all screens that use the data element are regenerated, you can transfer Report rsmodfdg from the correction instructions and start it with se38. The Report uses the affected data element as the input parameter and regenerates all screens that use the data element.
    9. Field exit is not visible in CMOD, although created.
    If you want to create a field exit for a data element, a function module is proposed with the name FIELD_EXIT_<data_element>. This function module must exist for the field exit to work. If you do not create this function module, but do create one with a suffix, the data element is not displayed in CMOD.
    10. Field exit is not executed although it is active.
    Fields which do not have the 'Input field' attribute usually do not trigger a field exit. The field exit is designed to allow an extended input check. It is therefore only called for input fields - even if they are not ready for input at runtime of the application by LOOP AT SCREEN.
    This rule does not apply, however, if the field is located within a steploop. Here the field will be always activated, even if it is invisible.
    Field exits can only be executed for fields that are directly related to the dictionary. If the relation is indirect, i.e. via an ABAP declaration (<fieldname> LIKE <dictionary element>), no field exit can be executed.
    11. Field exits do not work on selection screens.
    Results from the previous item since ABAP-internal fields and never the original Dictionary fields are used on selection screens.
    12. Field exists do not work on check buttons.
    Field exits are only intended for input fields. As check buttons count as graphical elements, you cannot install field exits on them.
    13. How can all screens that use a data element be generated?
    If you want to be sure that all screens that use a specific data element are regenerated, you can transfer Report rsmodfdg from the correction instructions into a customer report (e.g. zsmodfdg). The Report regenerates all screens. In this way, you can ensure that active field exits refer to screens and that inactive exits cannot be called on any screen. The Report uses the affected data element as the input parameter. The affected data element is in the name of the exit: FIELD_EXIT_<data element name>.
    14. Restriction of usage
    Field exit technology was developed for input fields on dynpros and cannot be used for other/new dynpro elements. This means that this technology does not offer support for the new ScreenPainter elements such as graphical elements (e.g. checkbuttons, radiobuttons, dropdown listboxes), controls (except for table controls which are supported like a step loop), or selection screens.
    Erwan

  • Ignore exit from jython

    Hi,     
    I would like to ignore sys.exit(0) caused by Python function.
    //myscript.py
    def usage()
          sys.stderr.write("USAGE: %s [options] [file] Version: %s"  % (sys.argv[0], VERSION))
          sys.exit(2)
           .......................//Test.java
    interp.exec("Lib.myscript.usage()");this code causes the end of the JVM, but I would like return at my application (Test.java).

    Excuse me for error:
    def usage()
          sys.stderr.write("USAGE: %s [options] [file] Version: %s"  % (sys.argv[0], VERSION))
    def main()
        for o, a in opts:
            if o in ("-h", "--help"):
                usage()
                sys.exit(0)
            elif o in ("-a", "--add"):
                try:               
                  sum = sum + int(a)                   
                except ValueError:
                    sum = 0

  • [SOLVED] tv_grab_nl_py works with python 2.6.5, fails on 3.1.2

    Hi All,
    I have updated my mediacenter. Now tv_grab_nl_py does not work anymore:
    [cedric@tv ~]$ tv_grab_nl_py --output ~/listings.xml --fast
    File "/usr/bin/tv_grab_nl_py", line 341
    print 'tv_grab_nl_py: A grabber that grabs tvguide data from tvgids.nl\n'
    ^
    SyntaxError: invalid syntax
    [cedric@tv ~]$
    the version of python on the mediacenter (running arch linux):
    [cedric@tv ~]$ python
    Python 3.1.2 (r312:79147, Oct 4 2010, 12:35:40)
    [GCC 4.5.1] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    I have copied the file to my laptop, there it looks like it's working:
    ./tv_grab_nl_py --output ~/listings.xml --fast
    Config file /home/cedric/.xmltv/tv_grab_nl_py.conf not found.
    Re-run me with the --configure flag.
    cedric@laptop:~$
    the version of python on my laptop (running arch linux):
    cedric@laptop:~$ python
    Python 2.6.5 (r265:79063, Apr 1 2010, 05:22:20)
    [GCC 4.4.3 20100316 (prerelease)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    the script I'm trying to run:
    [cedric@tv ~]$ cat tv_grab_nl_py
    #!/usr/bin/env python
    # $LastChangedDate: 2009-11-14 10:06:41 +0100 (Sat, 14 Nov 2009) $
    # $Rev: 104 $
    # $Author: pauldebruin $
    SYNOPSIS
    tv_grab_nl_py is a python script that trawls tvgids.nl for TV
    programming information and outputs it in XMLTV-formatted output (see
    http://membled.com/work/apps/xmltv). Users of MythTV
    (http://www.mythtv.org) will appreciate the output generated by this
    grabber, because it fills the category fields, i.e. colors in the EPG,
    and has logos for most channels automagically available. Check the
    website below for screenshots. The newest version of this script can be
    found here:
    http://code.google.com/p/tvgrabnlpy/
    USAGE
    Check the web site above and/or run script with --help and start from there
    HISTORY
    tv_grab_nl_py used to be called tv_grab_nl_pdb, first released on
    2003/07/09. The name change was necessary because more and more people
    are actively contributing to this script and I always disliked using my
    initials (I was just too lazy to change it). At the same time I switched
    from using CVS to SVN and as a result the version numbering scheme has
    changed. The lastest official release of tv_grab_nl_pdb is 0.48. The
    first official release of tv_grab_nl_py is 6.
    QUESTIONS
    Questions (and patches) are welcome at: paul at pwdebruin dot net.
    IMPORTANT NOTES
    If you were using tv_grab_nl from the XMLTV bundle then enable the
    compat flag or use the --compat command-line option. Otherwise, the
    xmltvid's are wrong and you will not see any new data in MythTV.
    CONTRIBUTORS
    Main author: Paul de Bruin (paul at pwdebruin dot net)
    Michel van der Laan made available his extensive collection of
    high-quality logos that is used by this script.
    Michael Heus has taken the effort to further enhance this script so that
    it now also includes:
    - Credit info: directors, actors, presenters and writers
    - removal of programs that are actually just groupings/broadcasters
    (e.g. "KETNET", "Wild Friday", "Z@pp")
    - Star-rating for programs tipped by tvgids.nl
    - Black&White, Stereo and URL info
    - Better detection of Movies
    - and much, much more...
    Several other people have provided feedback and patches (these are the
    people I could find in my email archive, if you are missing from this
    list let me know):
    Huub Bouma, Roy van der Kuil, Remco Rotteveel, Mark Wormgoor, Dennis van
    Onselen, Hugo van der Kooij, Han Holl, Ian Mcdonald, Udo van den Heuvel.
    # Modules we need
    import re, urllib2, getopt, sys
    import time, random
    import htmlentitydefs, os, os.path, pickle
    from string import replace, split, strip
    from threading import Thread
    from xml.sax import saxutils
    # Extra check for the datetime module
    try:
    import datetime
    except:
    sys.stderr.write('This script needs the datetime module that was introduced in Python version 2.3.\n')
    sys.stderr.write('You are running:\n')
    sys.stderr.write('%s\n' % sys.version)
    sys.exit(1)
    # XXX: fix to prevent crashes in Snow Leopard [Robert Klep]
    if sys.platform == 'darwin' and sys.version_info[:3] == (2, 6, 1):
    try:
    urllib2.urlopen('http://localhost.localdomain')
    except:
    pass
    # do extra debug stuff
    debug = 1
    try:
    import redirect
    except:
    debug = 0
    pass
    # globals
    # compile only one time
    r_entity = re.compile(r'&(#x[0-9A-Fa-f]+|#[0-9]+|[A-Za-z]+);')
    tvgids = 'http://www.tvgids.nl/'
    uitgebreid_zoeken = tvgids + 'zoeken/'
    # how many seconds to wait before we timeout on a
    # url fetch, 10 seconds seems reasonable
    global_timeout = 10
    # Wait a random number of seconds between each page fetch.
    # We want to be nice and not hammer tvgids.nl (these are the
    # friendly people that provide our data...).
    # Also, it appears tvgids.nl throttles its output.
    # So there, there is not point in lowering these numbers, if you
    # are in a hurry, use the (default) fast mode.
    nice_time = [1, 2]
    # Maximum length in minutes of gaps/overlaps between programs to correct
    max_overlap = 10
    # Strategy to use for correcting overlapping prgramming:
    # 'average' = use average of stop and start of next program
    # 'stop' = keep stop time of current program and adjust start time of next program accordingly
    # 'start' = keep start time of next program and adjust stop of current program accordingly
    # 'none' = do not use any strategy and see what happens
    overlap_strategy = 'average'
    # Experimental strategy for clumping overlapping programming, all programs that overlap more
    # than max_overlap minutes, but less than the length of the shortest program are clumped
    # together. Highly experimental and disabled for now.
    do_clump = False
    # Create a category translation dictionary
    # Look in mythtv/themes/blue/ui.xml for all category names
    # The keys are the categories used by tvgids.nl (lowercase please)
    cattrans = { 'amusement' : 'Talk',
    'animatie' : 'Animated',
    'comedy' : 'Comedy',
    'documentaire' : 'Documentary',
    'educatief' : 'Educational',
    'erotiek' : 'Adult',
    'film' : 'Film',
    'muziek' : 'Art/Music',
    'informatief' : 'Educational',
    'jeugd' : 'Children',
    'kunst/cultuur' : 'Arts/Culture',
    'misdaad' : 'Crime/Mystery',
    'muziek' : 'Music',
    'natuur' : 'Science/Nature',
    'nieuws/actualiteiten' : 'News',
    'overige' : 'Unknown',
    'religieus' : 'Religion',
    'serie/soap' : 'Drama',
    'sport' : 'Sports',
    'theater' : 'Arts/Culture',
    'wetenschap' : 'Science/Nature'}
    # Create a role translation dictionary for the xmltv credits part
    # The keys are the roles used by tvgids.nl (lowercase please)
    roletrans = {'regie' : 'director',
    'acteurs' : 'actor',
    'presentatie' : 'presenter',
    'scenario' : 'writer'}
    # We have two sources of logos, the first provides the nice ones, but is not
    # complete. We use the tvgids logos to fill the missing bits.
    logo_provider = [ 'http://visualisation.tudelft.nl/~paul/logos/gif/64x64/',
    'http://static.tvgids.nl/gfx/zenders/' ]
    logo_names = {
    1 : [0, 'ned1'],
    2 : [0, 'ned2'],
    3 : [0, 'ned3'],
    4 : [0, 'rtl4'],
    5 : [0, 'een'],
    6 : [0, 'canvas_color'],
    7 : [0, 'bbc1'],
    8 : [0, 'bbc2'],
    9 : [0,'ard'],
    10 : [0,'zdf'],
    11 : [1, 'rtl'],
    12 : [0, 'wdr'],
    13 : [1, 'ndr'],
    14 : [1, 'srsudwest'],
    15 : [1, 'rtbf1'],
    16 : [1, 'rtbf2'],
    17 : [0, 'tv5'],
    18 : [0, 'ngc'],
    19 : [1, 'eurosport'],
    20 : [1, 'tcm'],
    21 : [1, 'cartoonnetwork'],
    24 : [0, 'canal+red'],
    25 : [0, 'mtv-color'],
    26 : [0, 'cnn'],
    27 : [0, 'rai'],
    28 : [1, 'sat1'],
    29 : [0, 'discover-spacey'],
    31 : [0, 'rtl5'],
    32 : [1, 'trt'],
    34 : [0, 'veronica'],
    35 : [0, 'tmf'],
    36 : [0, 'sbs6'],
    37 : [0, 'net5'],
    38 : [1, 'arte'],
    39 : [0, 'canal+blue'],
    40 : [0, 'at5'],
    46 : [0, 'rtl7'],
    49 : [1, 'vtm'],
    50 : [1, '3sat'],
    58 : [1, 'pro7'],
    59 : [1, 'kanaal2'],
    60 : [1, 'vt4'],
    65 : [0, 'animal-planet'],
    73 : [1, 'mezzo'],
    86 : [0, 'bbc-world'],
    87 : [1, 'tve'],
    89 : [1, 'nick'],
    90 : [1, 'bvn'],
    91 : [0, 'comedy_central'],
    92 : [0, 'rtl8'],
    99 : [1, 'sport1_1'],
    100 : [0, 'rtvu'],
    101 : [0, 'tvwest'],
    102 : [0, 'tvrijnmond'],
    103 : [1, 'tvnoordholland'],
    104 : [1, 'bbcprime'],
    105 : [1, 'spiceplatinum'],
    107 : [0, 'canal+yellow'],
    108 : [0, 'tvnoord'],
    109 : [0, 'omropfryslan'],
    114 : [0, 'omroepbrabant']}
    # A selection of user agents we will impersonate, in an attempt to be less
    # conspicuous to the tvgids.nl police.
    user_agents = [ 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)',
    'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/2.0.0.9',
    'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)',
    'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.7) Gecko/20060909 Firefox/1.5.0.7',
    'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)',
    'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.9) Gecko/20071105 Firefox/2.0.0.9',
    'Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/2.0.0.9',
    'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.8) Gecko/20071022 Ubuntu/7.10 (gutsy) Firefox/2.0.0.8'
    # Work in progress, the idea is to cache program categories and
    # descriptions to eliminate a lot of page fetches from tvgids.nl
    # for programs that do not have interesting/changing descriptions
    class ProgramCache:
    A cache to hold program name and category info.
    TVgids stores the detail for each program on a separate URL with an
    (apparently unique) ID. This cache stores the fetched info with the ID.
    New fetches will use the cached info instead of doing an (expensive)
    page fetch.
    def __init__(self, filename=None):
    Create a new ProgramCache object, optionally from file
    # where we store our info
    self.filename = filename
    if filename == None:
    self.pdict = {}
    else:
    if os.path.isfile(filename):
    self.load(filename)
    else:
    self.pdict = {}
    def load(self, filename):
    Loads a pickled cache dict from file
    try:
    self.pdict = pickle.load(open(filename,'r'))
    except:
    sys.stderr.write('Error loading cache file: %s (possibly corrupt)' % filename)
    sys.exit(2)
    def dump(self, filename):
    Dumps a pickled cache, and makes sure it is valid
    if os.access(filename, os.F_OK):
    try:
    os.remove(filename)
    except:
    sys.stderr.write('Cannot remove %s, check permissions' % filename)
    pickle.dump(self.pdict, open(filename+'.tmp', 'w'))
    os.rename(filename+'.tmp', filename)
    def query(self, program_id):
    Updates/gets/whatever.
    try:
    return self.pdict[program_id]
    except:
    return None
    def add(self, program):
    Adds a program
    self.pdict[program['ID']] = program
    def clear(self):
    Clears the cache (i.e. empties it)
    self.pdict = {}
    def clean(self):
    Removes all cached programming before today.
    Also removes erroneously cached programming.
    now = time.localtime()
    dnow = datetime.datetime(now[0],now[1],now[2])
    for key in self.pdict.keys():
    try:
    if self.pdict[key]['stop-time'] < dnow or self.pdict[key]['name'].lower() == 'onbekend':
    del self.pdict[key]
    except:
    pass
    def usage():
    print 'tv_grab_nl_py: A grabber that grabs tvguide data from tvgids.nl\n'
    print 'and stores it in XMLTV-combatible format.\n'
    print 'Usage:'
    print '--help, -h = print this info'
    print '--configure = create configfile (overwrites existing file)'
    print '--config-file = name of the configuration file (default = ~/.xmltv/tv_grab_py.conf'
    print '--capabilities = xmltv required option'
    print '--desc-length = maximum allowed length of programme descriptions in bytes.'
    print '--description = prints a short description of the grabber'
    print '--output = file where to put the output'
    print '--days = # number of days to grab'
    print '--preferredmethod = returns the preferred method to be called'
    print '--fast = do not grab descriptions of programming'
    print '--slow = grab descriptions of programming'
    print '--quiet = suppress all output'
    print '--compat = append tvgids.nl to the xmltv id (use this if you were using tv_grab_nl)'
    print '--logos 0/1 = insert urls to channel icons (mythfilldatabase will then use these)'
    print '--nocattrans = do not translate the grabbed genres into MythTV-genres'
    print '--cache = cache descriptions and use the file to store'
    print '--clean_cache = clean the cache file before fetching'
    print '--clear_cache = empties the cache file before fetching data'
    print '--slowdays = grab slowdays initial days and the rest in fast mode'
    print '--max_overlap = maximum length of overlap between programming to correct [minutes]'
    print '--overlap_strategy = what strategy to use to correct overlaps (check top of source code)'
    def filter_line_identity(m, defs=htmlentitydefs.entitydefs):
    # callback: translate one entity to its ISO Latin value
    k = m.group(1)
    if k.startswith("#") and k[1:] in xrange(256):
    return chr(int(k[1:]))
    try:
    return defs[k]
    except KeyError:
    return m.group(0) # use as is
    def filter_line(s):
    Removes unwanted stuff in strings (adapted from tv_grab_be)
    # do the latin1 stuff
    s = r_entity.sub(filter_line_identity, s)
    s = replace(s,'&nbsp;',' ')
    # Ik vermoed dat de volgende drie regels overbodig zijn, maar ze doen
    # niet veel kwaad -- Han Holl
    s = replace(s,'\r',' ')
    x = re.compile('(<.*?>)') # Udo
    s = x.sub('', s) #Udo
    s = replace(s, '~Q', "'")
    s = replace(s, '~R', "'")
    # Hmm, not sure if I understand this. Without it, mythfilldatabase barfs
    # on program names like "Steinbrecher &..."
    # We most create valid XML -- Han Holl
    s = saxutils.escape(s)
    return s
    def calc_timezone(t):
    Takes a time from tvgids.nl and formats it with all the required
    timezone conversions.
    in: '20050429075000'
    out:'20050429075000 (CET|CEST)'
    Until I have figured out how to correctly do timezoning in python this method
    will bork if you are not in a zone that has the same DST rules as 'Europe/Amsterdam'.
    year = int(t[0:4])
    month = int(t[4:6])
    day = int(t[6:8])
    hour = int(t[8:10])
    minute = int(t[10:12])
    #td = {'CET': '+0100', 'CEST': '+0200'}
    #td = {'CET': '+0100', 'CEST': '+0200', 'W. Europe Standard Time' : '+0100', 'West-Europa (standaardtijd)' : '+0100'}
    td = {0 : '+0100', 1 : '+0200'}
    pt = time.mktime((year,month,day,hour,minute,0,0,0,-1))
    timezone=''
    try:
    #timezone = time.tzname[(time.localtime(pt))[-1]]
    timezone = (time.localtime(pt))[-1]
    except:
    sys.stderr.write('Cannot convert time to timezone')
    return t+' %s' % td[timezone]
    def format_timezone(td):
    Given a datetime object, returns a string in XMLTV format
    tstr = td.strftime('%Y%m%d%H%M00')
    return calc_timezone(tstr)
    def get_page_internal(url, quiet=0):
    Retrieves the url and returns a string with the contents.
    Optionally, returns None if processing takes longer than
    the specified number of timeout seconds.
    txtdata = None
    txtheaders = {'Keep-Alive' : '300',
    'User-Agent' : user_agents[random.randint(0, len(user_agents)-1)] }
    try:
    #fp = urllib2.urlopen(url)
    rurl = urllib2.Request(url, txtdata, txtheaders)
    fp = urllib2.urlopen(rurl)
    lines = fp.readlines()
    page = "".join(lines)
    return page
    except:
    if not quiet:
    sys.stderr.write('Cannot open url: %s\n' % url)
    return None
    class FetchURL(Thread):
    A simple thread to fetch a url with a timeout
    def __init__ (self, url, quiet=0):
    Thread.__init__(self)
    self.quiet = quiet
    self.url = url
    self.result = None
    def run(self):
    self.result = get_page_internal(self.url, self.quiet)
    def get_page(url, quiet=0):
    Wrapper around get_page_internal to catch the
    timeout exception
    try:
    fu = FetchURL(url, quiet)
    fu.start()
    fu.join(global_timeout)
    return fu.result
    except:
    if not quiet:
    sys.stderr.write('get_page timed out on (>%s s): %s\n' % (global_timeout, url))
    return None
    def get_channels(file, quiet=0):
    Get a list of all available channels and store these
    in a file.
    # store channels in a dict
    channels = {}
    # tvgids stores several instances of channels, we want to
    # find all the possibile channels
    channel_get = re.compile('<optgroup label=.*?>(.*?)</optgroup>', re.DOTALL)
    # this is how we will find a (number, channel) instance
    channel_re = re.compile('<option value="([0-9]+)" >(.*?)</option>', re.DOTALL)
    # this is where we will try to find our channel list
    total = get_page(uitgebreid_zoeken, quiet)
    if total == None:
    return
    # get a list of match objects of all the <select blah station>
    stations = channel_get.finditer(total)
    # and create a dict of number, channel_name pairs
    # we do this this way because several instances of the
    # channel list are stored in the url and not all of the
    # instances have all the channels, this way we get them all.
    for station in stations:
    m = channel_re.finditer(station.group(0))
    for p in m:
    try:
    a = int(p.group(1))
    b = filter_line(p.group(2))
    channels[a] = b
    except:
    sys.stderr.write('Oops, [%s,%s] does not look like a valid channel, skipping it...\n' % (p.group(1),p.group(2)))
    # sort on channel number (arbitrary but who cares)
    keys = channels.keys()
    keys.sort()
    # and create a file with the channels
    f = open(file,'w')
    for k in keys:
    f.write("%s %s\n" % (k, channels[k]))
    f.close()
    def get_channel_all_days(channel, days, quiet=0):
    Get all available days of programming for channel number
    The output is a list of programming in order where each row
    contains a dictionary with program information.
    now = datetime.datetime.now()
    programs = []
    # Tvgids shows programs per channel per day, so we loop over the number of days
    # we are required to grab
    for offset in range(0, days):
    channel_url = 'http://www.tvgids.nl/zoeken/?d=%i&z=%s' % (offset, channel)
    # For historic purposes, the old style url that gave us a full week in advance:
    # channel_url = 'http://www.tvgids.nl/zoeken/?trefwoord=Titel+of+trefwoord&interval=0&timeslot='+\
    # '&station=%s&periode=%i&genre=&order=0' % (channel,days-1)
    # Sniff, we miss you...
    if offset > 0:
    time.sleep(random.randint(nice_time[0], nice_time[1]))
    # get the raw programming for the day
    total = get_page(channel_url, quiet)
    if total == None:
    return programs
    # Setup a number of regexps
    # checktitle will match the title row in H2 tags of the daily overview page, e.g.
    # <h2>zondag 19 oktober 2008</h2>
    checktitle = re.compile('<h2>(.*?)</h2>',re.DOTALL)
    # getrow will locate each row with program details
    getrow = re.compile('<a href="/programma/(.*?)</a>',re.DOTALL)
    # parserow matches the required program info, with groups:
    # 1 = program ID
    # 2 = broadcast times
    # 3 = program name
    parserow = re.compile('(.*?)/.*<span class="time">(.*?)</span>.*<span class="title">(.*?)</span>', re.DOTALL)
    # normal begin and end times
    times = re.compile('([0-9]+:[0-9]+) - ([0-9]+:[0-9]+)?')
    # Get the day of month listed on the page as well as the expected date we are grabbing and compare these.
    # If these do not match, we skip parsing the programs on the page and issue a warning.
    #dayno = int(checkday.search(total).group(1))
    title = checktitle.search(total)
    if title:
    title = title.group(1)
    dayno = title.split()[1]
    else:
    sys.stderr.write('\nOops, there was a problem with page %s. Skipping it...\n' % (channel_url))
    continue
    expected = now + datetime.timedelta(days=offset)
    if (not dayno.isdigit() or int(dayno) != expected.day):
    sys.stderr.write('\nOops, did not expect page %s to list programs for "%s", skipping it...\n' % (channel_url,title))
    continue
    # and find relevant programming info
    allrows = getrow.finditer(total)
    for r in allrows:
    detail = parserow.search(r.group(1))
    if detail != None:
    # default times
    start_time = None
    stop_time = None
    # parse for begin and end times
    t = times.search(detail.group(2))
    if t != None:
    start_time = t.group(1)
    stop_time = t.group(2)
    program_url = 'http://www.tvgids.nl/programma/' + detail.group(1) + '/'
    program_name = detail.group(3)
    # store time, name and detail url in a dictionary
    tdict = {}
    tdict['start'] = start_time
    tdict['stop'] = stop_time
    tdict['name'] = program_name
    if tdict['name'] == '':
    tdict['name'] = 'onbekend'
    tdict['url'] = program_url
    tdict['ID'] = detail.group(1)
    tdict['offset'] = offset
    #Add star rating if tipped by tvgids.nl
    tdict['star-rating'] = '';
    if r.group(1).find('Tip') != -1:
    tdict['star-rating'] = '4/5'
    # and append the program to the list of programs
    programs.append(tdict)
    # done
    return programs
    def make_daytime(time_string, offset=0, cutoff='00:00', stoptime=False):
    Given a string '11:35' and an offset from today,
    return a datetime object. The cuttoff specifies the point where the
    new day starts.
    Examples:
    In [2]:make_daytime('11:34',0)
    Out[2]:datetime.datetime(2006, 8, 3, 11, 34)
    In [3]:make_daytime('11:34',1)
    Out[3]:datetime.datetime(2006, 8, 4, 11, 34)
    In [7]:make_daytime('11:34',0,'12:00')
    Out[7]:datetime.datetime(2006, 8, 4, 11, 34)
    In [4]:make_daytime('11:34',0,'11:34',False)
    Out[4]:datetime.datetime(2006, 8, 3, 11, 34)
    In [5]:make_daytime('11:34',0,'11:34',True)
    Out[5]:datetime.datetime(2006, 8, 4, 11, 34)
    h,m = [int(x) for x in time_string.split(':')];
    hm = int(time_string.replace(':',''))
    chm = int(cutoff.replace(':',''))
    # check for the cutoff, if the time is before the cutoff then
    # add a day
    extra_day = 0
    if (hm < chm) or (stoptime==True and hm == chm):
    extra_day = 1
    # and create a datetime object, DST is handled at a later point
    pt = time.localtime()
    dt = datetime.datetime(pt[0],pt[1],pt[2],h,m)
    dt = dt + datetime.timedelta(offset+extra_day)
    return dt
    def correct_times(programs, quiet=0):
    Parse a list of programs as generated by get_channel_all_days() and
    convert begin and end times to xmltv compatible times in datetime objects.
    if programs == []:
    return programs
    # the start time of programming for this day, times *before* this time are
    # assumed to be on the next day
    day_start_time = '06:00'
    # initialise using the start time of the first program on this day
    if programs[0]['start'] != None:
    day_start_time = programs[0]['start']
    for program in programs:
    if program['start'] == program['stop']:
    program['stop'] = None
    # convert the times
    if program['start'] != None:
    program['start-time'] = make_daytime(program['start'], program['offset'], day_start_time)
    else:
    program['start-time'] = None
    if program['stop'] != None:
    program['stop-time'] = make_daytime(program['stop'], program['offset'], day_start_time, stoptime=True)
    # extra correction, needed because the stop time of a program may be on the next day, after the
    # day cutoff. For example:
    # 06:00 - 23:40 Long Program
    # 23:40 - 00:10 Lala
    # 00:10 - 08:00 Wawa
    # This puts the end date of Wawa on the current, instead of the next day. There is no way to detect
    # this with a single cutoff in make_daytime. Therefore, check if there is a day difference between
    # start and stop dates and correct if necessary.
    if program['start-time'] != None:
    # make two dates
    start = program['start-time']
    stop = program['stop-time']
    single_day = datetime.timedelta(1)
    startdate = datetime.datetime(start.year,start.month,start.day)
    stopdate = datetime.datetime(stop.year,stop.month,stop.day)
    if startdate - stopdate == single_day:
    program['stop-time'] = program['stop-time'] + single_day
    else:
    program['stop-time'] = None
    def parse_programs(programs, offset=0, quiet=0):
    Parse a list of programs as generated by get_channel_all_days() and
    convert begin and end times to xmltv compatible times.
    # good programs
    good_programs = []
    # calculate absolute start and stop times
    correct_times(programs, quiet)
    # next, correct for missing end time and copy over all good programming to the
    # good_programs list
    for i in range(len(programs)):
    # Try to correct missing end time by taking start time from next program on schedule
    if (programs[i]['stop-time'] == None and i < len(programs)-1):
    if not quiet:
    sys.stderr.write('Oops, "%s" has no end time. Trying to fix...\n' % programs[i]['name'])
    programs[i]['stop-time'] = programs[i+1]['start-time']
    # The common case: start and end times are present and are not
    # equal to each other (yes, this can happen)
    if programs[i]['start-time'] != None and \
    programs[i]['stop-time'] != None and \
    programs[i]['start-time'] != programs[i]['stop-time']:
    good_programs.append(programs[i])
    # Han Holl: try to exclude programs that stop before they begin
    for i in range(len(good_programs)-1,-1,-1):
    if good_programs[i]['stop-time'] <= good_programs[i]['start-time']:
    if not quiet:
    sys.stderr.write('Deleting invalid stop/start time: %s\n' % good_programs[i]['name'])
    del good_programs[i]
    # Try to exclude programs that only identify a group or broadcaster and have overlapping start/end times with
    # the actual programs
    for i in range(len(good_programs)-2,-1,-1):
    if good_programs[i]['start-time'] <= good_programs[i+1]['start-time'] and \
    good_programs[i]['stop-time'] >= good_programs[i+1]['stop-time']:
    if not quiet:
    sys.stderr.write('Deleting grouping/broadcaster: %s\n' % good_programs[i]['name'])
    del good_programs[i]
    for i in range(len(good_programs)-1):
    # PdB: Fix tvgids start-before-end x minute interval overlap. An overlap (positive or
    # negative) is halved and each half is assigned to the adjacent programmes. The maximum
    # overlap length between programming is set by the global variable 'max_overlap' and is
    # default 10 minutes. Examples:
    # Positive overlap (= overlap in programming):
    # 10:55 - 12:00 Lala
    # 11:55 - 12:20 Wawa
    # is transformed in:
    # 10:55 - 11.57 Lala
    # 11:57 - 12:20 Wawa
    # Negative overlap (= gap in programming):
    # 10:55 - 11:50 Lala
    # 12:00 - 12:20 Wawa
    # is transformed in:
    # 10:55 - 11.55 Lala
    # 11:55 - 12:20 Wawa
    stop = good_programs[i]['stop-time']
    start = good_programs[i+1]['start-time']
    dt = stop-start
    avg = start + dt / 2
    overlap = 24*60*60*dt.days + dt.seconds
    # check for the size of the overlap
    if 0 < abs(overlap) <= max_overlap*60:
    if not quiet:
    if overlap > 0:
    sys.stderr.write('"%s" and "%s" overlap %s minutes. Adjusting times.\n' % \
    (good_programs[i]['name'],good_programs[i+1]['name'],overlap / 60))
    else:
    sys.stderr.write('"%s" and "%s" have gap of %s minutes. Adjusting times.\n' % \
    (good_programs[i]['name'],good_programs[i+1]['name'],abs(overlap) / 60))
    # stop-time of previous program wins
    if overlap_strategy == 'stop':
    good_programs[i+1]['start-time'] = good_programs[i]['stop-time']
    # start-time of next program wins
    elif overlap_strategy == 'start':
    good_programs[i]['stop-time'] = good_programs[i+1]['start-time']
    # average the difference
    elif overlap_strategy == 'average':
    good_programs[i]['stop-time'] = avg
    good_programs[i+1]['start-time'] = avg
    # leave as is
    else:
    pass
    # Experimental strategy to make sure programming does not disappear. All programs that overlap more
    # than the maximum overlap length, but less than the shortest length of the two programs are
    # clumped.
    if do_clump:
    for i in range(len(good_programs)-1):
    stop = good_programs[i]['stop-time']
    start = good_programs[i+1]['start-time']
    dt = stop-start
    overlap = 24*60*60*dt.days + dt.seconds
    length0 = good_programs[i]['stop-time'] - good_programs[i]['start-time']
    length1 = good_programs[i+1]['stop-time'] - good_programs[i+1]['start-time']
    l0 = length0.days*24*60*60 + length0.seconds
    l1 = length1.days*24*60*60 + length0.seconds
    if abs(overlap) >= max_overlap*60 <= min(l0,l1)*60 and \
    not good_programs[i].has_key('clumpidx') and \
    not good_programs[i+1].has_key('clumpidx'):
    good_programs[i]['clumpidx'] = '0/2'
    good_programs[i+1]['clumpidx'] = '1/2'
    good_programs[i]['stop-time'] = good_programs[i+1]['stop-time']
    good_programs[i+1]['start-time'] = good_programs[i]['start-time']
    # done, nothing to see here, please move on
    return good_programs
    def get_descriptions(programs, program_cache=None, nocattrans=0, quiet=0, slowdays=0):
    Given a list of programs, from get_channel, retrieve program information
    # This regexp tries to find details such as Genre, Acteurs, Jaar van Premiere etc.
    detail = re.compile('<li>.*?<strong>(.*?):</strong>.*?<br />(.*?)</li>', re.DOTALL)
    # These regexps find the description area, the program type and descriptive text
    description = re.compile('<div class="description">.*?<div class="text"(.*?)<div class="clearer"></div>',re.DOTALL)
    descrtype = re.compile('<div class="type">(.*?)</div>',re.DOTALL)
    descrline = re.compile('<p>(.*?)</p>',re.DOTALL)
    # randomize detail requests
    nprograms = len(programs)
    fetch_order = range(0,nprograms)
    random.shuffle(fetch_order)
    counter = 0
    for i in fetch_order:
    counter += 1
    if programs[i]['offset'] >= slowdays:
    continue
    if not quiet:
    sys.stderr.write('\n(%3.0f%%) %s: %s ' % (100*float(counter)/float(nprograms), i, programs[i]['name']))
    # check the cache for this program's ID
    cached_program = program_cache.query(programs[i]['ID'])
    if (cached_program != None):
    if not quiet:
    sys.stderr.write(' [cached]')
    # copy the cached information, except the start/end times, rating and clumping,
    # these may have changed.
    tstart = programs[i]['start-time']
    tstop = programs[i]['stop-time']
    rating = programs[i]['star-rating']
    try:
    clump = programs[i]['clumpidx']
    except:
    clump = False
    programs[i] = cached_program
    programs[i]['start-time'] = tstart
    programs[i]['stop-time'] = tstop
    programs[i]['star-rating'] = rating
    if clump:
    programs[i]['clumpidx'] = clump
    continue
    else:
    # be nice to tvgids.nl
    time.sleep(random.randint(nice_time[0], nice_time[1]))
    # get the details page, and get all the detail nodes
    descriptions = ()
    details = ()
    try:
    if not quiet:
    sys.stderr.write(' [normal fetch]')
    total = get_page(programs[i]['url'])
    details = detail.finditer(total)
    descrspan = description.search(total);
    descriptions = descrline.finditer(descrspan.group(1))
    except:
    # if we cannot find the description page,
    # go to next in the loop
    if not quiet:
    sys.stderr.write(' [fetch failed or timed out]')
    continue
    # define containers
    programs[i]['credits'] = {}
    programs[i]['video'] = {}
    # now parse the details
    line_nr = 1;
    # First, we try to find the program type in the description section.
    # Note that this is not the same as the generic genres (these are searched later on), but a more descriptive one like "Culinair programma"
    # If present, we store this as first part of the regular description:
    programs[i]['detail1'] = descrtype.search(descrspan.group(1)).group(1).capitalize()
    if programs[i]['detail1'] != '':
    line_nr = line_nr + 1
    # Secondly, we add one or more lines of the program description that are present.
    for descript in descriptions:
    d_str = 'detail' + str(line_nr)
    programs[i][d_str] = descript.group(1)
    # Remove sponsored link from description if present.
    sponsor_pos = programs[i][d_str].rfind('<i>Gesponsorde link:</i>')
    if sponsor_pos > 0:
    programs[i][d_str] = programs[i][d_str][0:sponsor_pos]
    programs[i][d_str] = filter_line(programs[i][d_str]).strip()
    line_nr = line_nr + 1
    # Finally, we check out all program details. These are generically denoted as:
    # <li><strong>(TYPE):</strong><br />(CONTENT)</li>
    # Some examples:
    # <li><strong>Genre:</strong><br />16 oktober 2008</li>
    # <li><strong>Genre:</strong><br />Amusement</li>
    for d in details:
    type = d.group(1).strip().lower()
    content_asis = d.group(2).strip()
    content = filter_line(content_asis).strip()
    if content == '':
    continue
    elif type == 'genre':
    # Fix detection of movies based on description as tvgids.nl sometimes
    # categorises a movie as e.g. "Komedie", "Misdaadkomedie", "Detectivefilm".
    genre = content;
    if (programs[i]['detail1'].lower().find('film') != -1 \
    or programs[i]['detail1'].lower().find('komedie') != -1)\
    and programs[i]['detail1'].lower().find('tekenfilm') == -1 \
    and programs[i]['detail1'].lower().find('animatiekomedie') == -1 \
    and programs[i]['detail1'].lower().find('filmpje') == -1:
    genre = 'film'
    if nocattrans:
    programs[i]['genre'] = genre.title()
    else:
    try:
    programs[i]['genre'] = cattrans[genre.lower()]
    except:
    programs[i]['genre'] = ''
    # Parse persons and their roles for credit info
    elif roletrans.has_key(type):
    programs[i]['credits'][roletrans[type]] = []
    persons = content_asis.split(',');
    for name in persons:
    if name.find(':') != -1:
    name = name.split(':')[1]
    if name.find('-') != -1:
    name = name.split('-')[0]
    if name.find('e.a') != -1:
    name = name.split('e.a')[0]
    programs[i]['credits'][roletrans[type]].append(filter_line(name.strip()))
    elif type == 'bijzonderheden':
    if content.find('Breedbeeld') != -1:
    programs[i]['video']['breedbeeld'] = 1
    if content.find('Zwart') != -1:
    programs[i]['video']['blackwhite'] = 1
    if content.find('Teletekst') != -1:
    programs[i]['teletekst'] = 1
    if content.find('Stereo') != -1:
    programs[i]['stereo'] = 1
    elif type == 'url':
    programs[i]['infourl'] = content
    else:
    # In unmatched cases, we still add the parsed type and content to the program details.
    # Some of these will lead to xmltv output during the xmlefy_programs step
    programs[i][type] = content
    # do not cache programming that is unknown at the time
    # of fetching.
    if programs[i]['name'].lower() != 'onbekend':
    program_cache.add(programs[i])
    if not quiet:
    sys.stderr.write('\ndone...\n\n')
    # done
    def title_split(program):
    Some channels have the annoying habit of adding the subtitle to the title of a program.
    This function attempts to fix this, by splitting the name at a ': '.
    if (program.has_key('titel aflevering') and program['titel aflevering'] != '') \
    or (program.has_key('genre') and program['genre'].lower() in ['movies','film']):
    return
    colonpos = program['name'].rfind(': ')
    if colonpos > 0:
    program['titel aflevering'] = program['name'][colonpos+1:len(program['name'])].strip()
    program['name'] = program['name'][0:colonpos].strip()
    def xmlefy_programs(programs, channel, desc_len, compat=0, nocattrans=0):
    Given a list of programming (from get_channels())
    returns a string with the xml equivalent
    output = []
    for program in programs:
    clumpidx = ''
    try:
    if program.has_key('clumpidx'):
    clumpidx = 'clumpidx="'+program['clumpidx']+'"'
    except:
    print program
    output.append(' <programme start="%s" stop="%s" channel="%s%s" %s> \n' % \
    (format_timezone(program['start-time']), format_timezone(program['stop-time']),\
    channel, compat and '.tvgids.nl' or '', clumpidx))
    output.append(' <title lang="nl">%s</title>\n' % filter_line(program['name']))
    if program.has_key('titel aflevering') and program['titel aflevering'] != '':
    output.append(' <sub-title lang="nl">%s</sub-title>\n' % filter_line(program['titel aflevering']))
    desc = []
    for detail_row in ['detail1','detail2','detail3']:
    if program.has_key(detail_row) and not re.search('[Gg]een detailgegevens be(?:kend|schikbaar)', program[detail_row]):
    desc.append('%s ' % program[detail_row])
    if desc != []:
    # join and remove newlines from descriptions
    desc_line = "".join(desc).strip()
    desc_line.replace('\n', ' ')
    if len(desc_line) > desc_len:
    spacepos = desc_line[0:desc_len-3].rfind(' ')
    desc_line = desc_line[0:spacepos] + '...'
    output.append(' <desc lang="nl">%s</desc>\n' % desc_line)
    # Process credits section if present.
    # This will generate director/actor/presenter info.
    if program.has_key('credits') and program['credits'] != {}:
    output.append(' <credits>\n')
    for role in program['credits']:
    for name in program['credits'][role]:
    if name != '':
    output.append(' <%s>%s</%s>\n' % (role, name, role))
    output.append(' </credits>\n')
    if program.has_key('jaar van premiere') and program['jaar van premiere'] != '':
    output.append(' <date>%s</date>\n' % program['jaar van premiere'])
    if program.has_key('genre') and program['genre'] != '':
    output.append(' <category')
    if nocattrans:
    output.append(' lang="nl"')
    output.append ('>%s</category>\n' % program['genre'])
    if program.has_key('infourl') and program['infourl'] != '':
    output.append(' <url>%s</url>\n' % program['infourl'])
    if program.has_key('aflevering') and program['aflevering'] != '':
    output.append(' <episode-num system="onscreen">%s</episode-num>\n' % filter_line(program['aflevering']))
    # Process video section if present
    if program.has_key('video') and program['video'] != {}:
    output.append(' <video>\n');
    if program['video'].has_key('breedbeeld'):
    output.append(' <aspect>16:9</aspect>\n')
    if program['video'].has_key('blackwhite'):
    output.append(' <colour>no</colour>\n')
    output.append(' </video>\n')
    if program.has_key('stereo'):
    output.append(' <audio><stereo>stereo</stereo></audio>\n')
    if program.has_key('teletekst'):
    output.append(' <subtitles type="teletext" />\n')
    # Set star-rating if applicable
    if program['star-rating'] != '':
    output.append(' <star-rating><value>%s</value></star-rating>\n' % program['star-rating'])
    output.append(' </programme>\n')
    return "".join(output)
    def main():
    # Parse command line options
    try:
    opts, args = getopt.getopt(sys.argv[1:], "h", ["help", "output=", "capabilities",
    "preferredmethod", "days=",
    "configure", "fast", "slow",
    "cache=", "clean_cache",
    "slowdays=","compat",
    "desc-length=","description",
    "nocattrans","config-file=",
    "max_overlap=", "overlap_strategy=",
    "clear_cache", "quiet","logos="])
    except getopt.GetoptError:
    usage()
    sys.exit(2)
    # DEFAULT OPTIONS - Edit if you know what you are doing
    # where the output goes
    output = None
    output_file = None
    # the total number of days to fetch
    days = 6
    # Fetch data in fast mode, i.e. do NOT grab all the detail information,
    # fast means fast, because as it then does not have to fetch a web page for each program
    # Default: fast=0
    fast = 0
    # number of days to fetch in slow mode. For example: --days 5 --slowdays 2, will
    # fetch the first two days in slow mode (with all the details) and the remaining three
    # days in fast mode.
    slowdays = 6
    # no output
    quiet = 0
    # insert url of channel logo into the xml data, this will be picked up by mythfilldatabase
    logos = 1
    # enable this option if you were using tv_grab_nl, it adjusts the generated
    # xmltvid's so that everything works.
    compat = 0
    # enable this option if you do not want the tvgids categories being translated into
    # MythTV-categories (genres)
    nocattrans = 0
    # Maximum number of characters to use for program description.
    # Different values may work better in different versions of MythTV.
    desc_len = 475
    # default configuration file locations
    hpath = ''
    if os.environ.has_key('HOME'):
    hpath = os.environ['HOME']
    # extra test for windows users
    elif os.environ.has_key('HOMEPATH'):
    hpath = os.environ['HOMEPATH']
    # hpath = ''
    xmltv_dir = hpath+'/.xmltv'
    program_cache_file = xmltv_dir+'/program_cache'
    config_file = xmltv_dir+'/tv_grab_nl_py.conf'
    # cache the detail information.
    program_cache = None
    clean_cache = 1
    clear_cache = 0
    # seed the random generator
    random.seed(time.time())
    for o, a in opts:
    if o in ("-h", "--help"):
    usage()
    sys.exit(1)
    if o == "--quiet":
    quiet = 1;
    if o == "--description":
    print "The Netherlands (tv_grab_nl_py $Rev: 104 $)"
    sys.exit(0)
    if o == "--capabilities":
    print "baseline"
    print "cache"
    print "manualconfig"
    print "preferredmethod"
    sys.exit(0)
    if o == '--preferredmethod':
    print 'allatonce'
    sys.exit(0)
    if o == '--desc-length':
    # Use the requested length for programme descriptions.
    desc_len = int(a)
    if not quiet:
    sys.stderr.write('Using description length: %d\n' % desc_len)
    for o, a in opts:
    if o == "--config-file":
    # use the provided name for configuration
    config_file = a
    if not quiet:
    sys.stderr.write('Using config file: %s\n' % config_file)
    for o, a in opts:
    if o == "--configure":
    # check for the ~.xmltv dir
    if not os.path.exists(xmltv_dir):
    if not quiet:
    sys.stderr.write('You do not have the ~/.xmltv directory,')
    sys.stderr.write('I am going to make a shiny new one for you...')
    os.mkdir(xmltv_dir)
    if not quiet:
    sys.stderr.write('Creating config file: %s\n' % config_file)
    get_channels(config_file)
    sys.exit(0)
    if o == "--days":
    # limit days to maximum supported by tvgids.nl
    days = min(int(a),6)
    if o == "--compat":
    compat = 1
    if o == "--nocattrans":
    nocattrans = 1
    if o == "--fast":
    fast = 1
    if o == "--output":
    output_file = a
    try:
    output = open(output_file,'w')
    # and redirect output
    if debug:
    debug_file = open('/tmp/kaas.xml','w')
    blah = redirect.Tee(output, debug_file)
    sys.stdout = blah
    else:
    sys.stdout = output
    except:
    if not quiet:
    sys.stderr.write('Cannot write to outputfile: %s\n' % output_file)
    sys.exit(2)
    if o == "--slowdays":
    # limit slowdays to maximum supported by tvgids.nl
    slowdays = min(int(a),6)
    # slowdays implies fast == 0
    fast = 0
    if o == "--logos":
    logos = int(a)
    if o == "--clean_cache":
    clean_cache = 1
    if o == "--clear_cache":
    clear_cache = 1
    if o == "--cache":
    program_cache_file = a
    if o == "--max_overlap":
    max_overlap = int(a)
    if o == "--overlap_strategy":
    overlap_strategy = a
    # get configfile if available
    try:
    f = open(config_file,'r')
    except:
    sys.stderr.write('Config file %s not found.\n' % config_file)
    sys.stderr.write('Re-run me with the --configure flag.\n')
    sys.exit(1)
    #check for cache
    program_cache = ProgramCache(program_cache_file)
    if clean_cache != 0:
    program_cache.clean()
    if clear_cache != 0:
    program_cache.clear()
    # Go!
    channels = {}
    # Read the channel stuff
    for blah in f.readlines():
    blah = blah.lstrip()
    blah = blah.replace('\n','')
    if blah:
    if blah[0] != '#':
    channel = blah.split()
    channels[channel[0]] = " ".join(channel[1:])
    # channels are now in channels dict keyed on channel id
    # print header stuff
    print '<?xml version="1.0" encoding="ISO-8859-1"?>'
    print '<!DOCTYPE tv SYSTEM "xmltv.dtd">'
    print '<tv generator-info-name="tv_grab_nl_py $Rev: 104 $">'
    # first do the channel info
    for key in channels.keys():
    print ' <channel id="%s%s">' % (key, compat and '.tvgids.nl' or '')
    print ' <display-name lang="nl">%s</display-name>' % channels[key]
    if (logos):
    ikey = int(key)
    if logo_names.has_key(ikey):
    full_logo_url = logo_provider[logo_names[ikey][0]]+logo_names[ikey][1]+'.gif'
    print ' <icon src="%s" />' % full_logo_url
    print ' </channel>'
    num_chans = len(channels.keys())
    channel_cnt = 0
    if program_cache != None:
    program_cache.clean()
    fluffy = channels.keys()
    nfluffy = len(fluffy)
    for id in fluffy:
    channel_cnt += 1
    if not quiet:
    sys.stderr.write('\n\nNow fetching %s(xmltvid=%s%s) (channel %s of %s)\n' % \
    (channels[id], id, (compat and '.tvgids.nl' or ''), channel_cnt, nfluffy))
    info = get_channel_all_days(id, days, quiet)
    blah = parse_programs(info, None, quiet)
    # fetch descriptions
    if not fast:
    get_descriptions(blah, program_cache, nocattrans, quiet, slowdays)
    # Split titles with colon in it
    # Note: this only takes place if all days retrieved are also grabbed with details (slowdays=days)
    # otherwise this function might change some titles after a few grabs and thus may result in
    # loss of programmed recordings for these programs.
    if slowdays == days:
    for program in blah:
    title_split(program)
    print xmlefy_programs(blah, id, desc_len, compat, nocattrans)
    # save the cache after each channel fetch
    if program_cache != None:
    program_cache.dump(program_cache_file)
    # be nice to tvgids.nl
    time.sleep(random.randint(nice_time[0], nice_time[1]))
    if program_cache != None:
    program_cache.dump(program_cache_file)
    # print footer stuff
    print "</tv>"
    # close the outputfile if necessary
    if output != None:
    output.close()
    # and return success
    sys.exit(0)
    # allow this to be a module
    if __name__ == '__main__':
    main()
    # vim:tw=0:et:sw=4
    [cedric@tv ~]$
    Best regards,
    Cedric
    Last edited by cdwijs (2010-11-04 18:44:51)

    Running the script by python2 solves it for me:
    su - mythtv -c "nice -n 19 python2 /usr/bin/tv_grab_nl_py --output ~/listings.xml"
    Best regards,
    Cedric

  • Decrypt the encrypted password

    Hi there,
    I have been scratching my head for some time to fix one issue. We are planning to change the plateform/technology and we need to bring over existing login to new system. In order to have the same password I need to decrypt the password before I send it to new system. When we stored the password, it encrypts them and stores it in database. I am using following code to decrypt it. it's not worlking . This is error I am getting.
    Given final block not properly padded
    Here is some more information:
    Key is :javax.crypto.spec.SecretKeySpec@18f3a
    Format is :RAW
    getAlgorithm() is :DES
    String encrypted = abcdefgh
    Provider is: com.sun.crypto.provider.SunJCE()
    This is my code to decrypt which throws error " Given final block not properly padded" :
    public String decrypt(String encrypted){
              Cipher ci = null;
              byte [] result = null;
              try {
                   ci = Cipher.getInstance("DES");
                   ci.init(Cipher.DECRYPT_MODE, key);
                   System.out.println("CryptoUtil()" +"before hexToByteArray. Byte Data: "+encrypted);
                   byte [] encryptedData = hexToByteArray(encrypted, false);
                   //Log.out("CryptoUtil()" +"after hexToByteArray. lenth: "+ encryptedData.length);
                   result = ci.doFinal(encryptedData);
              catch (Exception e) {
                   System.out.println("CryptoUtil()" +"ERROR: "+ e.getMessage());
                   return encrypted;
              String strResult = new String(result);
              return strResult;
    Please help.
    Thank you.

    These are the two values I am getting for encrypted password:
    97654de7857cd9aab331995cba044fc6
    a125a6b2a71e23adc002ac7fbe1a1042
    Is this a hex code?
    I think the key is: abcdefgh
    This is my code to encrypt and decrypt:
          * empty constructor
          * @param keydata
         public CryptoUtil(String keydata){
              if (keydata.trim().equals("")){
                   logDebug("CryptoUtil()" +" Constructor didn't get a valid key!");
                   usage();
                   System.exit(0);
              }else{
                   keyBytes = keydata.getBytes();
                   key = new SecretKeySpec(keyBytes, 0, keyBytes.length, "DES");
              try {
                   Provider sp = new com.sun.crypto.provider.SunJCE();
                   //logDebug("CryptoUtil() " + sp.getInfo());
                    Security.addProvider(sp);
                  }catch (Exception ex) {
                         logDebug("CryptoUtil() " +"Problem loading crypto provider \n error:"+ex.getMessage());
                   usage();
                    System.exit(0);
          * Encrypt
          * @param s
         public String encrypt(String s){
              Cipher ci = null;
                  byte [] result = null;
                  try {
                   ci = Cipher.getInstance("DES");
                   ci.init(Cipher.ENCRYPT_MODE, key);
                   result = ci.doFinal(s.getBytes());
                  }catch (Exception e) {
                        logDebug("CryptoUtil()" +"ERROR: "+ e.getMessage());
              String strResult = byteArrayToHex(result);
                  return strResult;
          * decrypt a card number
          * @param encrypted
         public String decrypt(String encrypted){
              Cipher ci = null;
                  byte [] result = null;
                  try {
                   ci = Cipher.getInstance("DES");
                   ci.init(Cipher.DECRYPT_MODE, key);
                   //Log.out("CryptoUtil()" +"before hexToByteArray. Byte Data: "+encrypted);
                   byte [] encryptedData = hexToByteArray(encrypted, false);
                   //Log.out("CryptoUtil()" +"after hexToByteArray. lenth: "+ encryptedData.length);
                   result = ci.doFinal(encryptedData);
                  catch (Exception e) {
                   logError("CryptoUtil()" +"ERROR: "+ e.getMessage());
                   return encrypted;
              String strResult = new String(result);
              return strResult;
         static final String hexDigitChars = "0123456789abcdef";
          * @param a
         public static final String byteArrayToHex(byte [] a) {
              int hn, ln, cx;
              StringBuffer buf = new StringBuffer(a.length * 2);
              for(cx = 0; cx < a.length; cx++) {
                    hn = ((int)(a[cx]) & 0x00ff) / 16;
                    ln = ((int)(a[cx]) & 0x000f);
                    buf.append(hexDigitChars.charAt(hn));
                    buf.append(hexDigitChars.charAt(ln));
                    buf.append(' ');
             return buf.toString();
          * @param str
          * @param rev
         public static final byte [] hexToByteArray(String str, boolean rev) {
              StringBuffer acc = new StringBuffer(str.length() + 1);
              int cx, rp, ff, val;
              char [] s = new char[str.length()];
              str.toLowerCase().getChars(0, str.length(), s, 0);
              for(cx = str.length() - 1, ff = 0; cx >= 0; cx--) {
              if (hexDigitChars.indexOf(s[cx]) >= 0) {
                   acc.append(s[cx]);
                   ff++;
               }else {
                   if ((ff % 2) > 0) acc.append('0');
                        ff = 0;
              if ((ff % 2) > 0) acc.append('0');
              byte [] ret = new byte[acc.length() / 2];
              for(cx = 0, rp = ret.length - 1; cx < acc.length(); cx++, rp--) {
                    val = hexDigitChars.indexOf(acc.charAt(cx));
                    cx++;
                    val += 16 * hexDigitChars.indexOf(acc.charAt(cx));
                    ret[rp] = (byte)val;
              if (rev) {
                    byte tmp;
                    int fx, bx;
                    for(fx = 0, bx = ret.length - 1; fx < (ret.length / 2); fx++, bx--) {
                        tmp = ret[bx];
                        ret[bx] = ret[fx];
                        ret[fx] = tmp;
              return ret;
    Will that give you any more information to help me?

  • Open a new url in  same  window

    I am displayed a button using web dynpro abap,
    if i click the button means a new url page should be
    opened in the same window.
    I did the application but when i click the button means
    a new window is opened.It should not be happened.
    Anyone can plz send me the correct coding immediately....

    >
    cranjith kumar wrote:
    > I am displayed a button using web dynpro abap,
    > if i click the button means a new url page should be
    > opened in the same window.
    >
    > I did the application but when i click the button means
    > a new window is opened.It should not be happened.
    >
    > Anyone can plz send me the correct coding immediately....
    First of all how is anyone supposed to help you correct your coding when you have posted any.  We can't possibly know what is going on inside the event handler for your button. I suggest that post some of your coding here.  In general if you want to open another URL in the same page without using the linkToURL UI element, you should consider the usage of Exit Plugs:
    [http://help.sap.com/saphelp_nw70/helpdata/EN/45/1bc575ba064574e10000000a114a6b/frameset.htm|http://help.sap.com/saphelp_nw70/helpdata/EN/45/1bc575ba064574e10000000a114a6b/frameset.htm]
    Second, please don't ask people to do something "immediately".  Everything done in the forum is on a volunteer basis and people help out as fast as possible.  Your prompting for immediate action is quite unnecessary and could be considered somewhat rude.

  • Getting objects to move between PCs

    After CS 150, I find myself back in the world of Java. I recently learned a neat language called Processing (a.k.a. Proce55ing), and I am one of the coders (and am way rusty to be of much use at this point) for a really cool project.
    I'm wondering if I can nag you with some questions on java.net.*. I need to get some objects passed around between 3 PCs. I need to know about latency issues. Basically, we've got Java doing OpenGL graphics on 6 projectors powered by 3 computers. Imagine each PC having a really wide screen... when a autonomous creature gets to the edge of one PC, it needs to continue its thang on the next PC... move fluidly.
    I've checked out some Java.net.* sample code on sun's site. Specifically their KnockKnock Server. However, its multithread support is for interacting with clients on a one-on-one basis... not like a chat-room style environment. So, I don't even have any sample code for a ultra-basic Java Chat Room.... nor do I know how to pass anything but a string to the server, or to the client.
    There are ways to use my limited knowledge to do what I want to do... just pass a string, and have the server store that into a variable which is accessible by every server thread. Then, create a loop in main that keeps searching through that array of strings to pass them off to the PC... the string would have the coordinate information of the autonomous creature, and create a new one of that object with those Vec3f point. However, latency is a key issue, and it would be easiest if I could just pass an object to the server (in this case: a SimpleVehicle) along with an intended target computer, and then that computer would get that vehicle to add to its array of SimpleVehicles. The important thing is speed, so it might be best to have every computer have a client<->server connection with each other... I get utterly baffled reading the Java Docs. But, I seem to understand code when I see it (I can only reverse engineer). I especially understand the KnockKnock Server and MultiClient code on the Sun's Java Networking Tutorial.
    Any pointers to which methods I need to learn (I already realize I'm going to need to downcast the SimpleVehicle object back into a SimpleVehicle after it gets sent). Thanks a million.

    Ok, try this.
    The simplistic application sends colored balls between instances of itself which can be on any machine on your network.
    As a ball reaches the left side of the window it is in, it gets sent to the machine on it's left (if any), likewise if it reaches the right side of the window it gets sent to the machine on it's right. If there is no machine on the side the ball is trying to go, it rebounds within the window it is in.
    So, a simple test is to run three instances on the same machine, one is regarded as one the left on as on the right and one as in the middle
    To start the one on the left:
    java Ziniman1 8000 -right localhost:8001
    To start the one in the middle:
    java Ziniman1 8001 -left localhost:8000 -right localhost:8002
    To start the one on the right:
    java Ziniman1 8002 -left localhost:8001
    Note: You need to start these pretty quickly one after the other or the socket creation will time out. I'll leave that to you to fix ;)
    Once the apps are running, move them so they are next to each other, left to right (the port numbers used as the server port are in the JFrame title).
    To get create a ball, just click on one of the white panels, use the radio buttons at the bottom to change size/color/direction of the new balls.
    Once you've got the hang of the thing, try moving some instances to other machnes.
    Enjoy!
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class Ziniman1
         static final String LEFT= "Left";
         static final String RIGHT= "Right";
         static class Ball
              implements Serializable
              public int x= -1;
              public int y;
              public int size= 10;
              private Color mColor;
              public Ball(Color color) { mColor= color; }
              public Ball(Color color, int y) { mColor= color; this.y= y; }
              public Color getColor() { return mColor; }
              public String toString() { return "(" +x +"," +y +") x " +size; }
         static interface DirectionalListener
              public void left(Ball ball);
              public void right(Ball ball);
         static class Directional
              private DirectionalListener mListener= null;
              public final void setListener(DirectionalListener listener) {
                   mListener= listener;
              protected final void fireLeft(Ball ball)
                   if (mListener != null)
                        mListener.left(ball);
              protected final void fireRight(Ball ball)
                   if (mListener != null)
                        mListener.right(ball);
         static class Server
              extends Directional
              public Server(final int port)
                   new Thread() {
                        public void run() {
                             try {
                                  ServerSocket listenSocket= new ServerSocket(port);
                                  System.err.println("Server listening on port " +port);
                                  while (true)
                                       connect(listenSocket.accept());
                             catch (Exception e) {
                                  e.printStackTrace();
                   }.start();
              private synchronized void connect(final Socket socket)
                   Thread thread= new Thread() {
                        public void run() {
                             try {
                                  ObjectInputStream is=
                                       new ObjectInputStream(socket.getInputStream());
                                  while (true) {
                                       String side= (String) is.readObject();
                                       Ball ball= (Ball) is.readObject();
                                       if (side.equals(RIGHT))
                                            fireLeft(ball);
                                       else
                                            fireRight(ball);
                             catch (Exception e) {
                                  e.printStackTrace();
                   thread.setDaemon(true);
                   thread.start();
         static class Client
              private ObjectOutputStream mOs;
              private String mSide;
              public Client(String host, int port, String side)
                   throws Exception
                   mSide= side;
                   Socket socket= new Socket(host, port);
                   mOs= new ObjectOutputStream(socket.getOutputStream());
                   System.err.println(
                        mSide +" client connected to " +host +":" +port);
              private void send(Ball ball)
                   try {
                        mOs.writeObject(mSide);
                        mOs.writeObject(ball);
                   catch (Exception e) {
                        e.printStackTrace();
         static abstract class BallPanel
              extends JPanel
              public void paint(Graphics g)
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, getSize().width, getSize().height);
                   Iterator balls= getBalls();
                   while (balls.hasNext()) {
                        Ball ball= (Ball) balls.next();
                        g.setColor(ball.getColor());
                        g.fillOval(ball.x, ball.y, ball.size, ball.size);
              public Dimension getPreferredSize() {
                   return new Dimension(300, 240);
              public abstract Iterator getBalls();
         static class Gui
              extends Directional
              private Runnable mUpdater= new Runnable() {
                   public void run() { mBallPanel.repaint(); }
              private ArrayList mLeft= new ArrayList();
              private ArrayList mRight= new ArrayList();
              private ArrayList mBalls= new ArrayList();
              private BallPanel mBallPanel= new BallPanel() {
                   public Iterator getBalls() {
                        return mBalls.iterator();
              public Gui(String title)
                   final JRadioButton red= new JRadioButton("Red");
                   final JRadioButton green= new JRadioButton("Green");
                   final JRadioButton blue= new JRadioButton("Blue");
                   ButtonGroup group= new ButtonGroup();
                   group.add(red);
                   group.add(blue);
                   group.add(green);
                   final JRadioButton large= new JRadioButton("Large");
                   final JRadioButton small= new JRadioButton("Small");
                   group= new ButtonGroup();
                   group.add(large);
                   group.add(small);
                   final JRadioButton left= new JRadioButton("Left");
                   final JRadioButton right= new JRadioButton("Right");
                   group= new ButtonGroup();
                   group.add(left);
                   group.add(right);
                   red.setSelected(true);
                   small.setSelected(true);
                   right.setSelected(true);
                   mBallPanel.addMouseListener(new MouseAdapter() {
                        public void mousePressed(MouseEvent e) {
                             Ball ball= new Ball(
                                  red.isSelected() ? Color. RED :
                                  blue.isSelected() ? Color.BLUE : Color.GREEN);
                             ball.x= e.getX();
                             ball.y= e.getY();
                             ball.size= large.isSelected() ? 20 : 10;
                             if (left.isSelected())
                                  left(ball);
                             else
                                  right(ball);
                   JPanel panel= new JPanel(new FlowLayout(FlowLayout.LEFT, 4, 4));
                   panel.add(red);
                   panel.add(blue);
                   panel.add(green);
                   panel.add(large);
                   panel.add(small);
                   panel.add(left);
                   panel.add(right);
                   JFrame frame= new JFrame(title);
                   frame.getContentPane().add(mBallPanel, BorderLayout.CENTER);
                   frame.getContentPane().add(panel, BorderLayout.SOUTH);
                   frame.pack();
                   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   frame.setVisible(true);
              public synchronized void move(int delta)
                   Iterator left= mLeft.iterator();
                   while (left.hasNext()) {
                        Ball ball= (Ball) left.next();
                        ball.x -= delta;
                        if (ball.x <= 0) {
                             left.remove();
                             mBalls.remove(ball);
                             fireLeft(ball);
                   Iterator right= mRight.iterator();
                   while (right.hasNext()) {
                        Ball ball= (Ball) right.next();
                        ball.x += delta;
                        if (ball.x >= (mBallPanel.getSize().width -ball.size)) {
                             right.remove();
                             mBalls.remove(ball);
                             fireRight(ball);
                   SwingUtilities.invokeLater(mUpdater);
              public synchronized void left(Ball ball)
                   mLeft.add(ball);
                   mBalls.add(ball);
                   if (ball.x < 0)
                        ball.x= mBallPanel.getSize().width -(ball.size/2);
                   SwingUtilities.invokeLater(mUpdater);
              public synchronized void right(Ball ball)
                   mRight.add(ball);
                   mBalls.add(ball);
                   if (ball.x < 0)
                        ball.x= ball.size/2;
                   SwingUtilities.invokeLater(mUpdater);
         static class Controller
              public Controller(
                   final Gui gui, final Server server,
                   final Client left, final Client right)
                   gui.setListener(new DirectionalListener() {
                        // Ball reached the left
                        public void left(Ball ball)
                             ball.x= -1;
                             if (left == null)
                                  gui.right(ball);
                             else
                                  left.send(ball);
                        // Ball reached the right
                        public void right(Ball ball)
                             ball.x= -1;
                             if (right == null)
                                  gui.left(ball);
                             else
                                  right.send(ball);
                   server.setListener(new DirectionalListener() {
                        // Ball came from the left
                        public void left(Ball ball) {
                             gui.right(ball);
                        // Ball came from the right
                        public void right(Ball ball) {
                             gui.left(ball);
                   Thread thread= new Thread() {
                        public void run() {
                             while (true) {
                                  try { sleep(100); }
                                  catch (InterruptedException e) { }
                                  gui.move(10);
                   thread.setDaemon(true);
                   thread.start();
         private static final String USAGE=
              "Usage: java Ziniman1 " +
              "<server port> [-left <host:port>] [-right <host:port>]";
            public static void main(String[] argv)
              throws Exception
              if (argv.length < 1)
                   barf();
              int leftPort= -1;
              int rightPort= -1;
              String leftHost= "localhost";
              String rightHost= "localhost";
              int serverPort= Integer.parseInt(argv[0]);
              for (int i= 1; i< argv.length; i += 2) {
                   if (argv.equals("-left")) {
                        if (argv.length == i+1)
                             barf();
                        String url= argv[i+1];
                        if (url.indexOf(":") < 0)
                             barf();
                        leftHost= url.substring(0, url.indexOf(":"));
                        leftPort= Integer.parseInt(url.substring(url.indexOf(":")+1));
                   else if (argv[i].equals("-right")) {
                        if (argv.length == i+1)
                             barf();
                        String url= argv[i+1];
                        if (url.indexOf(":") < 0)
                             barf();
                        rightHost= url.substring(0, url.indexOf(":"));
                        rightPort= Integer.parseInt(url.substring(url.indexOf(":")+1));
              new Controller(
                   new Gui("Balls @ " +serverPort),
                   new Server(serverPort),
                   leftPort > 0 ? new Client(leftHost, leftPort, LEFT) : null,
                   rightPort > 0 ? new Client(rightHost, rightPort, RIGHT) : null);
         private static void barf()
              System.err.println(USAGE);
              System.exit(-1);

  • Tricky bug!!

    Hi there, ive been using lucence for a assignment that i am doing i was wondering if some you could have a look that this piece of code that i have been working on.
    The code that i am working on this below
    package Search;
    import org.apache.lucene.analysis.Analyzer;
    import org.apache.lucene.analysis.standard.StandardAnalyzer;
    import org.apache.lucene.document.Document;
    import org.apache.lucene.index.FilterIndexReader;
    import org.apache.lucene.index.IndexReader;
    import org.apache.lucene.queryParser.QueryParser;
    import org.apache.lucene.search.Hits;
    import org.apache.lucene.search.IndexSearcher;
    import org.apache.lucene.search.Query;
    import org.apache.lucene.search.Searcher;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    /** Simple command-line based search demo. */
    public class searchHTML {
    /** Use the norms from one field for all fields. Norms are read into memory,
    * using a byte of memory per document per searched field. This can cause
    * search of large collections with a large number of fields to run out of
    * memory. If all of the fields contain only a single token, then the norms
    * are all identical, then single norm vector may be shared. */
    private static class OneNormsReader extends FilterIndexReader {
    private String field;
    public OneNormsReader(IndexReader in, String field) {
    super(in);
    this.field = field;
    public byte[] norms(String field) throws IOException {
    return in.norms(this.field);
    public searchHTML() {}
    /** Simple command-line based search demo. */
    public String querySearch(String[] args,String searchValue) throws Exception
         String result = "";
    String usage =
    "Usage: java Lucene.SearchFiles [-index dir] [-field f] [-repeat n] [-queries file] [-raw] [-norms field]";
    if (args.length > 0 && ("-h".equals(args[0]) || "-help".equals(args[0])))
    System.out.println(usage);
    System.exit(0);
    String index = "{index-dir}";
    String field = "contents";
    String queries = null;
    int repeat = 0;
    boolean raw = false;
    String normsField = null;
    for (int i = 0; i < args.length; i++) {
    if ("-index".equals(args)) {
    index = args[i+1];
    i++;
    } else if ("-field".equals(args[i])) {
    field = args[i+1];
    i++;
    } else if ("-queries".equals(args[i])) {
    queries = args[i+1];
    i++;
    } else if ("-repeat".equals(args[i])) {
    repeat = Integer.parseInt(args[i+1]);
    i++;
    } else if ("-raw".equals(args[i])) {
    raw = true;
    } else if ("-norms".equals(args[i])) {
    normsField = args[i+1];
    i++;
    IndexReader reader = IndexReader.open(index);
    if (normsField != null)
    reader = new OneNormsReader(reader, normsField);
    Searcher searcher = new IndexSearcher(reader);
    Analyzer analyzer = new StandardAnalyzer();
    BufferedReader in = null;
    if (queries != null) {
    in = new BufferedReader(new FileReader(queries));
    } else {
    in = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
    QueryParser parser = new QueryParser(field, analyzer);
    if(true)
         if (queries == null) // prompt the user
         System.out.println("Enter query: " + searchValue);
         String line = searchValue;
         if (line == null || line.length() == -1)
              System.out.println("test");
         //break;
         line = line.trim();
         if (line.length() == 0)
              System.out.println("test2");
         //break;
         Query query = parser.parse(line);
         System.out.println("Searching for: " + query.toString(field));
         Hits hits = searcher.search(query);
         // if (repeat > 0) {                           // repeat & time as benchmark
         // Date start = new Date();
         // for (int i = 0; i < repeat; i++) {
         // hits = searcher.search(query);
         // Date end = new Date();
         // System.out.println("Time: "+(end.getTime()-start.getTime())+"ms");
         System.out.println(hits.length() + " total matching documents");
         final int HITS_PER_PAGE = hits.length();
         int end = Math.min(hits.length(), HITS_PER_PAGE);
         for (int start = 0; start < end; start++)
         //for (int i = start; i < end; i++)
         //if (raw)
              //     {                              // output raw format
         // System.out.println("doc="+hits.id(i)+" score="+hits.score(i));
         // continue;
         Document doc = hits.doc(start);
         // System.out.println(hits.length());
         for(int i = 0; i<hits.length(); i++)
              ArrayList<String> st = new ArrayList<String>();
              st.add(doc.toString());
              // System.out.println(st);
         String path = doc.get("path");
         if (path != null)
              System.out.println((start + 1) + ". " + path);
         String title = doc.get("title");
         if (title != null)
              ArrayList<String> r = new ArrayList<String>();
              r.add(result = "Title:" + doc.get("title"));
              //System.out.println(result.length());
              //result = " Title: " + doc.get("path");
         else
         result = (start+1) + ". " + "No path for this document";
         //if (queries != null) // non-interactive
         // break;
         if (hits.length() > end)
         System.out.println("more (y/n) ? ");
         line = in.readLine();
         if (line.length() == 0 || line.charAt(0) == 'n')
         break;
         reader.close();
    else
         System.out.println("finished");
    return result;
    At the mintue i am using JSP pages to display the result however, i am getting different results on the jsp page from what i am getting on the consle.
    This is the result from the jsp page
    Value Searched on:myspace
    1Title:MySpace
    2Title:MySpace
    3Title:MySpace
    4Title:MySpace
    5Title:MySpace
    6Title:MySpace
    7Title:MySpace
    8Title:MySpace
    9Title:MySpace
    10Title:MySpace
    11Title:MySpace
    12Title:MySpace
    13Title:MySpace
    14Title:MySpace
    The title MySpace is the title of the html document
    and from the console this is what i am getting : -
    3 total matching documents
    1. H:/Lucenetext/output4.html
    2. H:/Lucenetext/output8.html
    3. H:/Lucenetext/output1.html
    Ive been looking at this for a couple of weeks and was wondering if i could have a fresh pair of eyes to look at it.
    Any help would be very grateful
    Yours
    Chris

    OK
                 System.out.println("Enter query: " + searchValue); What's the point of that unless you then read some input from the user?
               if (line == null || line.length() == -1) line.length() can never be -1. This is rubbish.
              // if (repeat > 0) {                           // repeat & time as benchmark
               //  Date start = new Date();
               //  for (int i = 0; i < repeat; i++) {
                //   hits = searcher.search(query);
               //  Date end = new Date();
               //  System.out.println("Time: "+(end.getTime()-start.getTime())+"ms");
              // } Remove this junk.
               System.out.println(hits.length() + " total matching documents"); This goes to the console. A JSP doesn't have a console so you will never see it - it might be in a log file somewhere if you're lucky.
                 //for (int i = start; i < end; i++) Remove all this commented-out junk.
                   for(int i = 0; i<hits.length(); i++)
                        ArrayList<String> st = new ArrayList<String>();
                        st.add(doc.toString());
                       // System.out.println(st);
                   } As 'st' now gets thrown away this is all junk. Remove it.
                      System.out.println((start + 1) + ". " + path); See above remarks about the console.
                     if (title != null)
                          ArrayList<String> r = new ArrayList<String>();
                          r.add(result = "Title:" + doc.get("title"));
                          //System.out.println(result.length());
                          //result = "   Title: " + doc.get("path");
                     } See above. 'r' gets thrown away. Remove this junk except for the assignment to 'result'.
                   System.out.println("more (y/n) ? ");
                   line = in.readLine(); See above re console. You need to think more clearly about the difference between a console application and a JSP. A JSP writes a page of HTML.

  • Applet has illegal start of expression at public VNCViewer() method{  )

    package viewer;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Label;
    public class VNCViewer extends java.applet.Applet implements Runnable
      public static final String version = "4.1";
      public static final String about1 = "VNC Viewer Free Edition "+version;
      public static final String about2 = "Copyright (C) 2002-2005 RealVNC Ltd.";
      public static final String about3 = ("See http://www.realvnc.com for "+
                                           "information on VNC.");
      public static final String aboutText = about1+"\n"+about2+"\n"+about3;
      public static void main(String[] argv) {
        VNCViewer viewer = new VNCViewer(argv);
        viewer.start();
      public VNCViewer(String[] argv) {
        applet = false;
        // Override defaults with command-line options
        for (int i = 0; i < argv.length; i++) {
          if (argv.equalsIgnoreCase("-log")) {
    if (++i >= argv.length) usage();
    System.err.println("Log setting: "+argv[i]);
    rfb.LogWriter.setLogParams(argv[i]);
    continue;
    if (rfb.Configuration.setParam(argv[i]))
    continue;
    if (argv[i].charAt(0) == '-') {
    if (i+1 < argv.length) {
    if (rfb.Configuration.setParam(argv[i].substring(1), argv[i+1])) {
    i++;
    continue;
    usage();
    if (vncServerName.getValue() != null)
    usage();
    vncServerName.setParam(argv[i]);
    public static void usage() {
    String usage = ("\nusage: vncviewer [options/parameters] "+
    "[host:displayNum] [options/parameters]\n"+
    //" vncviewer [options/parameters] -listen [port] "+
    //"[options/parameters]\n"+
    "\n"+
    "Options:\n"+
    " -log <level> configure logging level\n"+
    "\n"+
    "Parameters can be turned on with -<param> or off with "+
    "-<param>=0\n"+
    "Parameters which take a value can be specified as "+
    "-<param> <value>\n"+
    "Other valid forms are <param>=<value> -<param>=<value> "+
    "--<param>=<value>\n"+
    "Parameter names are case-insensitive. The parameters "+
    "are:\n\n"+
    rfb.Configuration.listParams());
    //System.err.print(usage);
    //System.exit(1);
    //Illegal Start of Expression is here...
    public VNCViewer() {
    applet = true;
    firstApplet = true;
    public static void newViewer(VNCViewer oldViewer) {
    VNCViewer viewer = new VNCViewer();
    viewer.applet = oldViewer.applet;
    viewer.firstApplet = false;
    viewer.start();
    public void init() {
    vlog.debug("init called");
    setBackground(Color.white);
    logo = getImage(getDocumentBase(), "logo150x150.gif");
    public void start() {
    vlog.debug("start called");
    nViewers++;
    if (firstApplet) {
    alwaysShowServerDialog.setParam(true);
    rfb.Configuration.readAppletParams(this);
    String host = getCodeBase().getHost();
    if (vncServerName.getValue() == null && vncServerPort.getValue() != 0) {
    int port = vncServerPort.getValue();
    vncServerName.setParam(host + ((port >= 5900 && port <= 5999)
    ? (":"+(port-5900))
    : ("::"+port)));
    thread = new Thread(this);
    thread.start();
    public void paint(Graphics g) {
    g.drawImage(logo, 0, 0, this);
    int h = logo.getHeight(this)+20;
    g.drawString(about1, 0, h);
    h += g.getFontMetrics().getHeight();
    g.drawString(about2, 0, h);
    h += g.getFontMetrics().getHeight();
    g.drawString(about3, 0, h);
    public void run() {
    CConn cc = null;
    try {
    cc = new CConn(this);
    if (cc.init(null, vncServerName.getValue(),
    alwaysShowServerDialog.getValue())) {
    while (true)
    cc.processMsg();
    } catch (rdr.EndOfStream e) {
    vlog.info(e.toString());
    } catch (Exception e) {
    if (cc != null) cc.removeWindow();
    if (cc == null || !cc.shuttingDown) {
    e.printStackTrace();
    new MessageBox(e.toString());
    if (cc != null) cc.removeWindow();
    nViewers--;
    if (!applet && nViewers == 0) {
    System.exit(0);
    rfb.BoolParameter fastCopyRect
    = new rfb.BoolParameter("FastCopyRect",
    "Use fast CopyRect - turn this off if you get "+
    "screen corruption when copying from off-screen",
    true);
    rfb.BoolParameter useLocalCursor
    = new rfb.BoolParameter("UseLocalCursor",
    "Render the mouse cursor locally", true);
    rfb.BoolParameter autoSelect
    = new rfb.BoolParameter("AutoSelect",
    "Auto select pixel format and encoding", true);
    rfb.BoolParameter fullColour
    = new rfb.BoolParameter("FullColour",
    "Use full colour - otherwise 6-bit colour is used "+
    "until AutoSelect decides the link is fast enough",
    false);
    rfb.AliasParameter fullColor
    = new rfb.AliasParameter("FullColor", "Alias for FullColour", fullColour);
    rfb.StringParameter preferredEncoding
    = new rfb.StringParameter("PreferredEncoding",
    "Preferred encoding to use (ZRLE, hextile or"+
    " raw) - implies AutoSelect=0", null);
    rfb.BoolParameter viewOnly
    = new rfb.BoolParameter("ViewOnly", "Don't send any mouse or keyboard "+
    "events to the server", false);
    rfb.BoolParameter shared
    = new rfb.BoolParameter("Shared", "Don't disconnect other viewers upon "+
    "connection - share the desktop instead", false);
    rfb.BoolParameter acceptClipboard
    = new rfb.BoolParameter("AcceptClipboard",
    "Accept clipboard changes from the server", true);
    rfb.BoolParameter sendClipboard
    = new rfb.BoolParameter("SendClipboard",
    "Send clipboard changes to the server", true);
    rfb.BoolParameter alwaysShowServerDialog
    = new rfb.BoolParameter("AlwaysShowServerDialog",
    "Always show the server dialog even if a server "+
    "has been specified in an applet parameter or on "+
    "the command line", false);
    rfb.StringParameter vncServerName
    = new rfb.StringParameter("Server",
    "The VNC server <host>[:<dpyNum>] or "+
    "<host>::<port>", null);
    rfb.IntParameter vncServerPort
    = new rfb.IntParameter("Port",
    "The VNC server's port number, assuming it is on "+
    "the host from which the applet was downloaded", 0);
    Thread thread;
    boolean applet, firstApplet;
    Image logo;
    Label versionLabel;

    Looks like you have at least two missing "}"
    You have commented out one that you seem to need, right at the error.

  • Error in using Class class

    This is probably to do with my enviroment having a problem but when I try to compilee ShowMethods.java from Chapter 10 of thinking in Jave (code below after error messages) I get the following error:-
    ShowMethods.java:23: cannot access Class
    bad class file: .\Class.java
    file does not contain class Class
    Please remove or make sure it appears in the correct subdirectory of the classpa
    th.
          Class c = Class.forName(args[0]);
          ^
    1 errorAny ideas?
    Ben
    //: c10:ShowMethods.java
    // Using reflection to show all the methods of a class,
    // even if the methods are defined in the base class.
    // {Args: ShowMethods}
    import java.lang.reflect.*;
    import java.util.regex.*;
    public class ShowMethods {
      private static final String usage =
        "usage: \n" +
        "ShowMethods qualified.class.name\n" +
        "To show all methods in class or: \n" +
        "ShowMethods qualified.class.name word\n" +
        "To search for methods involving 'word'";
      private static Pattern p = Pattern.compile("\\w+\\.");
      public static void main(String[] args) {
        if(args.length < 1) {
          System.out.println(usage);
          System.exit(0);
        int lines = 0;
        try {
          Class c = Class.forName(args[0]);
          Method[] m = c.getMethods();
          Constructor[] ctor = c.getConstructors();
          if(args.length == 1) {
            for(int i = 0; i < m.length; i++)
              System.out.println(
                p.matcher(m.toString()).replaceAll(""));
    for(int i = 0; i < ctor.length; i++)
    System.out.println(
    p.matcher(ctor[i].toString()).replaceAll(""));
    lines = m.length + ctor.length;
    } else {
    for(int i = 0; i < m.length; i++)
    if(m[i].toString().indexOf(args[1]) != -1) {
    System.out.println(
    p.matcher(m[i].toString()).replaceAll(""));
    lines++;
    for(int i = 0; i < ctor.length; i++)
    if(ctor[i].toString().indexOf(args[1]) != -1) {
    System.out.println(p.matcher(
    ctor[i].toString()).replaceAll(""));
    lines++;
    } catch(ClassNotFoundException e) {
    System.out.println("No such class: " + e);
    } ///:~

    This is probably to do with my enviroment having a
    problem but when I try to compilee ShowMethods.java
    from Chapter 10 of thinking in Jave (code below after
    error messages) I get the following error:-==SNIP==
    This is during compile time, correct?
    It sounds like you might have a CLASSPATH error... (a search of the Forums should indicate at least 120000 potential posts involving this issue, since last tuesday ;-))
    It does seem strange--that is the code actually posted from the file "ShowMethods.java" that you have keyed into a notepad editor of some sort?
    What command are you using to compile?

  • Urgent Help........Error at Runtime.....

    here are the errors i am getting
    C:\Documents and Settings\Sumit\Desktop>java ab.SearchFiles -index c:\opt\lucene
    \index
    Enter query:
    bill gates
    Searching for: bill gates
    2 total matching documents
    *************INSIDE LINKSPOPULARITY METHOD**************
    Keyword in this step is  bill and the ITERATION NO. is 0
    the string so[]
    com is2
    Keyword in this step is  gates and the ITERATION NO. is 1
    the string so[]
    com is2
    *************INSIDE HYPERLINK POPULARITY METHOD**************
    the string so[]
    *************INSIDE IMPKEYWORDS METHOD**************
    the string so[]
    the score is 0
    1. ../data/b.txt
    the Score of the document is 0.57754713
    the id of the document is26
       Title:
    enter the id of the hyperlink you want to select
    26
    str[]0 is  sony
    str[]1 is  hi
    str[]2 is  bye
    str[]3 is  lucene
    arr[] length is 2
    str[] length is j4
    not doing anything
    arr [k] is0 str[l] is0
    Comparing bill//////////sony
    not doing anything
    arr [k] is0 str[l] is1
    Comparing bill//////////hi
    not doing anything
    arr [k] is0 str[l] is2
    Comparing bill//////////bye
    not doing anything
    arr [k] is0 str[l] is3
    Comparing bill//////////lucene
    bill is stored with 1st condition
    arr [k] is0 str[l] is4
    not doing anything
    arr [k] is1 str[l] is0
    Comparing gates//////////sony
    not doing anything
    arr [k] is1 str[l] is1
    Comparing gates//////////hi
    not doing anything
    arr [k] is1 str[l] is2
    Comparing gates//////////bye
    not doing anything
    arr [k] is1 str[l] is3
    Comparing gates//////////lucene
    gates is stored with 1st condition
    arr [k] is1 str[l] is4
    *************INSIDE STORE HYPERLINK METHOD**************
    Keyword in this step is  bill and the ITERATION NO. is 0
    the string so[bill/null]
    hyperlink for bill is null
    ***********DATABASE UPDATE SUCESSFUL*****************
    Updated Database
    6
    gates/null
    sony/35:1
    hi/a:1
    bye/d:7
    lucene/29:1
    bill/26:1
    Iteration No. 0 is finished
    Keyword in this step is  gates and the ITERATION NO. is 1
    the string so[gates/null]
    hyperlink for gates is null
    ***********DATABASE UPDATE SUCESSFUL*****************
    Updated Database
    6
    gates/26:1
    sony/35:1
    hi/a:1
    bye/d:7
    lucene/29:1
    bill/26:1
    Iteration No. 1 is finished
    INSIDE STOREHYPERLINK 2 METHOD
    str[]0 is  35
    str[]1 is  29
    str[]2 is  a
    str[]3 is  d
    str[] length is j 4
    not doing anything
    hypobj is26 str[l] is0
    Comparing 26//////////35
    not doing anything
    hypobj is26 str[l] is1
    Comparing 26//////////29
    not doing anything
    hypobj is26 str[l] is2
    Comparing 26//////////a
    not doing anything
    hypobj is26 str[l] is3
    Comparing 26//////////d
    26 is stored with 1st condition
    hypobj is26 str[l] is4
    STORE HYPERLINK2 IS FINISHED
    *************INSIDE STORE HYPERLINK  2 METHOD**************
    the keyword to be added isbill
    the hyperlink is26
    the string so[26/null]
    ***********DATABASE UPDATE SUCESSFUL*****************
    Updated Database
    5
    35/sony:1
    26/bill:1
    29/lucene:1
    a/hi:1
    d/bye:7
    Iteration No. 0 is finished
    the keyword to be added isgates
    the hyperlink is26
    the string so[26/bill:1]
    in else if
    value of keyword is   bill
    do nothing
    new entry added
    ***********DATABASE UPDATE SUCESSFUL*****************
    Updated Database
    6
    35/sony:1
    26/bill:1
    29/lucene:1
    26/gates:1
    a/hi:1
    d/bye:7
    Iteration No. 1 is finished
    Enter query:
    Exception in thread "main" java.io.IOException: Stream closed
            at java.io.BufferedInputStream.getBufIfOpen(Unknown Source)
            at java.io.BufferedInputStream.read(Unknown Source)
            at sun.nio.cs.StreamDecoder$CharsetSD.readBytes(Unknown Source)
            at sun.nio.cs.StreamDecoder$CharsetSD.implRead(Unknown Source)
            at sun.nio.cs.StreamDecoder.read(Unknown Source)
            at java.io.InputStreamReader.read(Unknown Source)
            at java.io.BufferedReader.fill(Unknown Source)
            at java.io.BufferedReader.readLine(Unknown Source)
            at java.io.BufferedReader.readLine(Unknown Source)
            at ab.SearchFiles.main(SearchFiles.java:123)
    [db4o 6.4.14.8131   2008-03-26 12:16:15]
    'formula1.db4o' closed by ShutdownHook.and here is my code
    package ab;
    * Licensed to the Apache Software Foundation (ASF) under one or more
    * contributor license agreements.  See the NOTICE file distributed with
    * this work for additional information regarding copyright ownership.
    * The ASF licenses this file to You under the Apache License, Version 2.0
    * (the "License"); you may not use this file except in compliance with
    * the License.  You may obtain a copy of the License at
    *     http://www.apache.org/licenses/LICENSE-2.0
    * Unless required by applicable law or agreed to in writing, software
    * distributed under the License is distributed on an "AS IS" BASIS,
    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    * See the License for the specific language governing permissions and
    * limitations under the License.
    import org.apache.lucene.analysis.Analyzer;
    import org.apache.lucene.analysis.standard.StandardAnalyzer;
    import org.apache.lucene.document.Document;
    import org.apache.lucene.index.FilterIndexReader;
    import org.apache.lucene.index.IndexReader;
    import org.apache.lucene.queryParser.QueryParser;
    import org.apache.lucene.search.Hits;
    import org.apache.lucene.search.IndexSearcher;
    import org.apache.lucene.search.Query;
    import org.apache.lucene.search.Searcher;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Date;
    import java.io.*;
    import java.util.*;
    import com.db4o.Db4o;
    import com.db4o.ObjectContainer;
    import com.db4o.ObjectSet;
    import com.db4o.query.Predicate;
    /** Simple command-line based search demo. */
    public class SearchFiles {
      /** Use the norms from one field for all fields.  Norms are read into memory,
       * using a byte of memory per document per searched field.  This can cause
       * search of large collections with a large number of fields to run out of
       * memory.  If all of the fields contain only a single token, then the norms
       * are all identical, then single norm vector may be shared. */
      private static class OneNormsReader extends FilterIndexReader {
        private String field;
        public OneNormsReader(IndexReader in, String field) {
          super(in);
          this.field = field;
        public byte[] norms(String field) throws IOException {
          return in.norms(this.field);
      private SearchFiles() {}
      /** Simple command-line based search demo. */
      public static void main(String[] args) throws Exception {
           ObjectContainer db=Db4o.openFile(Util.DB4OFILENAME);
        String usage =
          "Usage: java org.apache.lucene.demo.SearchFiles [-index dir] [-field f] [-repeat n] [-queries file] [-raw] [-norms field]";
        if (args.length > 0 && ("-h".equals(args[0]) || "-help".equals(args[0]))) {
          System.out.println(usage);
          System.exit(0);
        String index = "index";
        String field = "contents";
        String queries = null;
        int repeat = 0;
        boolean raw = false;
        String normsField = null;
        for (int i = 0; i < args.length; i++) {
          if ("-index".equals(args)) {
    index = args[i+1];
    i++;
    } else if ("-field".equals(args[i])) {
    field = args[i+1];
    i++;
    } else if ("-queries".equals(args[i])) {
    queries = args[i+1];
    i++;
    } else if ("-repeat".equals(args[i])) {
    repeat = Integer.parseInt(args[i+1]);
    i++;
    } else if ("-raw".equals(args[i])) {
    raw = true;
    } else if ("-norms".equals(args[i])) {
    normsField = args[i+1];
    i++;
    IndexReader reader = IndexReader.open(index);
    if (normsField != null)
    reader = new OneNormsReader(reader, normsField);
    Searcher searcher = new IndexSearcher(reader);
    Analyzer analyzer = new StandardAnalyzer();
    BufferedReader in = null;
    if (queries != null) {
    in = new BufferedReader(new FileReader(queries));
    } else {
    in = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
    QueryParser parser = new QueryParser(field, analyzer);
    while (true) {
    if (queries == null) // prompt the user
    System.out.println("Enter query: ");
    String line = in.readLine();
    if (line == null || line.length() == -1)
    break;
    line = line.trim();
    if (line.length() == 0)
    break;
    Query query = parser.parse(line);
    System.out.println("Searching for: " + query.toString(field));
    String[] arr = query.toString(field).split (" ");
    Hits hits = searcher.search(query);
    if (repeat > 0) {                           // repeat & time as benchmark
    Date start = new Date();
    for (int i = 0; i < repeat; i++) {
    hits = searcher.search(query);
    Date end = new Date();
    System.out.println("Time: "+(end.getTime()-start.getTime())+"ms");
    System.out.println(hits.length() + " total matching documents");
    final int HITS_PER_PAGE = 10;
    for (int start = 0; start < hits.length(); start += HITS_PER_PAGE) {
    int end = Math.min(hits.length(), start + HITS_PER_PAGE);
    for (int i = start; i < end; i++) {
    if (raw) {                              // output raw format
    System.out.println("doc="+hits.id(i)+" score="+hits.score(i));
    continue;
    Document doc = hits.doc(i);
    String path = doc.get("path");
    if (path != null) {
         int temphyp = hits.id(i);
         String hypobj = Integer.toString(temphyp);
    int a1,a2,a3;     
    temporary abc1 = new temporary();
              a1 = abc1.linkspopularity(db,arr,hypobj);
              temporary abc2 = new temporary();
              a2 = abc2.hyperlinkspopularity(db,hypobj);
              temporary abc3 = new temporary();
              a3 = abc3.impkeywords(db,arr,hypobj);
    int totalscore;
              totalscore = a1+a2+a3;
              System.out.println("the score is " + totalscore );
    System.out.println((i+1) + ". " + path);
    System.out.println("the Score of the document is " + hits.score(i));
    System.out.println("the id of the document is" + hits.id(i));
    String title = doc.get("title");
    if (title != null) {
    System.out.println(" Title: " + doc.get("title"));
    } else {
    System.out.println((i+1) + ". " + "No path for this document");
    System.out.println("enter the id of the hyperlink you want to select");
    BufferedReader in5 = new BufferedReader(new InputStreamReader(System.in));
    String hypobj = in.readLine();
    modules a1 = new modules();
              a1.StoreKeywords(db,arr);
              modules a2 = new modules();
              a2.StoreHyperlinks(db,arr,hypobj);
              modules a3 = new modules();
              a3.StoreHyperlinks2(db,hypobj);
              modules a4 = new modules();
              a4.StoreKeywords2(db,arr,hypobj);
    in5.close();
    break;
    if (queries != null) // non-interactive
    break;
    if (hits.length() > end) {
    System.out.println("more (y/n) ? ");
    line = in.readLine();
    if (line.length() == 0 || line.charAt(0) == 'n')
    break;
    reader.close();

    Here is my help:
    The entire line of output up until the actual error means absolutely nothing to me or anyone else except you; it is means anything at all, then you need to get into your debugger and start stepping thorugh your code until you hit the error and see what is actually happening, then if you are stuck, write a question stating what the problem is and where it occurs in your code. You chould give some of the variable states in the same scope during the iteration inwhich the error occures, but unless you are willing to do this, I doubt anyone is going to do your debugging for you--paticulary since this is not even your own code.

  • Error in code..please help

    Hi,
    I'm writing a SIP messaging klient and i am having problem with connecting the client to my SIP-server (OpenSER)
    javax.sip.InvalidArgumentException: 300:[email protected]: 300:[email protected]
    at gov.nist.javax.sip.SipStackImpl.createListeningPoint(SipStackImpl.java:645)
    at sipTrade.createProvider(sip.java:274)
    at sipTrade.main(sip.java:299)
    Caused by: java.net.UnknownHostException: 300:[email protected]: 300:[email protected]
    at java.net.InetAddress.getAllByName0(Unknown Source)
    at java.net.InetAddress.getAllByName0(Unknown Source)
    at java.net.InetAddress.getAllByName(Unknown Source)
    at java.net.InetAddress.getByName(Unknown Source)
    at gov.nist.javax.sip.SipStackImpl.createListeningPoint(SipStackImpl.java:625)
    ... 2 more
    import java.io.*;
    import javax.sip.*;
    import javax.sip.address.*;
    import javax.sip.header.*;
    import javax.sip.message.*;
    import java.util.*;
    public class sip implements SipListener {
         private static AddressFactory addressFactory;
         private static MessageFactory messageFactory;
         private static HeaderFactory headerFactory;
         private static SipStack sipStack;
         private int port;
         protected SipProvider udpProvider;
         protected Dialog dialog;
         protected int notifyCount = 0;
         protected final String serverIP = "300:[email protected]";
         class MyEventSource implements Runnable {
              private sipTrade st;
              private EventHeader eventHeader;
              public MyEventSource(sipTrade notifier, EventHeader eventHeader ) {
                   this.st = notifier;
                   this.eventHeader = eventHeader;
              public void run() {
                   try {
                        for (int i = 0; i < 100; i++) {
                             Thread.sleep(100);
                             Request request = this.st.dialog.createRequest(Request.NOTIFY);
                             SubscriptionStateHeader subscriptionState = headerFactory.createSubscriptionStateHeader(SubscriptionStateHeader.ACTIVE);
                             request.addHeader(subscriptionState);
                             request.addHeader(eventHeader);
                             // Lets mark our Contact
                             ((SipURI)dialog.getLocalParty().getURI()).setParameter("id","not2");
                             ClientTransaction ct = udpProvider.getNewClientTransaction(request);
                             System.out.println("NOTIFY Branch ID "+((ViaHeader)request.getHeader(ViaHeader.NAME)).getParameter("branch"));
                             this.st.dialog.sendRequest(ct);
                             System.out.println("Dialog " + dialog);
                             System.out.println("Dialog state after active NOTIFY: " + dialog.getState());
                             synchronized (sipTrade.this) {
                             notifyCount ++;
                   } catch (Throwable e) {
                        e.printStackTrace();
         private static void usage() {
              System.exit(0);
         public void processRequest(RequestEvent requestEvent) {
              Request request = requestEvent.getRequest();
              ServerTransaction serverTransactionId = requestEvent.getServerTransaction();
              System.out.println("\n\nRequest " + request.getMethod()+" received at " + sipStack.getStackName()+" with server transaction id " + serverTransactionId+" and dialog id "+requestEvent.getDialog());
              if (request.getMethod().equals(Request.SUBSCRIBE)) {
                   processSubscribe(requestEvent, serverTransactionId);
          * Process the invite request.
         public void processSubscribe(RequestEvent requestEvent,
                   ServerTransaction serverTransaction) {
              SipProvider sipProvider = (SipProvider) requestEvent.getSource();
              Request request = requestEvent.getRequest();
              try {
                   System.out.println("notifier: got an Subscribe sending OK");
                   System.out.println("notifier:  " + request);
                   System.out.println("notifier : dialog = " + requestEvent.getDialog());
                   EventHeader eventHeader = (EventHeader) request.getHeader(EventHeader.NAME);
                   if ( eventHeader == null) {
                        System.out.println("Cannot find event header.... dropping request.");
                        return;
                   // Always create a ServerTransaction, best as early as possible in the code
                   Response response = null;
                   ServerTransaction st = requestEvent.getServerTransaction();               
                   if (st == null) {
                        st = sipProvider.getNewServerTransaction(request);
                   // Check if it is an initial SUBSCRIBE or a refresh / unsubscribe
                   boolean isInitial = requestEvent.getDialog() == null;
                   if ( isInitial ) {
                        // need random tags to test forking
                        String toTag = Integer.toHexString( (int) (Math.random() * Integer.MAX_VALUE) );
                        response = messageFactory.createResponse(202, request);
                        ToHeader toHeader = (ToHeader) response.getHeader(ToHeader.NAME);
                        // Sanity check: to header should not ahve a tag. Else the dialog
                        // should have matched
                        if (toHeader.getTag()!=null) {
                             System.err.println( "####ERROR: To-tag!=null but no dialog match! My dialog=" + dialog.getState() );
                        toHeader.setTag(toTag); // Application is supposed to set.
                        this.dialog = st.getDialog();
                        // subscribe dialogs do not terminate on bye.
                        this.dialog.terminateOnBye(false);
                        if (dialog != null) {
                             System.out.println("Dialog " + dialog);
                             System.out.println("Dialog state " + dialog.getState());
                   } else {
                        response = messageFactory.createResponse(200, request);
                   // Both 2xx response need a Contact
                   Address address = addressFactory.createAddress("xTrade <sip:127.0.0.1>");
                   ((SipURI)address.getURI()).setPort( udpProvider.getListeningPoint("udp").getPort() );                    
                   ContactHeader contactHeader = headerFactory.createContactHeader(address);               
                   response.addHeader(contactHeader);
                   // Expires header is mandatory in 2xx responses to SUBSCRIBE
                   ExpiresHeader expires = (ExpiresHeader) request.getHeader( ExpiresHeader.NAME );
                   if (expires==null) {
                        expires = headerFactory.createExpiresHeader(30);     // rather short
                   response.addHeader( expires );
                   st.sendResponse(response);
                    * NOTIFY requests MUST contain a "Subscription-State" header with a
                    * value of "active", "pending", or "terminated". The "active" value
                    * indicates that the subscription has been accepted and has been
                    * authorized (in most cases; see section 5.2.). The "pending" value
                    * indicates that the subscription has been received, but that
                    * policy information is insufficient to accept or deny the
                    * subscription at this time. The "terminated" value indicates that
                    * the subscription is not active.
                   Request notifyRequest = dialog.createRequest( "NOTIFY" );
                   // Mark the contact header, to check that the remote contact is updated
                   ((SipURI)contactHeader.getAddress().getURI()).setParameter("id","not");
                   // Initial state is pending, second time we assume terminated (Expires==0)
                   SubscriptionStateHeader sstate = headerFactory.createSubscriptionStateHeader(
                             isInitial ? SubscriptionStateHeader.PENDING : SubscriptionStateHeader.TERMINATED );
                   // Need a reason for terminated
                   if ( sstate.getState().equalsIgnoreCase("terminated") ) {
                        sstate.setReasonCode( "deactivated" );
                   notifyRequest.addHeader(sstate);
                   notifyRequest.setHeader(eventHeader);
                   notifyRequest.setHeader(contactHeader);
                   // notifyRequest.setHeader(routeHeader);
                   ClientTransaction ct = udpProvider.getNewClientTransaction(notifyRequest);
                   // Let the other side know that the tx is pending acceptance
                   dialog.sendRequest(ct);
                   System.out.println("NOTIFY Branch ID " +
                        ((ViaHeader)request.getHeader(ViaHeader.NAME)).getParameter("branch"));
                   System.out.println("Dialog " + dialog);
                   System.out.println("Dialog state after pending NOTIFY: " + dialog.getState());
                   if (isInitial) {
                        Thread myEventSource = new Thread(new MyEventSource(this,eventHeader));
                        myEventSource.start();
              } catch (Throwable ex) {
                   ex.printStackTrace();
                   // System.exit(0);
         public synchronized void processResponse(ResponseEvent responseReceivedEvent) {
              Response response = (Response) responseReceivedEvent.getResponse();
              Transaction tid = responseReceivedEvent.getClientTransaction();
              if ( response.getStatusCode() !=  200 ) {
                   this.notifyCount --;
              } else {
                  System.out.println("Notify Count = " + this.notifyCount);
         public void processTimeout(javax.sip.TimeoutEvent timeoutEvent) {
              Transaction transaction;
              if (timeoutEvent.isServerTransaction()) {
                   transaction = timeoutEvent.getServerTransaction();
              } else {
                   transaction = timeoutEvent.getClientTransaction();
              System.out.println("state = " + transaction.getState());
              System.out.println("dialog = " + transaction.getDialog());
              System.out.println("dialogState = "
                        + transaction.getDialog().getState());
              System.out.println("Transaction Time out");
        private static void initFactories ( int port ) throws Exception {
              SipFactory sipFactory = SipFactory.getInstance();
              sipFactory.setPathName("gov.nist");
              Properties properties = new Properties();
              properties.setProperty("javax.sip.STACK_NAME", "notifier" + port );
              // You need 16 for logging traces. 32 for debug + traces.
              // Your code will limp at 32 but it is best for debugging.
              properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "32");
              properties.setProperty("gov.nist.javax.sip.DEBUG_LOG",
                        "notifierdebug_"+port+".txt");
              properties.setProperty("gov.nist.javax.sip.SERVER_LOG",
                        "notifierlog_"+port+".txt");
              try {
                   // Create SipStack object
                   sipStack = sipFactory.createSipStack(properties);
                   System.out.println("sipStack = " + sipStack);
              } catch (PeerUnavailableException e) {
                   // could not find
                   // gov.nist.jain.protocol.ip.sip.SipStackImpl
                   // in the classpath
                   e.printStackTrace();
                   System.err.println(e.getMessage());
                   if (e.getCause() != null)
                        e.getCause().printStackTrace();
                   System.exit(0);
              try {
                   headerFactory = sipFactory.createHeaderFactory();
                   addressFactory = sipFactory.createAddressFactory();
                   messageFactory = sipFactory.createMessageFactory();
              } catch  (Exception ex) {
                   ex.printStackTrace();
                   System.exit(0);
         public void createProvider() {
              try {
                   ListeningPoint lp = sipStack.createListeningPoint(this.serverIP, this.port, "udp");
                   this.udpProvider = sipStack.createSipProvider(lp);
                   System.out.println("udp provider " + udpProvider);
              } catch (Exception ex) {
                   System.out.println((ex.getMessage()));
                   ex.printStackTrace();
                   usage();
         public sipTrade( int port ) {
              this.port = port;
         public sipTrade(){
         public static void main(String args[]) throws Exception {
              int port = args.length > 0 ? Integer.parseInt(args[0]) : 5060;
              initFactories( port );
              sipTrade notifier = new sipTrade( port );
              notifier.createProvider( );
              notifier.udpProvider.addSipListener(notifier);
              //sipTrade st = new sipTrade();
              //st.Send2xTrade("198202050897", "testdata");
              //st.getXTmsg(0);
         public void processIOException(IOExceptionEvent exceptionEvent) {
         public void processTransactionTerminated(
                   TransactionTerminatedEvent transactionTerminatedEvent) {
         public void processDialogTerminated(
                   DialogTerminatedEvent dialogTerminatedEvent) {
              // TODO Auto-generated method stub
          * Xtrade connection - DATA IN
          public void Send2xTrade(String data, String info) {
               try{
                    IServer is = ServerFactory.createObject(ip);
                    is.logOn(clientName_in, SessionType.LogOnRxTx);
                    is.sendMsg(contract_in,MsgPriority.Def, data.getBytes(), info);
                    is.logOff();
               catch (Exception e){
                    e.printStackTrace();
                    System.err.println(e.getMessage());
          public void getXTmsg(int xtMsgAck){
              IMsg msg;               // A single xTrade message
              MsgInfo msgInfo = null;      // Message information
              byte[] theData;
              try {
                   IServer is = ServerFactory.createObject(ip);
                   is.logOn(clientName_out, SessionType.LogOnRxTx);
                   msg = is.createNextRxMsg(contract_out);
                   FileOutputStream myStream = new FileOutputStream("rx" + msg.getHandle() + ".msg");     // Create the stream                    
                   msg.getData(myStream);
                   myStream.close();
                   if(msgInfo.getAcknowledge() == false){
                             msg.setReceived();
                        else if(msgInfo.getAcknowledge() == true && xtMsgAck == 0){
                              msg.setReceived();
                              msg.setAck();
                         else if(msgInfo.getAcknowledge() == true && xtMsgAck == 1){
                              msg.setReceived();
                              msg.setNack();
                   is.logOff();
              }catch (XTException e){
              catch(Exception e){
    }

    Made som more fixes:
    sipStack = gov.nist.javax.sip.SipStackImpl@e24e2a
    sipStack = gov.nist.javax.sip.SipStackImpl@e24e2a
    SipProviders: java.util.LinkedList$ListItr@1a73d3c
    AddressFactory: class gov.nist.javax.sip.address.AddressFactoryImpl
    InvalidArgumentException Cannot assign requested address: Cannot bindjavax.sip.InvalidArgumentException: Cannot assign requested address: Cannot bind
         at gov.nist.javax.sip.SipStackImpl.createListeningPoint(SipStackImpl.java:645)
         at sipClient.createProvider(sipClient.java:267)
         at sipClient.main(sipClient.java:302)
    Caused by: java.io.IOException: Cannot assign requested address: Cannot bind
         at gov.nist.javax.sip.stack.UDPMessageProcessor.<init>(UDPMessageProcessor.java:135)
         at gov.nist.javax.sip.stack.SIPTransactionStack.createMessageProcessor(SIPTransactionStack.java:1652)
         at gov.nist.javax.sip.SipStackImpl.createListeningPoint(SipStackImpl.java:626)
         ... 2 more
    Exception in thread "main" java.lang.NullPointerException
         at sipClient.main(sipClient.java:303)
    import java.io.*;
    import javax.sip.*;
    import javax.sip.address.*;
    import javax.sip.header.*;
    import javax.sip.message.*;
    import java.util.*;
    public class sipClient implements SipListener {
         private static AddressFactory addressFactory;
         private static MessageFactory messageFactory;
         private static HeaderFactory headerFactory;
         private static Address address;
         private static SipStack sipStack;
         private int port;
         protected SipProvider udpProvider;
         protected Dialog dialog;
         protected int notifyCount = 0;
         public static final int PORT_5060 = 5070;     
         protected final String serverIP = "192.168.1.99";
         class MyEventSource implements Runnable {
              private sipClient st;
              private EventHeader eventHeader;
              public MyEventSource(sipClient notifier, EventHeader eventHeader ) {
                   this.st = notifier;
                   this.eventHeader = eventHeader;
              public void run() {
                   try {
                        for (int i = 0; i < 100; i++) {
                             Thread.sleep(100);
                             Request request = this.st.dialog.createRequest(Request.NOTIFY);
                             SubscriptionStateHeader subscriptionState = headerFactory.createSubscriptionStateHeader(SubscriptionStateHeader.ACTIVE);
                             request.addHeader(subscriptionState);
                             request.addHeader(eventHeader);
                             // Lets mark our Contact
                             ((SipURI)dialog.getLocalParty().getURI()).setParameter("id","not2");
                             ClientTransaction ct = udpProvider.getNewClientTransaction(request);
                             System.out.println("NOTIFY Branch ID "+((ViaHeader)request.getHeader(ViaHeader.NAME)).getParameter("branch"));
                             this.st.dialog.sendRequest(ct);
                             System.out.println("Dialog " + dialog);
                             System.out.println("Dialog state after active NOTIFY: " + dialog.getState());
                             synchronized (sipClient.this) {
                             notifyCount ++;
                   } catch (Throwable e) {
                        e.printStackTrace();
         private static void usage() {
              System.exit(0);
         public void processRequest(RequestEvent requestEvent) {
              Request request = requestEvent.getRequest();
              ServerTransaction serverTransactionId = requestEvent.getServerTransaction();
              System.out.println("\n\nRequest " + request.getMethod()+" received at " + sipStack.getStackName()+" with server transaction id " + serverTransactionId+" and dialog id "+requestEvent.getDialog());
              if (request.getMethod().equals(Request.SUBSCRIBE)) {
                   processSubscribe(requestEvent, serverTransactionId);
          * Process the invite request.
         public void processSubscribe(RequestEvent requestEvent,
                   ServerTransaction serverTransaction) {
              SipProvider sipProvider = (SipProvider) requestEvent.getSource();
              Request request = requestEvent.getRequest();
              try {
                   System.out.println("notifier: got an Subscribe sending OK");
                   System.out.println("notifier:  " + request);
                   System.out.println("notifier : dialog = " + requestEvent.getDialog());
                   EventHeader eventHeader = (EventHeader) request.getHeader(EventHeader.NAME);
                   if ( eventHeader == null) {
                        System.out.println("Cannot find event header.... dropping request.");
                        return;
                   // Always create a ServerTransaction, best as early as possible in the code
                   Response response = null;
                   ServerTransaction st = requestEvent.getServerTransaction();               
                   if (st == null) {
                        st = sipProvider.getNewServerTransaction(request);
                   // Check if it is an initial SUBSCRIBE or a refresh / unsubscribe
                   boolean isInitial = requestEvent.getDialog() == null;
                   if ( isInitial ) {
                        // need random tags to test forking
                        String toTag = Integer.toHexString( (int) (Math.random() * Integer.MAX_VALUE) );
                        response = messageFactory.createResponse(202, request);
                        ToHeader toHeader = (ToHeader) response.getHeader(ToHeader.NAME);
                        // Sanity check: to header should not ahve a tag. Else the dialog
                        // should have matched
                        if (toHeader.getTag()!=null) {
                             System.err.println( "####ERROR: To-tag!=null but no dialog match! My dialog=" + dialog.getState() );
                        toHeader.setTag(toTag); // Application is supposed to set.
                        this.dialog = st.getDialog();
                        // subscribe dialogs do not terminate on bye.
                        this.dialog.terminateOnBye(false);
                        if (dialog != null) {
                             System.out.println("Dialog " + dialog);
                             System.out.println("Dialog state " + dialog.getState());
                   } else {
                        response = messageFactory.createResponse(200, request);
                   // Both 2xx response need a Contact
                   address = addressFactory.createAddress("xTrade <sip:192.168.1.99>");
                   ((SipURI)address.getURI()).setPort( udpProvider.getListeningPoint("udp").getPort() );                    
                   ContactHeader contactHeader = headerFactory.createContactHeader(address);               
                   response.addHeader(contactHeader);
                   // Expires header is mandatory in 2xx responses to SUBSCRIBE
                   ExpiresHeader expires = (ExpiresHeader) request.getHeader( ExpiresHeader.NAME );
                   if (expires==null) {
                        expires = headerFactory.createExpiresHeader(30);     // rather short
                   response.addHeader( expires );
                   st.sendResponse(response);
                    * NOTIFY requests MUST contain a "Subscription-State" header with a
                    * value of "active", "pending", or "terminated". The "active" value
                    * indicates that the subscription has been accepted and has been
                    * authorized (in most cases; see section 5.2.). The "pending" value
                    * indicates that the subscription has been received, but that
                    * policy information is insufficient to accept or deny the
                    * subscription at this time. The "terminated" value indicates that
                    * the subscription is not active.
                   Request notifyRequest = dialog.createRequest( "NOTIFY" );
                   // Mark the contact header, to check that the remote contact is updated
                   ((SipURI)contactHeader.getAddress().getURI()).setParameter("id","not");
                   // Initial state is pending, second time we assume terminated (Expires==0)
                   SubscriptionStateHeader sstate = headerFactory.createSubscriptionStateHeader(
                             isInitial ? SubscriptionStateHeader.PENDING : SubscriptionStateHeader.TERMINATED );
                   // Need a reason for terminated
                   if ( sstate.getState().equalsIgnoreCase("terminated") ) {
                        sstate.setReasonCode( "deactivated" );
                   notifyRequest.addHeader(sstate);
                   notifyRequest.setHeader(eventHeader);
                   notifyRequest.setHeader(contactHeader);
                   // notifyRequest.setHeader(routeHeader);
                   ClientTransaction ct = udpProvider.getNewClientTransaction(notifyRequest);
                   // Let the other side know that the tx is pending acceptance
                   dialog.sendRequest(ct);
                   System.out.println("NOTIFY Branch ID " +
                        ((ViaHeader)request.getHeader(ViaHeader.NAME)).getParameter("branch"));
                   System.out.println("Dialog " + dialog);
                   System.out.println("Dialog state after pending NOTIFY: " + dialog.getState());
                   if (isInitial) {
                        Thread myEventSource = new Thread(new MyEventSource(this,eventHeader));
                        myEventSource.start();
              } catch (Throwable ex) {
                   ex.printStackTrace();
                   // System.exit(0);
         public synchronized void processResponse(ResponseEvent responseReceivedEvent) {
              Response response = (Response) responseReceivedEvent.getResponse();
              Transaction tid = responseReceivedEvent.getClientTransaction();
              if ( response.getStatusCode() !=  200 ) {
                   this.notifyCount --;
              } else {
                  System.out.println("Notify Count = " + this.notifyCount);
         public void processTimeout(javax.sip.TimeoutEvent timeoutEvent) {
              Transaction transaction;
              if (timeoutEvent.isServerTransaction()) {
                   transaction = timeoutEvent.getServerTransaction();
              } else {
                   transaction = timeoutEvent.getClientTransaction();
              System.out.println("state = " + transaction.getState());
              System.out.println("dialog = " + transaction.getDialog());
              System.out.println("dialogState = "
                        + transaction.getDialog().getState());
              System.out.println("Transaction Time out");
        private static void initFactories ( int port ) throws Exception {
              SipFactory sipFactory = SipFactory.getInstance();
              sipFactory.setPathName("gov.nist");
              Properties properties = new Properties();
              properties.setProperty("javax.sip.STACK_NAME", "notifier" + port );
              // You need 16 for logging traces. 32 for debug + traces.
              // Your code will limp at 32 but it is best for debugging.
              properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "32");
              properties.setProperty("gov.nist.javax.sip.DEBUG_LOG","Xtradedebug_"+port+".txt");
              properties.setProperty("gov.nist.javax.sip.SERVER_LOG","Xtradelog_"+port+".txt");
              properties.setProperty("javax.sip.OUTBOUND_PROXY","192.168.1.99:5070/UDP");
              properties.setProperty("javax.sip.USE_ROUTER_FOR_ALL_URIS", "true");
              properties.setProperty("javax.sip.AUTOMATIC_DIALOG_SUPPORT","ON");
              try {
                   // Create SipStack object
                   sipStack = sipFactory.createSipStack(properties);
                   System.out.println("sipStack = " + sipStack);
              } catch (PeerUnavailableException e) {
                   // could not find
                   // gov.nist.jain.protocol.ip.sip.SipStackImpl
                   // in the classpath
                   e.printStackTrace();
                   System.err.println(e.getMessage());
                   if (e.getCause() != null)
                        e.getCause().printStackTrace();
                   System.exit(0);
              try {
                   headerFactory = sipFactory.createHeaderFactory();
                   addressFactory = sipFactory.createAddressFactory();
                   messageFactory = sipFactory.createMessageFactory();
              } catch  (Exception ex) {
                   ex.printStackTrace();
                   System.exit(0);
         public void createProvider() {
              try {
                   System.out.println("sipStack = " + sipStack);
                   System.out.println("SipProviders: "+sipStack.getSipProviders().toString());
                   System.out.println("AddressFactory: "+addressFactory.getClass());
                   ListeningPoint lp = sipStack.createListeningPoint(this.serverIP, 5070, ListeningPoint.UDP);
                   this.udpProvider = sipStack.createSipProvider(lp);
                   System.out.println("udp provider " + udpProvider);
              }catch(SipException e){
                   System.out.print("SipException "+e.getMessage());
                   e.printStackTrace();
              /*catch(TransportNotSupportedException e){
                   System.out.print("TransportNotSupportedException "+e.getMessage());
              catch (InvalidArgumentException e){
                   System.out.print("InvalidArgumentException "+e.getMessage());
                   e.printStackTrace();
              catch (Exception ex) {
                   System.err.println((ex.getMessage()));
                   ex.printStackTrace();
                   usage();
         public sipClient( int port ) {
              this.port = port;
         public sipClient(){
         public static void main(String args[]) throws Exception {
              int port = args.length > 0 ? Integer.parseInt(args[0]) : 5070;
              initFactories( port );
              sipClient st = new sipClient( port );
              st.createProvider();
              st.udpProvider.addSipListener(st);
         public void processIOException(IOExceptionEvent exceptionEvent) {
         public void processTransactionTerminated(
                   TransactionTerminatedEvent transactionTerminatedEvent) {
         public void processDialogTerminated(
                   DialogTerminatedEvent dialogTerminatedEvent) {
              // TODO Auto-generated method stub
    }

  • Running in invisible mode

    Hi,
    I have a Java Frame that i want to run in invisible mode. The problem is that i have to set it to visible first, then invisible otherwise it doesn't seem to execute. Also if i set it to ICONIFIED, the program doesn't run until it is maximized.
    How can i make it so i never have to make it visible and have it still run?
    Thanks for any help.

    First explain what you mean by "executing a frame". Hi, this is the first time i have done anything in Java. I am trying to run this java program from a C program, but don't want to see the window pop up at all. But if i don't have the f.setVisible(true) where it is, the viewer modules, which are capturing streaming data and writing to bmp's to not work. The same is true if i set to ICONIFIED.
    Thanks, hope this helps...
    public static void main(String args[])
    ms_standalone = true;
    Frame f = new Frame(AppID.getAppID().getAppName());
    f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we)
    System.exit(0);
    f.setSize(352, 320);
    f.setLayout(new BorderLayout());
    int numCams = 0;
    StringBuffer concatURL = new StringBuffer();
    for (int i=0;i< args.length;i++)
    String arg = args;
    if (arg.startsWith("-")) {
    int eqidx = arg.indexOf("=")+1;
    if (arg.startsWith("-num=")) {
    numCams = Character.getNumericValue(arg.charAt(eqidx));
    } else {
    usage();
    System.exit(0);
    } else {
    if (concatURL.length() != 0)
    concatURL.append("|");
    concatURL.append(arg.trim());
    // create multiple viewers
    Viewer cv[] = new Viewer[numCams];
    for (int i = 0;i < numCams; i++) {
    cv[i] = new Viewer();
    cv[i].m_parameters.put(PAR_ACCESSORIES, "none");
    String tmpStr = concatURL.toString() + i + ".a";
    cv[i].m_parameters.put("url", tmpStr);
    cv[i].m_camNum = i;
    f.add(BorderLayout.CENTER, cv[i]);
    cv[i].init();
    f.setVisible(true);
    cv[i].start();
    f.setVisible(false);

Maybe you are looking for