Basic toString

Argh! this is such a simple question but my mind aint working and you know the rest....
here is my code snipet..
public class Sieve
     private boolean[] eratostenes;
     private long j;
     public Sieve (int n)
          boolean[] eratostenes = new boolean [n];
          long j = 2;
               for (int i = 2; i < eratostenes.length; i += 2)
                    eratostenes[i] = false;
                for (int i = 3; i < eratostenes.length; i += 3)
                    eratostenes[i] = false;
      public String toString()
           String current= new String();
           String total = new String();
           current = "dog";
           /*for (int i = 2; i < eratostenes.length; i ++)
                if (eratostenes[i] == false)
                     current = (i + "   ");
                     total = (total + current);
           return(j);
}the problem is in the return statment! it wont accept the int(just a test variable, eventually there will be an array of ints i.e eratostenes..). How can I convert that int to a string? any help is appreciated

yes thanks you Sagnam! The "" + J is total cheese! I am looking at a tutorial simialr to what I am trying to do and they threw a "\t" at the end of their return statement, which confused me :/

Similar Messages

  • How to access SOAP web service with authentication, HTTP basic Authentication

    Dear All
    i use Flash Builder 4.5, flex 4..1, i am developing a flex client to soap webservices hosted over Glassfish 2 Java server, the web services is protected by HTTP Basic Authentication, everythime i run my code , the prombt for username and password show up, i need to pass user name and password through action script, i followed the flollowing (but was for http web service, not soap) but really did not work.
    http://stackoverflow.com/questions/490806/http-basic-authentication-wi th-httpservice-objects-in-adobe-flex-air
    http://forums.adobe.com/message/4262868
    private function authAndSend(service:HTTPService):void
            var encoder:Base64Encoder = new Base64Encoder();
            encoder.insertNewLines = false; // see below for why you need to do this
            encoder.encode("someusername:somepassword");
            service.headers = {Authorization:"Basic " +encoder.toString()};                                               
            service.send();
    Also i noticed in debug mode, always that WARNNING raised up
    Warning: Ignoring 'secure' attribute in policy file from http://fpdownload.adobe.com/pub/swz/crossdomain.xml.  The 'secure' attribute is only permitted in HTTPS and socket policy files.  See http://www.adobe.com/go/strict_policy_files for details.
    any idea ?

    Hello,
    I don't know if this could help.
    Another way to connect to a web service by SOAP and WSDL is to click on the Data/Services panel, then click on "Connect to Data/Services" and then select the "Web Service" (WSDL) icon. This could help as well.

  • Access Denied error with basic XML file operations

    Hi,
    I'm trying to set up a basic read, write and delete code for XML files which I can build upon in the future. The three methods are bound to three buttons on the page and all three calls are awaited. Here's my code:
    Write:
    XElement uservarnodes = new XElement("uservars",
    new XElement("uservar1", "1"),
    new XElement("uservar2", "2"),
    new XElement("uservar3", "3"),
    new XElement("uservar4", "4"),
    new XElement("uservar5", "5"),
    new XElement("uservar6", "6"),
    new XElement("uservar7", "7"),
    new XElement("uservar8", "8"));
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    var file = await local.CreateFileAsync("uservarfile.xml", CreationCollisionOption.ReplaceExisting);
    var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
    using (var outputStream = stream.GetOutputStreamAt(0))
    DataWriter mydataWriter = new DataWriter(outputStream);
    mydataWriter.WriteString(uservarnodes.ToString());
    await mydataWriter.StoreAsync();
    await outputStream.FlushAsync();
    Read (outputs the data to a textblock):
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    var file = await local.GetFileAsync("uservarfile.xml");
    string readtext = await Windows.Storage.FileIO.ReadTextAsync(file);
    XElement uservarnodes = XElement.Parse(readtext);
    txtTarget.Text = uservarnodes.ToString();
    Delete:
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    var file = await local.GetFileAsync("uservarfile.xml");
    await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
    When I tap each of the buttons once it all seems to work. But when I tap any of the buttons again within the same debug session I get an Access denied exception (E_ACCESSDENIED). Other people with this error had to await when calling their method, but I'm
    already doing that: private async void btnWrite_Click(object sender, RoutedEventArgs e) { await WriteToXMLFile(); }, etc.
    And the intervals between my taps isn't that short that you'd expect that the previously called method still had not finished completing. I don't understand why I'm getting the access denied error.
    Related to my question: I have added XML to the File Type Associations, File Open Picker and File Save Picker in the appxmanifest, but somewhere I read that you do not need to do this if you're working with local app data only. Is this true?

    var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
    I think because of your file stream hasn't been closed.
    by the way, it can be easier  by using System.IO.OpenStreamForWriteAsync extension method
    async public static Task<bool> SaveTextFileAsync(string filename, string data)
    byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(data);
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    var file = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
    try
    using (var s = await file.OpenStreamForWriteAsync())
    s.Write(fileBytes, 0, fileBytes.Length);
    return true;
    catch
    return false;
    (need using System.IO namespace)
    在現實生活中,你和誰在一起的確很重要,甚至能改變你的成長軌跡,決定你的人生成敗。 和什麼樣的人在一起,就會有什麼樣的人生。 和勤奮的人在一起,你不會懶惰; 和積極的人在一起,你不會消沈; 與智者同行,你會不同凡響; 與高人為伍,你能登上巔峰。

  • How do I protect my JNLP, my JARs etc. (with Basic Authentication)???

    hi all,
    i know that there is a FAQ ( [see here|http://lopica.sourceforge.net/faq.html#obfuscate] ) answering a related question with "You can use an obfuscator...". ok, but is there really no other solution?
    this is the simplified folder structure of my application on the server:
    [application]
      [etc]
        xyz.xml
      [jars]
        myapp.jar
      launch.jnlp
    website.jsp
    initial start and basic authentication:*
    my first idea was to secure everything underneath "application" with basic authentication via my web.xml (yes, i'm aware of the security concerns). this means everybody can access my website (here: website.jsp) which contains a start button that links to "launch.jnlp". as soon as the user clicks on it, the browser opens its standard authentication dialog since launch.jsp is in a protected area. after entering the correct credentials the jnlp-file is downloaded and java web start takes over control. first of all it seems as it tries to access the same jnlp-file again (??? --> probably in order to check for changes in the jnlp file --> this is certainly not the case for the initial startup) and then wants to download the relevant jar (myapp.jar). because both resources are protected jws opens its own basic authentication dialog where i have to enter the same credentials the second time. as far as i know, there is no solution to pass the credentials between the browser and the jvm.
    second start and basic authentication:*
    if the user starts my application for the 2nd, 3rd, ... time via desktop-link (set in jnlp-file) there is no need for accessing my website with a browser. therefore only the authentication dialog of jws gets displayed. so far, so good!
    and now the actual problem:*
    during runtime my application (signed with verisign certificate and having all permissions) uses commons-vfs and commons-httpclient to access resources on the same server (e.g. etc/xyz.xml). since they're underneath the protected "application" directory as well, my application needs the same credentials the user already entered in the authentication dialog of jws. now i could retrieve these credentials by calling Authenticator.requestPasswordAuthentication() within my application and passing them to vfs and httpclient. however, doing so opens up jws' authentication dialog again. grrr!!! is there a way to prevent this?
    related thougts:*
    i know i could disable jws' default Authenticatior and set my own Authenticator which might be able to return already entered credentials without opening the dialog a second time. however, it seems that even with <property name="javaws.cfg.jauthenticator" value="none" /> jws still opens its own dialog when acessing the JNLP file and the relevant JARs during the startup/download phase. of course, who else if not jws could handle that phase? my application might not even be downloaded at this point. so i guess setting my own Authenticator would not be a solution either (at least not if i want to secure my jnlp and my jars, too). quite the contrary, it would have to open another dialog... :-(
    my current solution:*
    for the moment i use jws' default Authenticatior which allows me to easily protect all my stuff on the server side (jnlp, jar, etc). i can live with the two login dialogs at the initial startup. and instead of querying the credentials from jws' default Authenticatior at runtime, i set two system properties for username and password in the (protected) jnlp-file, query them at runtime and hand it to vfs and httpclient. this prevents the 2nd (or 3rd) dialog but is definitely not a great solution. most of all i'm not happy with the fact that this somehow "destroys" the container-based security advantage of easily configuring authorized users via a separate mechanism e.g. tomcat-users.xml. now there has to be one master-password that has to be set in the jnlp-file! grrr!
    a possible alternative:*
    i'm not sure but would it be better to secure everything with form-based authentication on the website, and dynamically generate username and password into the jnlp-file? but what happens when the admin changes the password on the server and the user starts its application via desktop-link??? in case of basic authentication i think jws would popup the login dialog again. however, if i use the old username and password generated into the jnlp it won't work. i think the user then has to access the website again. this is not good at all! :-(
    the only real solution:*
    should i write a small application which can be downloaded by everybody and on startup queries the user's credentials, validates them with the help of our server, and uses the javax.jnlp-api to download the secured JARs of my real application? this seems so much overkill! does anybody have experiences with this approach? how difficult is it to implement the whole download/update stuff with javax.jnlp?
    WHAT HAVE I MISSED???
    AM I COMPLETELY WRONG???
    WHAT IS THE EASIEST WAY???
    AND WHAT IS THE BEST WAY???
    thank you so much,
    stephan

    Not sure, whether I understood correctly, what you wanna do - but up to now I can't see any problem.
    if you have a structure like this:
    /ctxroot/
           launch.jnlp
           /app/
               *.jar
               *.whateveryou may use in your web.xml:
         <servlet>
              <servlet-name>JnlpDownloadServlet</servlet-name>
              <servlet-class>jnlp.sample.servlet.JnlpDownloadServlet</servlet-class>
         </servlet>
         <servlet-mapping>
              <servlet-name>JnlpDownloadServlet</servlet-name>
              <url-pattern>*.jnlp</url-pattern>
              <url-pattern>/app/*</url-pattern>
         </servlet-mapping>
         <security-constraint>
              <web-resource-collection>
                   <web-resource-name>Application</web-resource-name>
                   <url-pattern>/app/*</url-pattern>
                   <http-method>GET</http-method>
                   <http-method>POST</http-method>
              </web-resource-collection>
              <auth-constraint>
                   <role-name>bla</role-name>
                   <role-name>fahsel</role-name>
              </auth-constraint>
              <user-data-constraint>
                   <transport-guarantee>CONFIDENTIAL</transport-guarantee>
              </user-data-constraint>
         </security-constraint>
         <security-constraint>
              <web-resource-collection>
                   <web-resource-name>Subscription</web-resource-name>
                   <url-pattern>*.jnlp</url-pattern>
              </web-resource-collection>
              <user-data-constraint>
                   <transport-guarantee>CONFIDENTIAL</transport-guarantee>
              </user-data-constraint>
         </security-constraint>
         <login-config>
              <auth-method>BASIC</auth-method>
              <realm-name>whatever-realm</realm-name>
         </login-config>
         <security-role><role-name>bla</role-name></security-role>
         <security-role><role-name>fahsel</role-name></security-role>
    ...Than you may use the Service stuff like:
         BasicService bs = (BasicService)ServiceManager.lookup("javax.jnlp.BasicService");
         URL codeBase = bs.getCodeBase();
         URL pu = new URL(codeBase.toString() + "whatever.bla");
         HttpURLConnection res = (HttpURLConnection) pu.openConnection();
         res.setInstanceFollowRedirects(true);
         res.setRequestMethod("GET");
         res.setConnectTimeout(10 * 60 * 1000);
         res.connect();
         String enc = res.getContentType();
    ...Where is the problem? If you wanna intercept certain "calls" to an app resource, just use a filter, which decides, whether to answer the request directly by itself or to pass it to the JnlpDownloadServlet ...

  • JTextField1.toString() has no "text="

    Instances of JButton, JLabel and JTextField all have a getText() method. However, the following produces strings containing the text for JButton and JLabel, but not for JTextField (see below). Why would that be? There are occasions when it would be useful to check what the text was, for example when using event.getComponent().toString(), but it is not there for JTextField.
    System.out.println("" + jButton1.toString());
    System.out.println("" + jLabel1.toString());
    System.out.println("" + jTextField1.toString());
    javax.swing.JButton[,12,446,98x26,alignmentX=0.0,alignmentY=0.5,border=
    javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@e2eec8,flags=
    296,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,
    disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,
    left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,
    rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,
    text=jButtonAAA,defaultCapable=true]
    javax.swing.JLabel[,12,478,58x16,alignmentX=0.0,alignmentY=0.0,border=,
    flags=8388608,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,
    disabledIcon=,horizontalAlignment=LEADING,horizontalTextPosition=
    TRAILING,iconTextGap=4,labelFor=,text=jLabelBBB,verticalAlignment=CENTER,
    verticalTextPosition=CENTER]
    javax.swing.JTextField[,12,500,83x20,layout=javax.swing.plaf.basic.
    BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=javax.
    swing.plaf.BorderUIResource$CompoundBorderUIResource@aa9835,flags=296,
    maximumSize=,minimumSize=,preferredSize=,caretColor=javax.swing.plaf.
    ColorUIResource[r=51,g=51,b=51],disabledTextColor=javax.swing.plaf.
    ColorUIResource[r=184,g=207,b=229],editable=true,margin=javax.swing.plaf.
    InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=javax.
    swing.plaf.ColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.
    plaf.ColorUIResource[r=184,g=207,b=229],columns=0,columnWidth=0,command=,
    horizontalAlignment=LEADING]

    I'm not sure I understand "commonly permanent". All
    three can be easily changed (and often are changed).This is not true in my experience. Button text is and should be
    relatively static. The same is true of labels. I respectfully submit
    that if this is not the case, you have UI design issues you need to
    address.
    The getText() method is not available in the example
    I showed (evt.getComponent()) which I am trying to
    use to identify which component from within a custom
    bean an event is coming from. It works for JButton
    and JLabel but not for JTextField. Probably there is
    a more elegant way of doing this, but I haven't
    figured it out.If you're trying to identify a component based on the text it
    contains, you need to rethink your design.
    If jTextField1.toString() doesn't show the "text="
    field, then it really isn't converting all of
    jTextField1 to a string.The API makes no such promise. The API promises it will return
    "a string representation of the object." There is no guarantee of
    completeness.

  • Requesting standard basic build and deployment requirements

    Operational Data: 
    Microsoft visual Studio 2008
    Visual Basic Windows Forms Application
    Crystal Reports 12.0.2000.0
    Deploying on Windows Server 2003, Standard Edition
    I have been having difficulty deploying a WindowsForms CrystalReports application that I developed.  The specifics of my troubles all bottom out in the tangle of runtime and development redistribution files.  It has taken some time for me to get to the point where I can see what is going on.
    In order to save others from the pitfalls that I have encountered I wanted to give a short history. 
    I wrote a report.rpt that placed "Hello World!" in the header, no data, no dependencies.  I created a simple application that instantiates a CRViewer and places a new report based on the input report in that viewer.  Works great in house, and on most machines with the simple runtime.
    My first crack at this application failed miserably on a Windows XP environment.  When I launched the application nothing appeared to happen at all.  This was disconcerting, but a check of the Event Viewer (Control Panel/Administrative Tools), revealed that the application was failing to load the form initialization.  This was failing before my try catch block, which seems to be hitting other devs who have had troubles indicated on other forums.  To get past this I removed the CrystalReportViewer widget from my actual windows form, and instead wiffled one into existence on the fly in my form load code:
    try
       Dim viewer As CrystalDecisions.Windows.Forms.CrystalReportViewer
       Dim report As ReportDocument
       viewer = New CrystalDecisions.Windows.Forms.CrystalReportViewer
       report = New ReportDocument
    Catch ex As ApplicationException
                 MessageBox.Show("Could not start viewer. "&ex.ToString(), "ApplicationException: ",MessageBoxButtons.OK )        End Try
    This did not eliminate the trouble, but it did move the issue to inside an exception handler.  What I learned from my handler is that there were missing assemblies from my installation.  I began adding these assemblies into my installer one by one until I came to a working report.  The missing bits were:
    BusinessObjects.Licensing.KeycodeDecoder.dll
    CEReportSource.dll
    CrystalDecisions.CrystalReports.Engine.dll
    CrystalDecisions.Enterprise.Desktop.Report.dll
    CrystalDecisions.Enterprise.Viewing.ReportSource.dll
    CrystalDecisions.ReportAppServer.DataSetConversion.dll
    CrystalDecisions.ReportAppServer.Prompting.dll
    CrystalDecisions.ReportSource.dll
    CrystalDecisions.Shared.dll
    CrystalDecisions.Web.dll
    CrystalDecisions.Windows.Forms.dll
    I then tried to reinstall the runtime library, as well as the runtime from my particular version of Visual Studio.  I was able to remove the hand pulled libs from my deployment.
    So, this brings me to the question:  What should I do to create and deploy a simple application based on the CrystalReports development kit that I have purchased?  What needs to be redistributed to the client's machine?  Is there a common repository for licensed developers to get the missing bits?  Is it expected that I have to install the VisualStudio redist and a machine specific runtime?  Is there one thing that will get it done?
    I am using CRRedist2008_x86.msi and Crystal2008.exe, this seems like too much...
    Thanks in advance

    Joe,
    Your notes indicate that you are using Crystal Reports 12. I noticed that you mentioned you have been attempting to deploy your application with CRRedist2008_x86.msi and Crystal2008.exe.
    Please note those runtime packages are for Crystal Reports Basic for Visual Studio .NET. This version is the bundled version of Crystal Reports that comes with Visual Studio .NET 2008 (v 10.5).
    You should be using the version 12 merge modules or server install packages. For specific information on how to deploy an application that uses the CR .NET runtime please review our deployment procedures here - https://boc.sdn.sap.com/node/8546.
    You should be using these:
    http://resources.businessobjects.com/support/communityCS/FilesAndUpdates/cr120_redist_msi.zip
    http://resources.businessobjects.com/support/communityCS/FilesAndUpdates/cr120_redist_exe.zip
    http://resources.businessobjects.com/support/communityCS/FilesAndUpdates/cr120_merge_modules.zip

  • Problem accessing servlet from java class which uses Basic Authentication

    "Hi,
    I am using weblogic 6.1 server. I am calling a servlet file from a class file using HttpURLConnection. This is the code below.
              String theUsername="B1A1Z1T2";
              String thePassword="hlladmin";
              String urlString="http://rsnetserver:113/hll/servlet/CallSSRUpload";
              String userPassword = theUsername ":" thePassword;
              String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes());
              try
                   URL url = new URL (urlString);
                   HttpURLConnection uc=(HttpURLConnection)url.openConnection();
                   int it = 0;
                   while ((it = encoding.indexOf('\n')) != -1
                        || (it = encoding.indexOf('\r')) != -1) {
                             encoding = encoding.substring(0, it)
                             encoding.substring(it 1);
                   uc.setRequestProperty("Authorization","BASIC " encoding);
                   uc.setRequestProperty("SOAPAction", url.toString());
                   System.out.println(uc.getResponseCode());
                   System.out.println(uc.getResponseMessage());
              catch(Exception io)
                   io.printStackTrace();
                   System.out.println("error message........" io.getMessage());     
    In web.xml I have d

    Hello,
    Could you post the stack trace?
    Thanks,
    Bruce
    Vijay Babu wrote:
    >
    "Hi,
    I am using weblogic 6.1 server. I am calling a servlet file from a class file using HttpURLConnection. This is the code below.
    String theUsername="B1A1Z1T2";
    String thePassword="hlladmin";
    String urlString="http://rsnetserver:113/hll/servlet/CallSSRUpload";
    String userPassword = theUsername ":" thePassword;
    String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes());
    try
    URL url = new URL (urlString);
    HttpURLConnection uc=(HttpURLConnection)url.openConnection();
    int it = 0;
    while ((it = encoding.indexOf('\n')) != -1
    || (it = encoding.indexOf('\r')) != -1) {
    encoding = encoding.substring(0, it)
    encoding.substring(it 1);
    uc.setRequestProperty("Authorization","BASIC " encoding);
    uc.setRequestProperty("SOAPAction", url.toString());
    System.out.println(uc.getResponseCode());
    System.out.println(uc.getResponseMessage());
    catch(Exception io)
    io.printStackTrace();
    System.out.println("error message........" io.getMessage());
    In web.xml I have d

  • Adding full screen code into Captivate 5's basic Button Widget

    Hi everyone!
    I was able to create a full screen button in Flash that works with Captivate 5 projects, however, I want to be able to active the full screen feature for every button created using the basic 'button' widget that comes with the Captivate program.  I am not a AS3 programmer so I think my issue is that I am confused as  to where to place the full screen code into the existing 'button widget'  code. Below is the code ...
    Thanks in advance!!
    edlearner
    HERE IS THE FULLSCREEN CODE THAT I USE
    button_name.addEventListener(MouseEvent.CLICK, fullScreen_action);
    function fullScreen_action(event:MouseEvent):void {
    stage.displayState=StageDisplayState.FULL_SCREEN;
    stop();
    HERE IS THE BASIC CODE FOR THE BUTTON WIDGET IN CAPTIVATE 5
    //..........................Template for Static Widget(AS3)....................
    //flash construct to use external interface : This is needed to use flash functionality for communication between two swfs
    import flash.external.ExternalInterface;
    import fl.controls.ComboBox;
    var widgetMode:String = '';
    var widgetParam:String = '';
    var varHand:Object = null;
    var movieHandle:Object = null;
    XML.prettyIndent = 0;
    XML.prettyPrinting = false;
    XML.ignoreWhitespace = true;
    var checkUpdatedXML = false;
    var playedByButton = false;
    var pauseFrame = 0;
    var addednoskipframe = false
    var myXML:XML;
    var myData:String = '<element1><textProperties><font face="Trebuchet MS" style="" size="12"/><textDecoration bold="true" underline="false" italic="false"/><color textColor="0x000000" highlightRequired="false" highlightColor="0xffffff"/></textProperties><captions style="BUTTON_1" themeLabel="0" backColor="0xffffcc" eventAssign="" eventParam="" txtXPos="9" txtYPos="4" imgXPos="190" imgYPos="40" a="1" b="0" c="0" d="1" tx="0" ty="0" bgSelected="false" borderColor="0xff9933" borderSelected="false" containerXPos="" containerYPos=""><text visible="true" width="42" height="20" a="1" b="0" c="0" d="1" tx="18" ty="4">Button</text><image visible="false" width="22" height="18" a="1" b="0" c="0" d="1" tx="NaN" ty="NaN"></image></captions></element1>';
    var xmlConfig:String = '<configs><styles label="Ivory" movieclip="BUTTON_1" backColor=""/><styles label="Frosted" movieclip="BUTTON_8" backColor=""/><styles label="Grey Space" movieclip="BUTTON_9" backColor=""/><styles label="Honey Comb" movieclip="BUTTON_10" backColor=""/><styles label="Mountain Blue" movieclip="BUTTON_11" backColor=""/><styles label="Aero" movieclip="BUTTON_12" backColor=""/><styles label="Gradient" movieclip="BUTTON_13" backColor=""/><styles label="Vivid 1" movieclip="BUTTON_14" backColor=""/><styles label="Vivid 2" movieclip="BUTTON_15" backColor=""/><styles label="Aqua" movieclip="BUTTON_16" backColor=""/><styles label="Glitter" movieclip="BUTTON_17" backColor=""/></configs>';
    //var xmlConfig:String = '<configs><styles label="Button 1" movieclip="BUTTON_1" backColor=""/><styles label="Button 2" movieclip="BUTTON_2" backColor=""/><styles label="Button 1" movieclip="BUTTON_1" backColor=""/><styles label="Button 2" movieclip="BUTTON_2" backColor=""/><styles label="Button 3" movieclip="BUTTON_3" backColor=""/><styles label="Button 4" movieclip="BUTTON_4" backColor=""/></configs>';
    var myConfig:XML = new XML(xmlConfig);
    var myWM = "";
    var mc:MovieClip;
    CaptionMc.visible = false;
    textFormatterMc.visible = false;
    //update ();
    var objName;
    function fnHandleButtonEvent (evt:MouseEvent)
        if (varHand != null)
            switch (Number(myXML.captions.@eventAssign))
                case 1 :
                    varHand.rdcmndResume = 1;
                    break;
                case 2 :
                    varHand.rdcmndPrevious = 1;
                    break;
                case 3 :
                    varHand.rdcmndNextSlide = 1;
                    break;
                case 4 :
                    varHand.cpCmndGotoSlide = varHand.cpInfoLastVisitedSlide;
                    varHand.rdcmndResume = 1;
                    break;
                case 5 :
                    if(varHand.rdinfoCurrentSlide != (Number(myXML.captions.@eventParam) - 1)){
                        varHand.cpCmndGotoSlide = Number(myXML.captions.@eventParam) - 1;
                        varHand.rdcmndResume = 1;
                    break;
                case 6 :
                    navigateToURL (new URLRequest(myXML.captions.@eventParam), "_blank");
                    break;
                case 7 :
                    navigateToURL (new URLRequest("mailto:"+myXML.captions.@eventParam), "_blank");
                    break;
            playedByButton = true;
    function update ()
        myXML = new XML(myData);
        if (myWM == "Edit")
            textFormatterMc.setData (myXML.textProperties);//strCaptivateXML:String
            textFormatterMc.init ();
            CaptionMc.setData (myXML.captions, textFormatterMc);
            CaptionMc.setConfig (myConfig.styles);
            CaptionMc.init ();
            CaptionMc.visible = true;
            textFormatterMc.visible = true;
            var arr = [textFormatterMc.sizeSelectorMc];
            initCursor(arr);
        else
            CaptionMc.visible = false;
            textFormatterMc.visible = false;
            if(mc != null){
                removeAllChildren(mc);
            }else{
                mc = new MovieClip();
                addChild (mc);
            var xmlRef = myXML.captions;
            var textMatrix:Matrix = new Matrix(xmlRef.text.@a, xmlRef.text.@b, xmlRef.text.@c, xmlRef.text.@d, xmlRef.text.@tx, xmlRef.text.@ty)
            var txt:TextField = new TextField();
            objName = txt;
            txt.name = "txt";
            txt.mouseEnabled = false;
            txt.selectable = false;
            txt.multiline = true;
            txt.wordWrap = true;
            mc.addChild (txt);
            txt.text = xmlRef.text;
            txt.mouseEnabled = false;
            txt.width = Number(xmlRef.text.@width);
            txt.height = Number(xmlRef.text.@height);
            //txt.x = Number(xmlRef.text.@tx);
            //txt.y = Number(xmlRef.text.@ty);
            txt.transform.matrix = textMatrix;
            var txtProp = myXML.textProperties;
            var tf = new TextFormat(txtProp.font. @ face,txtProp.font. @ size,txtProp.color. @ textColor,getBool(txtProp.textDecoration. @ bold),getBool(txtProp.textDecoration. @ italic),getBool(txtProp.textDecoration. @ underline));
            txt.setTextFormat (tf);
            if (txtProp.color. @ highlightRequired == "true")
                txt.background = true;
                txt.backgroundColor = uint(txtProp.color. @ highlightColor);
            txt.visible = getBool(xmlRef.text. @visible)
            var mcCaption = new MovieClip();
            var mcCaptionMatrix = new Matrix(xmlRef.@a, xmlRef.@b, xmlRef.@c, xmlRef.@d, xmlRef.@tx, xmlRef.@ty);
            var ClassName:Class = getDefinitionByName(xmlRef.@style) as Class;
            var objHolder = new ClassName();
            objHolder.buttonMode = true;
            objHolder.addEventListener (MouseEvent.CLICK, fnHandleButtonEvent);
            mcCaption.addChild (objHolder);
            objHolder.transform.matrix = mcCaptionMatrix;
            if (SimpleButton(objHolder.getChildByName("btn")) != null && xmlRef.@bgSelected == "true")
                var tempColorStr = [email protected]();
                if (tempColorStr.length > 0)
                    var objColorTransform = new ColorTransform();
                    objColorTransform.color = uint(tempColorStr);
                    SimpleButton(objHolder.getChildByName("btn")).transform.colorTransform = objColorTransform;
            if (MovieClip(objHolder.getChildByName("mcBorder")) != null && xmlRef.@borderSelected == "true")
                var borderColorStr = [email protected]();
                if (borderColorStr.length > 0)
                    var borderColorTransform = new ColorTransform();
                    borderColorTransform.color = uint(borderColorStr);
                    MovieClip(objHolder.getChildByName("mcBorder")).transform.colorTransform = borderColorTransform;
            mcCaption.addChild (objHolder);
            mc.addChildAt (mcCaption, 0);
            var mcIconMatrix = new Matrix(xmlRef.image.@a, xmlRef.image.@b, xmlRef.image.@c, xmlRef.image.@d, xmlRef.image.@tx, xmlRef.image.@ty)
            var mcIcon = new Loader();//IconMovie();
            mcIcon.contentLoaderInfo.addEventListener (Event.COMPLETE, imageLoaded);
            if (xmlRef.image != ""){
                mcIcon.load (new URLRequest(String(xmlRef.image)));
            mcIcon.name = "mcIcon";
            mcIcon.transform.matrix = mcIconMatrix;
            mcIcon.visible = getBool(xmlRef.image. @visible)
            mc.addChild (mcIcon);
    var cursor;
    var otherCursor;
    var downState = false;
    function initCursor(arr:Array){
        cursor = new Cursor();
        cursor.mouseEnabled = false
        cursor.visible = false;
        addChild(cursor);
        otherCursor = new StretchCursor();
        otherCursor.mouseEnabled = false
        otherCursor.visible = false;
        addChild(otherCursor);
        for(var i=0 ; i< arr.length; i++){
            arr[i].addEventListener(MouseEvent.ROLL_OVER, showCursor)
            arr[i].addEventListener(MouseEvent.ROLL_OUT, hideCursor)
            arr[i].addEventListener(MouseEvent.MOUSE_DOWN, showOtherCursor)
            arr[i].addEventListener(MouseEvent.MOUSE_UP, hideOtherCursor)
        this.addEventListener(MouseEvent.MOUSE_UP, hideOtherCursor);
        this.addEventListener(MouseEvent.ROLL_OUT, hideOtherCursor);
    function showCursor(e:MouseEvent){
        var txt = MovieClip(e.target).sizeTxt;
        if(!downState && txt.type == "dynamic"){
            cursor.visible = true;
            cursor.startDrag(true)
            Mouse.hide();
    function hideCursor(e:MouseEvent){
        if(!downState){
            cursor.stopDrag()
            cursor.visible = false;
            Mouse.show();
    function showOtherCursor(e:MouseEvent){
        var txt = MovieClip(e.currentTarget).sizeTxt;
        if(txt.type == "dynamic"){
            hideCursor(e);
            downState = true
            otherCursor.startDrag(true)
            otherCursor.visible = true;
            Mouse.hide();
    function hideOtherCursor(e:MouseEvent){
        downState = false;
        otherCursor.stopDrag()
        otherCursor.visible = false;
        Mouse.show();
    function removeAllChildren(mcRef:MovieClip){
        for(var i=(mcRef.numChildren-1); i>=0; i--){
            mcRef.removeChildAt(i);
    function imageLoaded (e:Event)
        var mc = e.target.content;
        mc.width = Number(myXML.captions.image. @ width);
        mc.height = Number(myXML.captions.image. @ height);
    function getBool (str:String):Boolean
        var ret:Boolean;
        if (str == "true")
            ret = true;
        else
            ret = false;
        return ret;
    function getModifiedXML ():String
        return myXML.toString();
    //to register enter frame function
    this.addEventListener (Event.ENTER_FRAME,onEnterEveryFrame);
    //Captivate App will not recognize a Static Widget unless this function is implemented and returns true
    function isStatic ():Boolean
        return true;//denotes that this is indeed a Captivate Interactive Learning Object
    //a object needs to be created and values filled in . This is taken by captivate and stored as //xml string. This is the mean to pass values between captivate and widget swf.
    function getInspectorParameters ():Object
        //dev//Apply
        //set the data in _parameters fields. This is called by captivate to get the values of widget swf
        var _parameters: Object = new Object();
        _parameters.dataXML = getModifiedXML();
        return _parameters;
    // whenever widget is inserted the widget swf is passed on the parameters stored inside captivate so that it is drawn in updated stage.
    function setInspectorParameters (inParam:Object):void
        //Dev//on Double click //edit window
        myData = inParam.dataXML;
        myWM = widgetMode;
        update ();
    //is called whenever widget needs to be drawn as per the changed
    //parameters like OK to widget dialog and stage swf is updated with the current values.
    function setParameters (inParam:Object):void
        if (inParam.dataXML != null)
            //redraw the widget as parameters has changed
            //dev//OK button
            myData = inParam.dataXML;
            myWM = widgetMode;
            update ();
    //this function is called to set the variable on player
    function cpSetValue (variable:String, val):void
        if (variable == 'movieHandle')
            movieHandle = val;
            varHand = movieHandle.getMovieProps().variablesHandle;
            //using varHand the variables can be accessed for eg. varHand.rdcmndPause = 1;
        if (variable == 'widgetMode')
            widgetMode = val;
            //dev//set mode
    function getEditModeWidth ( ):int
        return 411;// return required width of widget properties dialog here
    function getEditModeHeight ( ):int
        return 480;// return required height of widget properties dialog here
    //Register all the functions with ExternalInterface
    if (ExternalInterface.available == true)
        ExternalInterface.addCallback ("isStatic",isStatic);
        ExternalInterface.addCallback ("getInspectorParameters",getInspectorParameters);
        ExternalInterface.addCallback ("setInspectorParameters",setInspectorParameters);
        ExternalInterface.addCallback ("setParameters",setParameters);
        ExternalInterface.addCallback ("cpSetValue", cpSetValue);
        ExternalInterface.addCallback ( "getEditModeWidth", getEditModeWidth);
        ExternalInterface.addCallback ( "getEditModeHeight", getEditModeHeight);
    //take care of optimised drawing inside this function. Check the widgetMode , widgetParams  and draw accordingly
    function onEnterEveryFrame (aevent:Event):void
        var wm:String = widgetMode;//this variable will be provided by Captivate App or Captivate Movie
        if (wm == null)
            wm = widgetMode;
        if (wm == null)
            wm = 'Stage';
            this.removeEventListener (Event.ENTER_FRAME,onEnterEveryFrame);
        else if (wm == 'Edit')
            //Property inspection inside Captivate app
            myWM = wm;
            update ();
            this.removeEventListener (Event.ENTER_FRAME,onEnterEveryFrame);
        else if (wm == 'Preview')
            //The code here is used for previewing the widget in the preview window of widget panel
            myWM = wm;
            update ();
            this.removeEventListener (Event.ENTER_FRAME,onEnterEveryFrame);
        else
            //On stage scrubbing/live preview inside Captivate app (OR) at runtime inside Captivate movie.
            if(!checkUpdatedXML){
                if (movieHandle != null)
                    widgetParam = movieHandle.widgetParams();
                if (widgetParam != "")
                    var myXml:XML = new XML(widgetParam);
                    myData = myXml.property.(@id == "dataXML").string;
                    wm = "Runtime";
                    myWM = wm;
                    update ();
                    checkUpdatedXML = true
            if (movieHandle != null)
                if (movieHandle.isWidgetEnabled() == true)
                    if(addednoskipframe == false)
                        var slidestart = movieHandle.getSlideProps().startFrame;
                        var slideend = movieHandle.getSlideProps().endFrame;
                        pauseFrame = Math.ceil((slidestart  + slideend)/2);
                        var SlidePauseFrame = pauseFrame - slidestart + 1;
                        movieHandle.getSlideProps().slideHandle.AddNoSkipFrame(SlidePauseFrame);
                        addednoskipframe = true;
                    if(movieHandle.isWidgetEnabled()  && varHand.rdinfoCurrentFrame == pauseFrame && playedByButton == false)
                        varHand.rdcmndPause = 1;
                        this.removeEventListener (Event.ENTER_FRAME,onEnterEveryFrame);
    stage.scaleMode = StageScaleMode.NO_SCALE;
    stage.align = StageAlign.TOP_LEFT;

    Hi again,
    I just added a virtual keyboard widget, so that you can enter text even in Fullscreen Mode
    http://www.m-gd.com/virtual-keyboard-captivate-widget-en/

  • Best way to implement a basic text output window

    Hello,
    I want to monitor the activity of an hardware devices which sends text, in some case, a lot and fairly fast. So far I send this to the standard output and this is fine.
    Now I need to support several devices concurrently so I need to create a very basic window which just display some read only text with a scroll bar (I must have only one instance of my app running on a system). As there are hundreds of ways to do that in Java, I would like some advice to make something which minimize latencies and resources consumption (e.g. using a JTextPane with a StyledDocument might not be optimal for this...)
    Sebastien

    As recommended, I used a JTextArea. With that I use the default document and "Piped" streams.
    I tested it with the little loop below:
            String text = "";
            PipedOutputStream pos=new PipedOutputStream();
            final int PIPE_BUFFER_SIZE=0x100000;
            dialog.monitorStream(new PipedInputStream(pos,PIPE_BUFFER_SIZE));
            long start=System.nanoTime();
            for (int i = 0; i < 0x100000; i++) {
                String zeroes="";
                for(int j=0;j<Integer.numberOfLeadingZeros(i);j++)
                    zeroes+='0';
                text = zeroes+Integer.toBinaryString(i) + "\n";
                pos.write(text.getBytes());//use JTextArea/PipedOutputStream
                //System.out.print(text);//use console
            long end=System.nanoTime();
            System.out.println("exectime: "+Long.toString((end-start)/1000000));With the (win32) console it took around 195 seconds on my laptop
    I got a similar timing with NetBean's output window (but I must say that it is quite good result if we take into account that it keeps all the data while win32 console keeps only the 300 last lines!)
    Using the JTextArea/PipedOutputStream, times fall down to 22 seconds !! (I made it to accept up to 8MB of data and to keep at least the last 4MB chunk of data)
    Ok, I will never put JTextArea performance in question...
    Thanks for your answers.
    Note for those who do similar things: the PIPE_BUFFER_SIZE is a key parameter for the speed of operations, the bigger the better. For example, when I double its size, the times fall down to 15 seconds !
    Still for those interested in that kind of stuff, the core of the monitoring thread:
        protected class StreamMonitor implements Runnable {
            //This will display correctly ony ANSI characters
            //"&#50504;&#45397;" is displayed as "??"
            public StreamMonitor() {
            public void run() {
                int totalCount=0;
                try {
                    byte[] buf=new byte[0x8000];
                    StringBuffer sb=new StringBuffer();
                    sb.ensureCapacity(0x10000);
                    int emptyCnt=0;
                    while (true) {
                        if (toMonitor.available()>0) {
                            emptyCnt=0;
                            int n = toMonitor.read(buf);
                            totalCount+=n;
                            for (int i = 0; i < n; i++) {
                                sb.append((char)buf);
    if(sb.length()>0x8000)
    int MAX_SIZE=0x0800000;
    if(totalCount>MAX_SIZE)
    doc.remove(0,(MAX_SIZE / 2));
    totalCount-=MAX_SIZE / 2;
    doc.insertString(doc.getLength(), sb.toString(), null);
    outputTextArea.setCaretPosition(doc.getLength());
    sb.setLength(0);
    else
    doc.insertString(doc.getLength(), sb.toString(), null);
    outputTextArea.setCaretPosition(doc.getLength());
    sb.setLength(0);
    emptyCnt++;
    if(emptyCnt<1000){
    Thread.yield();
    else{
    //if we execute this thread repeatedly for nothing,
    //make it sleep a while to reduce CPU load
    Thread.sleep(20);
    } catch (Exception ex) {
    Logger.getLogger(ATextScreenOutput.class.getName()).log(Level.SEVERE, null, ex);

  • Basic blackjack program - help please

    can soemone please still me if this will work?
    this will become a VERY rudimentary blackjack program
    meaning there is no AI.
    this is how i wanted
    You got a "card"
    You got a "card"
    your score is:
    would you like to hit or stay?
    and then if it hits it tells u the dealers score
    then it keeps on doing the same thing..like
    you got a..
    your score is...
    hit or stay?
    and of course im trying to add to ask the user if they want A to be 1 or 11 (which i have but dont know how to incorporate)
    sorry this is my second day learning java so be easy on me.
    no double down or splits or betting is required.
    this is basically a skeleton that im having trouble using
    but i have to use the given randomGenerator
    can somone help me organize this or help me add codes to do this?
    import java.io.*;
    import java.util.*;
    public class blackjack
        public static void main ( String [] args )
            ConsoleReader console = new ConsoleReader( System.in );
            int uscore = ucard1 + ucard2;
            int dscore = dcard1 + dcard2;
            int dcard1; // dealer card1
            int dcard2; // dealer card2
            int dcard3; // dealer card3
            int dcard4; // dealer card4
            int dcard5; // dealer card5
            int ucard1; // user card1
            int ucard2; // user card2
            int ucard3; // user card3
            int ucard4; // user card4
            int ucard5; // user card5
            int hit = 1;
            while (hit == 1)
            Random generator = new Random ();
            int diamonds = 1 + generator.nextInt( 13 );
            int spades = 1 + generator.nextInt( 13 ); 
            int hearts = 1 + generator.nextInt( 13 ); 
            int clubs = 1 + generator.nextInt( 13 ); 
            System.out.println ("Welcome to the Blackjack Game");
            switch ( dcard )
               case 1:   return "Ace";
               case 2:   return "2";
               case 3:   return "3";
               case 4:   return "4";
               case 5:   return "5";
               case 6:   return "6";
               case 7:   return "7";
               case 8:   return "8";
               case 9:   return "9";
               case 10:  return "10";
               case 11:  return "Jack";
               case 12:  return "Queen";
               case 13:  return "King";
            switch ( ucard )
               case 1:   return "Ace";
               case 2:   return "2";
               case 3:   return "3";
               case 4:   return "4";
               case 5:   return "5";
               case 6:   return "6";
               case 7:   return "7";
               case 8:   return "8";
               case 9:   return "9";
               case 10:  return "10";
               case 11:  return "Jack";
               case 12:  return "Queen";
               case 13:  return "King";
           if ( dcard1 + dcard2  == 21) {
                System.out.println("Dealer has Blackjack.  Dealer wins.");
               return false;
          if (  ucard1 + ucard2   == 21) {
              System.out.println("You have Blackjack.  You win.");
               return true;
            System.out.println(" You got "+ ucard1 +"  ");
            System.out.println(" You got "+ ucard2 +"  ");
            if ( value2 == case 1 )
                System.out.println("Would you like your A to be 1 or 11?")
            System.out.println("Your score is " + uscore + ":");
            System.out.println("To hit press 1 and to stay press 2");
            hit = 0;
            hit = console.readInt();
            if ( hit =  1 )
                System.out.println("You got + ucard3 + ")
            System.out.println("Your score is " + uscore + ":");
            System.out.println("To hit press 1 and to stay press 2");
            hit = 0;
            hit = console.readInt();
                System.out.println("You got + ucard4 + ")
            System.out.println("Your score is " + uscore + ":");
            System.out.println("To hit press 1 and to stay press 2");
            hit = 0;
            hit = console.readInt();
            System.out.println("You got + ucard5 + ");
            System.out.println("Your score is " + uscore + ":");
            System.out.println("To hit press 1 and to stay press 2");
            hit = 0;
            hit = console.readInt();
            if (cont = 2);
            System.out.println("Dealer's score is + "dscore" + :");
            System.out.println("Your score is + "uscore" + :");
            if (dscore >= uscore)
                System.out.println("I won! get better!")
            if (uscore > dscore)
                System.out.println("Somehow, you beat me")
            

    Here is an example of what I've done before, and it needs to be fixed in several ways...
    my playing card value enum
    enum PlayingCardValue
        NO_CARD("","", 0, -1),  // placeholder so that ace starts at one
        ACE("A", "ace", 1, 11),  // has two values 1 or 11
        DEUCE("2", "deuce", 2, -1),  // everything else has only 1 numeric value
        THREE("3", "three", 3, -1),  // -1 is a marker that says "don't use this"
        FOUR("4", "four", 4, -1),
        FIVE("5", "five", 5, -1),
        SIX("6", "six", 6, -1),
        SEVEN("7", "seven", 7, -1),
        EIGHT("8", "eight", 8, -1),
        NINE("9", "nine", 9, -1),
        TEN("10", "ten", 10, -1),
        JACK("J", "jack", 10, -1),
        QUEEN("Q", "queen", 10, -1),
        KING("K", "king", 10, -1);
        private String shortName;
        private String name;
        private int value1;  // main valuve
        private int value2;  // -1 if not valid, a positive number if valid (if the ace)
        // enums have private constructors
        private PlayingCardValue(String shortName, String name, int value1, int value2)
            this.shortName = shortName;
            this.name = name;
            this.value1 = value1;
            this.value2 = value2;
        public String getRep()
            return this.shortName;
        public int getValue1()
            return this.value1;
        public int getValue2()
            return this.value2;
        @Override
        public String toString()
            return this.name;
    }my Playing card suit enum
    enum PlayingCardSuit
        SPADES ("spades"),
        HEARTS ("hearts"),
        DIAMONDS("diamonds"),
        CLUBS("clubs");
        private String name;
        private PlayingCardSuit(String name)
            this.name = name;
        @Override
        public String toString()
            return name;
    }My playingcard class
    * http://forum.java.sun.com/thread.jspa?threadID=5184760&tstart=0
    * @author Pete
    class PlayingCard
        private PlayingCardValue value;
        private PlayingCardSuit suit;
        public PlayingCard(PlayingCardValue value, PlayingCardSuit suit)
            this.value = value;
            this.suit = suit;
        public PlayingCardValue getValue()
            return this.value;
        public PlayingCardSuit getSuit()
            return this.suit;
        @Override
        public String toString()
            return this.value + " of " + this.suit;
    }You get the idea?

  • HTTP Basic Auth and Proxy Auth

    Hi,
    i have a problem with the authentication against a proxy server and against a content provider. At first I have to authenticate against the proxy to get "free internet". The next step is to authenticate against the content provider to get a html or xml file.
    The following source code runs very good in Eclipse, i.e. as JUnitTest. But If I execute the same code within a weblogic server, I will get an error (not authenticated). I believe I get this message from the content provider and not from the proxy because If I test this code within the weblogic server and with no authentication (i.e. google needs no authentication), I will get a valide xml/html file.
    StringBuffer sb = new StringBuffer();
              SimpleAuthenticator simple = new SimpleAuthenticator("joeuser","a.b.C.D"); //from openbook
              Authenticator.setDefault(simple);
              String strUrl = "http://www.rahul.net/joeuser/";
              URL url = null;
              try {
                   url = new URL(strUrl);
              } catch (MalformedURLException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              URLConnection conn = null;
              InetSocketAddress addr = new InetSocketAddress("proxy.domain",8080);
              Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
              try {
                   conn = url.openConnection(proxy);
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              String proxyStr = "username" + ":" + "passwordl";
              String encoded = new String(Base64.encodeBase64(proxyStr.getBytes()));
              conn.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
              // get http status code which is located in header field 0
              String status = conn.getHeaderField(0);
              if (status.contains("200")) {
                   BufferedReader in = null;
                   try {
                        in = new BufferedReader(new InputStreamReader(conn.getInputStream(),
                                  "ISO-8859-1"));
                        String inputLine;
                        while ((inputLine = in.readLine()) != null) {
                             sb.append(inputLine);
                        in.close();
                   } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                   } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
              else {
                   System.out.println("Error");
              System.out.println(sb.toString());
    public class SimpleAuthenticator
    extends Authenticator
         private String username,
         password;
         public SimpleAuthenticator(String username,String password)
              this.username = username;
              this.password = password;
         protected PasswordAuthentication getPasswordAuthentication()
              return new PasswordAuthentication(
                        username,password.toCharArray());
    Does somebody know a solution? I need the authentication against proxy and content provider in "one application".
    Thank you very much,
    André

    I typically have used Apache Commons HttpClient for anything but trivial URL connections, and especially when combining both basic auth and proxy auth. When you use it, be aware of the "preemptive authentication" flag. One server I worked with didn't send the correct parameters back on particular requests, so I had to turn on this flag to get it to work.

  • HTTPService basic authorization headers...

    Hi,
    I am trying to programatically add the Authorization header to a HTTPService call, but apparently the flash player 9 and 10 remove this header. crossdomain.xml with
    <?xml version="1.0"?>
    <!DOCTYPE cross-domain-policy SYSTEM
    "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
    <cross-domain-policy>
      <allow-access-from domain="*"/>
      <allow-http-request-headers-from domain="*" headers="Authorization"/>
    </cross-domain-policy>
    Does not work either.
    My code is as follows:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
        <mx:Script>
        <![CDATA[
        import mx.controls.Alert;
        import mx.rpc.events.ResultEvent;
        import mx.rpc.events.FaultEvent;
        import mx.utils.Base64Encoder;
           private function addAuthHeader(serv:*, username:String,password:String):void {
                 //add the header to request
                 var encoder : Base64Encoder = new mx.utils.Base64Encoder();
                 encoder.insertNewLines = false;
                 encoder.encode(username + ":" + password);
                 var prop:String = "Basic "+ encoder.toString();
                 serv.headers = {"Authorization":prop};
                 //serv.headers["Authorization"] = "Basic " + encoder.toString();
                 serv.send();
               private function getURL():void {
                  addAuthHeader(myService, "admin", "crypticpassw");
                private function widgetResultHandler(event:ResultEvent):void
                    myText.text = event.result as XML;
                private function widgetFaultHandler(event:FaultEvent):void
                    Alert.show(event.fault.message, "Oeps..." + event);
        ]]>
        </mx:Script>
    <mx:HTTPService id="myService"
                url="http://localhost:8080/test/search/firstpage.xml"
                resultFormat="e4x"
                        result="widgetResultHandler(event);"
                        fault="widgetFaultHandler(event);"/>
    <mx:Button id="go" label="GO" click="getURL()" x="97" y="145"/>
    <mx:TextArea id="myText" x="97" y="48" width="223" height="89"/>
    <mx:Label x="97" y="22" text="Stop the custom search"/>
    </mx:Application>
    Can anyone tell me how I can get this functionality to work. The numerous examples on the web all look like mine, but none works because the header is removed before sending the request to the server.
    Kind regards,
    Marc de Kwant

    Hi,
    I am trying to programatically add the Authorization header to a HTTPService call, but apparently the flash player 9 and 10 remove this header. crossdomain.xml with
    <?xml version="1.0"?>
    <!DOCTYPE cross-domain-policy SYSTEM
    "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
    <cross-domain-policy>
      <allow-access-from domain="*"/>
      <allow-http-request-headers-from domain="*" headers="Authorization"/>
    </cross-domain-policy>
    Does not work either.
    My code is as follows:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
        <mx:Script>
        <![CDATA[
        import mx.controls.Alert;
        import mx.rpc.events.ResultEvent;
        import mx.rpc.events.FaultEvent;
        import mx.utils.Base64Encoder;
           private function addAuthHeader(serv:*, username:String,password:String):void {
                 //add the header to request
                 var encoder : Base64Encoder = new mx.utils.Base64Encoder();
                 encoder.insertNewLines = false;
                 encoder.encode(username + ":" + password);
                 var prop:String = "Basic "+ encoder.toString();
                 serv.headers = {"Authorization":prop};
                 //serv.headers["Authorization"] = "Basic " + encoder.toString();
                 serv.send();
               private function getURL():void {
                  addAuthHeader(myService, "admin", "crypticpassw");
                private function widgetResultHandler(event:ResultEvent):void
                    myText.text = event.result as XML;
                private function widgetFaultHandler(event:FaultEvent):void
                    Alert.show(event.fault.message, "Oeps..." + event);
        ]]>
        </mx:Script>
    <mx:HTTPService id="myService"
                url="http://localhost:8080/test/search/firstpage.xml"
                resultFormat="e4x"
                        result="widgetResultHandler(event);"
                        fault="widgetFaultHandler(event);"/>
    <mx:Button id="go" label="GO" click="getURL()" x="97" y="145"/>
    <mx:TextArea id="myText" x="97" y="48" width="223" height="89"/>
    <mx:Label x="97" y="22" text="Stop the custom search"/>
    </mx:Application>
    Can anyone tell me how I can get this functionality to work. The numerous examples on the web all look like mine, but none works because the header is removed before sending the request to the server.
    Kind regards,
    Marc de Kwant

  • Basic authentication when calling a web service

    I am attempting to call a web service using ActionScript. The
    web service provider requires that I use HTTP Basic Authentication
    to communicate my SOAP requests. I cannot seem to get this done in
    ActionScript. If I instantiate a WebService object and call its
    SetCredentials method, I get an error "Authentication not supported
    on DirectHTTPChannel (no proxy)". I have the WebService object's
    useProxy property set to true. HELP!

    I know this is five years later on this forum but there's no solution here or on any other forum.  So after two day's of hammering this out I was able to produce a workable solution.  Create a new user account for testing.
    Wu_Xiao's explanation of the issue was dead on.  The WebService does a GET then a POST and for the GET we are unable to supply the Authorization in the header and this is why we get the popup. The POST has the Authorization but it already to late. 
    Take these actions
    1 Create a new user on the machine with the web services. Start with a simple name and password (text only)  I had issues with different users. Start clean and simple.
    2 Copy your web services a second usable service.  You'll see in my example below i have Ive copied  ServicesSECURE/Services1.asmx?WSDL to ServicesDEFINITION/Services1.asmx?WSDL
    3 Remove all of the code inside of your services making the new set of service like a definition service. Make sure all of the inputs and outputs are the same. ServicesDEFINITION will have no coding and empty returns.
    Example  
    [WebMethod]
            public String CountUsers(string group)
                return "";
    4 Implement the code below. Call the init() right away to instantiate the web service and wait until it loads to use any of the services.  I use a button event to test.
    private var testws:WebService = new WebService;
      private function init():void
      testws.wsdl="http://test.com/ServicesDEFINITION/Services1.asmx?WSDL";
      var encoder:Base64Encoder= new Base64Encoder();
      encoder.insertNewLines = false; // see below for why you need to do this
      encoder.encode("USERNAME:PASSWORD");
      testws.httpHeaders = {Authorization:" Basic " + encoder.toString()};
      testws.loadWSDL();
      testws.addEventListener("load", wsdlLoadHandler);
      protected function test_clickHandler(event:MouseEvent):void
      testws["CountUsers"].addEventListener(mx.rpc.events.FaultEvent.FAULT,testFaultHandler);
      testws["CountUsers"].addEventListener(mx.rpc.events.ResultEvent.RESULT,testResultHandler) ;
      testws.endpointURI="http://test.com/ServicesSECURE/Services1.asmx?WSDL";
      testws.getOperation("CountUsers").send("Test");
      protected function wsdlLoadHandler (event:LoadEvent) : void
      //the service has to load before using the getOperation function
      //you could try using mx.core.UIComponent.callLater from
      //this listener and call the gettestws.getOperation("Co....
    So you'll see that the ServicesDEFINITION (GET) is called and grabs the definition of the Service1 service but this unsecured services is useless because we've removed all of the code.  After the definition GET is called we can change the end point using endpointURI and perform the POST against our secure ServicesSECURE.

  • Basic Authentication in WebService

    Hi,
       I am trying to authenticate in web service with basic authentication but I can not.
       The code:
       var w:WebService = new WebService();
       var encoder:Base64Encoder = new Base64Encoder();
       encoder.insertNewLines = false;
       encoder.encode("teste:teste");
       w.httpHeaders = {Authorization:"Basic " + encoder.toString()};
       w.loadWSDL("http://192.168.0.205:8080/jasperserver-pro/services/repository?wsdl");
       When I run the browser always asks for username and password and in a sniffer, for example firebug, I do not see the authentication header in HTTP package.
       Can anyone help me?
    Thank you.

    var enc:Base64Encoder = new  Base64Encoder();
                    enc.encode("test:supp0rt");
                    web_Service_id.httpHeaders= {Authorization:"Basic " + enc.toString()};

  • Setting Basic Authentication for Web Service in WLS 6.1

    Hi,
    I am trying to set-up a Basic Username/Password authentication for a Web Service
    that is hosted in WLS 6.1.
    How do I go about doing that? Also once I get the username and password, how do
    I pass that info
    to the SOAP servlet to do the authentication? Can you give me some pointers on
    this?
    Thanks
    Madhu

    How do you want to do it? Through use of client.jar for the service or
    directly? Here is how I do it directly:
    String auth = "guest", pwd = "guest";
    URL url = new URL("http://localhost:7001");
    URL cmdURL = new URL(url.toString()+"/systemtest/TestWebService");
    HttpURLConnection conn = (HttpURLConnection) cmdURL.openConnection();
    String encAuth =
    new BASE64Encoder().encode((auth + ":" + pwd).getBytes());
    // BASE64Encode distributes long strings on multiple
    // lines; we don't like that, no siree
    int it = 0;
    while ((it = encAuth.indexOf('\n')) != -1
    || (it = encAuth.indexOf('\r')) != -1) {
    encAuth = encAuth.substring(0, it) +
    encAuth.substring(it + 1);
    conn.setRequestProperty("Authorization", "Basic " + encAuth);
    conn.setRequestProperty("Content-Type", "text/xml");
    conn.setRequestProperty("SOAPAction", cmdURL.toString());
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    OutputStream oStr = conn.getOutputStream();
    String cmd =
    "<?xml version=\"1.0\" ?>\n"
    + "<soap:Envelope xmlns:soap=\"http://schemas.xmls"
         + "oap.org/soap/envelope/\"><soap:Body>"
    + "<ping><arg0>false</arg0></ping>"
    + "</soap:Body></soap:Envelope>";
    oStr.write(cmd.getBytes());
    oStr.close();
    InputStream iStr = conn.getInputStream();
    byte[] buffer = new byte[1024];
    while (true) {
    int size = iStr.read(buffer);
    if (size == -1)
    break;
    System.out.println(new String(buffer, 0, size));
    ThorAAge

Maybe you are looking for

  • Hello windows vista/7 bootcamp drivers downloadable?

    I need a windows vista bootcamp dirvers or windows 7 for macbook pro. I will like to say I am currently using tiger again after something happened -.-. I some how was able to create and go in vista from some old partition I had and realized I can pro

  • I am using Firefox with OS X and suddenly I lost the slot in which I type URL's in the top of the browser. How can I get it back?

    I am using FIREFOX with OS X and suddenly I lost the slot at the top of the browswer in which to type the URL's. It just disappeared. How can I get it back?

  • HELP!!! I've fallen and I can't get up!

    This is insane-- itunes support has been no help in this matter, so hopefully someone can help me. I woke up on sunday morning to multiple instances of fraud on my itunes account-- most were charged through paypal & they have been very helpful in tak

  • Wls1211_generic.jar & wls_121200.jar & OCI

    DriverManager.getConnection("jdbc:oracle:oci:@", info); work prefect on weblogic installed from(wls1211_generic.jar)! But when i try run it under weblogic installed from wls_121200.jar it throw "java.lang.UnsatisfiedLinkError: no ocijdbc11 in java.li

  • Help! Skype won't sign in!

    I've uninstalled and reinstalled Skype. It says I have the latest version. But when I try and sign in the sign in screen opens and it says "Signing in..." and the little spinney thing just keeps spinning and spinning and spinnung. I don't know what t