GetOutputStream on the serverside?

I have a simple client and server application.
At the client side there is a block of code like this:
Socket kkSocket = null;
        PrintWriter out = null;
        BufferedReader in = null;
        try {
            kkSocket = new Socket("localhost", 4444);
            out = new PrintWriter(kkSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: localhost.");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: localhost.");
            System.exit(1);
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        String fromServer;
        String fromUser;
        while ((fromServer = in.readLine()) != null)
            System.out.println("Server: " + fromServer);
            if (fromServer.equals("Bye."))
                break;
            fromUser = stdIn.readLine();
            if (fromUser != null)
                out.println(fromUser);
...On the serverside a ServerThread is created that looks like this:
public void run()
         try
              PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
              BufferedReader in = new BufferedReader(
                        new InputStreamReader(
                        socket.getInputStream()));
              String inputLine, outputLine;
              out.println("WHY??");
              while ((inputLine = in.readLine()) != null)
                   outputLine = inputLine + " TXT ADDED";
                   out.println(outputLine);
...the server simply looks like this:
import java.net.*;
import java.io.*;
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;
        boolean listening = true;
        try {
            serverSocket = new ServerSocket(4444);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 4444.");
            System.exit(-1);
        while (listening)
        new ServerThread(serverSocket.accept()).start();
        serverSocket.close();
}In ther serverThread there is the line:
out.println("WHY??");
just before the while loop. If I remove it the application just terminates. But why do I need that line to make it work?
It seems that there is some rule that the server initially has to put something into the 'getOutputStream' so the while loop in the client can be evaluated.
But I have not been able to find any documentation for this so I would be nice with an explanation.

Neither the server or client actually terminates. It seems that they both block in the while loop.
I have tried inserting a System.out.println statement after the while loop in the client but it never gets executed.
Normaly the client would wait for user input but I cannot type anything.
My guess is that the is somekind of deadlock. The while loop in the client are waiting for in.readLine() to give some input and on the serverside the same thing happens.
To 'break' this deadlock its necessary to initially make the server insert some arbitrary text into the getOutputStream so the while loop on the client side will get evaluated. Does this make any sense?

Similar Messages

  • Cannot open the pdf when using the xml publisher to generate rtf report

    Hello Everyone,
    I followed the below link to generate a pdf using xml publisher in OAF.
    http://apps2fusion.com/at/ps/260-integrating-xml-publisher-and-oa-framework
    When i try to save the pdf and open it, i get the below error:
    Adobe Reader could not open the pdf because it is either not a supported file type or because the file has been damaged(for example, it was sent as an email attachment and wasn't correctly decoded).
    Below is the code in CO.
    public void processFormRequest(OAPageContext pageContext, OAWebBean webBean)
    super.processFormRequest(pageContext, webBean);
    OAApplicationModule am= (OAApplicationModule)pageContext.getApplicationModule(webBean);
    String event = pageContext.getParameter("event");
    if("GenerateReport".equals(event))
    // Get the HttpServletResponse object from the PageContext. The report output is written to HttpServletResponse.
    DataObject sessionDictionary = (DataObject)pageContext.getNamedDataObject("_SessionParameters");
    HttpServletResponse response = (HttpServletResponse)sessionDictionary.selectValue(null,"HttpServletResponse");
    try {
    ServletOutputStream os = response.getOutputStream();
    // Set the Output Report File Name and Content Type
    String contentDisposition = "attachment;filename=EmpReport.pdf";
    response.setHeader("Content-Disposition",contentDisposition);
    response.setContentType("application/pdf");
    // Get the Data XML File as the XMLNode
    XMLNode xmlNode = (XMLNode) am.invokeMethod("getEmpDataXML");
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    xmlNode.print(outputStream);
    // System.out.println(outputStream.toString());//Testing the output by printing the contents in the outputstream.
    ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
    ByteArrayOutputStream pdfFile = new ByteArrayOutputStream();
    // System.out.println("language is "+pageContext.getApplicationModule(webBean).getOADBTransaction()).getUserLocale().getLanguage());
    // System.out.println("country is "+pageContext.getApplicationModule(webBean).getOADBTransaction()).getUserLocale().geCountry());
    //Generate the PDF Report.
    TemplateHelper.processTemplate(
    ((OADBTransactionImpl)pageContext.getApplicationModule(webBean).getOADBTransaction()).getAppsContext(),
    // APP_NAME,
    "PER",
    // TEMPLATE_CODE,
    "Emp_Template",
    // ((OADBTransactionImpl)pageContext.getApplicationModule(webBean).getOADBTransaction()).getUserLocale().getLanguage(),
    "English",
    // ((OADBTransactionImpl)pageContext.getApplicationModule(webBean).getOADBTransaction()).getUserLocale().getCountry(),
    "United States",
    inputStream,
    TemplateHelper.OUTPUT_TYPE_PDF,
    null,
    pdfFile);
    // Write the PDF Report to the HttpServletResponse object and flush.
    byte[] b = pdfFile.toByteArray();
    response.setContentLength(b.length);
    os.write(b, 0, b.length);
    os.flush();
    os.close();
    pdfFile.flush();
    pdfFile.close();
    catch(Exception e)
    response.setContentType("application/pdf");
    throw new OAException(e.getMessage(), OAException.ERROR);
    pageContext.setDocumentRendered(false);
    Any suggestions on this would be great!
    Thanks
    Kumar

    Below is the code. Can you change so that that the output can be seen in HTML? I checked the language, country etc and they are fine.
    super.processFormRequest(pageContext, webBean);
    OAApplicationModule am= (OAApplicationModule)pageContext.getApplicationModule(webBean);
    String event = pageContext.getParameter("event");
    if("GenerateReport".equals(event))
    // Get the HttpServletResponse object from the PageContext. The report output is written to HttpServletResponse.
    DataObject sessionDictionary = (DataObject)pageContext.getNamedDataObject("_SessionParameters");
    HttpServletResponse response = (HttpServletResponse)sessionDictionary.selectValue(null,"HttpServletResponse");
    try {
    ServletOutputStream os = response.getOutputStream();
    // Set the Output Report File Name and Content Type
    String contentDisposition = "attachment;filename=PrintPage.pdf";
    response.setHeader("Content-Disposition",contentDisposition);
    response.setContentType("application/pdf");
    // Get the Data XML File as the XMLNode
    XMLNode xmlNode = (XMLNode) am.invokeMethod("getEmpDataXML");
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    // xmlNode.print(outputStream);
    // System.out.println(outputStream.toString());//Testing the output by printing the contents in the outputstream.
    ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
    ByteArrayOutputStream pdfFile = new ByteArrayOutputStream();
    // System.out.println("language is "+pageContext.getApplicationModule(webBean).getOADBTransaction()).getUserLocale().getLanguage());
    // System.out.println("country is "+pageContext.getApplicationModule(webBean).getOADBTransaction()).getUserLocale().geCountry());
    //Generate the PDF Report.
    TemplateHelper.processTemplate(
    ((OADBTransactionImpl)pageContext.getApplicationModule(webBean).getOADBTransaction()).getAppsContext(),
    // APP_NAME,
    "PER",
    // TEMPLATE_CODE,
    "Emp_Template",
    // ((OADBTransactionImpl)pageContext.getApplicationModule(webBean).getOADBTransaction()).getUserLocale().getLanguage(),
    "en",
    // ((OADBTransactionImpl)pageContext.getApplicationModule(webBean).getOADBTransaction()).getUserLocale().getCountry(),
    "US",
    inputStream,
    TemplateHelper.OUTPUT_TYPE_PDF,
    null,
    pdfFile);
    // Write the PDF Report to the HttpServletResponse object and flush.
    byte[] b = pdfFile.toByteArray();
    response.setContentLength(b.length);
    os.write(b, 0, b.length);
    os.flush();
    os.close();
    pdfFile.flush();
    pdfFile.close();
    catch(Exception e)
    response.setContentType("text/html");
    throw new OAException(e.getMessage(), OAException.ERROR);
    pageContext.setDocumentRendered(true);
    Thanks

  • How do we read the values in a tiled view,in the submitted form ?

    Hi,
    I have a form, which is having a tiled view. Each row in the tiled
    view has a check box. I have to read these check box selections, once
    the page is submitted. Is there any built in mechanism in JATO to do
    this ?
    One way I know is to maintain a hidden field in the form and have a
    javascript handler to create a string to reflect the check box
    selectios and set that string as hidden field value, before submitting
    the form. On the serverside read the hidden field's value and parse
    that string to get the selections.
    Are there any other options?
    Thanks in Advance,
    syam.

    While a front panel variable is inside a loop, it's not available to other loops.
    I want to access the value of the variable in many loops.
    And I want to write to a front panel variable in many loops, too.

  • Getting the response from a FileReference upload

    This question is about the "upload" method of the
    FileReference class.
    Is there any way to read the HTTP response after a file
    upload is complete? For example, a user uploads an file to a
    server. The server saves the file and assigns it an ID. The server
    then writes the ID to the HTTP response. How does the client read
    that response?

    inlineblue wrote:
     This was kicked around a while back in the Flexcoders list.
    Everyone agrees this would be very useful, but not currently
    available. Sigh.
    Flexcoders said what?  (Am I missing something? Ahh - the date of the original post...)
    fileReference.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, uploadComplete);
    private function uploadComplete(event:DataEvent):void {
         trace(event.data);
    getWriter() or getOutputStream() on the servlet response to send "stuff" back...

  • Getting the error while calling the report from oaf page

    Dear all
    when i am calling the report from oaf page
    if (pageContext.getParameter("PrintPDF") != null)
    DataObject sessionDictionary =
    (DataObject)pageContext.getNamedDataObject("_SessionParameters");
    HttpServletResponse response =
    (HttpServletResponse)sessionDictionary.selectValue("HttpServletResponse");
    try
    ServletOutputStream os = response.getOutputStream();
    // Set the Output Report File Name and Content Type
    String contentDisposition = "attachment;filename=EmpReport.pdf";
    response.setHeader("Content-Disposition", contentDisposition);
    response.setContentType("application/pdf");
    // Get the Data XML File as the XMLNode
    XMLNode xmlNode = (XMLNode)am.invokeMethod("getEmpDataXML");
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    xmlNode.print(outputStream);
    ByteArrayInputStream inputStream =
    new ByteArrayInputStream(outputStream.toByteArray());
    ByteArrayOutputStream pdfFile = new ByteArrayOutputStream();
    //Generate the PDF Report.
    TemplateHelper.processTemplate(((OADBTransactionImpl)pageContext.getApplicationModule(webBean).getOADBTransaction()).getAppsContext(),
    "XXCRM", "XXCRM_EMP",
    ((OADBTransactionImpl)pageContext.getApplicationModule(webBean).getOADBTransaction()).getUserLocale().getLanguage(),
    ((OADBTransactionImpl)pageContext.getApplicationModule(webBean).getOADBTransaction()).getUserLocale().getCountry(),
    inputStream,
    TemplateHelper.OUTPUT_TYPE_PDF, null,
    pdfFile);
    // Write the PDF Report to the HttpServletResponse object and flush.
    byte[] b = pdfFile.toByteArray();
    response.setContentLength(b.length);
    os.write(b, 0, b.length);
    os.flush();
    os.close();
    } catch (Exception e)
    response.setContentType("text/html");
    throw new OAException(e.getMessage(), OAException.ERROR);
    pageContext.setDocumentRendered(false);
    i am getting the error java.classcastexception at this line
    DataObject sessionDictionary =
    (DataObject)pageContext.getNamedDataObject("_SessionParameters");
    regards
    Sreekanth

    check if you have import oracle.cabo.ui.data.DataObject; in your import statement.
    --Prasanna                                                                                                                                                                                               

  • How to set the parameter

    hi i am creating xml publisher and from OAF with parameters
    cusname:
    runreportdate:
    go clear buttons
    click go open report in pdf
    SELECT hp.party_name CustomerName,
      csi.incident_number SRNumber,
      to_char(csi.incident_date,'DD-MON-YYYY') SRDate,
      to_char(csi.close_date,'DD-MON-YYYY') SRCloseDate,
      mtl.description SRItemName,
      csi.summary Summary,
      csi.problem_code,
      csi.incident_address SRAddress,
      csi.INCIDENT_COUNTRY SRCountry,
      '31-DEC-2008' Reportrundate,
      COUNT ( * ) over () cnt,
      cis.name,
      COUNT(
      CASE
        WHEN cis.name='Low'
        THEN 1
      END) over () Low,
      COUNT(
      CASE
        WHEN cis.name='Medium'
        THEN 1
      END) over () Medium,
      COUNT(
      CASE
        WHEN cis.name='High'
        THEN 1
      END) over () High1,
    to_char(csi.incident_date,'MON-YYYY') SrMonth
    FROM hz_parties hp,
      hz_cust_accounts hca,
      hz_contact_points hc,
      cs_incidents_all_b csi,
      ar_lookups arl,
      cs_incident_severities_b cis,
      mtl_system_items_kfv mtl
    WHERE hca.cust_account_id   =csi.account_id
    AND hp.party_type          IN ('PERSON','ORGANIZATION')
    AND hp.status               ='A'
    AND hp.party_id             = hca.party_id
    AND hca.status              ='A'
    AND hp.party_id             =hc.owner_table_id(+)
    AND hc.owner_table_name(+)  ='HZ_PARTIES'
    AND hp.party_id             =hca.cust_account_id
    AND hc.contact_point_type(+)='PHONE'
    AND hc.primary_flag(+)      ='Y'
    AND hc.status(+)            ='A'
    AND arl.lookup_type(+)      = 'PHONE_LINE_TYPE'
    AND arl.lookup_code(+)      = hc.phone_line_type
    AND hp.party_name='Business World'
    AND csi.incident_date BETWEEN to_date('01-JAN-2000','DD-MON-YYYY') AND to_date('31-DEC-2008','DD-MON-YYYY')
    AND cis.incident_severity_id=csi.incident_severity_id
    AND mtl.inventory_item_id=csi.inventory_item_id
    GROUP BY hp.party_name,
      csi.incident_number,
      csi.incident_date,
      csi.close_date,
      csi.summary,
      csi.problem_code,
      csi.incident_address,
      cis.name,
      csi.INCIDENT_COUNTRY,
      mtl.description,
      to_char(csi.incident_date,'MON-YYYY')
    Am code
        public void initQuery(String paramString1, String paramString2)
              SrReportVOImpl vo=getSrReportVO1();
            if ((paramString1 != null) && (!("".equals(paramString1.trim()))) && (paramString2 != null) && (!("".equals(paramString2.trim()))))
              vo.setWhereClauseParams(null);
              vo.setWhereClauseParam(0, paramString1);
              vo.setWhereClauseParam(1, paramString2);
              vo.executeQuery();
        public XMLNode getPrintDataXML()
        //SrReportVOImpl vo=getSrReportVO1();
        OAViewObject vo = (OAViewObject)findViewObject("SrReportVO1");
        //vo.initQuery(s,s1);
        XMLNode xmlNode=(XMLNode) vo.writeXML(4,XMLInterface.XML_OPT_ALL_ROWS);
            return xmlNode;
    CO code
          SrAMImpl am=(SrAMImpl)pageContext.getApplicationModule(webBean);
          if(pageContext.getParameter("Go")!=null)
              //am.searchSrDetails(pageContext,webBean);   
               String s=pageContext.getParameter("CustomerName");
               String s1=pageContext.getParameter("RunReportDate");
                   am.initQuery(s,s1);
                 // Get the HttpServletResponse object from the PageContext. The report output is written to HttpServletResponse.
                 DataObject sessionDictionary = (DataObject)pageContext.getNamedDataObject("_SessionParameters");
                 HttpServletResponse response = (HttpServletResponse)sessionDictionary.selectValue(null,"HttpServletResponse");
                 try {
                 ServletOutputStream os = response.getOutputStream();
                 // Set the Output Report File Name and Content Type
                 String contentDisposition ="attachment;filename=ServiceReport.pdf";
                 response.setHeader("Content-Disposition",contentDisposition);
                 response.setContentType("application/pdf");
                     Serializable param[]={pageContext.getParameter("CustomerName"),pageContext.getParameter("RunReportDate")};
                     System.out.println("hiiii 12");
                     // Get the Data XML Output as the XMLNode
                     XMLNode xmlNode = (XMLNode) am.invokeMethod("getPrintDataXML",param);
                     System.out.println("hiiii 13");
                     System.out.println(xmlNode.toString());
                     System.out.println("hiiii 14");
                 // Get the Data XML File as the XMLNode
                 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                 xmlNode.print(outputStream);
                 ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
                 ByteArrayOutputStream pdfFile = new ByteArrayOutputStream();
                 //Generate the PDF Report.
                 TemplateHelper.processTemplate(
                 ((OADBTransactionImpl)pageContext.getApplicationModule(webBean).getOADBTransaction()).getAppsContext(),
                 APP_NAME,
                 TEMPLATE_CODE,
                 ((OADBTransactionImpl)pageContext.getApplicationModule(webBean).getOADBTransaction()).getUserLocale().getLanguage(),
                 ((OADBTransactionImpl)pageContext.getApplicationModule(webBean).getOADBTransaction()).getUserLocale().getCountry(),
                 inputStream,
                 TemplateHelper.OUTPUT_TYPE_PDF,
                 null,
                 pdfFile);
                 // Write the PDF Report to the HttpServletResponse object and flush.
                 byte[] b = pdfFile.toByteArray();
                 response.setContentLength(b.length);
                 os.write(b, 0, b.length);
                 os.flush();
                 os.close();
                 pdfFile.flush();
                 pdfFile.close();
                 catch(Exception e)
                 response.setContentType("text/html");
                 throw new OAException(e.getMessage(), OAException.ERROR);
                 pageContext.setDocumentRendered(false);
                   System.out.println("hiiii 13");
          if(pageContext.getParameter("Clear")!=null)
              am.ClearFields(pageContext,webBean);
          }can any one tell me how to set the bind parameters or setting parameter

    Hi,
    Could not understand your problem exactly. DId you try adding bind variables in the query like below:
    AND hp.party_name='Business World'
    AND csi.incident_date BETWEEN to_date('01-JAN-2000','DD-MON-YYYY') AND to_date('31-DEC-2008','DD-MON-YYYY')
    change to
    AND hp.party_name=:1
    AND csi.incident_date BETWEEN :2 AND :3
    Please note you will need three bind variables. Second and third for SR Dates.
    ~Amol

  • Running Interactive commands in java and displaying the output.

    Hi All,
    I'm running a sample code to execute a user defined command (cmd1) and display the results. The output of the command when executed in command prompt is
    (1) Executing the command cmd1
    (2) Do you want to continue(Y/N)_ <waits for user input>
    (3) Based on user input
    (Y) Displays the results
    (N) Interrupted
    But i'm facing problem when i execute the below code. When the results are being displayed instead of displaying line(1) and (2) and then waiting for the input- the code waits for the input and then only displays the results.
    O/p
    inside output
    inside input
    y (------ gets the input and then only displays the results).
    Executing the command cmd1
    Do you want to continue(Y/N)
    results
    Please help out how to resolve this issue.
    Thanks.
    Sample Code for reference.
    import java.util.*;
    import java.io.*;
    public class SampleCheck {
         public static void main(String[] args) throws Exception {
              (new SampleCheck()).test();
         void test() throws Exception {
              Process proc = Runtime.getRuntime().exec("cmd1");
              // any error from the process?
              StreamHandlerErr errorStream = new StreamHandlerErr(proc
                        .getErrorStream(), System.err);
              // any output from the process?
              StreamHandlerOutput outputStream = new StreamHandlerOutput(proc
                        .getInputStream(), null);
              // any input to the process?
              // FileInputStream fin = new FileInputStream(new File("textfile1.txt"));
              StreamHandlerInput inputStream = new StreamHandlerInput(System.in, proc
                        .getOutputStream());
              // start the stream threads
              // errorStream.start();
              outputStream.start();
              inputStream.start();
              // wait till it returns
              int exitVal = proc.waitFor();
              System.exit(exitVal);
         class StreamHandlerInput extends Thread {
              InputStream is;
              OutputStream os;
              StreamHandlerInput(InputStream is, OutputStream os) {
                   this.is = is;
                   this.os = os;
              public void run() {
                   System.out.println("inside input");
                   try {
                        int c;
                        while ((c = is.read()) != -1) {
                             os.write(c);
                             System.out.println("c= " + c);
                             os.flush();
                   } catch (IOException e) {
                   System.out.println("End of Run Method..Input");
         class StreamHandlerOutput extends Thread {
              InputStream is;
              OutputStream os;
              File f=new File("jbsrt_output.txt");
              StreamHandlerOutput(InputStream is, OutputStream os) {
                   this.is = is;
                   this.os = os;
              public void run() {
                   System.out.println("inside output");
                   try {
                        int c;
                        FileOutputStream fs=new FileOutputStream(f);
                        /*PrintStream ps =new PrintStream(;
                        ps.print(arg0)
                        ps.close();*/
                        InputStreamReader ir = new InputStreamReader(is);
                        //System.out.println(ir.read());
                        BufferedReader br = new BufferedReader(ir);
                        String line = null;
                        while((line=br.readLine())!=null)
                             System.out.println(line);
                   } catch (Exception e) {
                   System.out.println("End of Run Method..Output");
         class StreamHandlerErr extends Thread {
              InputStream is;
              OutputStream os;
              StreamHandlerErr(InputStream is, OutputStream os) {
                   this.is = is;
                   this.os = os;
              public void run() {
                   System.out.println("inside Err");
                   try {
                        int c;
                        while ((c = is.read()) != -1) {
                             os.write(c);
                             os.flush();
                   } catch (IOException e) {
                   System.out.println("End of Run Method..Err");
    }

    Console input is line buffered. This means you only get the first character a line after the newline has been inputed.
    The same thing happen if you just type on the console.
    I am not aware of any simple way around this.
    IDEs get around this by changing the application run so that the input/output is captured as it happens and sent over a socket connection.

  • ACCESSING a file out of the web contex in JSP

    hi
    i'm a new JSP developer ius eclipse 3.2 environment and tomcat 5.
    i wanna include an html file from somewhere outside of the web directory (for exapmle "c:\test.html")with <jsp:include> ; but i cant!what shold I do?

    If you're going to be using a FileReader, piping the request through a servlet using FileIinputStream -> response.getOutputStream() seems the best option
    Putting it in a servlet means that you only send the contents of the file, without any of the extra carriage returns that can be included in a JSP.

  • How to show the file contents in a streaming manner on the browser

    Hi,
    I have a log file which gets appended to by another program.
    I need to show the contents of this log file in the browser window but in a streaming manner. Reading the file in one shot and refreshing the page every few seconds is not a solution as it makes the browser hang when the file size is huge. A unix tail functionality is also acceptable but it should be streaming. Would a servlet or applet do the trick?
    Please advise!

    is your log file present on web/application server? if yes, you can do the following:
    1. create a web page containing text area. (for displaying log file)
    2. use XmlHttpRequstObject (Ajax) for querying the next available data from Servlet.
    On the Serverside:
    You can store the the FileScanner object in session scope. and use it to read the next available data and send it as response.
    On the client Side(webpage/javascript)
    read the contents of the response and append it to textarea.
    In Simple words, I'd say AJAX is the way to go.

  • Usung a href Tag, open the linked file in associated editor

    Hi,
    I have a functionality where a file location would be fetched from the database, shown to the user as a hyperlink. On clicking the hyperlink the file should open in its associated editor i.e if it is a .doc it should open in word, if it is an xls it should open in Excel.
    I tried different ways but its opening in the IE browser itself ,Is there a way that it opens up in its associated editor.
    Infact even if it opens in browser its ok, but then if a user modifies the xls and tries to "SAve AS" the pop up does not appears to save the file.How can i get the pop up so that user can save the modified file in it local computer.

    Hi ,
    Thanks a lot. What i have done is
    File excelFile = new File("\full file name");
    ServletOutputStream out = res.getOutputStream ();
    // Set the output data's mime type
    //res.setContentType( "application/text" ); // MIME type for pdf doc
    res.setContentType( "application/vnd.ms-excel");
    // create an input stream from fileURL
    String fileURL =
    full file name";
    // Content-disposition header - don't open in browser and
    // set the "Save As..." filename.
    // *There is reportedly a bug in IE4.0 which ignores this...
    res.setHeader("Content-disposition",
    "attachment; filename=\"file name\"");
    // PROXY_HOST and PROXY_PORT should be your proxy host and port
    // that will let you go through the firewall without authentication.
    // Otherwise set the system properties and use URLConnection.getInputStream().
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
    // Use Buffered Stream for reading/writing.
    bis = new BufferedInputStream(new FileInputStream(excelFile));
    bos = new BufferedOutputStream(out);
    byte[] buff = new byte[2048];
    int bytesRead;
    // Simple read/write loop.
    while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
    bos.write(buff, 0, bytesRead);
    } catch(final Exception e) {
    System.out.println ( "Exception" );
    throw e;
    } finally {
    if (bis != null)
    bis.close();
    if (bos != null)
    bos.close();
    This is the code for excel, and its doing what i needed.
    I havent tested it for other formats hopefully it would work. :)

  • How to update progressbar while doing serverside processing?

    Hi,
    I have the following use case:
    - When the user clicks a button a file must be downloaded. Because it can take some time before the server gathered the data, a progressindicator must be shown. After that the file is presented to the user.
    Currently, I have clientside javascript that shows the popup, and then queues a server event that starts the serverside processing. A poller is running that should keep track of the progress.
    My problem is that the popup only shows at the end of the serverside method. Also, the poller doesnt poll while the serverside method is executed, and resumes at the end of the serverside method execution. So even when the popup would show, it wouldnt properly display the progress.
    I have the following code:function showProgressPopup(event) {
                                var popup = AdfPage.PAGE.findComponent("pt:progressPopup");
                                var hints = {};
                                hints[AdfRichPopup.HINT_ALIGN] = AdfRichPopup.ALIGN_OVERLAP;
                                hints[AdfRichPopup.HINT_ALIGN_ID] = "pt:downloadButton";           
                                popup.show(hints);
                                var source = event.getSource();
                                AdfCustomEvent.queue(source, "startDownload", {}, false); //at this moment, popup should show and serverside processing starts
    <af:panelGroupLayout id="pgl6">
                    <af:poll id="poller"/>
                    <af:commandButton text="Download in Excel-formaat" id="downloadButton" partialSubmit="true">
                        <af:clientListener type="action" method="showProgressPopup"/>
                        <af:serverListener type="startDownload" method="#{CombinotaExportBean.startDownload}"/>
                    </af:commandButton>
                    <af:popup id="progressPopup" clientComponent="true">
                      <af:dialog id="downloadDialog" type="cancel" modal="true" closeIconVisible="false" title="Downloading..." partialTriggers="downloadButton poller">
                        <af:switcher id="downloadSwitcher" defaultFacet="showRunning"
                                     facetName="#{CombinotaExportBean.value == CombinotaExportBean.maximum ? 'showReady' : 'showRunning'}">
                          <f:facet name="showRunning">
                            <af:panelGroupLayout id="pgl7">
                              <af:panelHeader text="One moment please" id="ph3"/>
                              <af:progressIndicator id="progressIndicator" value="#{CombinotaExportBean}" partialTriggers="poller">
                                <af:outputFormatted styleUsage="instruction" value="Data is being collected..." id="of1"/>
                              </af:progressIndicator>
                            </af:panelGroupLayout>
                          </f:facet>
                          <f:facet name="showReady">
                            <af:goLink text="Click to download file" id="gl1" partialTriggers="poller" destination="#{CombinotaExportBean.downloadFile}">
                              <af:clientListener type="click" method="closeProgressPopup"/>
                            </af:goLink>
                          </f:facet>
                        </af:switcher>
                      </af:dialog>
                      <af:clientListener method="downloadDialogCanceled" type="popupCanceled"/>
                      <af:serverListener type="downloadCanceled" method="#{CombinotaExportBean.downloadCanceled}"/>
                    </af:popup>
                    </af:panelGroupLayout>When I start a new Thread in my serverside CombinotaExportBean.startDownload method, it works because then that method returns while the server is still processing. However then I have problems with quering my RowSetIterators, they start throwing NPE's. Multithreading is evil in webapps I guess.
    So how can I do this in one thread? How can I make sure my popup shows first, and my poller keeps polling while the server collects data?
    with kind regards,
    Gerben

    Hi Frank,
    Thanks for your suggestion. In my current implementation I'm basically using a animated image, because I'm now using the ProgressIndicator without BoundedRangeModel and then it just shows a running clock.
    However, in my case its quite easy to monitor the progress on the server thread. So I thought this is the typical use case for a real ProgressIndicator. Unfortunately I can only find 10g examples of the progress indicator and I dont get the 11g progressindicator to work like that. So what I am curious about is, if a typical ProgressIndicator use case is any different. And if there's any example of it, with or without the usage of the poller.
    I already found the answer to part of my question. If I set noResponseExpected to the serverevent, the client event finishes and is effective immediately, before the server event is finished:var source = event.getSource();
    var customEvent =  new AdfCustomEvent(source, "startDownload", {}, false);
    customEvent.noResponseExpected();
    customEvent.queue(true);with kind regards,
    Gerben

  • Connection works but program does not continue in the code ?

    Hello,
    I have a client, a server and a data class implementing Serializable interface.
    Both classes communicate via sockets.
    Between the sockets I transfer objects from the type of the data class.
    The client and the server are running each in a Thread.
    First the server is started then pressing a certain button in the GUI the client is started.
    1. Why is the code in the clients Thread never going beyond this code line: System.out.println("test"); ???
    2. Why is the file satz.dat not written ?
    This is the part code of all 3 classes which is making me trouble:
    Client code:
    public class ClientThread extends Thread
           ClientThread()
           public void run()
                try
                     InetAddress ip = InetAddress.getByName("localhost");                 
                     Socket socket = new Socket(ip , ServerThread.PORT); 
                     System.out.println("test");
                     ObjectInputStream incomingObject = new ObjectInputStream(socket.getInputStream());             
                     ObjectOutputStream outgoingObject = new ObjectOutputStream(socket.getOutputStream());                    
                      outgoingObject.writeObject(serializeObjekt(meineBuchdaten)); // serialize the object "meineBuchdaten"
                      incomingObject.close();
                      outgoingObject.close();
                      socket.close();              
                catch (Exception e)
                      e.printStackTrace();                
    Method to serialize the string data of the data class called Buchdaten class:
    public Object serializeObjekt(Object objekt) throws IOException
              ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("d:/satz.dat")));
             oos.writeObject(objekt);
             oos.flush();
             oos.close(); 
             return oos;
    server class:
    public class ServerThread extends Thread
         public static final int PORT = 8080;
         private ServerSocket myServerSocket = null;
         private Socket myClientSocket;     
         private Database myDatabase = new Database();     
         public ServerThread()
        public void run()
              try
                   myServerSocket = new ServerSocket(PORT);               
              catch (IOException e)
                   e.printStackTrace();
              System.out.println("Started: " + myServerSocket);          
              try
                   while(true)
                        // Warten until the client connects...               
                        myClientSocket = myServerSocket.accept();     
                        System.out.println("Connection done - handshake " + myClientSocket);
                        ObjectInputStream incomingObject = new ObjectInputStream(myClientSocket.getInputStream());
                     ObjectOutputStream outgoingObject = new ObjectOutputStream(myClientSocket.getOutputStream());                    
                        Buchdaten bd = (Buchdaten) incomingObject.readObject();
                        System.out.println("This should be the deserialized data: " + bd);
                        myClientSocket.close();                    
              catch(Exception ex)
                   System.out.println(ex.getMessage());
    data class:
    public class Buchdaten implements Serializable
         private static final long serialVersionUID = 1L;
         private String autor;
         private String titel;
         private String jahr;
         private String verlag;
         private int number;
         private int id;
         public Buchdaten()
         public void setDataToArray(String autor, String titel, String jahr, String verlag , int number)
           this.autor = autor;
           this.titel = titel;
           this.jahr  = jahr;
           this.verlag = verlag;
           this.number = number;     
         public void setDataToArray(int number , int id)
           this.number = number;     
           this.id = id;
         public void setDataToArray(String autor, String titel, String jahr, String verlag , int number , int id)
           this.autor = autor;
           this.titel = titel;
           this.jahr  = jahr;
           this.verlag = verlag;
           this.number = number;     
           this.id = id;
    }

    >
    Oh, and by the way, is there a reason you aren't just using normal java RMI?
    Edited by: jtahlborn on Feb 1, 2008 9:34 PMOh, and by the way, is there a reason you aren't just using normal java RMI?
    yes for now i have to do it this way. The app must only run on my home pc but later i have to do it with RMI, but first it must work with sockets and streams etc stupd i know... ;-)
    sabre150: quote:"As with all two way communication, one thread should be used for writing and another for reading. This ways the blocking nature of the streams works for and not against."
    0: Does that mean i have to open 4 threads ? 2 threads for the client class and 2 threads for the server class? each one has an ObjectInput/Output - stream right?
    For now i have only opened the outputstream on client side and the inputstream on server side to see wether it works at all. Furthermore my object is now serialized to the satz.dat file and it works.
    1. Is there a way to serialize my data "meineBuchdaten" on-the-fly without writing it into a file on harddisk?
    2. I want to print out the deserialized data but it doesnt work i get no output using the system.out.println method?
    3. After this output: Connection done - handshake Socket[addr=/127.0.0.1,port=3139,localport=10001] I get this output: null
    why null? from where does this null come?
    Edit: ok my debugger work now again i reinstalled eclipse... debugging the cast into "meineBuchdaten" is the problem because right after this the debugger jumps into an exception this one
    catch(Exception ex)
                   System.out.println(ex.getMessage());
              }Edit: I have changed again the code a bit only this:
    // Output of the deserialized data for test purposes
    System.out.println("This should be the deserialized data: Autor: " + bd.getAutor());
    its accessing the autor attribute variable of the bd object in a proper way but still the bd object is null i guess the problem is my serialized data on the client side is not transported what do i wrong can someone pls help me please ?
    changed code:
    client class:
    public class ClientThread extends Thread
           ClientThread()
           public void run()
                  try
                          InetAddress ip = InetAddress.getByName("localhost");                 
                          Socket socket = new Socket(ip , ServerThread.PORT); 
                          System.out.println("test");                
                           // ObjectOutputStream for the object to be sent over socket to the server
                          ObjectOutputStream outgoingObject = new ObjectOutputStream(socket.getOutputStream());
                          // writing the class object "meineBuchdaten" into a file on the hard disk
                          try
                               ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("d:/satz.dat")));
                          oos.writeObject(meineBuchdaten);
                          oos.flush();
                          oos.close();
                          catch (NotSerializableException nse)
                               System.out.println("No Serialization of the class " + nse.getLocalizedMessage() + " is possible");                           
                          catch(IOException ioe)
                               System.out.println(ioe.getMessage());
                          // closing the ObjectOutputStream and the client connection to free resources
                           outgoingObject.close();
                           socket.close();              
                     catch (Exception e)
                           e.printStackTrace();                
    server class:
    public class ServerThread extends Thread
         public static final int PORT = 10001;
         private ServerSocket myServerSocket = null;
         private Socket myClientSocket;     
         private Database myDatabase = new Database();     
         public ServerThread()
        public void run()
              try
                   myServerSocket = new ServerSocket(PORT);               
              catch (IOException e)
                   e.printStackTrace();
              System.out.println("Started: " + myServerSocket);          
              try
                   while(true)
                        // wait until the client connects...               
                        myClientSocket = myServerSocket.accept();     
                        System.out.println("Connection done - handshake " + myClientSocket);
                        ObjectInputStream incomingObject = new ObjectInputStream(myClientSocket.getInputStream());                
                        // Reading the serialized data and cast it to the proper type
                        Buchdaten bd = (Buchdaten) incomingObject.readObject();
                        // Output of the deserialized data for test purposes
                        System.out.println("This should be the deserialized data: " + bd);
                        // closing the ObjectInputStream and the client connection to free resources
                        incomingObject.close();
                        myClientSocket.close();                    
              catch(Exception ex)
                   System.out.println(ex.getMessage());
    }Edited by: pel on Feb 2, 2008 2:04 AM

  • Problem with the firstcup tutorial

    Hi, I'm a developer that is new to Java. I walked through the "firstcup" tutorial using the netbeans 6.5.1 ide and glassfish 2.1 server.
    I thought I had successfuly completed all the code and xml config files.
    When I got to p14.html, "Building, Packaging, Deploying, and Running the firstcup Enterprise Application", I run into a problem trying to run the tutorial app.
    Posted below is the error I get in the webpage. The server log file error is too long to post because of the character limit of this forum.
    If anybody could point me in the right direction I would appreciate it. Also if this question should be posted on a different forum please advise,
    Thanks,
    Paul
    WEBPAGE ERROR
    type Exception report
    message
    descriptionThe server encountered an internal error () that prevented it from fulfilling this request.
    exception
    javax.servlet.ServletException: Cant instantiate class: com.sun.firstcup.web.DukesBDay.. com.sun.firstcup.web.DukesBDay
    root cause
    javax.faces.FacesException: Cant instantiate class: com.sun.firstcup.web.DukesBDay.. com.sun.firstcup.web.DukesBDay
    root cause
    java.lang.ClassNotFoundException: com.sun.firstcup.web.DukesBDay
    note The full stack traces of the exception and its root causes are available in the Sun GlassFish Enterprise Server v2.1 logs.

    Paul,
    What does the below diagnostic message mean to you?
    java.lang.ClassNotFoundException: com.sun.firstcup.web.DukesBDayTell me, I'll confirm or repudiate... and then we'll looking to why that might be the case, leading to what to do about it.
    <aside>
    If you're new to Java then jumping straight into J2EE probably isn't the way to go... especially if you're totally new to programming, especially web-programming... The serverside EE-technology-stack builds on the core Java langauge and API's (J2SE)... and without at-least a basic understanding of the Java language itself I predict that you're going to really really struggle with the EE tutorials... and that therefore you'll probably give up in disgust.
    They call this page [getting started|http://java.sun.com/docs/books/tutorial/getStarted/index.html]... I (for one) think it's aptly named... Nobody gets to skip HelloWorld, or the universe will implode, or something ;-)
    </aside>
    Cheers. Keith.

  • Calling serverside function

    Hi
    I wonder spry has the function request the serverside
    functions to reflect on the page
    I know it is possible using XML with queries, but without
    xml?
    Thanks

    As far i know,
    Spry is build up in JavaScript, JavaScript is a Client side
    language, JavaScript is only able to read / process data it gets
    from the servers etc.
    (i don't know what u are trying to do) But i doubt its
    possible,
    I don't if this helped u,
    V1.

  • How to send echo msg to client after regular time to verify the client

    Hi
    I have socket program which used for communicating information. tow part client and server.
    I am having problem. that is I want to send a msg to client (like echo) after some time duration. so how to do that?
    help
    Kapila

    This is the run method of inner class. when the sever is ideal, the sever has to send the msg to client. I think that I want to declare the this part "byte[] b = byteConcatenate(header, responsefornac,response.length); and out.write(b);" elsewhere. first I want to check the server is ideal then if it is ok, send the msg to client.
    problem is how to recognise the client?
              * Description : This inner class is used for handling the client session
         protected class SessionPda implements Runnable
    //********************************** DECLARATION OF COMMON VARIABLES ******************************************
         protected     byte[]      request;
         protected     byte[]      response;
         protected      byte[]      header;
         protected      byte[]      requestforserver;
         protected      byte[]      responsefornac;
         protected      Socket      client               ;
    //********************************** DEFINE CONSTRACTOR********************************************************
              * Description : This method is using for getting the opening client socket
              * @param e
         public SessionPda(Socket client)
         try
         this.client      =      client;
         catch (Exception e)
              System.out.println(">>>>>>>>>>>>>> This is error is occured when getting the opened clint socket at the inner sessionpda class in serve.>>>>>>>>>>>>>>>>>");
                   SysLog.logError(java.util.logging.Level.SEVERE, this.toString(), "Sessionpda()", StackTraceUtil.getStackTrace(e));
         header                     =      new byte[HEADER_SIZE];
         request                =      new byte[PACKET_SIZE];
         response                =      new byte[PACKET_SIZE];
         requestforserver      =      new byte[PACKET_SIZE];
         responsefornac           =      new byte[PACKET_SIZE];
    //********************************** OVERRIDING THE RUN METHOD IN JAVA LANG THREAD ****************************************************
              * Description : The proccessing the cliet sessionpda
              * @param request
              * @param respons
              public void run()
              try
                   while (true)
                        in     =     new     DataInputStream(client.getInputStream())     ;
                        out     =     new DataOutputStream(client.getOutputStream())     ;
                   //PRINTING THE REQUEST INFO-----------------------------------
                        int     len     =     in.read(request,0,PACKET_SIZE)                    ;
                        String recvString = "";
         for (int i = 0; i < len; i++)
              recvString +=adjustString(Integer.toHexString( (int) (request)));
         // System.out.println("Request Information :"+recvString);
         //PEPARING TO TO PRCESS--------------------------------------
         for (int j = 0; j < PACKET_SIZE - 3 ; j++)
                   requestforserver[j] = request[j + 3];
         Process p = ProcessFactory.getProcess(request);
         boolean redo = p.doProcess();
         ISOMsg m = new ISOMsg();
    m = p.getResponse();
    m.setPackager(new ISO87BPackager());
    response = m.pack();
    //PEPARATRING TO SEND BACK THE RESPOND----------------------
    header[1] = (byte) (response.length + 5);
              header[3] = (byte) 00;
              responsefornac[0] = (byte) Integer.parseInt(NII.substring(1,3),16); //17;
              for (int k = 0; k < response.length; k++)
                   responsefornac[k + 1] = response[k];
              byte[] b = byteConcatenate(header, responsefornac,response.length);
              out.write(b);
              out.flush();
    String sendinString = "";
    for (int i = 0; i < response.length + 5; i++)
         sendinString +=
              adjustString(Integer.toHexString( (int) (b[i])));
    SysLog.logInfo(java.util.logging.Level.INFO,"Response \n"+ sendinString);

Maybe you are looking for

  • ITunes Match and iPhone

    I have iTunes Match activated on both my devices, macbookpro and iPhone 5. I have noticed many diffences between the 2 library. I have an album that If I don't set the artist album tag, the artist don't work on iPhone. Also, I have an artist that all

  • Error while loading library fileQueries

    Hello, I am running runInstaller to install 10g database on Red Hat Enterprise Linux AS release 3. I get the following message: "There was an error while loading library fileQueries". This message is displayed after selecting "File System" radio butt

  • IPhoto problems

    When i plug my iphone into my imac for the first time it only shows up pictures from my camera roll and not pictures from other folders? I want to import all pictures from my iphone?

  • Adobe wont open

    adobe wont open, when I select open with protected mod disabled it says "acrobat failed to load its core dll"

  • V490 sol8 no disks found

    Hi, I have 2 V490, both with sol8 installed from DVDROM. both have 2 SCSI disks installed I run format and get the list of disks machine1: Searching for disks...done AVAILABLE DISK SELECTIONS:        0. c1t0d0 <SUN146G cyl 14087 alt 2 hd 24 sec 848>