Reading sequence of characters in Java-----HELP!!!

I need help with this program here..Im new to Java and struggling to get this to work..here's the problem..
The program monitors a possibly infinite stream of characters from the keyboard (standard input). If it detects the sequence "www" it outputs a "0". If it detects the sequence "wow" it outputs a "1". DO NOT detect sequences within sequences. The program should exit cleanly when it detects an End Of Input. For example:
The following sequence wwowowwwowww<End Of Input> would produce the following result: 100
While the following sequence wwwowowwwwoowowow<End Of Input> would produce the following result: 0101

If you want to catch each key input realtime, you should use KeyEvent in a Swing/AWT GUI program. Capture each triplet in a small char array and compare it against "www" or "wow".
Here's a simple code that shows the principle:
public class Exl5{
  public static void main(String[] args){
    String s1 = "wwowowwwowww";
    String s2 = "wwwowowwwwoowowow";
    System.out.println(convert(s1));
    System.out.println(convert(s2));
  static String convert(String s){
    StringBuffer sb = new StringBuffer();
    int p = 0;
    while (p < s.length() - 2){
      String ss = s.substring(p, p + 3);
      if (ss.equals("wow")){
        sb.append("1");
        p += 3;
      else if (ss.equals("www")){
        sb.append("0");
        p += 3;
      else{
        ++p;
    return new String(sb);
}

Similar Messages

  • Printing unicode characters in Java - help

    Hi there,
    I want to print out unicode characters through java programming language in windows system. For example, I want to print Devanagari characters. I found out that '\u0900' to '\u0975' represent devanagari characters. So I tried following,
    out = new PrintStream(System.out, true, "UTF-8");
    out.println('\u0911');
    but they print characters like ��� and not the actual devanagari characters. Just to be more clear, devanagari script is used by Hindi, Nepali and similar languages.
    If you knew about it and could give any suggestions, that would be very helpful.
    Thanks in advance!

    priyankabhar wrote:
    I am not sure, it is just a windows system and I am trying to print to the command line. Please suggest me how I can find out if my console supports it.Use the CHCP command to find out what code page your console uses. And as already suggested, Google is a good resource if you don't know what a "code page" is.

  • Replacing a sequence of characters

    Hello,
    I'm quite surprise (but I am sure that I miss something) that JAVA doesn't give us the equivalent of the function " ereg_replace " in PHP.
    Thus, i ask if there is any equivalent method as "replace" but for a String variable and
    not for a Char ?
    By example, i wish to replace in the following sequence of characters " 256; 134;; 45; 56;; 33; 33; 36; 98; 203;; 57 " each of 2 semicolons which follow each other By "; 0; ".
    I can use " indexOf ", combined with setCharAt (via StringBuffer) for example, but that annoys me to do this, because I have the impression to miss something.
    Thanks in advance.
    JP.

    I'm quite surprise (but I am sure that I miss
    something) that JAVA doesn't give us the equivalent of
    the function " ereg_replace " in PHP.Java is not a domain-specific language (as PHP is) and so it cannot (and shouldn't) afford to include all the possible domain-specific functions into the language.
    Such functionality is usually added by libraries, either standard (java.* and javax.* packages) or 3-d party.
    For regex functions you can choose from:
    - java.util.regex.* package, since JDK 1.4
    - jregex.* package, 3-d party, see http://jregex.sourceforge.net
    - other 3-d party packages, like jakarta-oro, gnu.regexp, etc.
    I can use " indexOf ", combined with setCharAt (via
    StringBuffer) Too burdensome. Use regular expressions.

  • How to read sequence numbers from RTP packets

    hi everyone.
    i want to know how to read sequence numbers of RTP packets. I will need that to reconstruct my stream from packet losses.
    URGENT Help needed!!

    The StreamTokenizer parses all numbers into only one type of value, a double. If you know that all the numeric values in the file will be integers, you could just cast the nval double field to an int and the toString() method will format it correctly.
    If you want to have different tokens and value types for different kinds of numbers, you will have to sub-class StreamTokenizer and add these capabilities yourself. You can add the type constant TT_INT, and provide an int field named ival. The toString() method would then format the value in the correct manner.
    If, on the other hand, you are actually looking for the exact text that was parsed, you could add code that collects the characters as they are parsed for any token type into the sval field in the nextToken() method, just like it already does when the token is a TT_WORD. In this manner sval is always valid for any token type.
    I hope you find this of some help.

  • Passing a wchar_t* containing asian characters into java

    I tried converting the wchar_t* into jstring in C, then passing that jstring into java, however, even though when I write the wchar_t* into a file, the asian characters read fine, the jstring in java becomes ????????????. Then I tried narrowing the wchar_t* into char*, then converting into jstring and passing that. Similarly, the char*, when written to a file, contains the proper asian characters, but when read in java, becomes ????????????.
    Any help is appreciated!

    ejp wrote:
    Java strings contain UTF8.Java Strings contain UTF-16.True - I was thinking more of GetStringUTFChars when I said that.
    A wchar is not even necessarily 8 bitsA wchar_t is necessarily at least 16 bits taking ISO/IEC 14882:1998 standard #3.9.1.5 into account.
    Interesting - I will look that up. The following discussion would seem to disagree with that however.
    [http://www.velocityreviews.com/forums/t289787-is-wchar_t-guaranteed-to-be-larger-than-char.html]

  • Special double quotes and apostrophes in java help

    We are writing help for an application and using doctor help to generate it. The help is written in Word and converted to html. Word however, converts all the " characters to those "squiggly ones" which point towards the word they're quoting.
    When we viewed the generated help with java help those squiggly were not rendered. They are rendered as a square which means java help does not understand them.
    I'm sure someone else must have encountered this issue.
    Please can you tell me how to successfully render the squiggly double quotes in java help?

    You need the following encoding for those characters:
    &#8220;
    &#8221;
    using an xml encoder, e.g. xmlenc solves this issue, otherwise you must do it manually.
    But I have a related problem. When characters in the XML file are encoded
    they are only displayed correctly if some non encoded character follows.
    When there are two successive encoded characters then only the first one
    is displayed correctly. Putting a whitespace in between them displays both
    characters correctly, but with the whitespace in between.
    I guess there is an issue with the XML parser. Changing the encoding of the XML file does not help.
    example: TOC.xml file (displayed correctly in IE)
    <?xml version='1.0' encoding='ISO-8859-9' standalone='yes' ?>
    <!DOCTYPE toc PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp TOC Version 1.0//EN" "http://java.sun.com/products/javahelp/toc_1_0.dtd"><!--generated by JHelpDev Version: 0.4, 18 August 2005, see jhelpdev.sourceforge.net-->
    <toc version="1.0">
    <tocitem text="images "/>
    <tocitem text="&#286;&#286;RENC&#304; MOD&#220;L&#220; " target="index"/>
    </toc>
    Any ideas?

  • XSLT mapping with Java helper classes

    Hi,
    I'm trying to implement a XSLT mapping to convert my request to a specific soap request message format for this I'm calling some methods from a java helper class. I have imported the jar file into the archives. When I tried to test the interface it keeps complaing there is some exception but doesn't give me the exact error. Has any one called any java helper classes with in XSLT mapping, if so I would appreciate if you could help me with this. Here is the code from xsl.
    <wsse:Security soapenv:actor="http://schemas.xmlsoap.org/soap/actor/next" soapenv:mustUnderstand="0" xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/07/secext"   xmlns:UserToken="java:com.company.test.mapping.UserTokenMap">
    <wsse:UsernameToken>
        <wsse:Username xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
          <xsl:value-of select="UserToken:getUsername()"/>
        </wsse:Username>
        <wsse:Password wsse:Type="wsse:PasswordDigest" xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
        <xsl:value-of select="UserToken:getPasswordDigest()"/>
        </wsse:Password>
        <wsse:Nonce xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
        <xsl:value-of select="UserToken:getNonce()"/>
        </wsse:Nonce>
        <wsu:Created xsi:type="soapenc:string" xmlns:wsu="http://schemas.xmlsoap.org/ws/2002/07/utility" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
        <xsl:value-of select="UserToken:getCreateDate()"/>
    </wsu:Created>
    </wsse:UsernameToken>
    </wsse:Security>
    Thanks,
    Joe

    Hi,
    I'm getting following exception when I refer to the java class with in my XSLT mapping. Any one encountered the same problem.
    com.sap.engine.services.ejb.exceptions.BaseRemoteException:
    Exception in method transform.
         at com.sap.aii.ibrep.sbeans.mapping.MapServiceRemoteObjectImpl0.transform(MapServiceRemoteObjectImpl0.java:218)
         at com.sap.aii.ibrep.sbeans.mapping.MapServiceRemoteObjectImpl0p4_Skel.dispatch(MapServiceRemoteObjectImpl0p4_Skel.java:104)
         at com.sap.engine.services.rmi_p4.DispatchImpl._runInternal(DispatchImpl.java:320)
         at com.sap.engine.services.rmi_p4.DispatchImpl._run(DispatchImpl.java:198)
         at com.sap.engine.services.rmi_p4.server.P4SessionProcessor.request(P4SessionProcessor.java:129)
         at com.sap.engine.core.service630.context.cluster.session.ApplicationSessionMessageListener.process(ApplicationSessionMessageListener.java:33)
         at com.sap.engine.core.cluster.impl6.session.MessageRunner.run(MessageRunner.java:41)
         at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37)
         at java.security.AccessController.doPrivileged(Native
    Method)
         at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:100)
         at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:170)
    Caused by: java.lang.UnsupportedClassVersionError:
    com/earthlink/xi/mapping/UserTokenMap (Unsupported
    major.minor version 49.0)
         at java.lang.ClassLoader.defineClass0(Native
    Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:539)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:448)
         at com.sap.aii.ibrep.server.mapping.ibrun.RepMappingLoader.findClass(RepMappingLoader.java:175)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:289)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:235)
         at com.sap.engine.lib.xsl.xpath.JLBLibrary.<init>(JLBLibrary.java:33)
         at com.sap.engine.lib.xsl.xpath.LibraryManager.getFunction(LibraryManager.java:69)
         at com.sap.engine.lib.xsl.xpath.ETFunction.evaluate(ETFunction.java:98)
         at com.sap.engine.lib.xsl.xpath.XPathProcessor.innerProcess(XPathProcessor.java:56)
         at com.sap.engine.lib.xsl.xpath.XPathProcessor.process(XPathProcessor.java:43)
         at com.sap.engine.lib.xsl.xpath.XPathProcessor.process(XPathProcessor.java:51)
         at com.sap.engine.lib.xsl.xslt.XSLValueOf.process(XSLValueOf.java:76)
         at com.sap.engine.lib.xsl.xslt.XSLNode.processFromFirst(XSLNode.java:296)
         at com.sap.engine.lib.xsl.xslt.XSLElement.process(XSLElement.java:248)
         at com.sap.engine.lib.xsl.xslt.XSLNode.processFromFirst(XSLNode.java:296)
         at com.sap.engine.lib.xsl.xslt.XSLElement.process(XSLElement.java:248)
         at com.sap.engine.lib.xsl.xslt.XSLNode.processFromFirst(XSLNode.java:296)
         at com.sap.engine.lib.xsl.xslt.XSLElement.process(XSLElement.java:248)
         at com.sap.engine.lib.xsl.xslt.XSLNode.processFromFirst(XSLNode.java:296)
         at com.sap.engine.lib.xsl.xslt.XSLElement.process(XSLElement.java:248)
         at com.sap.engine.lib.xsl.xslt.XSLNode.processFromFirst(XSLNode.java:296)
         at com.sap.engine.lib.xsl.xslt.XSLElement.process(XSLElement.java:248)
         at com.sap.engine.lib.xsl.xslt.XSLNode.processFromFirst(XSLNode.java:296)
         at com.sap.engine.lib.xsl.xslt.XSLTemplate.process(XSLTemplate.java:272)
         at com.sap.engine.lib.xsl.xslt.XSLStylesheet.process(XSLStylesheet.java:463)
         at com.sap.engine.lib.xsl.xslt.XSLStylesheet.process(XSLStylesheet.java:431)
         at com.sap.engine.lib.xsl.xslt.XSLStylesheet.process(XSLStylesheet.java:394)
         at com.sap.engine.lib.jaxp.TransformerImpl.transformWithStylesheet(TransformerImpl.java:398)
         at com.sap.engine.lib.jaxp.TransformerImpl.transform(TransformerImpl.java:240)
         at com.sap.aii.ibrep.server.mapping.ibrun.RepMappingTransformer.transform(RepMappingTransformer.java:150)
         at com.sap.aii.ibrep.server.mapping.ibrun.RepXSLTMapping.execute(RepXSLTMapping.java:81)
         at com.sap.aii.ibrep.server.mapping.ibrun.RepSequenceMapping.execute(RepSequenceMapping.java:54)
         at com.sap.aii.ibrep.server.mapping.ibrun.RepMappingHandler.run(RepMappingHandler.java:80)
         at com.sap.aii.ibrep.server.mapping.rt.MappingHandlerAdapter.run(MappingHandlerAdapter.java:107)
         at com.sap.aii.ibrep.server.mapping.ServerMapService.transformInterfaceMapping(ServerMapService.java:127)
         at com.sap.aii.ibrep.server.mapping.ServerMapService.transform(ServerMapService.java:104)
         at com.sap.aii.ibrep.sbeans.mapping.MapServiceBean.transform(MapServiceBean.java:40)
         at com.sap.aii.ibrep.sbeans.mapping.MapServiceRemoteObjectImpl0.transform(MapServiceRemoteObjectImpl0.java:167)
         ... 10 more
    ; nested exception is:
         java.lang.UnsupportedClassVersionError:
    com/earthlink/xi/mapping/UserTokenMap (Unsupported
    major.minor version 49.0)

  • Sir i am using datasocket read ,i am communicating with java but my problem is that bcz im using while loop to see if value has changed my labview consumes all the processors time ,sir i want a event like thing so that while loop is not in continuous loop

    sir i have given lot of effort but i am not able to solve my problem either with notifiers or with occurence fn,probably i do not know how to use these synchronisation tools.

    sir i am using datasocket read ,i am communicating with java but my problem is that bcz im using while loop to see if value has changed my labview consumes all the processors time ,sir i want a event like thing so that while loop is not in continuous loopHi Sam,
    I want to pass along a couple of tips that will get you more and better response on this list.
    1) There is an un-written rule that says more "stars" is better than just one star. Giving a one star rating will probably eliminate that responder from individuals that are willing to anser your question.
    2) If someone gives you an answer that meets your needs, reply to that answer and say that it worked.
    3) If someone suggests that you look at an example, DO IT! LV comes with a wonderful set of examples that demonstate almost all of the core functionality of LV. Familiarity with all of the LV examples will get you through about 80% of the Certified LabVIEW Developer exam.
    4) If you have a question first search the examples for something tha
    t may help you. If you can not find an example that is exactly what you want, find one that is close and post a question along the lines of "I want to do something similar to example X, how can I modify it to do Y".
    5) Some of the greatest LabVIEW minds offer there services and advice for free on this exchange. If you treat them good, they can get you through almost every challenge that can be encountered in LV.
    6) If English is not your native language, post your question in the language you favor. There is probably someone around that can help. "We're big, we're bad, we're international!"
    Trying to help,
    Welcome to the forum!
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • How to bundle java help class into jar file ?

    Hi, all,
    I have some package in my project, with which I have a java help jar file as classpath, when I run my project, I need the jh.jar file in directory /jar/jh.jar.
    Now, I bundled all my class packages into a jar file, my.jar, together with the /jar directory. When i run my jar file with command:
    java -jar my.jar
    It tells me couldn't find javahelp class.
    What shall I do? How can I create my jar file with the jh.jar?
    Thanks in advance.

    I think you'd be better off just adding the jh.jar as
    a classpath argument and running it like that:
    java -classpath /myjavalibdir/jh.jar -jar myjar.jar
    ...otherwise you're stepping into redistribution of
    binary issues licensing-wise. That won't work either; when you run java with the -jar option, it ignores both the -classpath option and the CLASSPATH environment variable. However, it will see jh.jar automatically if you put it in the <path-to-java>/jre/lib/ext directory. But for distribution purposes, it might be simpler just to combime the contents of jh.jar into myjar.jar (if you use Ant, its <jar> task makes that very easy). Or, you can just run it this way:java -classpath myjar.jar;jar/jh.jar MyMainClassBTW, I don't think redistribution is a problem; otherwise how anyone even use JavaHelp?

  • Browsers no longer able to read russian / cyrillic characters

    Ever since i upgrading to Snow Leopard just recently i noticed that my all browsers (safari, firefox, chrome etc) are unable to read russian / cyrillic characters. While i can type russian letters in the search bar or in pages / key notes for example i can not read or write in the browsers.
    As an example if i go to google.ru i can't read the writing ... I've uploaded a screenshot for you to see here: http://cl.ly/0g2u0e10363I2b1a0i1f/
    The text encoding is set how should be also.
    Please let me know if you can help ...

    As an example if i go to google.ru i can't read the writing ... I've uploaded a screenshot for you to see here: http://cl.ly/0g2u0e10363I2b1a0i1f/
    Very strange! There is of course one word which you can in fact read, namely веб at the upper left, the only one which is not a link of some sort. Could you provide another example where the site is showing text and not links?

  • How to get/read region item value in java script

    Hi All,
    i have text item on a page.
    how to read the item value in java script
    EXAMPLE
    P10_RESULT IS ITEM IT HAS VALUE "38.956472,-77.447777","38.999123,-77.026184","12.951497,70.668646","17.459075,78.456888"
    NOW I WANT TO REFER ABOVE ITEM VALUE IN JAVA SCRIPT LIKE
    var myPoints=new Array(&P10_RESULT.);
    SO I CAN POPULATE ARRAY WITH CORDINATES
    IT IS NOT WORKING
    WHAT IS THAT I AM MISSING.
    PLESE HELP .
    ThankS
    Rk

    region header code....
    <script src="http://maps.google.com/maps?file=api&v=2&key=&API_KEY." type="text/javascript"></script>
    <script type="text/javascript">
    //<![CDATA[
    //globals
    var bounds = new GLatLngBounds();
    var map;
    var centerPoint = new GLatLng(38.984898,-76.854549);
    var gmarkers = [];
    //var x= ""38.956472,-77.447777","38.999123,-//77.026184","12.951497,70.668646","17.459075,78.456888"";
    //var myPoints=new Array(x);
    //var myPoints=new Array($x('P10_RESULT').value);
    var myPoints=new Array(document.getElementById('P10_RESULT').value);
    //var myPoints=new Array("38.956472,-77.447777","38.999123,-77.026184","12.951497,70.668646","17.459075,78.456888");
    function initMap()
              doLoad();
                        addMarkers();
    function doLoad()
         if (GBrowserIsCompatible())
                   map = new GMap2(document.getElementById("map"));
                   map.setCenter(centerPoint, 7);
                   map.addControl(new GScaleControl());
                   map.addControl(new GLargeMapControl());
                   map.addControl(new GMapTypeControl());
    function myclick(i) {
    GEvent.trigger(gmarkers, "click");
    function addMarkers() {
         if (myPoints.length) {
              var bounds = new GLatLngBounds();
              for (n=0 ; n < myPoints.length ; n++ ) {
                   var mData = myPoints[n].split(',');
                   var point = new GLatLng(mData[0],mData[1]);
                   bounds.extend(point);
                   var marker = createMarker(mData[1],point, mData[0]);
         map.addOverlay(marker);
              map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
    function createMarker(i,point, title) {
         var marker = new GMarker(point,{title:title});
         GEvent.addListener(marker, "click", function() {
              marker.openInfoWindowHtml('<div style="width:250px;">' + title + '<hr>Lat: ' + point.y + '<br>Lon: ' + point.x + '</div>');
         gmarkers[i] = marker;
         return marker;
    //]]>
    </script>
    page body code
    onload="initMap()" onunload="GUnload()"

  • Java Error in RFC Lookup in XSLT Mapping usinf Java helper class

    Hi All,
    I am doing RFC Lookup in XSLT Mapping using Java Helper class.
    The Lookup works fine when called one RFC at a time However my requirement is I want to do 2 Lookups.
    Both Lookups works when done individually however when I call both lookups in one mapping I get following error "javax.xml.transform.TransformerException: DOMSource whose Node is null."
    Following is the code I have written in XSLT for the lookup:
         <xsl:template name="Lookup_1">
              <xsl:param name="STDPN"/>
                   <rfc:RFC_READ_TABLE>
                        <QUERY_TABLE>KNA1</QUERY_TABLE>
                        <OPTIONS><item><TEXT>
                                  <xsl:value-of select="$STDPN"/>
                             </TEXT></item>
                        </OPTIONS>
                        <FIELDS>
                             <item>
                                  <FIELDNAME>KUNNR</FIELDNAME>
                             </item>
                        </FIELDS>
                   </rfc:RFC_READ_TABLE>
              </xsl:variable>
              <xsl:variable name="response" xmlns:lookup="java:urn.mt.pi" select="lookup:execute($request, 'BS_D, 'cc_RfcLookup', $inputparam)"/>
              <xsl:element name="STDPN">
                   <xsl:value-of select="$response//DATA/item/WA"/>
              </xsl:element>
         </xsl:template>
         <xsl:template name="Lookup_2">
              <xsl:param name="BELNR"/>
                   <xsl:variable name="Query">AGMNT = '<xsl:value-of select="$BELNR"/>'</xsl:variable>
                   <xsl:variable name="request1">
                        <rfc:RFC_READ_TABLE>
                             <QUERY_TABLE>ZTABLE</QUERY_TABLE>
                             <OPTIONS><item><TEXT>
                                  <xsl:value-of select="$Query"/>
                                  </TEXT></item>
                             </OPTIONS>
                             <FIELDS>
                                  <item>
                                       <FIELDNAME>KUNAG</FIELDNAME>
                                  </item>
                             </FIELDS>
                        </rfc:RFC_READ_TABLE>
                   </xsl:variable>
                   <xsl:variable name="response1" xmlns:lookup="java:urn.mt.pi" select="lookup:execute($request1, 'BS_D','cc_RfcLookup', $inputparam)"/>
                   <xsl:element name="BELNR">
                        <xsl:value-of select="$response1//DATA/item/WA"/>
                   </xsl:element>
         </xsl:template>
    My Question: Am I doing anything wrong? Or Is it possible to call multiple lookups in one XSLT?
    Thanks and Regards,
    Atul

    Hi Atul,
    I had the same problem like you had.
    The main Problem is that with the example code the request variable is created as NodeList object. In XSLT a variable is somekind of a constant and can't be changed. As the request object is empty after the first request the programm fails at the following line:
    Source source = new DOMSource(request.item(0));
    So I've created a workaround for this problem.
    In the call of the template I've put the request as a parameter object at the template call:
    <xsl:with-param name="req">
    <rfc:PLM_EXPLORE_BILL_OF_MATERIAL xmlns:rfc="urn:sap-com:document:sap:rfc:functions">
      <APPLICATION>Z001</APPLICATION>
      <FLAG_NEW_EXPLOSION>X</FLAG_NEW_EXPLOSION>
      <MATERIALNUMBER><xsl:value-of select="value"/></MATERIALNUMBER>
      <PLANT>FSD0</PLANT>
      <VALIDFROM><xsl:value-of select="//Recordset/Row[name='DTM-031']/value"/></VALIDFROM>
      <BOMITEM_DATA/>
    </rfc:PLM_EXPLORE_BILL_OF_MATERIAL>
    </xsl:with-param>
    With this change the request will be provided as a String object and not as a NodeList object.
    Afterwards the RfcLookup.java has to be changed to the following:
    package com.franke.mappings;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.PrintWriter;
    import java.io.StringWriter;
    import java.util.Map;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Source;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import com.sap.aii.mapping.lookup.Channel;
    import com.sap.aii.mapping.api.StreamTransformationConstants;
    import com.sap.aii.mapping.api.AbstractTrace;
    import com.sap.aii.mapping.lookup.RfcAccessor;
    import com.sap.aii.mapping.lookup.LookupService;
    import com.sap.aii.mapping.lookup.XmlPayload;
    * @author Thorsten Nordholm Søbirk, AppliCon A/S
    * Helper class for using the XI Lookup API with XSLT mappings for calling RFCs.
    * The class is generic in that it can be used to call any remote-enabled
    * function module in R/3. Generation of the XML request document and parsing of
    * the XML response is left to the stylesheet, where this can be done in a very
    * natural manner.
    * TD:
    * Changed the class that request is sent as String, because of IndexOutOfBound-exception
    * When sending multiple requests in one XSLT mapping.
    public class RfcLookup {
         * Execute RFC lookup.
         * @param request RFC request - TD: changed to String
         * @param service name of service
         * @param channelName name of communication channel
         * @param inputParam mapping parameters
         * @return Node containing RFC response
         public static Node execute( String request,
                 String service,
                 String channelName,
                 Map inputParam)
              AbstractTrace trace = (AbstractTrace) inputParam.get(StreamTransformationConstants.MAPPING_TRACE);
              Node responseNode = null;
              try {
                  // Get channel and accessor
                  Channel channel = LookupService.getChannel(service, channelName);
                  RfcAccessor accessor = LookupService.getRfcAccessor(channel);
                   // Serialise request NodeList - TD: Not needed anymore as request is String
                   /*TransformerFactory factory = TransformerFactory.newInstance();
                   Transformer transformer = factory.newTransformer();
                   Source source = new DOMSource(request.item(0));
                   ByteArrayOutputStream baos = new ByteArrayOutputStream();
                   StreamResult streamResult = new StreamResult(baos);
                   transformer.transform(source, streamResult);*/
                    // TD: Add xml header and remove linefeeds for the request string
                    request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+request.replaceAll("[\r\n]+", ""); 
                    // TD: Get byte Array from request String to send afterwards
                    byte[] requestBytes = request.getBytes();
                   // TD: Not used anymore as request is String
                    //byte[] requestBytes = baos.toByteArray();
                    trace.addDebugMessage("RFC Request: " + new String(requestBytes));
                    // Create input stream representing the function module request message
                    InputStream inputStream = new ByteArrayInputStream(requestBytes);
                    // Create XmlPayload
                    XmlPayload requestPayload =LookupService.getXmlPayload(inputStream);
                    // Execute lookup
                    XmlPayload responsePayload = accessor.call(requestPayload);
                    InputStream responseStream = responsePayload.getContent();
                    TeeInputStream tee = new TeeInputStream(responseStream);
                    // Create DOM tree for response
                    DocumentBuilder docBuilder =DocumentBuilderFactory.newInstance().newDocumentBuilder();
                    Document document = docBuilder.parse(tee);
                    trace.addDebugMessage("RFC Response: " + tee.getStringContent());
                    responseNode = document.getFirstChild();
              } catch (Throwable t) {
                   StringWriter sw = new StringWriter();
                   t.printStackTrace(new PrintWriter(sw));
                   trace.addWarning(sw.toString());
              return responseNode;
         * Helper class which collects stream input while reading.
         static class TeeInputStream extends InputStream {
               private ByteArrayOutputStream baos;
               private InputStream wrappedInputStream;
               TeeInputStream(InputStream inputStream) {
                    baos = new ByteArrayOutputStream();
                    wrappedInputStream = inputStream;
               * @return stream content as String
               String getStringContent() {
                    return baos.toString();
              /* (non-Javadoc)
              * @see java.io.InputStream#read()
              public int read() throws IOException {
                   int r = wrappedInputStream.read();
                   baos.write(r);
                   return r;
    Then you need to compile and upload this class and it should work.
    I hope that this helps you.
    Best regards
    Till

  • How to read a text file using Java

    Guys,
    Good day!
    Please help me how to read a text file using Java and create/convert that text file into XML.
    Thanks and God Bless.
    Regards,
    I-Talk

         public void fileRead(){
                 File aFile =new File("myFile.txt");
             BufferedReader input = null;
             try {
               input = new BufferedReader( new FileReader(aFile) );
               String line = null;
               while (( line = input.readLine()) != null){
             catch (FileNotFoundException ex) {
               ex.printStackTrace();
             catch (IOException ex){
               ex.printStackTrace();
         }This code is to read a text file. But there is no such thing that will convert your text file to xml file. You have to have a defined XML format. Then you can read your data from text files and insert them inside your xml text. Or you may like to read xml tags from text files and insert your own data. The file format of .txt and .xml is far too different.
    cheers
    Mohammed Jubaer Arif.

  • Code Sample: Easy RFC Lookup From XSLT Mappings Using a Java Helper Class

    Hi everyone,
    This is just a shameless plug for my article: <a href="https://www.sdn.sap.comhttp://www.sdn.sap.comhttp://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/05a3d62e-0a01-0010-14bc-adc8efd4ee14">Easy RFC Lookup From XSLT Mappings Using a Java Helper Class</a>. I hope you're interested in reading it, and I welcome your comments in this thread.
    Kind regards,
    Thorsten

    Hi Stefan. Thanks for your post. I have already done that. It still does not work. As a base for my java helper class I have usesd Thorstens code.
    The problem is quite confusing. I will try to ouline both issues here.
    First of all, when try to test from within the Operation Mapping, I always get a java error saying it cannot find the communication channel (it is there and working because I have tested it with the RFCLookup in graphical mapping). I have found a way to work around this, and that is to uncheck the "Use SAP XMLToolkit" checkbox --> switch to test tab, enter my ReceiverService in the parameter tab (header parameter) --> switch back to Definition tab, check the "Use SAP XMLToolkit" checkbox --> switch to Test tab and run the test. Then the XSLT and call to java helper class will work. Of course this is not really something you want to do all the time. Maybe there is a bug.
    Secondly, it never works when I try to do it "live". I am using a file adapter to pick up one file, convert it and a file adapter to drop the converted file. I get the following error code in SXMB_MONI.
    <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
    <!--  Request Message Mapping   -->
    <SAP:Error xmlns:SAP="http://sap.com/xi/XI/Message/30" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" SOAP:mustUnderstand="">
      <SAP:Category>Application</SAP:Category>
      <SAP:Code area="MAPPING">TRANSFORMER_CONF_EX</SAP:Code>
      <SAP:P1>ATJ_Accounting2XML_Accounting.xsl</SAP:P1>
      <SAP:P2>http://rd.accounting.logica.com</SAP:P2>
      <SAP:P3>fd552c30-bad9-11dd-9761-c21dac1b818c</SAP:P3>
      <SAP:P4>-1</SAP:P4>
      <SAP:AdditionalText />
      <SAP:Stack>TransformerConfigurationException triggered while loading XSLT mapping ATJ_Accounting2XML_Accounting.xsl; http://rd.accounting.logica.comfd552c30-bad9-11dd-9761-c21dac1b818c-1</SAP:Stack>
      <SAP:Retry>M</SAP:Retry>
      </SAP:Error>
    Using an XSLT without a call to a java helper class, works just fine.
    I am totally at a loss here. Any more input would be much appreciated.
    /Patrik

  • How to Read a CAB File from JAVA?

    Hi,
    Anyone knows how to read a CAB File from java. I need to read a property file of txt file that is packaged in CAB file & then based on that, I have to do processing. Is there anyway to do it.
    I had tried using java.util.zip.ZipFile Class, but it does work for JAR, but not for CAB.
    siva.

    Perhaps there's something in the Cabinet SDK that will help:
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncabsdk/html/cabdl.asp

Maybe you are looking for

  • Help needed for writing query

    help needed for writing query i have the following tables(with data) as mentioned below FK*-foregin key (SUBJECTS) FK**-foregin key (COMBINATION) 1)SUBJECTS(table name)      SUB_ID(NUMBER) SUB_CODE(VARCHAR2) SUB_NAME (VARCHAR2) 2           02        

  • Need Help: UTL_FILE Reading and Writing to Text File

    Hello I am using version 11gR2 using the UTL_FILE function to read from a text file then write the lines where it begins with word 'foo' and end my writing to the text file where the line with the word 'ZEN' is found. Now, I have several lines that b

  • OAMessageRichTextEditor Icons are not rendering

    Hi All, I am using 11.5.10.6RUP and I added an OAMessageRichTextEditor to a messageComponentLayout. I don't see the icons when I run it from JDeveloper. What could be wrong? I see a standard screen with MRTE properly rendered in the same instance tha

  • Binding fault in SOA composite

    Hi all, we are having trouble with a soa composite wich has 1 web service and 3 jca db adapters. After deployment, only the first time the web service is consumed all is ok and the ws client receive the response (some data from db), but starting from

  • What are the differences between TestStand Version 1.0.2 and 1.0.3?

    I have TestStand version 1.0.2 and have a customer that uses 1.0.3. I am updating test software for that customer and need to know if I can use TestStand 1.0.2. What are the differences between 1.0.2 and 1.0.3?