Reading/writing attributes in encode/decode

In tipical scenario with two JSF pages, both working with a simple bean (user), and with navigation from page1 to page2:
Page1.jspx:
<h:inputText value="#{user.name}"/>Page2.jspx:
<h:outputText value="#{user.name}"/>I suppose that in the encodeBegin method of the InputTextRenderer class, to read the value of ‘value’ attribute there should be a sentence like this:
getAttributes().get("value");But, what kind of code is needed in the decode method of InputTextRenderer class, to receive the value from the request, and update the ‘name’ property of user bean, in order to display it correctly in outputText tag of page2 ??
Thanks!

[Edit] nevermind.
Edited by: BalusC on 30-apr-2009 20:37

Similar Messages

  • New Charset Encoder/Decoder for Microsoft telnet

    Hello,
    I have a problem for writing a server which is accessible by microsoft windows telnet.
    I have managed to find out these relationships:
              switch ((int) c) {
                   case -27: c = '�'; break;
                   case -28: c = '�'; break;
                   case -102: c = '�'; break;
                   case -103: c = '�'; break;
                   case -108: c = '�'; break;
                   case -114: c = '�'; break;
                   case -124: c = '�'; break;
                   case -127: c = '�'; break;
    So how could i write an encoder/decoder which could map these charcters specially and others as norma ISO-8859-1.
    I switched them after encoding/decoding but then i got problem, that
    i got two characters(in telnet window). First was some wierd symbol and second the right character.
    Any help lplease?

    Okay, got working the charset include and everything is okay.
    Now i need to look after charcodes below 0. I though that it would be useful to create new charset for this purpose which adds little extra functionality to IBM850. When running this code it says that IBM850 charset not found when initilizating X-MICRO charset. But it is accessible in main program. Any ideas what is wrong?... Please help me, this damn internationallization has driven me mad.
    package ee.feelfree.charset;
    import java.nio.charset.Charset;
    import java.nio.charset.spi.CharsetProvider;
    import java.util.HashSet;
    import java.util.Iterator;
    public class MicrosoftCharsetProvider extends CharsetProvider {
         private static final String CHARSET_NAME = "X-MICRO";
         private Charset micro = null;
         public MicrosoftCharsetProvider()
         this.micro = new MicrosoftCharset (CHARSET_NAME, new String [0]);
         public Iterator charsets() {
              HashSet set = new HashSet (1);
              set.add (micro);
              return (set.iterator());
         public Charset charsetForName (String charsetName) {
              if (charsetName.equalsIgnoreCase (CHARSET_NAME)) {
                   return (micro);
                   return (null);
    package ee.feelfree.charset;
    import java.nio.CharBuffer;
    import java.nio.charset.*;
    import java.nio.ByteBuffer;
    public class MicrosoftCharset extends Charset {
         private static final String BASE_CHARSET_NAME = "IBM850";
         Charset baseCharset;
         protected MicrosoftCharset(String canonical,String [] aliases) {
              super (canonical, aliases);
              baseCharset = Charset.forName(BASE_CHARSET_NAME);
         public CharsetEncoder newEncoder() {
              return new MicrosoftEncoder(this,baseCharset.newEncoder());
         public CharsetDecoder newDecoder() {
              return new MicrosoftDecoder(this,baseCharset.newDecoder());
         public boolean contains (Charset cs) {
              return false;
         private class MicrosoftEncoder extends CharsetEncoder {
              private CharsetEncoder baseEncoder;
              MicrosoftEncoder(Charset cs,CharsetEncoder baseEncoder) {
                   super(cs, baseEncoder.averageBytesPerChar(),
                             baseEncoder.maxBytesPerChar());
                   this.baseEncoder = baseEncoder;
              protected CoderResult encodeLoop (CharBuffer cb, ByteBuffer bb)
                   CharBuffer tmpcb = CharBuffer.allocate (cb.remaining());
                   while (cb.hasRemaining()) {
                   tmpcb.put (cb.get());
                   tmpcb.rewind();
                   baseEncoder.reset();
                   CoderResult cr = baseEncoder.encode (tmpcb, bb, true);
                   cb.position (cb.position() - tmpcb.remaining());
                   return (cr);
         private class MicrosoftDecoder extends CharsetDecoder
         private CharsetDecoder baseDecoder;
         private boolean microClient = false;
              MicrosoftDecoder (Charset cs, CharsetDecoder baseDecoder)
                   super (cs, baseDecoder.averageCharsPerByte(),
                   baseDecoder.maxCharsPerByte());
                   this.baseDecoder = baseDecoder;
              protected CoderResult decodeLoop (ByteBuffer bb, CharBuffer cb)
                   baseDecoder.reset();
                   CoderResult result = baseDecoder.decode (bb, cb, true);
                   myDecode (cb);
                   return (result);
              public boolean getClient() {
                   return microClient;
              private void myDecode(CharBuffer cb) {
                   microClient = false;
                   for (int pos = cb.position(); pos < cb.limit(); pos++) {
                        int c = (int) cb.get (pos);
                        if (c<0) microClient=true;
    }

  • How to read an attribute of an xml tag in jsp.

    hi guys,
    This is murali krishna. i have a small problem,
    i have one xml file (books.xml)
    <?xml version="1.0" encoding="iso-8859-1"?>
    <library>
    <book id="1">
    <name>Head First Java, 2nd Edition</name>
    <author>Kathy Sierra and Bert Bates</author>
    <publication-date>09-Feb-2005</publication-date>
    </book>
    <book id="2">
    <name>Effective Java</name>
    <author>Joshua Bloch</author>
    <publication-date>28-May-2008</publication-date>
    </book>
    <book id="3">
    <name>Java How to Program, 7th Edition</name>
    <author>Harvey M. Deitel and Paul J. Deitel</author>
    <publication-date>6-Jan-2007</publication-date>
    </book>
    </library>
    I tried to read this xml file in jsp as shown below
    <%@ page language="java" %>
    <%@ page import="org.w3c.dom.*" %>
    <%@ page import="javax.xml.parsers.DocumentBuilder" %>
    <%@ page import="javax.xml.parsers.DocumentBuilderFactory" %>
    <%
    DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
    DocumentBuilder db =dbf.newDocumentBuilder();
    Document doc=db.parse("c:\\books.xml");
    NodeList nl = doc.getElementsByTagName("book");
    %>
    <html>
    <head>
    <title>How to read XML file in JAVA</title>
    </head>
    <body>
    <%
    for(int i=0;i<nl.getLength();i++)
    NodeList nameNlc= doc.getElementsByTagName("name");
    Element nameElements=(Element)nameNlc.item(i);
    String nameTagValue=nameElements.getChildNodes().item(0).getNodeValue();
    NodeList authorNlc= doc.getElementsByTagName("author");
    Element authorElements=(Element)authorNlc.item(i);
    String authorTagValue=authorElements.getChildNodes().item(0).getNodeValue();
    NodeList dateNlc= doc.getElementsByTagName("publication-date");
    Element dateElements=(Element)dateNlc.item(i);
    String dateTagValue=dateElements.getChildNodes().item(0).getNodeValue();
    out.println("name :"+nameTagValue+"<br>");
    out.println("author :"+authorTagValue+"<br>");
    out.println("publication-date :"+dateTagValue+"<br><br>");
    %>
    </body>
    </html>
    so, my problem is I was unable to read the attribute of the tag book , that is "id".
    can any one tell me how to read this "id" attribute.
    Murali Krishna
    [email protected]

    hi,
    U r retriving the elements by tag name.So it just chks the tag name ie.<book> & gives u array of elements.But u need retrive d attribute of <book> tag itself.
    =Solution =====
    Add one more statement ----> var[]= doc.getElementsByName("book");
    Now u hav book elements as an array & can retrive id in for loop
    for(var; var.length;var++)
    doc.element[var].id.value

  • How to read the attribute of the xml file using jaxb

    Thanks,
    Buddy as i have a issue i have to read the xml file using jaxb and xml file contains this data and i have read the attribute like name , desc and action for a particular menu name pls tell the code how to do this it will be a great favour to me
    thanx in advance
    Rasool
    <contextmenu>
    <menu name='Lead' >
    <menuitem name='newlead' desc='New Lead' action='/leads.do?dispatch=insert' />
    <menuitem name='editlead' desc='Edit Lead' action='' />
    <menuitem name='leadinfo' desc='Lead Information' action='' />
    </menu>
    <menu name='Cases' >
    <menuitem name='' desc='' action='' />
    <menuitem name='' desc='' action='' />
    <menuitem name='' desc='' action='' />
    </menu>
    <menu name='Contact' >
    <menuitem name='' desc='' action='' />
    <menuitem name='' desc='' action='' />
    <menuitem name='' desc='' action='' />
    </menu>
    </contextmenu>

    What my program do is to get the encoding of XML files and convert them to UTF-8 encoding files, while I need this "encoding" information of the original XML document thus I can convert...
    After reading specifications and JDOM docs, the truth turns to be disappointed, no function is provided to get this information in JDOM level 2(the current released one), while it's promissed that this function will be provided in JDOM level API....
    Thanx all for your help and attention!!!

  • Stax reading /writing need help from xml guru plz

    hi, i have been told that stax reading /writing should involve no overhead and that is why i use it and i am now able to write my large data to file, but using my reader i seem to run out of memory, using netbeans profiler i ahve found that char[] seems to be the problem,
    by backtracing i ahve found that javax.xml.parser.SAXParser.parse calls the xerces packages which eventually leads to the char[ ], now my code for my reader is attatched here...
    package utilities;
    import Categorise.Collection;
    import Categorise.Comparison;
    import Categorise.TestCollection;
    import java.io.IOException;
    import javax.xml.parsers.*;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    import org.xml.sax.Attributes;
    import java.io.File;
    import java.util.ArrayList;
    import java.util.List;
    import measures.Protocol;
    * @author dthomas
    public class XMLParser extends DefaultHandler
        static Collection collection = new Collection();
        List<Short> cList;
        List<Comparison> comparisonList;
        File trainFileName;
        File testFileName;
        TestCollection tc;
        List<TestCollection> testCollectionList;
        List<File> testFileNameList = new ArrayList<File>();
        List<File> trainFileNameList = new ArrayList<File>();
        boolean allTrainsAdded = false;
        Protocol protocol;
        List<File> trainingDirList;
        File testingDir;
        int counter = 0;
        File[ ] trainingDirs;
        File[ ] trainingFileNames;
        File[ ] testFileNames;
        TestCollection[ ] testCollections;
        Comparison[ ] comparisons;
        Comparison c;
        short[ ] cCounts;
        String order;
        String value;
        File trainDir;
        /** Creates a new instance of XMLParser */
        public XMLParser() {
        public static Collection read( File aFile )
            long startTime = System.currentTimeMillis();
            System.out.println( "Reading XML..." );
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp;
            try {
                sp = spf.newSAXParser();
                sp.parse( aFile, new XMLParser() );
            } catch (IOException ex) {
                ex.printStackTrace();
            } catch (SAXException ex) {
                ex.printStackTrace();
            } catch (ParserConfigurationException ex) {
                ex.printStackTrace();
            long endTime = System.currentTimeMillis();
            long totalTime = ( endTime - startTime ) / 1000;
            System.out.println( "Done..."  + totalTime + " seconds" );
            return collection;
        public void startElement(String uri,String localName,String qName, Attributes attributes)
            if( qName.equals( "RE" ) )
                testCollectionList = new ArrayList<TestCollection>();
            else if( qName.equals( "p") )
                boolean isConcatenated = new Boolean( attributes.getValue( "c" ) );
                boolean isStatic = new Boolean( attributes.getValue( "s" ) );
                protocol = new Protocol( isConcatenated, isStatic );
            else if( qName.equals( "trdl" ) )
                trainingDirList = new ArrayList<File>();
            else if( qName.equals( "trd" ) )
                trainDir = new File( attributes.getValue( "fn" ) );
                trainingDirList.add( trainDir );
            else if( qName.equals( "td" ) )
                testingDir = new File( attributes.getValue( "fn" ) );
            else if( qName.equals( "TC" ) )
                counter++;
                System.out.println( counter );
                comparisonList = new ArrayList<Comparison>();
                testFileName = new File( attributes.getValue( "tfn" ) );
                testFileNameList.add( testFileName );
                tc = new TestCollection( );
                tc.setTestFileName( testFileName );
            else if ( qName.equals( "r" ) )
             order = attributes.getValue( "o" );
                value = attributes.getValue( "v" );
                cList.add( Short.parseShort( order ), new Short( value ) );
            else if( qName.equals( "c" ) )
                cList = new ArrayList<Short>();
                trainFileName = new File( attributes.getValue( "trfn" ) );
                if( !allTrainsAdded )
                    trainFileNameList.add( trainFileName );
        public void characters(char []ch,int start,int length)
            //String str=new String(ch,start,length);
            //System.out.print(str);
        public void endElement(String uri,String localName,String qName)
            if (qName.equals( "c") )
                allTrainsAdded = true;
                cCounts = new short[ cList.size() ];      
                for( int i = 0; i < cCounts.length; i++ )
                    cCounts[ i ] = cList.get( i );
                c = new Comparison( trainFileName, tc );
                c.setcCounts( cCounts );
                this.comparisonList.add( c );
            else if( qName.equals( "TC" ) )
                comparisons = new Comparison[ comparisonList.size() ];
                comparisonList.toArray( comparisons );           
                tc.setComparisons( comparisons );
                testCollectionList.add( tc );
            else if( qName.equals( "RE" ) )
                testCollections = new TestCollection[ testCollectionList.size() ];
                testCollectionList.toArray( testCollections );
                collection.setTestCollections( testCollections );
                testFileNames = new File[ testFileNameList.size() ];
                testFileNameList.toArray( testFileNames );
                collection.setTestingFiles( testFileNames );
                //String[ ] testCategories = new String[ testCategoryList.size() ];
                //testCategoryList.toArray( testCategories );
                //collection.setTestCategories( testCategories );
                trainingFileNames = new File[ trainFileNameList.size() ];
                trainFileNameList.toArray( trainingFileNames );
                collection.setTrainingFiles( trainingFileNames );
                //String[ ] trainingCategories = new String[ trainCategoryList.size() ];
                //trainCategoryList.toArray( trainingCategories );
                //collection.setTrainingCategories( trainingCategories );
                collection.setProtocol( protocol );
                trainingDirs = new File[ trainingDirList.size() ];
                trainingDirList.toArray( trainingDirs );           
                collection.setTrainingDirs( trainingDirs );
                collection.setTestingDir( testingDir );
         //else
             //System.out.println("End element:   {" + uri + "}" + localName);
    }i thought it may have been a recursive problme, hence having so many instance variables instead of local ones but that hasn't helped.
    all i need at the end of this is a Collection which holds an array of testCollections, which holds an array of cCounts and i was able to hold all of this in memory as all i am loading is what was in memory before it was written.
    can someone plz help
    ps when i use tail in unix to read the end of the xml file it doesnt work correctly as i cannot specify the number of lines to show, it shows all of the file as thought it is not split into lines or contains new line chars or anything, it is stored as one long stream, is this correct??
    here is a snippet of the xml file:
    <TC tfn="
    /homedir/dthomas/Desktop/4News2/output/split3/alt.atheism/53458"><c trfn="/homed
    ir/dthomas/Desktop/4News2/output/split0/alt.atheism/53586"><r o="0" v="0"></r><r
    o="1" v="724"></r><r o="2" v="640"></r><r o="3" v="413"></r><r o="4" v="245"></
    r><r o="5" v="148"></r><r o="6" v="82"></r><r o="7" v="52"></r><r o="8" v="40"><
    /r><r o="9" v="30"></r><r o="10" v="22"></r><r o="11" v="16"></r><r o="12" v="11
    "></r><r o="13" v="8"></r><r o="14" v="5"></r><r o="15" v="2"></r></c><c trfn="/
    homedir/dthomas/Desktop/4News2/output/split0/alt.atheism/53495"><r o="0" v="0"><
    /r><r o="1" v="720"></r><r o="2" v="589"></r><r o="3" v="349"></r><r o="
    please if anyone has any ideas from this code why a char[] would use 50% of the memory taken, and that the average age seems to show that the same one continues to grow..
    thanks in advance
    danny =)

    hi, i am still having lo luck with reading the xml data back into memory, as i have said before, the netbeans profiler is telling me it is a char[] that is using 50% of the memory but i cannot see how a char[] is created, my code doesn't so it must be the xml code...plz help

  • Public Read-Only Attributes

    I'm trying to pick up ABAP on my own by reading through various resources I've collected and writing my own programs.  Unfortunately I don't have an experienced ABAP guru to ask questions of.  I'm hoping someone can help me with the following:
    Based on my other programming experience I know that it is very common for object attributes to be defined as private and then accessor/mutator (getter/setter) methods to be defined to provide access to the attribute.
    In my study I noted that ABAP allows attributes to be made public but declared to be read-only.  This would seem to permit a structure where accessor/getter methods are not needed (the attribute can be read externally) and one would only have to define a mutator/setter method.
    My question:  what is typically done in 'real-world' programs?  Is there any reason why using read-only would be more or less preferred?
    Thanks for any help that can be provided.

    Hello Tony
    Below I have listed a few examples from standard ABAP classes. I cannot say whether you find more public read-only attributes than GETTER methods - you will find examples for both of them.
    I could imagine that before it was possible to use the functional method call in ABAP that public read-only attributes were an alternative to the "verbose" method cal (see below)l.
    " RE-FX: Contract
    CL_RECN_CONTRACT-IF_RECN_CONTRACT~MS_DETAIL   " public read-only attribute
    " MM: Material
    CL_IBASE_R3_MATERIAL->GET_MARA  " GETTER method
    "FI/CO: Company Code
    CL_REEXC_COMPANY_CODE=>GET_DETAIL  " GETTER method
    " HR: Employee
    CL_PT_EMPLOYEE->IF_PT_EMPLOYEE~PERNR   " public read-only attribute
    " Assumption: CL_IBASE_R3_MATERIAL would have
    " a public read-only attribute MS_DETAIL (of TYPE mara)
    " Normal method call (verbose):
    CALL METHOD go_material->GET_MARA
      RECEIVING
        R_MARA = ls_mara.
    " Functional method call:
      ls_mara = go_material->get_mara( ).
    " Accessing public attribute
      ls_mara = go_material->ms_detail.
    Regards
       Uwe

  • Issue: Characters / encode /decode & Solution

    Hey guys,
    Few issues on this, I think we will need an encode/decode filter.
    I guess this is related to how if you read a cookie in liquid it converts characters like a comma into its entity (This isn not fixed yet).
    Example:
    <meta property="og:description" content="{{description | strip_html | truncate:200,'...' }}">
    The resulting markup is:
    <meta property="og:description" content="Seven advisers within National Australia Bank's (NAB) salaried advice business, NAB Financial Planning (NAB FP), have transitioned to the bank&rsquo;s newly-launched self-employed model.
    As first ...">
    You can see it has stripped out the html markup but has encoded a ' with it's entity. I can see in some cases this is good but in other cases this is bad. You can also see that <br/> while stripped are treated as new lines instead.
    Liquid itself for these reasons have:
    escape - escape a string
    escape_once - returns an escaped version of html without affecting existing escaped entities
    strip_html - strip html from string
    strip_newlines - strip all newlines (\n) from string
    newline_to_br - replace each newline (\n) with html break
    You only have strip_html but not the other filters. I think if you implemented these then we can address these issues.

    Hi Liam,
    The encoding problem cannot be reproduced. Even in your example, some of the quotes are outputted correctly while a single one not. Can you edit the source of the content and try to re-enter the character from the editor, just to eliminate a possible copy / paste issue from word with a weird character encoding?
    On the new line issue, it seems to happen on some scenarios. For example:
    {{" <div>Seven advisers within National Australia Bank's (NAB) salaried advice business, NAB Financial Planning (NAB FP), have transitioned to the bank's newly-launched's self-employed <br /> model. at first's</div>" | strip_html }} - does not reproduce the problem
    <meta property="og:description" content="{{" <div>Seven advisers within National Australia Bank's (NAB) salaried advice business, NAB Financial Planning (NAB FP), have transitioned to the bank's newly-launched's self-employed <br /> model. at first's</div>" | strip_html }}”> - does reproduce the problem
    Cristinel

  • ASN.1 encoder/decoder

    Hi All,
    I have a asn.1 definition file.
    I need to encode/decode the a file with the help of the above definition file. I tried using JavaAsn1Compiler, this compiler fullfill all my requirments except the one GraphicString type is not supported in this compilier.
    Can any body suggest me a asn.1 encoder/decoder.
    Thanks in advance.
    Asif

    Pranitha wrote:
    We already used nokalva for OSS file parsing. From now onwards we dont want to use third party tools, is there any hand written code avialable for parsing an ASN.1 file using java.What part of my last reply did you not understand?
    The java API does not contain anything for ASN.
    Everything outside of the Java API would be consider third party.
    So either explain exactly what it is that you want without using the term "third party" or recognize that what you are asking does not exist.

  • Invalid Session ID - cookie encode/decode

    Hello,
    I'm looking for the correct combination of cookie encode/decode parameters for my own setup.
    Machine am : AM Server 7.0 on WS6.1
    Machine amc : my own webapps using AM client SDK & protected by a Policy agent. 2.2 Everything within a WS6.1 container.
    After being redirected to AM, I obtain my iPlanetDirectoryPro cookie and my webapp can obtain a SSOToken using the SSOToken token = manager.createSSOToken(String) if obtain the String via Cookie accessor's method.
    No luck with SSOToken token = manager.createSSOToken(HttpServletRequest) which always gives a Invalid Session Id message. I know that this is an encoding problem but I tried many combinations & heard that these settings are not always well documented. I have at the moment :
    am server AMConfig.properties :
    com.iplanet.am.cookie.encode=false
    am client sdk AMConfig.properties :
    com.iplanet.am.cookie.encode=false
    policy agent AMAgent.properties :
    com.sun.identity.agents.config.sso.decode = false
    com.iplanet.am.cookie.encode = false
    Has somebody worked that out ?
    Thanks !
    nieuwenj

    Hi, am using this code:
    AMUtil.java
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.IOException;
    import javax.security.auth.callback.Callback;
    import javax.security.auth.callback.ChoiceCallback;
    import javax.security.auth.callback.NameCallback;
    import javax.security.auth.callback.PasswordCallback;
    import javax.security.auth.callback.TextInputCallback;
    import javax.security.auth.callback.TextOutputCallback;
    import javax.security.auth.callback.UnsupportedCallbackException;
    import com.sun.identity.authentication.AuthContext;
    import com.sun.identity.authentication.spi.AuthLoginException;
    import com.iplanet.am.util.Debug;
    * @author hjimenez
    public class AMUtil {
        private String loginIndexName;
        private String orgName;
        private String user;
        private String password;
         * Creates a new instance of AMUtil
        public AMUtil(String loginIndexName, String orgName) {
            this.loginIndexName = loginIndexName;
            this.orgName = orgName;
        protected AuthContext getAuthContext()
        throws AuthLoginException, com.iplanet.sso.SSOException, Exception {
            AuthContext lc = new AuthContext(orgName);
            AuthContext.IndexType indexType = AuthContext.IndexType.MODULE_INSTANCE;
            lc.login(indexType, loginIndexName);
            debugMessage(loginIndexName + ": Se obtuvo login context");
            return lc;
        private void addLoginCallbackMessage(Callback[] callbacks)
        throws UnsupportedCallbackException {
            int i = 0;
            try {
                for (i = 0; i < callbacks.length; i++) {
                    if (callbacks[i] instanceof TextOutputCallback) {
                        handleTextOutputCallback((TextOutputCallback)callbacks);
    } else if (callbacks[i] instanceof NameCallback) {
    handleNameCallback((NameCallback)callbacks[i]);
    } else if (callbacks[i] instanceof PasswordCallback) {
    handlePasswordCallback((PasswordCallback)callbacks[i]);
    } else if (callbacks[i] instanceof TextInputCallback) {
    handleTextInputCallback((TextInputCallback)callbacks[i]);
    } else if (callbacks[i] instanceof ChoiceCallback) {
    handleChoiceCallback((ChoiceCallback)callbacks[i]);
    } catch (IOException e) {
    e.printStackTrace();
    throw new UnsupportedCallbackException(callbacks[i],e.getMessage());
    private void handleTextOutputCallback(TextOutputCallback toc) {
    debugMessage("Se ejecut� TextOutputCallback");
    // Mostrar mensaje de acuerdo al tipo especificado
    switch (toc.getMessageType()) {
    case TextOutputCallback.INFORMATION:
    debugMessage(toc.getMessage());
    break;
    case TextOutputCallback.ERROR:
    debugMessage("ERROR: " + toc.getMessage());
    break;
    case TextOutputCallback.WARNING:
    debugMessage("WARNING: " + toc.getMessage());
    break;
    default:
    debugMessage("Tipo de mensaje no soportaado: " +
    toc.getMessageType());
    private void handleNameCallback(NameCallback nc)
    throws IOException {
    // asignar usuario
    nc.setName(this.user);
    private void handleTextInputCallback(TextInputCallback tic)
    throws IOException {
    // poner un prompt para obtener datos
    System.out.print(tic.getPrompt());
    System.out.flush();
    tic.setText((new BufferedReader
    (new InputStreamReader(System.in))).readLine());
    private void handlePasswordCallback(PasswordCallback pc)
    throws IOException {
    // asignar password
    String passwd = this.password;
    pc.setPassword(passwd.toCharArray());
    private void handleChoiceCallback(ChoiceCallback cc)
    throws IOException {
    // ignorar el valor default dado
    System.out.print(cc.getPrompt());
    String[] strChoices = cc.getChoices();
    for (int j = 0; j < strChoices.length; j++) {
    System.out.print("choice[" + j + "] : " + strChoices[j]);
    System.out.flush();
    cc.setSelectedIndex(Integer.parseInt((new BufferedReader
    (new InputStreamReader(System.in))).readLine()));
    public boolean login(AuthContext lc)
    throws UnsupportedCallbackException {
    boolean succeed = false;
    Callback[] callbacks = null;
    // obtener informaci�n del m�dulo solicitada
    while (lc.hasMoreRequirements()) {
    callbacks = lc.getRequirements();
    if (callbacks != null) {
    addLoginCallbackMessage(callbacks);
    lc.submitRequirements(callbacks);
    if (lc.getStatus() == AuthContext.Status.SUCCESS) {
    System.out.println("Login exitoso.");
    succeed = true;
    } else if (lc.getStatus() == AuthContext.Status.FAILED) {
    System.out.println("Login fallo.");
    } else {
    System.out.println("Estatus desconocido: " + lc.getStatus());
    return succeed;
    public void logout(AuthContext lc)
    throws AuthLoginException {
    lc.logout();
    System.out.println("Log Out!!");
    static void debugMessage(String msg) {
    System.out.println(msg);
    public String getUser() {
    return user;
    public void setUser(String user) {
    this.user = user;
    public String getPassword() {
    return password;
    public void setPassword(String password) {
    this.password = password;
    and call it from:
    import com.iplanet.sso.SSOToken;
    import com.sun.identity.authentication.AuthContext;
    import com.sun.identity.authentication.spi.AuthLoginException;
    import javax.security.auth.callback.UnsupportedCallbackException;
    import com.iplanet.sso.SSOException;
    import java.net.InetAddress;
    * @author hjimenez
    public class TestLogin {
        /** Creates a new instance of TestLogin */
        public TestLogin() throws SSOException {
         * @param args the command line arguments
        public static void main(String[] args) {
            try {
                // arg0 = LDAP arg1 = tecnet
                AMUtil login = new AMUtil(args[0], args[1]);
                // arg2=usuario arg3=pass
                login.setUser(args[2]);
                login.setPassword(args[3]);
                AuthContext lc = login.getAuthContext();
                if (login.login(lc)) {
                    SSOToken token = lc.getSSOToken();
                    System.out.println("Token asignado: "+token.getTokenID().toString());
                    String host = token.getHostName();
                    java.security.Principal principal = token.getPrincipal();
                    String authType = token.getAuthType();
                    int level = token.getAuthLevel();
                    InetAddress ipAddress = token.getIPAddress();
                    long maxTime = token.getMaxSessionTime();
                    long idleTime = token.getIdleTime();
                    long maxIdleTime = token.getMaxIdleTime();
                    System.out.println("SSOToken host name: " + host);
                    System.out.println("SSOToken Principal name: " +
                            principal.getName());
                    System.out.println("Authentication type used: " + authType);
                    System.out.println("IPAddress of the host: " +
                            ipAddress.getHostAddress());   
                    login.logout(lc); 
            } catch (AuthLoginException e) {
                e.printStackTrace();
            } catch (UnsupportedCallbackException e) {
                e.printStackTrace();
            } catch (SSOException e) {
                e.printStackTrace();
            }  catch (Exception e) {
                e.printStackTrace();

  • Efficiency of reading/writing files character-by-character

    I've been assuming that when I do a file "open for access," that among the housekeeping functions set up behind the scenes, there is some sort of buffer created, the size of which is somehow related to the logical sector size of the disc in question, so that reading or writing short pieces of text, or even single characters, doesn't cause independent physical read/write actions at the disc drive.
    Does anyone know if this is true or false? Maybe the question would be clearer posed another way. Suppose I set up a loop to read or write 1024 characters, sequentially, but one at a time. Obviously the loop will require much more time to execute than a singe read or write statement calling for 1K of text all at once. But will there be significantly more activity at the disc drive itself? Will the data be read or written on 1024 successive spins of the platter, or will it be buffered down to one spin, or maybe a couple, depending on the exact location of sector boundaries and so on?
    Thanks.

    Thanks for this. I was sure some such facility was in operation, but I couldn't find anything explicit on the question. I have a task in which I'm trying to convert what looks like incredibly badly formed XML application files into properly tagged and well-formed XML so that I can then get them through a well-designed XML parser. To decode these utter shambles requires decision logic that goes nearly character-by-character. One tutorial page I found on Applescript file I/O suggested that reading/writing character-by-character was inherently inefficient, which I can see that it is, I just wanted to make sure the inefficiency didn't go all the way down to the mechanics of kicking the disc for every single character. The description in the tutorial was ambiguous, and a little disconcerting.
    The tutorial also suggested an alternative strategy of reading an entire file at once into a string and then working with the string. But my files are megabytes long, and I wonder how efficient operations are on megabyte strings, presuming there isn't a limit on string length. Short of trying to do some complex adaptive algorithm, which I might never get working right, I'm pretty sure that keeping to the KISS principal, and just going character-by-character, is a near-optimal strategy in my case.
    Cheers.

  • HTML Encode/Decode FLEX

    Is anyone familiar with classes that support html
    encoding/decoding in AS3 or Flex?
    Similar to:
    http://meyerweb.com/eric/tools/dencoder/
    what is being done here?

    Most folks float an Iframe over a spot in the SWF.

  • Sample java code which reads xml attributes using DOM Parser

    Hi Friends,
    I am looking for a sample java code which uses the DOM Parser to read the attributes values.
    My xml looks like below
    <?xml version='1.0' encoding='UTF-8'?>
    <root>
    <header unid="100" status="true">
    <validation stage="1" processed="10"/>
    </header>
    </root>
    Experts please help...
    Thanks in Advance
    JJ

    You have probably found lots of resources on the www for this by now, if not: [http://www.w3schools.com/dom/default.asp|http://www.w3schools.com/dom/default.asp]

  • Simple and very fast encoder-decoder

    I will explain my need with an example;
    www.domain.com/photo.jsp?id=23
    here id is 23 and people can try every photo by incresing or decreasing the id number. I want to encode the id's while printing the id to screen as url and will decode everytime when i get the request from user.
    So i need a very fast and simple logic of encode & decode. I have tested base64 at java but everyone knows the algortihm. Is there any other simple algorithm that i can generate on my own?
    What do you advice to me except changing my database and search with hex keys?

    believe me its strictly
    needed on a photo web site... there are too much
    reasons.I can't think of one.1)when ids are sequantial on db users can get the idea which after or before this photo is uploaded
    2)when you see the normal integer numbers on ids you can remember it easily and edit the link by hand and see whats going on...
    3)When u see user_id is=1 u can understand easily that he is an admin or one of the first member of website
    4)when u try the maximum photo id or user id every user can understand how many user or photos are there in website
    there are lots of things like above... They may be not that valueble for everyone but i think this have to be.

  • Basic Text Encoder/Decoder help

    Hi. I'm trying to make a Encoder/Decoder for a program to make the gamesaves safer, since they are in a .dat file and can be changed in Notepad. I was wondering if the Text can be Encoded (like a=l, b=m, ect) and decoded using a simple code before the UTF is written.

    Ok, now I have a bit of a problem. I am trying to at least read the hash using readByte(), but the hashes are different. This is the code I'm using:
    public void Load() //Load Script
         { try
                   md5Actor_2 = MessageDigest.getInstance("MD5","SUN");
                   md5Actor_1 = MessageDigest.getInstance("MD5","SUN");
                   md5_1 = md5Actor_1.digest(hash_1.getBytes());
                   md5_2 = md5Actor_2.digest(hash_2.getBytes());
              catch (NoSuchProviderException e1)
                   System.out.println(e1);
              catch (NoSuchAlgorithmException e2)
                   System.out.println(e2);
              //catch (UnsupportedEncodingException e3)
              //     System.out.println(e3);
              load = new FileDialog(dialog, "Load Game v1.1", FileDialog.LOAD);
              load.show();
              file_name = load.getFile();
              f = new File(file_name);
              long modified = f.lastModified();
              if(debug)
                   System.out.println("Last modified:");
                   System.out.println(modified);
              if (f != null)
              { if (file_name != null)
                   { try
                             FileInputStream fis = new FileInputStream(file_name);
                             DataInputStream dis = new DataInputStream(fis);
                             level = dis.readUTF(); //level
                             cur_HP = dis.readUTF(); //cur_HP
                             max_HP = dis.readUTF(); //max_HP
                             atk_str = dis.readUTF(); //atk_str
                             def_str = dis.readUTF(); //def_str
                             cur_exp = dis.readUTF(); //cur_exp
                             exp_ned = dis.readUTF(); //exp_ned
                             loc_x = dis.readUTF(); //loc_x
                             loc_y = dis.readUTF(); //loc_y
                             temp_md5_1[1] = dis.readByte();
                             temp_md5_2[1] = dis.readByte();
                             System.out.println(md5_1+"     "+temp_md5_1);
                             System.out.println(md5_2+"     "+temp_md5_2);
                             if (temp_md5_2 != md5_2)
                                  System.out.println("File Cannot be Loaded. Please Create a new GameSave");
                                  success = false;
                             else
                                  System.out.println("File Loaded Sucessfully: " + file_name);
                                  success = true;
                             if(success)
                             { if (temp_md5_1 != md5_1)
                                       System.out.println("The GameSave is out of date. Saving the game will update "+file_name+"'s GameSave Version");
                             fis.close();
                        catch (Exception e)
                             System.out.println("There was an Error Loading the File: " + file_name);
                             System.out.println(e);
                   if (success)
                        stats_txf.setText("Lvl: "+level+" Health: "+ cur_HP +"/"+ max_HP+"   Exp: "+cur_exp+"/"+exp_ned);
                        loaded = true;
                        setTitle(title+": "+ file_name);
         }Now, I may be reading the file wrong. I know the hash has a length of 16, but if I try to read 16 bytes, I get an EOFException. And, if it's possible, I would like to know how to read an Byte[ ], and not just a Byte.

  • Audio/Video encode & decoding

    I am very new to mac environment,
    and have a background as a linux developer. I worked mostly with avcodec and avformat api's (from ffmpeg project) to manipulate media. I could reach media devices/streams using oss, alsa, v4l or v4l2 interfaces/drivers and encode/decode them with avcodec API. Now I switched to mac and I want to get audio/video frames from input devices and encode/decode them as I want. I already took a look at QTkit and QT related topics but there is no codec variation and also no control of frames which has taken from input device/file. There is no flexibilty with almost just one way to encode media (h264 and AAC, with predefined bitrates). I am using snow leopard with Xcode 4 so AVfoundations is avaliable just for IOS env. and not for Mac environment.
    I can not find any detailed media encoding/decoding document or usable(flexible) framework in mac developer central. Please help me to find or give me some advice about mac environment.
    Thanks in advance .

    First of all thank you xnav. But I already searched for AVFoundations and related sample sources. I do not want to change my operating system and I do not want to believe that MacOS has not got a framework embracing the media related functions at all before Lion. As I mentioned in the text above I am using snow leopard.
    By the way I want to reach full control over media streams/frames and codec parameters. I want to be able to decode media stream/frame if it is encoded (for example: a web cam streaming jpeg captures using hw codec) I want to decode and resize it, maybe view it in a frame and encode it again and store it in a file or directly stream over rtsp. Is it possible ? Does't Apple have such a framework which I can find in open source environment easily (for example: ffmpeg - avcodec - avformat - avdevice). Device/driver level tools and codecs can be inside different frameworks but there must be some tools for it.

Maybe you are looking for

  • Please help for me fake profile !

    Hey!!  I would like to report this man who's been using may name and photo and my videos for his personal intention. Here are the  account  name  victor_ricar  Please do some action to prevent him using my name and personal informations and he is tri

  • Frustration! Refund for apps that don't do what they are supposed to?

    How quickly a $2 app turns into a $50 waste of time! I purchased a $2 unit converter app to use at work and whenever else I needed it. After playing with it for about 20-30 minutes, I realized that there were several calculation errors. The unit conv

  • Problem on HP Pavilion dv7-6c90el with Windows 8 Pro x64 on Video Card

    good evening, I just finished installing Windows 8 x64 from Win7 Pro, I was able to find all drivers for my notebook, but I have problems with the video card settings. My laptop is a HP Pavilion dv7-6c90el with two video cards, one run by the process

  • How do I auire data at every third pulse of an external trigger?

    I need to aquire 2048 data points where each one is triggered by the third pulse of an external trigger (TTL). Currently I can aquire 2048 data points where each is triggered by every pulse of an external trigger but I need to be able to do this at e

  • Adobe Elements 11 on Mac OSX 10.9 has crashed. What should I do?

    I opened Elements 11 today and tried to open a photo from my file, and instead of opening it stops responding, I even have to force quit because all options are greyed out. This has never happened before. What should I do?