Synchronizer Token Pattern - Generic example

Hi
We have web applications not developped with struts or JSF, it's just a servlet/JSP design.
We have big troubles with multiple forms submitted at the login-form, so our intention it's to "protect" this page with the synchronizer token pattern.
Where i have to handle the request? In a filter? When do i put the token into the session and many more questions?
Do you hava me a concrete example of this pattern? Thanks very much!
Kind regards
Michael

There is already a components - Shale Token [1] that helps you solve double submit issue. The wiki is here [2]. The component is in shale-core.jar which you can find in the sample apps [3]
[1] http://shale.apache.org/
[2] http://wiki.apache.org/shale/Token
[3] http://people.apache.org/builds/shale/nightly/

Similar Messages

  • Synchronizer token and JSF

    Hello,
    I am just wondering if JSF offers a synchronizer token feature in order to avoid multiple form submissions.
    Thanks in advance,
    Albert Steed.

    Here's how I've implemented a token synchronizer pattern in my web app.
    This example has a session-scope Visit object and request-scope RequestBean:
      <managed-bean>
        <description>Session bean that holds data and delegates needed by request beans.</description>
        <managed-bean-name>visit</managed-bean-name>
        <managed-bean-class>com.example.Visit</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
      </managed-bean>
      <managed-bean>
        <description>Some request bean.</description>
        <managed-bean-name>reqBean</managed-bean-name>
        <managed-bean-class>com.example.RequestBean</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
        <managed-property>
          <property-name>visit</property-name>
          <value>#{sessionScope.visit}</value>
        </managed-property>
      </managed-bean>My Visit class has the following:
        private long activeToken;
        private long receivedToken;
         * This returns the active save token.  Note that this is not the same
         * variable that is set by the setSaveToken() method.  This is so we can put a
         * tag in a JSP:<br/>
         *   <h:inputHidden value="#{visit.saveToken}" /> <br/>
         * That will retrieve the active token from Visit when the page
         * is rendered, and when the page is returned, setSaveToken() sets the
         * received token.  The tokens can then be compared to see if a save
         * should be performed.  See BaseBean.generateToken() for more details.
         * @return Returns the active save token.
        public long getSaveToken() {
            return this.activeToken;
         * Sets the received token.  Note that this method is only intended to be
         * called by a JSF EL expression such as: <br/>
         *   <h:inputHidden value="#{visit.saveToken}" /> <br/>
         * See getSaveToken() for more details on why.
         * @param received token value to set
        public void setSaveToken(long aToken) {
            this.receivedToken = aToken;
        void setReceivedToken(long aToken) {
            this.receivedToken = aToken;
        long getReceivedToken() {
            return this.receivedToken;
        void setActiveToken(long aToken) {
            this.activeToken = aToken;
        long getActiveToken() {
            return this.activeToken;
         * @return true if the active and received token are both non-zero and they match
        boolean tokensMatchAndAreNonZero() {
            return (this.activeToken != 0) && (this.receivedToken != 0) && (this.activeToken == this.receivedToken);
    . . .My backing beans extend a base class BaseBean with these methods:
         * Generates a new save token, saving it to a field in Visit. Guaranteed to not
         * generate a 0 (0 is used to denote an expired token).<br/><br/>
         * This token is used to make sure that
         * actions that modify data in a way that should not be immediately repeated.
         * Call this method prior to rendering a page that will submit the non-repeatable
         * request.  Then before saving any data, call saveTokenIsInvalid() to see if the
         * save should be executed.  If the token is valid, expire it and proceed with
         * saving.<br/>
         * The view that submits an unrepeatable request should have the tag:<br/>
         *      <h:inputHidden value="#{visit.saveToken}" /><br/>
         * in it.  Visit.getSaveToken() will set this field with the active token when the
         * page is rendered.  Visit.setSaveToken() will set a received token field, which
         * can then be compared to the active token to find out whether a save should be
         * performed.
        protected void generateSaveToken() {
            logger.debug("generateSaveToken()");
            Random random = new Random();
            long token = random.nextLong();
            while (token == 0) {
                token = random.nextLong();
            this.getVisit().setActiveToken(token);
            this.getVisit().setReceivedToken(0);
         * Checks the save token to see if it is valid.
         * @true if the save token is invalid.  It is invalid if either the received or the active
         * tokens in Visit are zero, or if the tokens do not match.
        protected boolean saveTokenIsInvalid() {
            if (logger.isDebugEnabled() ) {
                logger.debug("saveTokenIsInvalid():\nactive token: " + this.getVisit().getActiveToken() + "\nrecv'd token: " + this.getVisit().getReceivedToken() );
            boolean isValid = this.getVisit().tokensMatchAndAreNonZero();
            // return the inverse because this method is called "saveTokenIsInvalid"
            return !isValid;
         * Sets active token to zero, preventing any saves by methods that check for valid save token
         * before committing a change until generateSaveToken() is called again.
        protected void expireSaveToken() {
            logger.debug("expireSaveToken()");
            this.getVisit().setActiveToken(0);
         * Logs an info message saying that a save action was not performed because of invalid save
         * token.  Returns given String as outcome.
         * @param logger for subclass calling this method
         * @param outcome
         * @return outcome
        protected String logInvalidSaveAndReturn(Logger subclassLogger, String outcome) {
            if (subclassLogger.isInfoEnabled() ) {
                subclassLogger.info("User " + this.getVisit().getUsername() + " submitted a save request that was not " +
                        "processed because the save token was not valid.  Returning outcome: '" + outcome + "'.");
            return outcome;
        // Used by JSF managed bean creation facility
        public Visit getVisit() {
            return this.visit;
        // Used by JSF managed bean creation facility
        public void setVisit(Visit visit) {
            this.visit = visit;
    . . .Any method that sets up a view containing a form I only want submitted once generates a token:
           this.generateSaveToken();And the token gets embedded in the HTML form with the tag:
    <h:inputHidden value="#{visit.saveToken}" />An action method in RequestBean would then use the token to prevent multiple identical saves as follows:
        public String someActionMethod() {
            // prevent identical requests from being processed
            String normalOutcome = Constants.NavOutcome.OK;
            if (this.saveTokenIsInvalid() ) {
                return this.logInvalidSaveAndReturn(logger, normalOutcome);
            this.expireSaveToken();
            logger.debug("save token is valid.  attempting to save....");
            try {
                  // invoke some business logic here
            } catch (MyException exc) {
                  // important: if you are returning the user to the same form view with an error message,
                  // and want to be able to process subsequent form submissions, then the token
                  // needs to be regenerated
                  this.generateSaveToken();
                  return null;
    . . .It has worked great so far. The only problems I've had are when I forget to generate or expire a token, or I forget to embed it in my form.
    I also had a problem where I expired the token after my business logic completed, and my business logic took about 30-60 seconds to process--if the user clicks on the submit button several times while waiting for the page to return, the backing bean method still sees a valid token and processes the request. This was solved by simply expiring the token prior to invoking the business logic (as shown in the above example).
    HTH,
    Scott

  • Is there a way to turn the pattern matching example in Labview to instead of loading a rectangle around what you want the template to be you can use an image display , I've be trying and can get no where with it

    What I want to do is , have two images on image displays and the pass them through the same setup as the pattern matching example to get the number of matches , I have attached what I have done and also given the pattern matching example program as well.
    Hope to get answers back soon,
                                     Thanks Alan
    Attachments:
    screenshot.docx ‏48 KB
    Pattern Matching Example.vi ‏100 KB

    Hi there!
    The example used can be adapted for comparing two images, however the algorithm and coding for finding the differences is more specific to your actual problem. In terms of the loading and displaying of the images, this can be done in the same way.
    Once you have some sort of algorithm, then you can automate the learning and matching by simply wiring them in order. (in the example, these are put in case structures as they are waiting on response from the front panel)
    I hope that this helps,
    Liam A.
    National Instruments
    Applications Engineer

  • JMS Patterns - Generic Message Handler

    Hi,
    For those interested in Java EE patterns, I've created a [blog post|http://jonathanjwright.wordpress.com/2009/08/12/jms-patterns-generic-message-handler/] outlining the use of a generic message handler to simplify MDB message type checking and payload extraction.
    Regards,
    Jonathan

    This requirement has now gone away after implementing SP21

  • JNDI generic example

    Hello. I am trying to execute a generic javax.naming.Context example, which reads the env variable to initialize the Context from a jndi.properties file. I am aware the at runtime Java looks at the class path for the prop file and I have changed my classpath to reflect the prop file such as classpath=JAVA_HOME\lib\jndi.properties, where JAVA_HOME is where my java lib exists.
    The program is:
    import javax.naming.*;
    class AppList {
    public static void main(String[] args) {
    String target = "";
    try {
         Context ctx = new InitialContext();
         NamingEnumeration enum = ctx.list(target);
         while (enum.hasMore()) {
         System.out.println(enum.next());
         } catch (NamingException e) {
         e.printStackTrace();
    However when I execute it I get the following error:
    javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
    at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
    at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
    at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
    at javax.naming.InitialContext.list(Unknown Source)
    at AppList.main(AppList.java:54)
    I am aware that this error means that environment variables could not be found to initalize the Context.
    I have tried changing my classpath, my JAVA_HOME, and my path to reflect the jndi.properties file, but nothing seem to work and I keep gettign he above exception.
    I would apprecaite if someone could shed some light on this matter.
    Thank you.

    I have not tried that but -
    This is a standard example from my code.
    It is not exactly what you want but it may help.
    The following variables are initialized elsewhere by reading from a control file.
    LDAPPROVIDER = "ldap://192.168.1.103:636";
    LDAPAUTHENTICATION = "simple";
    LADPPROTOCOL = "ssl";
    LDAPPRINCIPAL = "cn=wim,ou=roles,dc=wim,dc=ca";
    LDAPCREDENTIALS = "Test1234";
    // global variable to hold context
    public static DirContext ctx = null;
    public static DirContext openLDAPContext() {
      // set up the environment
      Hashtable env = new Hashtable();
      env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
      env.put(Context.PROVIDER_URL, LDAPPROVIDER);
      env.put(Context.SECURITY_AUTHENTICATION,LDAPAUTHENTICATION);
      env.put(Context.SECURITY_PROTOCOL, LADPPROTOCOL);
      env.put(Context.SECURITY_PRINCIPAL,LDAPPRINCIPAL);
      env.put(Context.SECURITY_CREDENTIALS,LDAPCREDENTIALS);
      env.put(Context.REFERRAL,"ignore");
      ctx = null;
      try {
        ctx = new InitialDirContext(env);
        // if here LDAP connection successfully
      catch (NamingException ex) {
        // *** LDAP SYSTEM ERROR
      // if return null connection failed
      return ctx;
    }[b[With a search I got these - any help?[/b]
    http://forum.java.sun.com/thread.jspa?forumID=51&threadID=91031
    http://forum.java.sun.com/thread.jspa?forumID=51&threadID=238059
    http://forum.java.sun.com/thread.jspa?forumID=51&threadID=222762
    http://forum.java.sun.com/thread.jspa?forumID=48&threadID=184798
    http://forum.java.sun.com/thread.jspa?forumID=48&threadID=445564
    rykk

  • Generic example

    Please tell me a generic datasource with scenario. I want to learn how to put join condition.

    Hi deepthi,
    Independently of application, you can create and maintain generic DataSources for transaction data, master data attributes or texts from any kinds of transparent tables, database views, InfoSets of the SAP query or using a function module. As a result, you can make use of the generic extraction of data.
    Procedure
    Creating a Generic DataSource
    1. Select the DataSource type and give it a technical name.
    2. Choose Create.
    The creating a generic DataSource screen appears.
    3. Choose an application component to which the DataSource is to be assigned.
    4. Enter the descriptive texts. You can choose any text.
    5. Choose from which datasets the generic DataSource is to be filled.
    a. Choose Extraction from View, if you want to extract data from a transparent table or a database view. Enter the name of the table or the database view.
    After generation, you get a DataSource whose extract structure is congruent with the database view or the transparent table view.
    For more information about creating and maintaining database views and tables, see the ABAP Dictionary Documentation.
    b. Choose Extraction from Query, if you want to use a SAP query InfoSet as the data source. Select the required InfoSet from the InfoSet catalog.
    Notes on Extraction Using SAP Query
    After generation, you now have a DataSource whose extract structure matches the InfoSet.
    For more information about maintaining the InfoSet, see the System Administration documentation.
    c. Choose Extraction using FM, if you want to extract data using a function module. Enter the function module and extract structure.
    The data must be transferred by the function module in an interface table E_T_DATA.
    Interface Description and Extraction Process Flow
    For information about the function library, see the ABAP Workbench: Tools documentation.
    d. With texts, you also have the option of extraction from domain fixed values.
    6. Maintain the settings for delta transfer where appropriate.
    7. Choose Save.
    When extracting, look at SAP Query: Assigning to a User Group.
    Note when extracting from a transparent table or view:
    If the extract structure contains a key figure field, that references to a unit of measure or currency unit field, this unit field must appear in the same extract structure as the key figure field.
    A screen appears in which you can edit the fields of the extract structure.
    8. Editing the DataSource:
    &#61601; Selection
    When scheduling a data request in the BW Scheduler, you can enter the selection criteria for the data transfer. For example, you may want to determine that data requests are only to apply to data from the previous month.
    If you set the Selection indicator for a field within the extract structure, the data for this field is transferred in correspondence with the selection criteria in the scheduler.
    Hide field&#61601;
    You should set this indicator to exclude an extract structure field from the data transfer. As a result of your action, the field is no longer made available in BW when setting the transfer rules and generating the transfer structure.
    &#61601; Inversion
    Reverse postings are possible for customer-defined key figures. For this reason, inversion is only possible for certain transaction data DataSources. These include DataSources that have a field that is indicated as an inversion field, for example, the field update mode in the DataSource 0FI_AP_3. If this field has a value, then the data records are interpreted as reverse records in BW.
    Set the Inversion indicator if you want to carry out a reverse posting for a customer-defined field (key figure). The value of the key figure is then transferred in inverted form (multiplied by –1) into BW.
    Field only&#61601; known in exit
    You can enhance data by extending the extract structure for a DataSource using fields in append structures.
    The indicator Field only known in Exit is set for fields of an append structure. In other words, by default these fields are not passed onto the extractor from the field list and selection table.
    Deselect the indicator Field Only Known in Exit to enable the Service API to pass on the append structure field to the extractor together with the fields of the delivered extract structures in the field list as well as in the selection table.
    9. Choose DataSource ® Generate.
    The DataSource is now saved in the source system.
    Maintaining Generic DataSources
    • Change the DataSource
    To change a generic DataSource, in the initial screen of DataSource maintenance, enter the name of the DataSource and choose Change.
    You can change the assignment of a DataSource to an application component as well as the texts of a DataSource. Double-clicking on the name of the table, view, InfoSet or extract structure takes you to the appropriate maintenance screen. Here you can make changes required to add new fields. You can fully swap transparent tables and database views, but not InfoSets. If you return to the DataSource maintenance and choose Create, the screen for editing a DataSource appears. To save the DataSource in the SAP source system, choose DataSource ® Generate.
    If you want to test extraction in the source system independently of a BW system, choose DataSource ® Test Extraction.
    • Delta DataSource
    In the Change Generic DataSource screen, you can delete any DataSources that are no longer relevant. If you are extracting data from an InfoSet, delete the associated query. If you want to delete a DataSource, this must not be connected to a BW system.
    For more information about extracting using SAP Query, see Extraction using the SAP Query.
    Plz assign points if helpful. This is the only way to say thanks.
    And give me ur ID i send u some helpful documents...
    Regards
    Rakesh Jangir

  • I just updated my iPod touch to IOS 5.0.1...but after that my iPod touch cannot synchronise with Itunes. the iTunes do detect the iPod and synchronize it but for examples a new song or aplication that i just download does not appear on my iPod...

    i just updated my iPod touch 4G to IOS 5.0.1. after that my ipod cannot synchronise with itunes. during connecting to itunes my ipod seem to be synchronised with itunes but the song or application that i just downloaded did not appear in my ipod.

    - First try a rset. Nothing will be lost.
    Reset iPod touch:  Hold down the On/Off button and the Home button at the same time for at
    least ten seconds, until the Apple logo appears.
    - Next try restoring from backup

  • How do i stop duplicate requests in Struts

    Hi
    I am working on a project and i am kinda stuck on this one issue, Our Test Engineer found this great bug;) Man he clicks the sumbit button more than once and wants the job done only once.
    How do i handle duplicate requests in struts, i found some articles which talk about SYNCHRONIZER TOKEN PATTERN, i believe this pattern is aleady implemented by Struts, is there something configurable that i am not aware of
    Please help me at this, we are at the flag end of the project
    Thanks

    I have used tokens in the past, but have not heard of a system pre-built in to struts. It is easy enought to implement your own simple version.
    All you need to do is store a counter, or 'token', in the user's session. This session value must be used in a thread-safe manner. The token value is inserted in to your forms as a hidden field.
    When the form is sent back, check that the form and session tokens match. If they do, increment the session token and process the submission. If a duplicate submission is recieved the values won't match, so throw an error, ignore etc.etc.
    --Jon                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How to make the session expire when the refresh button is clicked

    Hi All,
    I am writing a Struts application where I want the session to expire when the user clicks refresh button or refresh the page by hitting F5, like any Bank sites. Any help will be appreciated.

    The trick isn't invalidating the session. The trick is detecting refresh requests.
    The Synchronizer Token pattern can handle this.
    Struts can do this for you. Check out [this article|http://www.javaworld.com/javaworld/javatips/jw-javatip136.html?page=1]
    Cheers,
    evnafets

  • How to handle Back button, Browser Refresh problem at server side.

    Hi Friends,
    How to handle Back button, Browser Refresh problem at server side in java?.
    I am able to trace that,
    request.getHeader("ACCEPT") is returning value- */*
    when the browser was refreshed and returning different MIME types
    for all other actions from browser.
    I have doubt, will the above solution works always for all servers,browsers?.
    Please also specify any solution to handle back button at server side?.
    Thanks in Advance.
    Venkat..

    I'm sorry I don't think tht's the right solution for
    the above question....
    We must be aware that whatever scripting methdologies
    we either javascript/vbscript would executed @
    client(browser) side not @ server side....
    Dud If U get a good solution keep me updated.....
    THANKS & REGARDS,
    RAHULMy dear friend ...
    the bad news is that u simply cant disable or add any listener to the back button of the browser.
    When u hit the back button of ur browser the URL gets re-executed. So in case u have a JSP then the history.forward() is the best solution. [only if the page doesnt get expired similar to secure https sites]
    Now dont say that user can have javascript disabled ...those users will have a pretty touch time browsing websites since javascripts r used extensively by almost all websites.
    But in case u have an action.do or servlet call then u need to manage it using a session variable since the request will be sent to the server rather than client.
    For multiple form submittion issues read the following article in javaworld...
    Client vs. server solutions
    Different solutions can solve this multiple form submission situation. Some transactional sites simply warn the user to wait for a response after submitting and not to submit twice. More sophisticated solutions involve either client scripting or server programming.
    In the client-only strategy, a flag is set on the first submission, and, from then on, the submit button is disabled based on this flag. While appropriate in some situations, this strategy is more or less browser dependent and not as dependable as server solutions.
    For a server-based solution, the Synchronizer Token pattern (from Core J2EE Patterns) can be applied, which requires minimal contribution from the client side. The basic idea is to set a token in a session variable before returning a transactional page to the client. This page carries the token inside a hidden field. Upon submission, request processing first tests for the presence of a valid token in the request parameter by comparing it with the one registered in the session. If the token is valid, processing can continue normally, otherwise an alternate course of action is taken. After testing, the token resets to null to prevent subsequent submissions until a new token is saved in the session, which must be done at the appropriate time based on the desired application flow of control.
    for more details refer :
    http://www.javaworld.com/javaworld/javatips/jw-javatip136.html
    Hope u got the idea.
    FYI I have been using both these ideas in my credit card payment gateway project. This concept has worked really well.

  • Prevent user from making to many requests...

    Hallo everybody,
    We are using Tomcat 5.0 and have some large jsp's (reports) that consume large memory.
    1. Is there an easy way to prevent a user from making to many requests (eg. if he refreshes the page too many times, Tomcat gets an Out-of-memory error).
    Of cource increasing the memory is not the answer I'm looking for (already did that).
    2. Or may be a way to retrict a user to a certain maximum of memory
    This seems like a common problem; anyone have good advice?
    Thanks in advance.
    Marcus

    The main reason for multiple refreshes is the report taking too long to run and users getting impatient? Or is there another reason.
    1 - Give the users fair warning. Put a message on the page saying "this report takes time to run. do NOT refresh this page as then the report will take even longer"
    2 - You might set it up as a two stage process. Generate the report to a file. Then give them a link to check the progress of the report or load it if it is finished.
    That way when they refresh, they don't regenerate the report, but just get back a immediate response that tells them "come back later"
    3 - Perhaps you might consider the synchronizer token pattern.
    http://www.javaworld.com/javaworld/javatips/jw-javatip136.html
    4 - restricting users to max amount of memory would be difficult. How do you tell it is the same user? You could use a session variable, and record how many reports they have currently running, and reject any more then 3-4 requests at one time. But that could be worked around quite easily - just open up a new browser and its a new session.

  • Oop specificat​ion pattern example

    I'm new to OOP so forgive my basic question.
    In this link, https://decibel.ni.com/content/docs/DOC-13709 the specification pattern is discussed. Since I'm new to OOP, it would help me to understand this by having an example. I can't find one and the link commits the famous error of assuming that we are all experts and so the pattern is too simple to merit an included example. The article talks about them being all over the place, so obviously I don't understand the pattern. Would someone point me to a specific example of this pattern? I am just learning class diagrams as well, so the illustrations I have seen using UML aren't breaking the logjam either.
    Help?

    I think it would better for you to start here: https://decibel.ni.com/content/docs/DOC-15014
    This link will give you the basic for the LVOOP and has some examples.
    If you have any question to LVOOP feel free to post them at the forum.
    Once you get a better grib on LVOOP there are also a place on LAVA for LVOOP programming:
    http://lavag.org/forum/26-object-oriented-programm​ing/
    There are some good discustion over there on LVOOP and design patterns with examples.

  • Image processing on matched patterns

    Hi all
    I am using LabVIEW 7.1 for image processing. I have used the pattern matching example to suit my requirements.
    Now i want that whatever image processing operations i perform after pattern matching, like, threshold, circle detection, particle filter etc.. be
    performed only on those patterns which have been recognised & not on the entire image. How can this be done?
    Thanks all in advance

    Hi James,
    I suggest you to Extract that image from the main image by using ROI tools,
    and thereby the you are left with the cropped image for your analysis.
    Use this and paste this on a new blank image for your processing.
    Regards,
    Sundar.

  • How to use multiple patterns for masking/format the input text

    Hi All,
    I am using Jdeveloper 11.1.1.5 and i have a requirement where i need to format my input Text value in these below patterns:-
    Format
    Example
    AA9A 9AA
    EC1A 1BB
    A9A 9AA
    W1A 1HQ
    A9 9AA
    M1 1AA
    B33 8TH
    A99 9AA
    AA9 9AA
    CR2 6XH
    DN55 1PT
    AA99 9AA
    For Example :-  If user puts value as EC1A1BB, it should automatically changed to EC1A 1BB
                                 if user puts value as W1A1HQ, it should be automatically changed to W1A 1HQ and so on..
    If it could have been one format , i might have followed this :- https://blogs.oracle.com/jdevotnharvest/entry/get_social_security_numbers_right
    But for multiple patterns i am not able to get through to the proper solution.
    Is there any way to achieve this ? Please suggest.
    Regards,
    Shah

    For the validation you should be able to use one regular expression where you add the logical or (|)  (check the doc http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html) between the groups. If none of the patterns matches you have an error.
    For the for formatting I'm not sure you can use only one expression.
    I suggest to write one method which does the checking on and the formatting may be using an array of patterns to check and iterate the patterns in a loop. Once you found a match you can read the needed format from another array (or an other dimension if you prefer to use a multidimensional array).
    Timo

  • How to Look at current Token

    When using the tokenizer in Java I see that you can count tokens "countTokens() " , see if a string has more tokens "hasMoreTokens()", etc. But how do you work with the current token?
    For example:
    while ((str = in.readLine()) != null )
         StringTokenizer tokens = new StringTokenizer(str);
         while (tokens.hasMoreTokens())
              System.out.println( tokens.nextToken() + "\n" );
              //tokenStr = tokens.nextToken();
              count++;
              //if (tokenStr.equals("<body>"))
              //     bodycount++;
             }I can count all the tokens in the string but how can I count the tokens "<body>"?
    Any help please
    eddiemjm

    You are almost there. Trywhile ((str = in.readLine()) != null )
         StringTokenizer tokens = new StringTokenizer(str);
         while (tokens.hasMoreTokens())
              tokenStr = tokens.nextToken();
              System.out.println( tokenStr + "\n" );
              count++;
              if (tokenStr.equals("<body>"))
                   bodycount++;
             }Note the change and move of the println() call.

Maybe you are looking for

  • How to Handle Junk Characters in BI Publisher Report?

    Hi Team, I have Created a column in obiee analytics report which has logic as '1/0'. After creating this column I am not getting result for this column(blank). When Extracted the report into XML file,I am not able to see value for that column as well

  • CSS tags and classes

    Hi, after playing around with css for a night, i still cannot figure out whats the difference between using a class and tag css. Under what circumstances should i use them? Helps are greatly appreciated. Thanks.

  • Contract N-Step approval workflow - WS14000148

    Hi, I have activated the workflow template WS14000148 and implemented the badi definition 'BBP_WFL_APPROV_BADI' to populate the agents for routing the workflow notification. When i create a contract, the workitem is going to the corresponding manager

  • Using RDBMS Security Realm in production?

    Hi, In the BEA documentation it is stated that 'The RDBMS Security Realm is an example and is not ment to be used in a production environment.' However, of the Realms that are available this one seems to be best suited for our needs, so I'm wondering

  • JES4 Gateway issues

    I'm having a gateway,rewriter proxy for my portal server 6.3. All the copmonenst are JES4 version. When I try to access the portal desktop, I get the following error: Unable to connect to host - Session: Unable to connect to host: xyz.abc.com The mes